LLParser: Simplify ParseInstructionMetadata(), NFC
[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/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ValueSymbolTable.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/SaveAndRestore.h"
31 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm;
33
34 static std::string getTypeString(Type *T) {
35   std::string Result;
36   raw_string_ostream Tmp(Result);
37   Tmp << *T;
38   return Tmp.str();
39 }
40
41 /// Run: module ::= toplevelentity*
42 bool LLParser::Run() {
43   // Prime the lexer.
44   Lex.Lex();
45
46   return ParseTopLevelEntities() ||
47          ValidateEndOfModule();
48 }
49
50 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
51 /// module.
52 bool LLParser::ValidateEndOfModule() {
53   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
54     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
55
56   // Handle any function attribute group forward references.
57   for (std::map<Value*, std::vector<unsigned> >::iterator
58          I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
59          I != E; ++I) {
60     Value *V = I->first;
61     std::vector<unsigned> &Vec = I->second;
62     AttrBuilder B;
63
64     for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
65          VI != VE; ++VI)
66       B.merge(NumberedAttrBuilders[*VI]);
67
68     if (Function *Fn = dyn_cast<Function>(V)) {
69       AttributeSet AS = Fn->getAttributes();
70       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
71       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
72                                AS.getFnAttributes());
73
74       FnAttrs.merge(B);
75
76       // If the alignment was parsed as an attribute, move to the alignment
77       // field.
78       if (FnAttrs.hasAlignmentAttr()) {
79         Fn->setAlignment(FnAttrs.getAlignment());
80         FnAttrs.removeAttribute(Attribute::Alignment);
81       }
82
83       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
84                             AttributeSet::get(Context,
85                                               AttributeSet::FunctionIndex,
86                                               FnAttrs));
87       Fn->setAttributes(AS);
88     } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
89       AttributeSet AS = CI->getAttributes();
90       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
91       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
92                                AS.getFnAttributes());
93       FnAttrs.merge(B);
94       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
95                             AttributeSet::get(Context,
96                                               AttributeSet::FunctionIndex,
97                                               FnAttrs));
98       CI->setAttributes(AS);
99     } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
100       AttributeSet AS = II->getAttributes();
101       AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
102       AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
103                                AS.getFnAttributes());
104       FnAttrs.merge(B);
105       AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
106                             AttributeSet::get(Context,
107                                               AttributeSet::FunctionIndex,
108                                               FnAttrs));
109       II->setAttributes(AS);
110     } else {
111       llvm_unreachable("invalid object with forward attribute group reference");
112     }
113   }
114
115   // If there are entries in ForwardRefBlockAddresses at this point, the
116   // function was never defined.
117   if (!ForwardRefBlockAddresses.empty())
118     return Error(ForwardRefBlockAddresses.begin()->first.Loc,
119                  "expected function name in blockaddress");
120
121   for (const auto &NT : NumberedTypes)
122     if (NT.second.second.isValid())
123       return Error(NT.second.second,
124                    "use of undefined type '%" + Twine(NT.first) + "'");
125
126   for (StringMap<std::pair<Type*, LocTy> >::iterator I =
127        NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
128     if (I->second.second.isValid())
129       return Error(I->second.second,
130                    "use of undefined type named '" + I->getKey() + "'");
131
132   if (!ForwardRefComdats.empty())
133     return Error(ForwardRefComdats.begin()->second,
134                  "use of undefined comdat '$" +
135                      ForwardRefComdats.begin()->first + "'");
136
137   if (!ForwardRefVals.empty())
138     return Error(ForwardRefVals.begin()->second.second,
139                  "use of undefined value '@" + ForwardRefVals.begin()->first +
140                  "'");
141
142   if (!ForwardRefValIDs.empty())
143     return Error(ForwardRefValIDs.begin()->second.second,
144                  "use of undefined value '@" +
145                  Twine(ForwardRefValIDs.begin()->first) + "'");
146
147   if (!ForwardRefMDNodes.empty())
148     return Error(ForwardRefMDNodes.begin()->second.second,
149                  "use of undefined metadata '!" +
150                  Twine(ForwardRefMDNodes.begin()->first) + "'");
151
152   // Resolve metadata cycles.
153   for (auto &N : NumberedMetadata) {
154     if (N.second && !N.second->isResolved())
155       N.second->resolveCycles();
156   }
157
158   // Look for intrinsic functions and CallInst that need to be upgraded
159   for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
160     UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
161
162   UpgradeDebugInfo(*M);
163
164   return false;
165 }
166
167 //===----------------------------------------------------------------------===//
168 // Top-Level Entities
169 //===----------------------------------------------------------------------===//
170
171 bool LLParser::ParseTopLevelEntities() {
172   while (1) {
173     switch (Lex.getKind()) {
174     default:         return TokError("expected top-level entity");
175     case lltok::Eof: return false;
176     case lltok::kw_declare: if (ParseDeclare()) return true; break;
177     case lltok::kw_define:  if (ParseDefine()) return true; break;
178     case lltok::kw_module:  if (ParseModuleAsm()) return true; break;
179     case lltok::kw_target:  if (ParseTargetDefinition()) return true; break;
180     case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
181     case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
182     case lltok::LocalVar:   if (ParseNamedType()) return true; break;
183     case lltok::GlobalID:   if (ParseUnnamedGlobal()) return true; break;
184     case lltok::GlobalVar:  if (ParseNamedGlobal()) return true; break;
185     case lltok::ComdatVar:  if (parseComdat()) return true; break;
186     case lltok::exclaim:    if (ParseStandaloneMetadata()) return true; break;
187     case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
188
189     // The Global variable production with no name can have many different
190     // optional leading prefixes, the production is:
191     // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
192     //               OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
193     //               ('constant'|'global') ...
194     case lltok::kw_private:             // OptionalLinkage
195     case lltok::kw_internal:            // OptionalLinkage
196     case lltok::kw_weak:                // OptionalLinkage
197     case lltok::kw_weak_odr:            // OptionalLinkage
198     case lltok::kw_linkonce:            // OptionalLinkage
199     case lltok::kw_linkonce_odr:        // OptionalLinkage
200     case lltok::kw_appending:           // OptionalLinkage
201     case lltok::kw_common:              // OptionalLinkage
202     case lltok::kw_extern_weak:         // OptionalLinkage
203     case lltok::kw_external:            // OptionalLinkage
204     case lltok::kw_default:             // OptionalVisibility
205     case lltok::kw_hidden:              // OptionalVisibility
206     case lltok::kw_protected:           // OptionalVisibility
207     case lltok::kw_dllimport:           // OptionalDLLStorageClass
208     case lltok::kw_dllexport:           // OptionalDLLStorageClass
209     case lltok::kw_thread_local:        // OptionalThreadLocal
210     case lltok::kw_addrspace:           // OptionalAddrSpace
211     case lltok::kw_constant:            // GlobalType
212     case lltok::kw_global: {            // GlobalType
213       unsigned Linkage, Visibility, DLLStorageClass;
214       bool UnnamedAddr;
215       GlobalVariable::ThreadLocalMode TLM;
216       bool HasLinkage;
217       if (ParseOptionalLinkage(Linkage, HasLinkage) ||
218           ParseOptionalVisibility(Visibility) ||
219           ParseOptionalDLLStorageClass(DLLStorageClass) ||
220           ParseOptionalThreadLocal(TLM) ||
221           parseOptionalUnnamedAddr(UnnamedAddr) ||
222           ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
223                       DLLStorageClass, TLM, UnnamedAddr))
224         return true;
225       break;
226     }
227
228     case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
229     case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
230     case lltok::kw_uselistorder_bb:
231                                  if (ParseUseListOrderBB()) return true; break;
232     }
233   }
234 }
235
236
237 /// toplevelentity
238 ///   ::= 'module' 'asm' STRINGCONSTANT
239 bool LLParser::ParseModuleAsm() {
240   assert(Lex.getKind() == lltok::kw_module);
241   Lex.Lex();
242
243   std::string AsmStr;
244   if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
245       ParseStringConstant(AsmStr)) return true;
246
247   M->appendModuleInlineAsm(AsmStr);
248   return false;
249 }
250
251 /// toplevelentity
252 ///   ::= 'target' 'triple' '=' STRINGCONSTANT
253 ///   ::= 'target' 'datalayout' '=' STRINGCONSTANT
254 bool LLParser::ParseTargetDefinition() {
255   assert(Lex.getKind() == lltok::kw_target);
256   std::string Str;
257   switch (Lex.Lex()) {
258   default: return TokError("unknown target property");
259   case lltok::kw_triple:
260     Lex.Lex();
261     if (ParseToken(lltok::equal, "expected '=' after target triple") ||
262         ParseStringConstant(Str))
263       return true;
264     M->setTargetTriple(Str);
265     return false;
266   case lltok::kw_datalayout:
267     Lex.Lex();
268     if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
269         ParseStringConstant(Str))
270       return true;
271     M->setDataLayout(Str);
272     return false;
273   }
274 }
275
276 /// toplevelentity
277 ///   ::= 'deplibs' '=' '[' ']'
278 ///   ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
279 /// FIXME: Remove in 4.0. Currently parse, but ignore.
280 bool LLParser::ParseDepLibs() {
281   assert(Lex.getKind() == lltok::kw_deplibs);
282   Lex.Lex();
283   if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
284       ParseToken(lltok::lsquare, "expected '=' after deplibs"))
285     return true;
286
287   if (EatIfPresent(lltok::rsquare))
288     return false;
289
290   do {
291     std::string Str;
292     if (ParseStringConstant(Str)) return true;
293   } while (EatIfPresent(lltok::comma));
294
295   return ParseToken(lltok::rsquare, "expected ']' at end of list");
296 }
297
298 /// ParseUnnamedType:
299 ///   ::= LocalVarID '=' 'type' type
300 bool LLParser::ParseUnnamedType() {
301   LocTy TypeLoc = Lex.getLoc();
302   unsigned TypeID = Lex.getUIntVal();
303   Lex.Lex(); // eat LocalVarID;
304
305   if (ParseToken(lltok::equal, "expected '=' after name") ||
306       ParseToken(lltok::kw_type, "expected 'type' after '='"))
307     return true;
308
309   Type *Result = nullptr;
310   if (ParseStructDefinition(TypeLoc, "",
311                             NumberedTypes[TypeID], Result)) return true;
312
313   if (!isa<StructType>(Result)) {
314     std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
315     if (Entry.first)
316       return Error(TypeLoc, "non-struct types may not be recursive");
317     Entry.first = Result;
318     Entry.second = SMLoc();
319   }
320
321   return false;
322 }
323
324
325 /// toplevelentity
326 ///   ::= LocalVar '=' 'type' type
327 bool LLParser::ParseNamedType() {
328   std::string Name = Lex.getStrVal();
329   LocTy NameLoc = Lex.getLoc();
330   Lex.Lex();  // eat LocalVar.
331
332   if (ParseToken(lltok::equal, "expected '=' after name") ||
333       ParseToken(lltok::kw_type, "expected 'type' after name"))
334     return true;
335
336   Type *Result = nullptr;
337   if (ParseStructDefinition(NameLoc, Name,
338                             NamedTypes[Name], Result)) return true;
339
340   if (!isa<StructType>(Result)) {
341     std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
342     if (Entry.first)
343       return Error(NameLoc, "non-struct types may not be recursive");
344     Entry.first = Result;
345     Entry.second = SMLoc();
346   }
347
348   return false;
349 }
350
351
352 /// toplevelentity
353 ///   ::= 'declare' FunctionHeader
354 bool LLParser::ParseDeclare() {
355   assert(Lex.getKind() == lltok::kw_declare);
356   Lex.Lex();
357
358   Function *F;
359   return ParseFunctionHeader(F, false);
360 }
361
362 /// toplevelentity
363 ///   ::= 'define' FunctionHeader '{' ...
364 bool LLParser::ParseDefine() {
365   assert(Lex.getKind() == lltok::kw_define);
366   Lex.Lex();
367
368   Function *F;
369   return ParseFunctionHeader(F, true) ||
370          ParseFunctionBody(*F);
371 }
372
373 /// ParseGlobalType
374 ///   ::= 'constant'
375 ///   ::= 'global'
376 bool LLParser::ParseGlobalType(bool &IsConstant) {
377   if (Lex.getKind() == lltok::kw_constant)
378     IsConstant = true;
379   else if (Lex.getKind() == lltok::kw_global)
380     IsConstant = false;
381   else {
382     IsConstant = false;
383     return TokError("expected 'global' or 'constant'");
384   }
385   Lex.Lex();
386   return false;
387 }
388
389 /// ParseUnnamedGlobal:
390 ///   OptionalVisibility ALIAS ...
391 ///   OptionalLinkage OptionalVisibility OptionalDLLStorageClass
392 ///                                                     ...   -> global variable
393 ///   GlobalID '=' OptionalVisibility ALIAS ...
394 ///   GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
395 ///                                                     ...   -> global variable
396 bool LLParser::ParseUnnamedGlobal() {
397   unsigned VarID = NumberedVals.size();
398   std::string Name;
399   LocTy NameLoc = Lex.getLoc();
400
401   // Handle the GlobalID form.
402   if (Lex.getKind() == lltok::GlobalID) {
403     if (Lex.getUIntVal() != VarID)
404       return Error(Lex.getLoc(), "variable expected to be numbered '%" +
405                    Twine(VarID) + "'");
406     Lex.Lex(); // eat GlobalID;
407
408     if (ParseToken(lltok::equal, "expected '=' after name"))
409       return true;
410   }
411
412   bool HasLinkage;
413   unsigned Linkage, Visibility, DLLStorageClass;
414   GlobalVariable::ThreadLocalMode TLM;
415   bool UnnamedAddr;
416   if (ParseOptionalLinkage(Linkage, HasLinkage) ||
417       ParseOptionalVisibility(Visibility) ||
418       ParseOptionalDLLStorageClass(DLLStorageClass) ||
419       ParseOptionalThreadLocal(TLM) ||
420       parseOptionalUnnamedAddr(UnnamedAddr))
421     return true;
422
423   if (Lex.getKind() != lltok::kw_alias)
424     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
425                        DLLStorageClass, TLM, UnnamedAddr);
426   return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
427                     UnnamedAddr);
428 }
429
430 /// ParseNamedGlobal:
431 ///   GlobalVar '=' OptionalVisibility ALIAS ...
432 ///   GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
433 ///                                                     ...   -> global variable
434 bool LLParser::ParseNamedGlobal() {
435   assert(Lex.getKind() == lltok::GlobalVar);
436   LocTy NameLoc = Lex.getLoc();
437   std::string Name = Lex.getStrVal();
438   Lex.Lex();
439
440   bool HasLinkage;
441   unsigned Linkage, Visibility, DLLStorageClass;
442   GlobalVariable::ThreadLocalMode TLM;
443   bool UnnamedAddr;
444   if (ParseToken(lltok::equal, "expected '=' in global variable") ||
445       ParseOptionalLinkage(Linkage, HasLinkage) ||
446       ParseOptionalVisibility(Visibility) ||
447       ParseOptionalDLLStorageClass(DLLStorageClass) ||
448       ParseOptionalThreadLocal(TLM) ||
449       parseOptionalUnnamedAddr(UnnamedAddr))
450     return true;
451
452   if (Lex.getKind() != lltok::kw_alias)
453     return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
454                        DLLStorageClass, TLM, UnnamedAddr);
455
456   return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
457                     UnnamedAddr);
458 }
459
460 bool LLParser::parseComdat() {
461   assert(Lex.getKind() == lltok::ComdatVar);
462   std::string Name = Lex.getStrVal();
463   LocTy NameLoc = Lex.getLoc();
464   Lex.Lex();
465
466   if (ParseToken(lltok::equal, "expected '=' here"))
467     return true;
468
469   if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
470     return TokError("expected comdat type");
471
472   Comdat::SelectionKind SK;
473   switch (Lex.getKind()) {
474   default:
475     return TokError("unknown selection kind");
476   case lltok::kw_any:
477     SK = Comdat::Any;
478     break;
479   case lltok::kw_exactmatch:
480     SK = Comdat::ExactMatch;
481     break;
482   case lltok::kw_largest:
483     SK = Comdat::Largest;
484     break;
485   case lltok::kw_noduplicates:
486     SK = Comdat::NoDuplicates;
487     break;
488   case lltok::kw_samesize:
489     SK = Comdat::SameSize;
490     break;
491   }
492   Lex.Lex();
493
494   // See if the comdat was forward referenced, if so, use the comdat.
495   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
496   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
497   if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
498     return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
499
500   Comdat *C;
501   if (I != ComdatSymTab.end())
502     C = &I->second;
503   else
504     C = M->getOrInsertComdat(Name);
505   C->setSelectionKind(SK);
506
507   return false;
508 }
509
510 // MDString:
511 //   ::= '!' STRINGCONSTANT
512 bool LLParser::ParseMDString(MDString *&Result) {
513   std::string Str;
514   if (ParseStringConstant(Str)) return true;
515   llvm::UpgradeMDStringConstant(Str);
516   Result = MDString::get(Context, Str);
517   return false;
518 }
519
520 // MDNode:
521 //   ::= '!' MDNodeNumber
522 bool LLParser::ParseMDNodeID(MDNode *&Result) {
523   // !{ ..., !42, ... }
524   unsigned MID = 0;
525   if (ParseUInt32(MID))
526     return true;
527
528   // If not a forward reference, just return it now.
529   if (NumberedMetadata.count(MID)) {
530     Result = NumberedMetadata[MID];
531     return false;
532   }
533
534   // Otherwise, create MDNode forward reference.
535   auto &FwdRef = ForwardRefMDNodes[MID];
536   FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
537
538   Result = FwdRef.first.get();
539   NumberedMetadata[MID].reset(Result);
540   return false;
541 }
542
543 /// ParseNamedMetadata:
544 ///   !foo = !{ !1, !2 }
545 bool LLParser::ParseNamedMetadata() {
546   assert(Lex.getKind() == lltok::MetadataVar);
547   std::string Name = Lex.getStrVal();
548   Lex.Lex();
549
550   if (ParseToken(lltok::equal, "expected '=' here") ||
551       ParseToken(lltok::exclaim, "Expected '!' here") ||
552       ParseToken(lltok::lbrace, "Expected '{' here"))
553     return true;
554
555   NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
556   if (Lex.getKind() != lltok::rbrace)
557     do {
558       if (ParseToken(lltok::exclaim, "Expected '!' here"))
559         return true;
560
561       MDNode *N = nullptr;
562       if (ParseMDNodeID(N)) return true;
563       NMD->addOperand(N);
564     } while (EatIfPresent(lltok::comma));
565
566   if (ParseToken(lltok::rbrace, "expected end of metadata node"))
567     return true;
568
569   return false;
570 }
571
572 /// ParseStandaloneMetadata:
573 ///   !42 = !{...}
574 bool LLParser::ParseStandaloneMetadata() {
575   assert(Lex.getKind() == lltok::exclaim);
576   Lex.Lex();
577   unsigned MetadataID = 0;
578
579   MDNode *Init;
580   if (ParseUInt32(MetadataID) ||
581       ParseToken(lltok::equal, "expected '=' here"))
582     return true;
583
584   // Detect common error, from old metadata syntax.
585   if (Lex.getKind() == lltok::Type)
586     return TokError("unexpected type in metadata definition");
587
588   bool IsDistinct = EatIfPresent(lltok::kw_distinct);
589   if (Lex.getKind() == lltok::MetadataVar) {
590     if (ParseSpecializedMDNode(Init, IsDistinct))
591       return true;
592   } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
593              ParseMDTuple(Init, IsDistinct))
594     return true;
595
596   // See if this was forward referenced, if so, handle it.
597   auto FI = ForwardRefMDNodes.find(MetadataID);
598   if (FI != ForwardRefMDNodes.end()) {
599     FI->second.first->replaceAllUsesWith(Init);
600     ForwardRefMDNodes.erase(FI);
601
602     assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
603   } else {
604     if (NumberedMetadata.count(MetadataID))
605       return TokError("Metadata id is already used");
606     NumberedMetadata[MetadataID].reset(Init);
607   }
608
609   return false;
610 }
611
612 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
613   return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
614          (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
615 }
616
617 /// ParseAlias:
618 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility
619 ///                     OptionalDLLStorageClass OptionalThreadLocal
620 ///                     OptionalUnNammedAddr 'alias' Aliasee
621 ///
622 /// Aliasee
623 ///   ::= TypeAndValue
624 ///
625 /// Everything through OptionalUnNammedAddr has already been parsed.
626 ///
627 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
628                           unsigned Visibility, unsigned DLLStorageClass,
629                           GlobalVariable::ThreadLocalMode TLM,
630                           bool UnnamedAddr) {
631   assert(Lex.getKind() == lltok::kw_alias);
632   Lex.Lex();
633
634   GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
635
636   if(!GlobalAlias::isValidLinkage(Linkage))
637     return Error(NameLoc, "invalid linkage type for alias");
638
639   if (!isValidVisibilityForLinkage(Visibility, L))
640     return Error(NameLoc,
641                  "symbol with local linkage must have default visibility");
642
643   Constant *Aliasee;
644   LocTy AliaseeLoc = Lex.getLoc();
645   if (Lex.getKind() != lltok::kw_bitcast &&
646       Lex.getKind() != lltok::kw_getelementptr &&
647       Lex.getKind() != lltok::kw_addrspacecast &&
648       Lex.getKind() != lltok::kw_inttoptr) {
649     if (ParseGlobalTypeAndValue(Aliasee))
650       return true;
651   } else {
652     // The bitcast dest type is not present, it is implied by the dest type.
653     ValID ID;
654     if (ParseValID(ID))
655       return true;
656     if (ID.Kind != ValID::t_Constant)
657       return Error(AliaseeLoc, "invalid aliasee");
658     Aliasee = ID.ConstantVal;
659   }
660
661   Type *AliaseeType = Aliasee->getType();
662   auto *PTy = dyn_cast<PointerType>(AliaseeType);
663   if (!PTy)
664     return Error(AliaseeLoc, "An alias must have pointer type");
665   Type *Ty = PTy->getElementType();
666   unsigned AddrSpace = PTy->getAddressSpace();
667
668   // Okay, create the alias but do not insert it into the module yet.
669   std::unique_ptr<GlobalAlias> GA(
670       GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
671                           Name, Aliasee, /*Parent*/ nullptr));
672   GA->setThreadLocalMode(TLM);
673   GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
674   GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
675   GA->setUnnamedAddr(UnnamedAddr);
676
677   // See if this value already exists in the symbol table.  If so, it is either
678   // a redefinition or a definition of a forward reference.
679   if (GlobalValue *Val = M->getNamedValue(Name)) {
680     // See if this was a redefinition.  If so, there is no entry in
681     // ForwardRefVals.
682     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
683       I = ForwardRefVals.find(Name);
684     if (I == ForwardRefVals.end())
685       return Error(NameLoc, "redefinition of global named '@" + Name + "'");
686
687     // Otherwise, this was a definition of forward ref.  Verify that types
688     // agree.
689     if (Val->getType() != GA->getType())
690       return Error(NameLoc,
691               "forward reference and definition of alias have different types");
692
693     // If they agree, just RAUW the old value with the alias and remove the
694     // forward ref info.
695     Val->replaceAllUsesWith(GA.get());
696     Val->eraseFromParent();
697     ForwardRefVals.erase(I);
698   }
699
700   // Insert into the module, we know its name won't collide now.
701   M->getAliasList().push_back(GA.get());
702   assert(GA->getName() == Name && "Should not be a name conflict!");
703
704   // The module owns this now
705   GA.release();
706
707   return false;
708 }
709
710 /// ParseGlobal
711 ///   ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
712 ///       OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
713 ///       OptionalExternallyInitialized GlobalType Type Const
714 ///   ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
715 ///       OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
716 ///       OptionalExternallyInitialized GlobalType Type Const
717 ///
718 /// Everything up to and including OptionalUnNammedAddr has been parsed
719 /// already.
720 ///
721 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
722                            unsigned Linkage, bool HasLinkage,
723                            unsigned Visibility, unsigned DLLStorageClass,
724                            GlobalVariable::ThreadLocalMode TLM,
725                            bool UnnamedAddr) {
726   if (!isValidVisibilityForLinkage(Visibility, Linkage))
727     return Error(NameLoc,
728                  "symbol with local linkage must have default visibility");
729
730   unsigned AddrSpace;
731   bool IsConstant, IsExternallyInitialized;
732   LocTy IsExternallyInitializedLoc;
733   LocTy TyLoc;
734
735   Type *Ty = nullptr;
736   if (ParseOptionalAddrSpace(AddrSpace) ||
737       ParseOptionalToken(lltok::kw_externally_initialized,
738                          IsExternallyInitialized,
739                          &IsExternallyInitializedLoc) ||
740       ParseGlobalType(IsConstant) ||
741       ParseType(Ty, TyLoc))
742     return true;
743
744   // If the linkage is specified and is external, then no initializer is
745   // present.
746   Constant *Init = nullptr;
747   if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
748                       Linkage != GlobalValue::ExternalLinkage)) {
749     if (ParseGlobalValue(Ty, Init))
750       return true;
751   }
752
753   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
754     return Error(TyLoc, "invalid type for global variable");
755
756   GlobalValue *GVal = nullptr;
757
758   // See if the global was forward referenced, if so, use the global.
759   if (!Name.empty()) {
760     GVal = M->getNamedValue(Name);
761     if (GVal) {
762       if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
763         return Error(NameLoc, "redefinition of global '@" + Name + "'");
764     }
765   } else {
766     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
767       I = ForwardRefValIDs.find(NumberedVals.size());
768     if (I != ForwardRefValIDs.end()) {
769       GVal = I->second.first;
770       ForwardRefValIDs.erase(I);
771     }
772   }
773
774   GlobalVariable *GV;
775   if (!GVal) {
776     GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
777                             Name, nullptr, GlobalVariable::NotThreadLocal,
778                             AddrSpace);
779   } else {
780     if (GVal->getType()->getElementType() != Ty)
781       return Error(TyLoc,
782             "forward reference and definition of global have different types");
783
784     GV = cast<GlobalVariable>(GVal);
785
786     // Move the forward-reference to the correct spot in the module.
787     M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
788   }
789
790   if (Name.empty())
791     NumberedVals.push_back(GV);
792
793   // Set the parsed properties on the global.
794   if (Init)
795     GV->setInitializer(Init);
796   GV->setConstant(IsConstant);
797   GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
798   GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
799   GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
800   GV->setExternallyInitialized(IsExternallyInitialized);
801   GV->setThreadLocalMode(TLM);
802   GV->setUnnamedAddr(UnnamedAddr);
803
804   // Parse attributes on the global.
805   while (Lex.getKind() == lltok::comma) {
806     Lex.Lex();
807
808     if (Lex.getKind() == lltok::kw_section) {
809       Lex.Lex();
810       GV->setSection(Lex.getStrVal());
811       if (ParseToken(lltok::StringConstant, "expected global section string"))
812         return true;
813     } else if (Lex.getKind() == lltok::kw_align) {
814       unsigned Alignment;
815       if (ParseOptionalAlignment(Alignment)) return true;
816       GV->setAlignment(Alignment);
817     } else {
818       Comdat *C;
819       if (parseOptionalComdat(Name, C))
820         return true;
821       if (C)
822         GV->setComdat(C);
823       else
824         return TokError("unknown global variable property!");
825     }
826   }
827
828   return false;
829 }
830
831 /// ParseUnnamedAttrGrp
832 ///   ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
833 bool LLParser::ParseUnnamedAttrGrp() {
834   assert(Lex.getKind() == lltok::kw_attributes);
835   LocTy AttrGrpLoc = Lex.getLoc();
836   Lex.Lex();
837
838   if (Lex.getKind() != lltok::AttrGrpID)
839     return TokError("expected attribute group id");
840
841   unsigned VarID = Lex.getUIntVal();
842   std::vector<unsigned> unused;
843   LocTy BuiltinLoc;
844   Lex.Lex();
845
846   if (ParseToken(lltok::equal, "expected '=' here") ||
847       ParseToken(lltok::lbrace, "expected '{' here") ||
848       ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
849                                  BuiltinLoc) ||
850       ParseToken(lltok::rbrace, "expected end of attribute group"))
851     return true;
852
853   if (!NumberedAttrBuilders[VarID].hasAttributes())
854     return Error(AttrGrpLoc, "attribute group has no attributes");
855
856   return false;
857 }
858
859 /// ParseFnAttributeValuePairs
860 ///   ::= <attr> | <attr> '=' <value>
861 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
862                                           std::vector<unsigned> &FwdRefAttrGrps,
863                                           bool inAttrGrp, LocTy &BuiltinLoc) {
864   bool HaveError = false;
865
866   B.clear();
867
868   while (true) {
869     lltok::Kind Token = Lex.getKind();
870     if (Token == lltok::kw_builtin)
871       BuiltinLoc = Lex.getLoc();
872     switch (Token) {
873     default:
874       if (!inAttrGrp) return HaveError;
875       return Error(Lex.getLoc(), "unterminated attribute group");
876     case lltok::rbrace:
877       // Finished.
878       return false;
879
880     case lltok::AttrGrpID: {
881       // Allow a function to reference an attribute group:
882       //
883       //   define void @foo() #1 { ... }
884       if (inAttrGrp)
885         HaveError |=
886           Error(Lex.getLoc(),
887               "cannot have an attribute group reference in an attribute group");
888
889       unsigned AttrGrpNum = Lex.getUIntVal();
890       if (inAttrGrp) break;
891
892       // Save the reference to the attribute group. We'll fill it in later.
893       FwdRefAttrGrps.push_back(AttrGrpNum);
894       break;
895     }
896     // Target-dependent attributes:
897     case lltok::StringConstant: {
898       std::string Attr = Lex.getStrVal();
899       Lex.Lex();
900       std::string Val;
901       if (EatIfPresent(lltok::equal) &&
902           ParseStringConstant(Val))
903         return true;
904
905       B.addAttribute(Attr, Val);
906       continue;
907     }
908
909     // Target-independent attributes:
910     case lltok::kw_align: {
911       // As a hack, we allow function alignment to be initially parsed as an
912       // attribute on a function declaration/definition or added to an attribute
913       // group and later moved to the alignment field.
914       unsigned Alignment;
915       if (inAttrGrp) {
916         Lex.Lex();
917         if (ParseToken(lltok::equal, "expected '=' here") ||
918             ParseUInt32(Alignment))
919           return true;
920       } else {
921         if (ParseOptionalAlignment(Alignment))
922           return true;
923       }
924       B.addAlignmentAttr(Alignment);
925       continue;
926     }
927     case lltok::kw_alignstack: {
928       unsigned Alignment;
929       if (inAttrGrp) {
930         Lex.Lex();
931         if (ParseToken(lltok::equal, "expected '=' here") ||
932             ParseUInt32(Alignment))
933           return true;
934       } else {
935         if (ParseOptionalStackAlignment(Alignment))
936           return true;
937       }
938       B.addStackAlignmentAttr(Alignment);
939       continue;
940     }
941     case lltok::kw_alwaysinline:      B.addAttribute(Attribute::AlwaysInline); break;
942     case lltok::kw_builtin:           B.addAttribute(Attribute::Builtin); break;
943     case lltok::kw_cold:              B.addAttribute(Attribute::Cold); break;
944     case lltok::kw_inlinehint:        B.addAttribute(Attribute::InlineHint); break;
945     case lltok::kw_jumptable:         B.addAttribute(Attribute::JumpTable); break;
946     case lltok::kw_minsize:           B.addAttribute(Attribute::MinSize); break;
947     case lltok::kw_naked:             B.addAttribute(Attribute::Naked); break;
948     case lltok::kw_nobuiltin:         B.addAttribute(Attribute::NoBuiltin); break;
949     case lltok::kw_noduplicate:       B.addAttribute(Attribute::NoDuplicate); break;
950     case lltok::kw_noimplicitfloat:   B.addAttribute(Attribute::NoImplicitFloat); break;
951     case lltok::kw_noinline:          B.addAttribute(Attribute::NoInline); break;
952     case lltok::kw_nonlazybind:       B.addAttribute(Attribute::NonLazyBind); break;
953     case lltok::kw_noredzone:         B.addAttribute(Attribute::NoRedZone); break;
954     case lltok::kw_noreturn:          B.addAttribute(Attribute::NoReturn); break;
955     case lltok::kw_nounwind:          B.addAttribute(Attribute::NoUnwind); break;
956     case lltok::kw_optnone:           B.addAttribute(Attribute::OptimizeNone); break;
957     case lltok::kw_optsize:           B.addAttribute(Attribute::OptimizeForSize); break;
958     case lltok::kw_readnone:          B.addAttribute(Attribute::ReadNone); break;
959     case lltok::kw_readonly:          B.addAttribute(Attribute::ReadOnly); break;
960     case lltok::kw_returns_twice:     B.addAttribute(Attribute::ReturnsTwice); break;
961     case lltok::kw_ssp:               B.addAttribute(Attribute::StackProtect); break;
962     case lltok::kw_sspreq:            B.addAttribute(Attribute::StackProtectReq); break;
963     case lltok::kw_sspstrong:         B.addAttribute(Attribute::StackProtectStrong); break;
964     case lltok::kw_sanitize_address:  B.addAttribute(Attribute::SanitizeAddress); break;
965     case lltok::kw_sanitize_thread:   B.addAttribute(Attribute::SanitizeThread); break;
966     case lltok::kw_sanitize_memory:   B.addAttribute(Attribute::SanitizeMemory); break;
967     case lltok::kw_uwtable:           B.addAttribute(Attribute::UWTable); break;
968
969     // Error handling.
970     case lltok::kw_inreg:
971     case lltok::kw_signext:
972     case lltok::kw_zeroext:
973       HaveError |=
974         Error(Lex.getLoc(),
975               "invalid use of attribute on a function");
976       break;
977     case lltok::kw_byval:
978     case lltok::kw_dereferenceable:
979     case lltok::kw_dereferenceable_or_null:
980     case lltok::kw_inalloca:
981     case lltok::kw_nest:
982     case lltok::kw_noalias:
983     case lltok::kw_nocapture:
984     case lltok::kw_nonnull:
985     case lltok::kw_returned:
986     case lltok::kw_sret:
987       HaveError |=
988         Error(Lex.getLoc(),
989               "invalid use of parameter-only attribute on a function");
990       break;
991     }
992
993     Lex.Lex();
994   }
995 }
996
997 //===----------------------------------------------------------------------===//
998 // GlobalValue Reference/Resolution Routines.
999 //===----------------------------------------------------------------------===//
1000
1001 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1002 /// forward reference record if needed.  This can return null if the value
1003 /// exists but does not have the right type.
1004 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1005                                     LocTy Loc) {
1006   PointerType *PTy = dyn_cast<PointerType>(Ty);
1007   if (!PTy) {
1008     Error(Loc, "global variable reference must have pointer type");
1009     return nullptr;
1010   }
1011
1012   // Look this name up in the normal function symbol table.
1013   GlobalValue *Val =
1014     cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1015
1016   // If this is a forward reference for the value, see if we already created a
1017   // forward ref record.
1018   if (!Val) {
1019     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1020       I = ForwardRefVals.find(Name);
1021     if (I != ForwardRefVals.end())
1022       Val = I->second.first;
1023   }
1024
1025   // If we have the value in the symbol table or fwd-ref table, return it.
1026   if (Val) {
1027     if (Val->getType() == Ty) return Val;
1028     Error(Loc, "'@" + Name + "' defined with type '" +
1029           getTypeString(Val->getType()) + "'");
1030     return nullptr;
1031   }
1032
1033   // Otherwise, create a new forward reference for this value and remember it.
1034   GlobalValue *FwdVal;
1035   if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1036     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1037   else
1038     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1039                                 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1040                                 nullptr, GlobalVariable::NotThreadLocal,
1041                                 PTy->getAddressSpace());
1042
1043   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1044   return FwdVal;
1045 }
1046
1047 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1048   PointerType *PTy = dyn_cast<PointerType>(Ty);
1049   if (!PTy) {
1050     Error(Loc, "global variable reference must have pointer type");
1051     return nullptr;
1052   }
1053
1054   GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1055
1056   // If this is a forward reference for the value, see if we already created a
1057   // forward ref record.
1058   if (!Val) {
1059     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1060       I = ForwardRefValIDs.find(ID);
1061     if (I != ForwardRefValIDs.end())
1062       Val = I->second.first;
1063   }
1064
1065   // If we have the value in the symbol table or fwd-ref table, return it.
1066   if (Val) {
1067     if (Val->getType() == Ty) return Val;
1068     Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1069           getTypeString(Val->getType()) + "'");
1070     return nullptr;
1071   }
1072
1073   // Otherwise, create a new forward reference for this value and remember it.
1074   GlobalValue *FwdVal;
1075   if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1076     FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1077   else
1078     FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1079                                 GlobalValue::ExternalWeakLinkage, nullptr, "");
1080
1081   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1082   return FwdVal;
1083 }
1084
1085
1086 //===----------------------------------------------------------------------===//
1087 // Comdat Reference/Resolution Routines.
1088 //===----------------------------------------------------------------------===//
1089
1090 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1091   // Look this name up in the comdat symbol table.
1092   Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1093   Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1094   if (I != ComdatSymTab.end())
1095     return &I->second;
1096
1097   // Otherwise, create a new forward reference for this value and remember it.
1098   Comdat *C = M->getOrInsertComdat(Name);
1099   ForwardRefComdats[Name] = Loc;
1100   return C;
1101 }
1102
1103
1104 //===----------------------------------------------------------------------===//
1105 // Helper Routines.
1106 //===----------------------------------------------------------------------===//
1107
1108 /// ParseToken - If the current token has the specified kind, eat it and return
1109 /// success.  Otherwise, emit the specified error and return failure.
1110 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1111   if (Lex.getKind() != T)
1112     return TokError(ErrMsg);
1113   Lex.Lex();
1114   return false;
1115 }
1116
1117 /// ParseStringConstant
1118 ///   ::= StringConstant
1119 bool LLParser::ParseStringConstant(std::string &Result) {
1120   if (Lex.getKind() != lltok::StringConstant)
1121     return TokError("expected string constant");
1122   Result = Lex.getStrVal();
1123   Lex.Lex();
1124   return false;
1125 }
1126
1127 /// ParseUInt32
1128 ///   ::= uint32
1129 bool LLParser::ParseUInt32(unsigned &Val) {
1130   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1131     return TokError("expected integer");
1132   uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1133   if (Val64 != unsigned(Val64))
1134     return TokError("expected 32-bit integer (too large)");
1135   Val = Val64;
1136   Lex.Lex();
1137   return false;
1138 }
1139
1140 /// ParseUInt64
1141 ///   ::= uint64
1142 bool LLParser::ParseUInt64(uint64_t &Val) {
1143   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1144     return TokError("expected integer");
1145   Val = Lex.getAPSIntVal().getLimitedValue();
1146   Lex.Lex();
1147   return false;
1148 }
1149
1150 /// ParseTLSModel
1151 ///   := 'localdynamic'
1152 ///   := 'initialexec'
1153 ///   := 'localexec'
1154 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1155   switch (Lex.getKind()) {
1156     default:
1157       return TokError("expected localdynamic, initialexec or localexec");
1158     case lltok::kw_localdynamic:
1159       TLM = GlobalVariable::LocalDynamicTLSModel;
1160       break;
1161     case lltok::kw_initialexec:
1162       TLM = GlobalVariable::InitialExecTLSModel;
1163       break;
1164     case lltok::kw_localexec:
1165       TLM = GlobalVariable::LocalExecTLSModel;
1166       break;
1167   }
1168
1169   Lex.Lex();
1170   return false;
1171 }
1172
1173 /// ParseOptionalThreadLocal
1174 ///   := /*empty*/
1175 ///   := 'thread_local'
1176 ///   := 'thread_local' '(' tlsmodel ')'
1177 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1178   TLM = GlobalVariable::NotThreadLocal;
1179   if (!EatIfPresent(lltok::kw_thread_local))
1180     return false;
1181
1182   TLM = GlobalVariable::GeneralDynamicTLSModel;
1183   if (Lex.getKind() == lltok::lparen) {
1184     Lex.Lex();
1185     return ParseTLSModel(TLM) ||
1186       ParseToken(lltok::rparen, "expected ')' after thread local model");
1187   }
1188   return false;
1189 }
1190
1191 /// ParseOptionalAddrSpace
1192 ///   := /*empty*/
1193 ///   := 'addrspace' '(' uint32 ')'
1194 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1195   AddrSpace = 0;
1196   if (!EatIfPresent(lltok::kw_addrspace))
1197     return false;
1198   return ParseToken(lltok::lparen, "expected '(' in address space") ||
1199          ParseUInt32(AddrSpace) ||
1200          ParseToken(lltok::rparen, "expected ')' in address space");
1201 }
1202
1203 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1204 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1205   bool HaveError = false;
1206
1207   B.clear();
1208
1209   while (1) {
1210     lltok::Kind Token = Lex.getKind();
1211     switch (Token) {
1212     default:  // End of attributes.
1213       return HaveError;
1214     case lltok::kw_align: {
1215       unsigned Alignment;
1216       if (ParseOptionalAlignment(Alignment))
1217         return true;
1218       B.addAlignmentAttr(Alignment);
1219       continue;
1220     }
1221     case lltok::kw_byval:           B.addAttribute(Attribute::ByVal); break;
1222     case lltok::kw_dereferenceable: {
1223       uint64_t Bytes;
1224       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1225         return true;
1226       B.addDereferenceableAttr(Bytes);
1227       continue;
1228     }
1229     case lltok::kw_dereferenceable_or_null: {
1230       uint64_t Bytes;
1231       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1232         return true;
1233       B.addDereferenceableOrNullAttr(Bytes);
1234       continue;
1235     }
1236     case lltok::kw_inalloca:        B.addAttribute(Attribute::InAlloca); break;
1237     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1238     case lltok::kw_nest:            B.addAttribute(Attribute::Nest); break;
1239     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1240     case lltok::kw_nocapture:       B.addAttribute(Attribute::NoCapture); break;
1241     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1242     case lltok::kw_readnone:        B.addAttribute(Attribute::ReadNone); break;
1243     case lltok::kw_readonly:        B.addAttribute(Attribute::ReadOnly); break;
1244     case lltok::kw_returned:        B.addAttribute(Attribute::Returned); break;
1245     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1246     case lltok::kw_sret:            B.addAttribute(Attribute::StructRet); break;
1247     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1248
1249     case lltok::kw_alignstack:
1250     case lltok::kw_alwaysinline:
1251     case lltok::kw_builtin:
1252     case lltok::kw_inlinehint:
1253     case lltok::kw_jumptable:
1254     case lltok::kw_minsize:
1255     case lltok::kw_naked:
1256     case lltok::kw_nobuiltin:
1257     case lltok::kw_noduplicate:
1258     case lltok::kw_noimplicitfloat:
1259     case lltok::kw_noinline:
1260     case lltok::kw_nonlazybind:
1261     case lltok::kw_noredzone:
1262     case lltok::kw_noreturn:
1263     case lltok::kw_nounwind:
1264     case lltok::kw_optnone:
1265     case lltok::kw_optsize:
1266     case lltok::kw_returns_twice:
1267     case lltok::kw_sanitize_address:
1268     case lltok::kw_sanitize_memory:
1269     case lltok::kw_sanitize_thread:
1270     case lltok::kw_ssp:
1271     case lltok::kw_sspreq:
1272     case lltok::kw_sspstrong:
1273     case lltok::kw_uwtable:
1274       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1275       break;
1276     }
1277
1278     Lex.Lex();
1279   }
1280 }
1281
1282 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1283 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1284   bool HaveError = false;
1285
1286   B.clear();
1287
1288   while (1) {
1289     lltok::Kind Token = Lex.getKind();
1290     switch (Token) {
1291     default:  // End of attributes.
1292       return HaveError;
1293     case lltok::kw_dereferenceable: {
1294       uint64_t Bytes;
1295       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1296         return true;
1297       B.addDereferenceableAttr(Bytes);
1298       continue;
1299     }
1300     case lltok::kw_dereferenceable_or_null: {
1301       uint64_t Bytes;
1302       if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1303         return true;
1304       B.addDereferenceableOrNullAttr(Bytes);
1305       continue;
1306     }
1307     case lltok::kw_inreg:           B.addAttribute(Attribute::InReg); break;
1308     case lltok::kw_noalias:         B.addAttribute(Attribute::NoAlias); break;
1309     case lltok::kw_nonnull:         B.addAttribute(Attribute::NonNull); break;
1310     case lltok::kw_signext:         B.addAttribute(Attribute::SExt); break;
1311     case lltok::kw_zeroext:         B.addAttribute(Attribute::ZExt); break;
1312
1313     // Error handling.
1314     case lltok::kw_align:
1315     case lltok::kw_byval:
1316     case lltok::kw_inalloca:
1317     case lltok::kw_nest:
1318     case lltok::kw_nocapture:
1319     case lltok::kw_returned:
1320     case lltok::kw_sret:
1321       HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1322       break;
1323
1324     case lltok::kw_alignstack:
1325     case lltok::kw_alwaysinline:
1326     case lltok::kw_builtin:
1327     case lltok::kw_cold:
1328     case lltok::kw_inlinehint:
1329     case lltok::kw_jumptable:
1330     case lltok::kw_minsize:
1331     case lltok::kw_naked:
1332     case lltok::kw_nobuiltin:
1333     case lltok::kw_noduplicate:
1334     case lltok::kw_noimplicitfloat:
1335     case lltok::kw_noinline:
1336     case lltok::kw_nonlazybind:
1337     case lltok::kw_noredzone:
1338     case lltok::kw_noreturn:
1339     case lltok::kw_nounwind:
1340     case lltok::kw_optnone:
1341     case lltok::kw_optsize:
1342     case lltok::kw_returns_twice:
1343     case lltok::kw_sanitize_address:
1344     case lltok::kw_sanitize_memory:
1345     case lltok::kw_sanitize_thread:
1346     case lltok::kw_ssp:
1347     case lltok::kw_sspreq:
1348     case lltok::kw_sspstrong:
1349     case lltok::kw_uwtable:
1350       HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1351       break;
1352
1353     case lltok::kw_readnone:
1354     case lltok::kw_readonly:
1355       HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1356     }
1357
1358     Lex.Lex();
1359   }
1360 }
1361
1362 /// ParseOptionalLinkage
1363 ///   ::= /*empty*/
1364 ///   ::= 'private'
1365 ///   ::= 'internal'
1366 ///   ::= 'weak'
1367 ///   ::= 'weak_odr'
1368 ///   ::= 'linkonce'
1369 ///   ::= 'linkonce_odr'
1370 ///   ::= 'available_externally'
1371 ///   ::= 'appending'
1372 ///   ::= 'common'
1373 ///   ::= 'extern_weak'
1374 ///   ::= 'external'
1375 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1376   HasLinkage = false;
1377   switch (Lex.getKind()) {
1378   default:                       Res=GlobalValue::ExternalLinkage; return false;
1379   case lltok::kw_private:        Res = GlobalValue::PrivateLinkage;       break;
1380   case lltok::kw_internal:       Res = GlobalValue::InternalLinkage;      break;
1381   case lltok::kw_weak:           Res = GlobalValue::WeakAnyLinkage;       break;
1382   case lltok::kw_weak_odr:       Res = GlobalValue::WeakODRLinkage;       break;
1383   case lltok::kw_linkonce:       Res = GlobalValue::LinkOnceAnyLinkage;   break;
1384   case lltok::kw_linkonce_odr:   Res = GlobalValue::LinkOnceODRLinkage;   break;
1385   case lltok::kw_available_externally:
1386     Res = GlobalValue::AvailableExternallyLinkage;
1387     break;
1388   case lltok::kw_appending:      Res = GlobalValue::AppendingLinkage;     break;
1389   case lltok::kw_common:         Res = GlobalValue::CommonLinkage;        break;
1390   case lltok::kw_extern_weak:    Res = GlobalValue::ExternalWeakLinkage;  break;
1391   case lltok::kw_external:       Res = GlobalValue::ExternalLinkage;      break;
1392   }
1393   Lex.Lex();
1394   HasLinkage = true;
1395   return false;
1396 }
1397
1398 /// ParseOptionalVisibility
1399 ///   ::= /*empty*/
1400 ///   ::= 'default'
1401 ///   ::= 'hidden'
1402 ///   ::= 'protected'
1403 ///
1404 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1405   switch (Lex.getKind()) {
1406   default:                  Res = GlobalValue::DefaultVisibility; return false;
1407   case lltok::kw_default:   Res = GlobalValue::DefaultVisibility; break;
1408   case lltok::kw_hidden:    Res = GlobalValue::HiddenVisibility; break;
1409   case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1410   }
1411   Lex.Lex();
1412   return false;
1413 }
1414
1415 /// ParseOptionalDLLStorageClass
1416 ///   ::= /*empty*/
1417 ///   ::= 'dllimport'
1418 ///   ::= 'dllexport'
1419 ///
1420 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1421   switch (Lex.getKind()) {
1422   default:                  Res = GlobalValue::DefaultStorageClass; return false;
1423   case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1424   case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1425   }
1426   Lex.Lex();
1427   return false;
1428 }
1429
1430 /// ParseOptionalCallingConv
1431 ///   ::= /*empty*/
1432 ///   ::= 'ccc'
1433 ///   ::= 'fastcc'
1434 ///   ::= 'intel_ocl_bicc'
1435 ///   ::= 'coldcc'
1436 ///   ::= 'x86_stdcallcc'
1437 ///   ::= 'x86_fastcallcc'
1438 ///   ::= 'x86_thiscallcc'
1439 ///   ::= 'x86_vectorcallcc'
1440 ///   ::= 'arm_apcscc'
1441 ///   ::= 'arm_aapcscc'
1442 ///   ::= 'arm_aapcs_vfpcc'
1443 ///   ::= 'msp430_intrcc'
1444 ///   ::= 'ptx_kernel'
1445 ///   ::= 'ptx_device'
1446 ///   ::= 'spir_func'
1447 ///   ::= 'spir_kernel'
1448 ///   ::= 'x86_64_sysvcc'
1449 ///   ::= 'x86_64_win64cc'
1450 ///   ::= 'webkit_jscc'
1451 ///   ::= 'anyregcc'
1452 ///   ::= 'preserve_mostcc'
1453 ///   ::= 'preserve_allcc'
1454 ///   ::= 'ghccc'
1455 ///   ::= 'cc' UINT
1456 ///
1457 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1458   switch (Lex.getKind()) {
1459   default:                       CC = CallingConv::C; return false;
1460   case lltok::kw_ccc:            CC = CallingConv::C; break;
1461   case lltok::kw_fastcc:         CC = CallingConv::Fast; break;
1462   case lltok::kw_coldcc:         CC = CallingConv::Cold; break;
1463   case lltok::kw_x86_stdcallcc:  CC = CallingConv::X86_StdCall; break;
1464   case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1465   case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1466   case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1467   case lltok::kw_arm_apcscc:     CC = CallingConv::ARM_APCS; break;
1468   case lltok::kw_arm_aapcscc:    CC = CallingConv::ARM_AAPCS; break;
1469   case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1470   case lltok::kw_msp430_intrcc:  CC = CallingConv::MSP430_INTR; break;
1471   case lltok::kw_ptx_kernel:     CC = CallingConv::PTX_Kernel; break;
1472   case lltok::kw_ptx_device:     CC = CallingConv::PTX_Device; break;
1473   case lltok::kw_spir_kernel:    CC = CallingConv::SPIR_KERNEL; break;
1474   case lltok::kw_spir_func:      CC = CallingConv::SPIR_FUNC; break;
1475   case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1476   case lltok::kw_x86_64_sysvcc:  CC = CallingConv::X86_64_SysV; break;
1477   case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1478   case lltok::kw_webkit_jscc:    CC = CallingConv::WebKit_JS; break;
1479   case lltok::kw_anyregcc:       CC = CallingConv::AnyReg; break;
1480   case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1481   case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1482   case lltok::kw_ghccc:          CC = CallingConv::GHC; break;
1483   case lltok::kw_cc: {
1484       Lex.Lex();
1485       return ParseUInt32(CC);
1486     }
1487   }
1488
1489   Lex.Lex();
1490   return false;
1491 }
1492
1493 /// ParseMetadataAttachment
1494 ///   ::= !dbg !42
1495 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1496   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1497
1498   std::string Name = Lex.getStrVal();
1499   Kind = M->getMDKindID(Name);
1500   Lex.Lex();
1501
1502   return ParseMDNode(MD);
1503 }
1504
1505 /// ParseInstructionMetadata
1506 ///   ::= !dbg !42 (',' !dbg !57)*
1507 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1508   do {
1509     if (Lex.getKind() != lltok::MetadataVar)
1510       return TokError("expected metadata after comma");
1511
1512     unsigned MDK;
1513     MDNode *N;
1514     if (ParseMetadataAttachment(MDK, N))
1515       return true;
1516
1517     Inst.setMetadata(MDK, N);
1518     if (MDK == LLVMContext::MD_tbaa)
1519       InstsWithTBAATag.push_back(&Inst);
1520
1521     // If this is the end of the list, we're done.
1522   } while (EatIfPresent(lltok::comma));
1523   return false;
1524 }
1525
1526 /// ParseOptionalAlignment
1527 ///   ::= /* empty */
1528 ///   ::= 'align' 4
1529 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1530   Alignment = 0;
1531   if (!EatIfPresent(lltok::kw_align))
1532     return false;
1533   LocTy AlignLoc = Lex.getLoc();
1534   if (ParseUInt32(Alignment)) return true;
1535   if (!isPowerOf2_32(Alignment))
1536     return Error(AlignLoc, "alignment is not a power of two");
1537   if (Alignment > Value::MaximumAlignment)
1538     return Error(AlignLoc, "huge alignments are not supported yet");
1539   return false;
1540 }
1541
1542 /// ParseOptionalDerefAttrBytes
1543 ///   ::= /* empty */
1544 ///   ::= AttrKind '(' 4 ')'
1545 ///
1546 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1547 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1548                                            uint64_t &Bytes) {
1549   assert((AttrKind == lltok::kw_dereferenceable ||
1550           AttrKind == lltok::kw_dereferenceable_or_null) &&
1551          "contract!");
1552
1553   Bytes = 0;
1554   if (!EatIfPresent(AttrKind))
1555     return false;
1556   LocTy ParenLoc = Lex.getLoc();
1557   if (!EatIfPresent(lltok::lparen))
1558     return Error(ParenLoc, "expected '('");
1559   LocTy DerefLoc = Lex.getLoc();
1560   if (ParseUInt64(Bytes)) return true;
1561   ParenLoc = Lex.getLoc();
1562   if (!EatIfPresent(lltok::rparen))
1563     return Error(ParenLoc, "expected ')'");
1564   if (!Bytes)
1565     return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1566   return false;
1567 }
1568
1569 /// ParseOptionalCommaAlign
1570 ///   ::=
1571 ///   ::= ',' align 4
1572 ///
1573 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1574 /// end.
1575 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1576                                        bool &AteExtraComma) {
1577   AteExtraComma = false;
1578   while (EatIfPresent(lltok::comma)) {
1579     // Metadata at the end is an early exit.
1580     if (Lex.getKind() == lltok::MetadataVar) {
1581       AteExtraComma = true;
1582       return false;
1583     }
1584
1585     if (Lex.getKind() != lltok::kw_align)
1586       return Error(Lex.getLoc(), "expected metadata or 'align'");
1587
1588     if (ParseOptionalAlignment(Alignment)) return true;
1589   }
1590
1591   return false;
1592 }
1593
1594 /// ParseScopeAndOrdering
1595 ///   if isAtomic: ::= 'singlethread'? AtomicOrdering
1596 ///   else: ::=
1597 ///
1598 /// This sets Scope and Ordering to the parsed values.
1599 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1600                                      AtomicOrdering &Ordering) {
1601   if (!isAtomic)
1602     return false;
1603
1604   Scope = CrossThread;
1605   if (EatIfPresent(lltok::kw_singlethread))
1606     Scope = SingleThread;
1607
1608   return ParseOrdering(Ordering);
1609 }
1610
1611 /// ParseOrdering
1612 ///   ::= AtomicOrdering
1613 ///
1614 /// This sets Ordering to the parsed value.
1615 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1616   switch (Lex.getKind()) {
1617   default: return TokError("Expected ordering on atomic instruction");
1618   case lltok::kw_unordered: Ordering = Unordered; break;
1619   case lltok::kw_monotonic: Ordering = Monotonic; break;
1620   case lltok::kw_acquire: Ordering = Acquire; break;
1621   case lltok::kw_release: Ordering = Release; break;
1622   case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1623   case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1624   }
1625   Lex.Lex();
1626   return false;
1627 }
1628
1629 /// ParseOptionalStackAlignment
1630 ///   ::= /* empty */
1631 ///   ::= 'alignstack' '(' 4 ')'
1632 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1633   Alignment = 0;
1634   if (!EatIfPresent(lltok::kw_alignstack))
1635     return false;
1636   LocTy ParenLoc = Lex.getLoc();
1637   if (!EatIfPresent(lltok::lparen))
1638     return Error(ParenLoc, "expected '('");
1639   LocTy AlignLoc = Lex.getLoc();
1640   if (ParseUInt32(Alignment)) return true;
1641   ParenLoc = Lex.getLoc();
1642   if (!EatIfPresent(lltok::rparen))
1643     return Error(ParenLoc, "expected ')'");
1644   if (!isPowerOf2_32(Alignment))
1645     return Error(AlignLoc, "stack alignment is not a power of two");
1646   return false;
1647 }
1648
1649 /// ParseIndexList - This parses the index list for an insert/extractvalue
1650 /// instruction.  This sets AteExtraComma in the case where we eat an extra
1651 /// comma at the end of the line and find that it is followed by metadata.
1652 /// Clients that don't allow metadata can call the version of this function that
1653 /// only takes one argument.
1654 ///
1655 /// ParseIndexList
1656 ///    ::=  (',' uint32)+
1657 ///
1658 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1659                               bool &AteExtraComma) {
1660   AteExtraComma = false;
1661
1662   if (Lex.getKind() != lltok::comma)
1663     return TokError("expected ',' as start of index list");
1664
1665   while (EatIfPresent(lltok::comma)) {
1666     if (Lex.getKind() == lltok::MetadataVar) {
1667       if (Indices.empty()) return TokError("expected index");
1668       AteExtraComma = true;
1669       return false;
1670     }
1671     unsigned Idx = 0;
1672     if (ParseUInt32(Idx)) return true;
1673     Indices.push_back(Idx);
1674   }
1675
1676   return false;
1677 }
1678
1679 //===----------------------------------------------------------------------===//
1680 // Type Parsing.
1681 //===----------------------------------------------------------------------===//
1682
1683 /// ParseType - Parse a type.
1684 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1685   SMLoc TypeLoc = Lex.getLoc();
1686   switch (Lex.getKind()) {
1687   default:
1688     return TokError(Msg);
1689   case lltok::Type:
1690     // Type ::= 'float' | 'void' (etc)
1691     Result = Lex.getTyVal();
1692     Lex.Lex();
1693     break;
1694   case lltok::lbrace:
1695     // Type ::= StructType
1696     if (ParseAnonStructType(Result, false))
1697       return true;
1698     break;
1699   case lltok::lsquare:
1700     // Type ::= '[' ... ']'
1701     Lex.Lex(); // eat the lsquare.
1702     if (ParseArrayVectorType(Result, false))
1703       return true;
1704     break;
1705   case lltok::less: // Either vector or packed struct.
1706     // Type ::= '<' ... '>'
1707     Lex.Lex();
1708     if (Lex.getKind() == lltok::lbrace) {
1709       if (ParseAnonStructType(Result, true) ||
1710           ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1711         return true;
1712     } else if (ParseArrayVectorType(Result, true))
1713       return true;
1714     break;
1715   case lltok::LocalVar: {
1716     // Type ::= %foo
1717     std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1718
1719     // If the type hasn't been defined yet, create a forward definition and
1720     // remember where that forward def'n was seen (in case it never is defined).
1721     if (!Entry.first) {
1722       Entry.first = StructType::create(Context, Lex.getStrVal());
1723       Entry.second = Lex.getLoc();
1724     }
1725     Result = Entry.first;
1726     Lex.Lex();
1727     break;
1728   }
1729
1730   case lltok::LocalVarID: {
1731     // Type ::= %4
1732     std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1733
1734     // If the type hasn't been defined yet, create a forward definition and
1735     // remember where that forward def'n was seen (in case it never is defined).
1736     if (!Entry.first) {
1737       Entry.first = StructType::create(Context);
1738       Entry.second = Lex.getLoc();
1739     }
1740     Result = Entry.first;
1741     Lex.Lex();
1742     break;
1743   }
1744   }
1745
1746   // Parse the type suffixes.
1747   while (1) {
1748     switch (Lex.getKind()) {
1749     // End of type.
1750     default:
1751       if (!AllowVoid && Result->isVoidTy())
1752         return Error(TypeLoc, "void type only allowed for function results");
1753       return false;
1754
1755     // Type ::= Type '*'
1756     case lltok::star:
1757       if (Result->isLabelTy())
1758         return TokError("basic block pointers are invalid");
1759       if (Result->isVoidTy())
1760         return TokError("pointers to void are invalid - use i8* instead");
1761       if (!PointerType::isValidElementType(Result))
1762         return TokError("pointer to this type is invalid");
1763       Result = PointerType::getUnqual(Result);
1764       Lex.Lex();
1765       break;
1766
1767     // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1768     case lltok::kw_addrspace: {
1769       if (Result->isLabelTy())
1770         return TokError("basic block pointers are invalid");
1771       if (Result->isVoidTy())
1772         return TokError("pointers to void are invalid; use i8* instead");
1773       if (!PointerType::isValidElementType(Result))
1774         return TokError("pointer to this type is invalid");
1775       unsigned AddrSpace;
1776       if (ParseOptionalAddrSpace(AddrSpace) ||
1777           ParseToken(lltok::star, "expected '*' in address space"))
1778         return true;
1779
1780       Result = PointerType::get(Result, AddrSpace);
1781       break;
1782     }
1783
1784     /// Types '(' ArgTypeListI ')' OptFuncAttrs
1785     case lltok::lparen:
1786       if (ParseFunctionType(Result))
1787         return true;
1788       break;
1789     }
1790   }
1791 }
1792
1793 /// ParseParameterList
1794 ///    ::= '(' ')'
1795 ///    ::= '(' Arg (',' Arg)* ')'
1796 ///  Arg
1797 ///    ::= Type OptionalAttributes Value OptionalAttributes
1798 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1799                                   PerFunctionState &PFS, bool IsMustTailCall,
1800                                   bool InVarArgsFunc) {
1801   if (ParseToken(lltok::lparen, "expected '(' in call"))
1802     return true;
1803
1804   unsigned AttrIndex = 1;
1805   while (Lex.getKind() != lltok::rparen) {
1806     // If this isn't the first argument, we need a comma.
1807     if (!ArgList.empty() &&
1808         ParseToken(lltok::comma, "expected ',' in argument list"))
1809       return true;
1810
1811     // Parse an ellipsis if this is a musttail call in a variadic function.
1812     if (Lex.getKind() == lltok::dotdotdot) {
1813       const char *Msg = "unexpected ellipsis in argument list for ";
1814       if (!IsMustTailCall)
1815         return TokError(Twine(Msg) + "non-musttail call");
1816       if (!InVarArgsFunc)
1817         return TokError(Twine(Msg) + "musttail call in non-varargs function");
1818       Lex.Lex();  // Lex the '...', it is purely for readability.
1819       return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1820     }
1821
1822     // Parse the argument.
1823     LocTy ArgLoc;
1824     Type *ArgTy = nullptr;
1825     AttrBuilder ArgAttrs;
1826     Value *V;
1827     if (ParseType(ArgTy, ArgLoc))
1828       return true;
1829
1830     if (ArgTy->isMetadataTy()) {
1831       if (ParseMetadataAsValue(V, PFS))
1832         return true;
1833     } else {
1834       // Otherwise, handle normal operands.
1835       if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1836         return true;
1837     }
1838     ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1839                                                              AttrIndex++,
1840                                                              ArgAttrs)));
1841   }
1842
1843   if (IsMustTailCall && InVarArgsFunc)
1844     return TokError("expected '...' at end of argument list for musttail call "
1845                     "in varargs function");
1846
1847   Lex.Lex();  // Lex the ')'.
1848   return false;
1849 }
1850
1851
1852
1853 /// ParseArgumentList - Parse the argument list for a function type or function
1854 /// prototype.
1855 ///   ::= '(' ArgTypeListI ')'
1856 /// ArgTypeListI
1857 ///   ::= /*empty*/
1858 ///   ::= '...'
1859 ///   ::= ArgTypeList ',' '...'
1860 ///   ::= ArgType (',' ArgType)*
1861 ///
1862 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1863                                  bool &isVarArg){
1864   isVarArg = false;
1865   assert(Lex.getKind() == lltok::lparen);
1866   Lex.Lex(); // eat the (.
1867
1868   if (Lex.getKind() == lltok::rparen) {
1869     // empty
1870   } else if (Lex.getKind() == lltok::dotdotdot) {
1871     isVarArg = true;
1872     Lex.Lex();
1873   } else {
1874     LocTy TypeLoc = Lex.getLoc();
1875     Type *ArgTy = nullptr;
1876     AttrBuilder Attrs;
1877     std::string Name;
1878
1879     if (ParseType(ArgTy) ||
1880         ParseOptionalParamAttrs(Attrs)) return true;
1881
1882     if (ArgTy->isVoidTy())
1883       return Error(TypeLoc, "argument can not have void type");
1884
1885     if (Lex.getKind() == lltok::LocalVar) {
1886       Name = Lex.getStrVal();
1887       Lex.Lex();
1888     }
1889
1890     if (!FunctionType::isValidArgumentType(ArgTy))
1891       return Error(TypeLoc, "invalid type for function argument");
1892
1893     unsigned AttrIndex = 1;
1894     ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1895                               AttributeSet::get(ArgTy->getContext(),
1896                                                 AttrIndex++, Attrs), Name));
1897
1898     while (EatIfPresent(lltok::comma)) {
1899       // Handle ... at end of arg list.
1900       if (EatIfPresent(lltok::dotdotdot)) {
1901         isVarArg = true;
1902         break;
1903       }
1904
1905       // Otherwise must be an argument type.
1906       TypeLoc = Lex.getLoc();
1907       if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1908
1909       if (ArgTy->isVoidTy())
1910         return Error(TypeLoc, "argument can not have void type");
1911
1912       if (Lex.getKind() == lltok::LocalVar) {
1913         Name = Lex.getStrVal();
1914         Lex.Lex();
1915       } else {
1916         Name = "";
1917       }
1918
1919       if (!ArgTy->isFirstClassType())
1920         return Error(TypeLoc, "invalid type for function argument");
1921
1922       ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1923                                 AttributeSet::get(ArgTy->getContext(),
1924                                                   AttrIndex++, Attrs),
1925                                 Name));
1926     }
1927   }
1928
1929   return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1930 }
1931
1932 /// ParseFunctionType
1933 ///  ::= Type ArgumentList OptionalAttrs
1934 bool LLParser::ParseFunctionType(Type *&Result) {
1935   assert(Lex.getKind() == lltok::lparen);
1936
1937   if (!FunctionType::isValidReturnType(Result))
1938     return TokError("invalid function return type");
1939
1940   SmallVector<ArgInfo, 8> ArgList;
1941   bool isVarArg;
1942   if (ParseArgumentList(ArgList, isVarArg))
1943     return true;
1944
1945   // Reject names on the arguments lists.
1946   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1947     if (!ArgList[i].Name.empty())
1948       return Error(ArgList[i].Loc, "argument name invalid in function type");
1949     if (ArgList[i].Attrs.hasAttributes(i + 1))
1950       return Error(ArgList[i].Loc,
1951                    "argument attributes invalid in function type");
1952   }
1953
1954   SmallVector<Type*, 16> ArgListTy;
1955   for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1956     ArgListTy.push_back(ArgList[i].Ty);
1957
1958   Result = FunctionType::get(Result, ArgListTy, isVarArg);
1959   return false;
1960 }
1961
1962 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1963 /// other structs.
1964 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1965   SmallVector<Type*, 8> Elts;
1966   if (ParseStructBody(Elts)) return true;
1967
1968   Result = StructType::get(Context, Elts, Packed);
1969   return false;
1970 }
1971
1972 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1973 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1974                                      std::pair<Type*, LocTy> &Entry,
1975                                      Type *&ResultTy) {
1976   // If the type was already defined, diagnose the redefinition.
1977   if (Entry.first && !Entry.second.isValid())
1978     return Error(TypeLoc, "redefinition of type");
1979
1980   // If we have opaque, just return without filling in the definition for the
1981   // struct.  This counts as a definition as far as the .ll file goes.
1982   if (EatIfPresent(lltok::kw_opaque)) {
1983     // This type is being defined, so clear the location to indicate this.
1984     Entry.second = SMLoc();
1985
1986     // If this type number has never been uttered, create it.
1987     if (!Entry.first)
1988       Entry.first = StructType::create(Context, Name);
1989     ResultTy = Entry.first;
1990     return false;
1991   }
1992
1993   // If the type starts with '<', then it is either a packed struct or a vector.
1994   bool isPacked = EatIfPresent(lltok::less);
1995
1996   // If we don't have a struct, then we have a random type alias, which we
1997   // accept for compatibility with old files.  These types are not allowed to be
1998   // forward referenced and not allowed to be recursive.
1999   if (Lex.getKind() != lltok::lbrace) {
2000     if (Entry.first)
2001       return Error(TypeLoc, "forward references to non-struct type");
2002
2003     ResultTy = nullptr;
2004     if (isPacked)
2005       return ParseArrayVectorType(ResultTy, true);
2006     return ParseType(ResultTy);
2007   }
2008
2009   // This type is being defined, so clear the location to indicate this.
2010   Entry.second = SMLoc();
2011
2012   // If this type number has never been uttered, create it.
2013   if (!Entry.first)
2014     Entry.first = StructType::create(Context, Name);
2015
2016   StructType *STy = cast<StructType>(Entry.first);
2017
2018   SmallVector<Type*, 8> Body;
2019   if (ParseStructBody(Body) ||
2020       (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2021     return true;
2022
2023   STy->setBody(Body, isPacked);
2024   ResultTy = STy;
2025   return false;
2026 }
2027
2028
2029 /// ParseStructType: Handles packed and unpacked types.  </> parsed elsewhere.
2030 ///   StructType
2031 ///     ::= '{' '}'
2032 ///     ::= '{' Type (',' Type)* '}'
2033 ///     ::= '<' '{' '}' '>'
2034 ///     ::= '<' '{' Type (',' Type)* '}' '>'
2035 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2036   assert(Lex.getKind() == lltok::lbrace);
2037   Lex.Lex(); // Consume the '{'
2038
2039   // Handle the empty struct.
2040   if (EatIfPresent(lltok::rbrace))
2041     return false;
2042
2043   LocTy EltTyLoc = Lex.getLoc();
2044   Type *Ty = nullptr;
2045   if (ParseType(Ty)) return true;
2046   Body.push_back(Ty);
2047
2048   if (!StructType::isValidElementType(Ty))
2049     return Error(EltTyLoc, "invalid element type for struct");
2050
2051   while (EatIfPresent(lltok::comma)) {
2052     EltTyLoc = Lex.getLoc();
2053     if (ParseType(Ty)) return true;
2054
2055     if (!StructType::isValidElementType(Ty))
2056       return Error(EltTyLoc, "invalid element type for struct");
2057
2058     Body.push_back(Ty);
2059   }
2060
2061   return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2062 }
2063
2064 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2065 /// token has already been consumed.
2066 ///   Type
2067 ///     ::= '[' APSINTVAL 'x' Types ']'
2068 ///     ::= '<' APSINTVAL 'x' Types '>'
2069 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2070   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2071       Lex.getAPSIntVal().getBitWidth() > 64)
2072     return TokError("expected number in address space");
2073
2074   LocTy SizeLoc = Lex.getLoc();
2075   uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2076   Lex.Lex();
2077
2078   if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2079       return true;
2080
2081   LocTy TypeLoc = Lex.getLoc();
2082   Type *EltTy = nullptr;
2083   if (ParseType(EltTy)) return true;
2084
2085   if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2086                  "expected end of sequential type"))
2087     return true;
2088
2089   if (isVector) {
2090     if (Size == 0)
2091       return Error(SizeLoc, "zero element vector is illegal");
2092     if ((unsigned)Size != Size)
2093       return Error(SizeLoc, "size too large for vector");
2094     if (!VectorType::isValidElementType(EltTy))
2095       return Error(TypeLoc, "invalid vector element type");
2096     Result = VectorType::get(EltTy, unsigned(Size));
2097   } else {
2098     if (!ArrayType::isValidElementType(EltTy))
2099       return Error(TypeLoc, "invalid array element type");
2100     Result = ArrayType::get(EltTy, Size);
2101   }
2102   return false;
2103 }
2104
2105 //===----------------------------------------------------------------------===//
2106 // Function Semantic Analysis.
2107 //===----------------------------------------------------------------------===//
2108
2109 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2110                                              int functionNumber)
2111   : P(p), F(f), FunctionNumber(functionNumber) {
2112
2113   // Insert unnamed arguments into the NumberedVals list.
2114   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2115        AI != E; ++AI)
2116     if (!AI->hasName())
2117       NumberedVals.push_back(AI);
2118 }
2119
2120 LLParser::PerFunctionState::~PerFunctionState() {
2121   // If there were any forward referenced non-basicblock values, delete them.
2122   for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2123        I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2124     if (!isa<BasicBlock>(I->second.first)) {
2125       I->second.first->replaceAllUsesWith(
2126                            UndefValue::get(I->second.first->getType()));
2127       delete I->second.first;
2128       I->second.first = nullptr;
2129     }
2130
2131   for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2132        I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2133     if (!isa<BasicBlock>(I->second.first)) {
2134       I->second.first->replaceAllUsesWith(
2135                            UndefValue::get(I->second.first->getType()));
2136       delete I->second.first;
2137       I->second.first = nullptr;
2138     }
2139 }
2140
2141 bool LLParser::PerFunctionState::FinishFunction() {
2142   if (!ForwardRefVals.empty())
2143     return P.Error(ForwardRefVals.begin()->second.second,
2144                    "use of undefined value '%" + ForwardRefVals.begin()->first +
2145                    "'");
2146   if (!ForwardRefValIDs.empty())
2147     return P.Error(ForwardRefValIDs.begin()->second.second,
2148                    "use of undefined value '%" +
2149                    Twine(ForwardRefValIDs.begin()->first) + "'");
2150   return false;
2151 }
2152
2153
2154 /// GetVal - Get a value with the specified name or ID, creating a
2155 /// forward reference record if needed.  This can return null if the value
2156 /// exists but does not have the right type.
2157 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2158                                           Type *Ty, LocTy Loc) {
2159   // Look this name up in the normal function symbol table.
2160   Value *Val = F.getValueSymbolTable().lookup(Name);
2161
2162   // If this is a forward reference for the value, see if we already created a
2163   // forward ref record.
2164   if (!Val) {
2165     std::map<std::string, std::pair<Value*, LocTy> >::iterator
2166       I = ForwardRefVals.find(Name);
2167     if (I != ForwardRefVals.end())
2168       Val = I->second.first;
2169   }
2170
2171   // If we have the value in the symbol table or fwd-ref table, return it.
2172   if (Val) {
2173     if (Val->getType() == Ty) return Val;
2174     if (Ty->isLabelTy())
2175       P.Error(Loc, "'%" + Name + "' is not a basic block");
2176     else
2177       P.Error(Loc, "'%" + Name + "' defined with type '" +
2178               getTypeString(Val->getType()) + "'");
2179     return nullptr;
2180   }
2181
2182   // Don't make placeholders with invalid type.
2183   if (!Ty->isFirstClassType()) {
2184     P.Error(Loc, "invalid use of a non-first-class type");
2185     return nullptr;
2186   }
2187
2188   // Otherwise, create a new forward reference for this value and remember it.
2189   Value *FwdVal;
2190   if (Ty->isLabelTy())
2191     FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2192   else
2193     FwdVal = new Argument(Ty, Name);
2194
2195   ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2196   return FwdVal;
2197 }
2198
2199 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2200                                           LocTy Loc) {
2201   // Look this name up in the normal function symbol table.
2202   Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2203
2204   // If this is a forward reference for the value, see if we already created a
2205   // forward ref record.
2206   if (!Val) {
2207     std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2208       I = ForwardRefValIDs.find(ID);
2209     if (I != ForwardRefValIDs.end())
2210       Val = I->second.first;
2211   }
2212
2213   // If we have the value in the symbol table or fwd-ref table, return it.
2214   if (Val) {
2215     if (Val->getType() == Ty) return Val;
2216     if (Ty->isLabelTy())
2217       P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2218     else
2219       P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2220               getTypeString(Val->getType()) + "'");
2221     return nullptr;
2222   }
2223
2224   if (!Ty->isFirstClassType()) {
2225     P.Error(Loc, "invalid use of a non-first-class type");
2226     return nullptr;
2227   }
2228
2229   // Otherwise, create a new forward reference for this value and remember it.
2230   Value *FwdVal;
2231   if (Ty->isLabelTy())
2232     FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2233   else
2234     FwdVal = new Argument(Ty);
2235
2236   ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2237   return FwdVal;
2238 }
2239
2240 /// SetInstName - After an instruction is parsed and inserted into its
2241 /// basic block, this installs its name.
2242 bool LLParser::PerFunctionState::SetInstName(int NameID,
2243                                              const std::string &NameStr,
2244                                              LocTy NameLoc, Instruction *Inst) {
2245   // If this instruction has void type, it cannot have a name or ID specified.
2246   if (Inst->getType()->isVoidTy()) {
2247     if (NameID != -1 || !NameStr.empty())
2248       return P.Error(NameLoc, "instructions returning void cannot have a name");
2249     return false;
2250   }
2251
2252   // If this was a numbered instruction, verify that the instruction is the
2253   // expected value and resolve any forward references.
2254   if (NameStr.empty()) {
2255     // If neither a name nor an ID was specified, just use the next ID.
2256     if (NameID == -1)
2257       NameID = NumberedVals.size();
2258
2259     if (unsigned(NameID) != NumberedVals.size())
2260       return P.Error(NameLoc, "instruction expected to be numbered '%" +
2261                      Twine(NumberedVals.size()) + "'");
2262
2263     std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2264       ForwardRefValIDs.find(NameID);
2265     if (FI != ForwardRefValIDs.end()) {
2266       if (FI->second.first->getType() != Inst->getType())
2267         return P.Error(NameLoc, "instruction forward referenced with type '" +
2268                        getTypeString(FI->second.first->getType()) + "'");
2269       FI->second.first->replaceAllUsesWith(Inst);
2270       delete FI->second.first;
2271       ForwardRefValIDs.erase(FI);
2272     }
2273
2274     NumberedVals.push_back(Inst);
2275     return false;
2276   }
2277
2278   // Otherwise, the instruction had a name.  Resolve forward refs and set it.
2279   std::map<std::string, std::pair<Value*, LocTy> >::iterator
2280     FI = ForwardRefVals.find(NameStr);
2281   if (FI != ForwardRefVals.end()) {
2282     if (FI->second.first->getType() != Inst->getType())
2283       return P.Error(NameLoc, "instruction forward referenced with type '" +
2284                      getTypeString(FI->second.first->getType()) + "'");
2285     FI->second.first->replaceAllUsesWith(Inst);
2286     delete FI->second.first;
2287     ForwardRefVals.erase(FI);
2288   }
2289
2290   // Set the name on the instruction.
2291   Inst->setName(NameStr);
2292
2293   if (Inst->getName() != NameStr)
2294     return P.Error(NameLoc, "multiple definition of local value named '" +
2295                    NameStr + "'");
2296   return false;
2297 }
2298
2299 /// GetBB - Get a basic block with the specified name or ID, creating a
2300 /// forward reference record if needed.
2301 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2302                                               LocTy Loc) {
2303   return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2304                                       Type::getLabelTy(F.getContext()), Loc));
2305 }
2306
2307 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2308   return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2309                                       Type::getLabelTy(F.getContext()), Loc));
2310 }
2311
2312 /// DefineBB - Define the specified basic block, which is either named or
2313 /// unnamed.  If there is an error, this returns null otherwise it returns
2314 /// the block being defined.
2315 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2316                                                  LocTy Loc) {
2317   BasicBlock *BB;
2318   if (Name.empty())
2319     BB = GetBB(NumberedVals.size(), Loc);
2320   else
2321     BB = GetBB(Name, Loc);
2322   if (!BB) return nullptr; // Already diagnosed error.
2323
2324   // Move the block to the end of the function.  Forward ref'd blocks are
2325   // inserted wherever they happen to be referenced.
2326   F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2327
2328   // Remove the block from forward ref sets.
2329   if (Name.empty()) {
2330     ForwardRefValIDs.erase(NumberedVals.size());
2331     NumberedVals.push_back(BB);
2332   } else {
2333     // BB forward references are already in the function symbol table.
2334     ForwardRefVals.erase(Name);
2335   }
2336
2337   return BB;
2338 }
2339
2340 //===----------------------------------------------------------------------===//
2341 // Constants.
2342 //===----------------------------------------------------------------------===//
2343
2344 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2345 /// type implied.  For example, if we parse "4" we don't know what integer type
2346 /// it has.  The value will later be combined with its type and checked for
2347 /// sanity.  PFS is used to convert function-local operands of metadata (since
2348 /// metadata operands are not just parsed here but also converted to values).
2349 /// PFS can be null when we are not parsing metadata values inside a function.
2350 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2351   ID.Loc = Lex.getLoc();
2352   switch (Lex.getKind()) {
2353   default: return TokError("expected value token");
2354   case lltok::GlobalID:  // @42
2355     ID.UIntVal = Lex.getUIntVal();
2356     ID.Kind = ValID::t_GlobalID;
2357     break;
2358   case lltok::GlobalVar:  // @foo
2359     ID.StrVal = Lex.getStrVal();
2360     ID.Kind = ValID::t_GlobalName;
2361     break;
2362   case lltok::LocalVarID:  // %42
2363     ID.UIntVal = Lex.getUIntVal();
2364     ID.Kind = ValID::t_LocalID;
2365     break;
2366   case lltok::LocalVar:  // %foo
2367     ID.StrVal = Lex.getStrVal();
2368     ID.Kind = ValID::t_LocalName;
2369     break;
2370   case lltok::APSInt:
2371     ID.APSIntVal = Lex.getAPSIntVal();
2372     ID.Kind = ValID::t_APSInt;
2373     break;
2374   case lltok::APFloat:
2375     ID.APFloatVal = Lex.getAPFloatVal();
2376     ID.Kind = ValID::t_APFloat;
2377     break;
2378   case lltok::kw_true:
2379     ID.ConstantVal = ConstantInt::getTrue(Context);
2380     ID.Kind = ValID::t_Constant;
2381     break;
2382   case lltok::kw_false:
2383     ID.ConstantVal = ConstantInt::getFalse(Context);
2384     ID.Kind = ValID::t_Constant;
2385     break;
2386   case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2387   case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2388   case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2389
2390   case lltok::lbrace: {
2391     // ValID ::= '{' ConstVector '}'
2392     Lex.Lex();
2393     SmallVector<Constant*, 16> Elts;
2394     if (ParseGlobalValueVector(Elts) ||
2395         ParseToken(lltok::rbrace, "expected end of struct constant"))
2396       return true;
2397
2398     ID.ConstantStructElts = new Constant*[Elts.size()];
2399     ID.UIntVal = Elts.size();
2400     memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2401     ID.Kind = ValID::t_ConstantStruct;
2402     return false;
2403   }
2404   case lltok::less: {
2405     // ValID ::= '<' ConstVector '>'         --> Vector.
2406     // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2407     Lex.Lex();
2408     bool isPackedStruct = EatIfPresent(lltok::lbrace);
2409
2410     SmallVector<Constant*, 16> Elts;
2411     LocTy FirstEltLoc = Lex.getLoc();
2412     if (ParseGlobalValueVector(Elts) ||
2413         (isPackedStruct &&
2414          ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2415         ParseToken(lltok::greater, "expected end of constant"))
2416       return true;
2417
2418     if (isPackedStruct) {
2419       ID.ConstantStructElts = new Constant*[Elts.size()];
2420       memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2421       ID.UIntVal = Elts.size();
2422       ID.Kind = ValID::t_PackedConstantStruct;
2423       return false;
2424     }
2425
2426     if (Elts.empty())
2427       return Error(ID.Loc, "constant vector must not be empty");
2428
2429     if (!Elts[0]->getType()->isIntegerTy() &&
2430         !Elts[0]->getType()->isFloatingPointTy() &&
2431         !Elts[0]->getType()->isPointerTy())
2432       return Error(FirstEltLoc,
2433             "vector elements must have integer, pointer or floating point type");
2434
2435     // Verify that all the vector elements have the same type.
2436     for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2437       if (Elts[i]->getType() != Elts[0]->getType())
2438         return Error(FirstEltLoc,
2439                      "vector element #" + Twine(i) +
2440                     " is not of type '" + getTypeString(Elts[0]->getType()));
2441
2442     ID.ConstantVal = ConstantVector::get(Elts);
2443     ID.Kind = ValID::t_Constant;
2444     return false;
2445   }
2446   case lltok::lsquare: {   // Array Constant
2447     Lex.Lex();
2448     SmallVector<Constant*, 16> Elts;
2449     LocTy FirstEltLoc = Lex.getLoc();
2450     if (ParseGlobalValueVector(Elts) ||
2451         ParseToken(lltok::rsquare, "expected end of array constant"))
2452       return true;
2453
2454     // Handle empty element.
2455     if (Elts.empty()) {
2456       // Use undef instead of an array because it's inconvenient to determine
2457       // the element type at this point, there being no elements to examine.
2458       ID.Kind = ValID::t_EmptyArray;
2459       return false;
2460     }
2461
2462     if (!Elts[0]->getType()->isFirstClassType())
2463       return Error(FirstEltLoc, "invalid array element type: " +
2464                    getTypeString(Elts[0]->getType()));
2465
2466     ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2467
2468     // Verify all elements are correct type!
2469     for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2470       if (Elts[i]->getType() != Elts[0]->getType())
2471         return Error(FirstEltLoc,
2472                      "array element #" + Twine(i) +
2473                      " is not of type '" + getTypeString(Elts[0]->getType()));
2474     }
2475
2476     ID.ConstantVal = ConstantArray::get(ATy, Elts);
2477     ID.Kind = ValID::t_Constant;
2478     return false;
2479   }
2480   case lltok::kw_c:  // c "foo"
2481     Lex.Lex();
2482     ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2483                                                   false);
2484     if (ParseToken(lltok::StringConstant, "expected string")) return true;
2485     ID.Kind = ValID::t_Constant;
2486     return false;
2487
2488   case lltok::kw_asm: {
2489     // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2490     //             STRINGCONSTANT
2491     bool HasSideEffect, AlignStack, AsmDialect;
2492     Lex.Lex();
2493     if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2494         ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2495         ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2496         ParseStringConstant(ID.StrVal) ||
2497         ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2498         ParseToken(lltok::StringConstant, "expected constraint string"))
2499       return true;
2500     ID.StrVal2 = Lex.getStrVal();
2501     ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2502       (unsigned(AsmDialect)<<2);
2503     ID.Kind = ValID::t_InlineAsm;
2504     return false;
2505   }
2506
2507   case lltok::kw_blockaddress: {
2508     // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2509     Lex.Lex();
2510
2511     ValID Fn, Label;
2512
2513     if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2514         ParseValID(Fn) ||
2515         ParseToken(lltok::comma, "expected comma in block address expression")||
2516         ParseValID(Label) ||
2517         ParseToken(lltok::rparen, "expected ')' in block address expression"))
2518       return true;
2519
2520     if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2521       return Error(Fn.Loc, "expected function name in blockaddress");
2522     if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2523       return Error(Label.Loc, "expected basic block name in blockaddress");
2524
2525     // Try to find the function (but skip it if it's forward-referenced).
2526     GlobalValue *GV = nullptr;
2527     if (Fn.Kind == ValID::t_GlobalID) {
2528       if (Fn.UIntVal < NumberedVals.size())
2529         GV = NumberedVals[Fn.UIntVal];
2530     } else if (!ForwardRefVals.count(Fn.StrVal)) {
2531       GV = M->getNamedValue(Fn.StrVal);
2532     }
2533     Function *F = nullptr;
2534     if (GV) {
2535       // Confirm that it's actually a function with a definition.
2536       if (!isa<Function>(GV))
2537         return Error(Fn.Loc, "expected function name in blockaddress");
2538       F = cast<Function>(GV);
2539       if (F->isDeclaration())
2540         return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2541     }
2542
2543     if (!F) {
2544       // Make a global variable as a placeholder for this reference.
2545       GlobalValue *&FwdRef =
2546           ForwardRefBlockAddresses.insert(std::make_pair(
2547                                               std::move(Fn),
2548                                               std::map<ValID, GlobalValue *>()))
2549               .first->second.insert(std::make_pair(std::move(Label), nullptr))
2550               .first->second;
2551       if (!FwdRef)
2552         FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2553                                     GlobalValue::InternalLinkage, nullptr, "");
2554       ID.ConstantVal = FwdRef;
2555       ID.Kind = ValID::t_Constant;
2556       return false;
2557     }
2558
2559     // We found the function; now find the basic block.  Don't use PFS, since we
2560     // might be inside a constant expression.
2561     BasicBlock *BB;
2562     if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2563       if (Label.Kind == ValID::t_LocalID)
2564         BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2565       else
2566         BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2567       if (!BB)
2568         return Error(Label.Loc, "referenced value is not a basic block");
2569     } else {
2570       if (Label.Kind == ValID::t_LocalID)
2571         return Error(Label.Loc, "cannot take address of numeric label after "
2572                                 "the function is defined");
2573       BB = dyn_cast_or_null<BasicBlock>(
2574           F->getValueSymbolTable().lookup(Label.StrVal));
2575       if (!BB)
2576         return Error(Label.Loc, "referenced value is not a basic block");
2577     }
2578
2579     ID.ConstantVal = BlockAddress::get(F, BB);
2580     ID.Kind = ValID::t_Constant;
2581     return false;
2582   }
2583
2584   case lltok::kw_trunc:
2585   case lltok::kw_zext:
2586   case lltok::kw_sext:
2587   case lltok::kw_fptrunc:
2588   case lltok::kw_fpext:
2589   case lltok::kw_bitcast:
2590   case lltok::kw_addrspacecast:
2591   case lltok::kw_uitofp:
2592   case lltok::kw_sitofp:
2593   case lltok::kw_fptoui:
2594   case lltok::kw_fptosi:
2595   case lltok::kw_inttoptr:
2596   case lltok::kw_ptrtoint: {
2597     unsigned Opc = Lex.getUIntVal();
2598     Type *DestTy = nullptr;
2599     Constant *SrcVal;
2600     Lex.Lex();
2601     if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2602         ParseGlobalTypeAndValue(SrcVal) ||
2603         ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2604         ParseType(DestTy) ||
2605         ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2606       return true;
2607     if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2608       return Error(ID.Loc, "invalid cast opcode for cast from '" +
2609                    getTypeString(SrcVal->getType()) + "' to '" +
2610                    getTypeString(DestTy) + "'");
2611     ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2612                                                  SrcVal, DestTy);
2613     ID.Kind = ValID::t_Constant;
2614     return false;
2615   }
2616   case lltok::kw_extractvalue: {
2617     Lex.Lex();
2618     Constant *Val;
2619     SmallVector<unsigned, 4> Indices;
2620     if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2621         ParseGlobalTypeAndValue(Val) ||
2622         ParseIndexList(Indices) ||
2623         ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2624       return true;
2625
2626     if (!Val->getType()->isAggregateType())
2627       return Error(ID.Loc, "extractvalue operand must be aggregate type");
2628     if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2629       return Error(ID.Loc, "invalid indices for extractvalue");
2630     ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2631     ID.Kind = ValID::t_Constant;
2632     return false;
2633   }
2634   case lltok::kw_insertvalue: {
2635     Lex.Lex();
2636     Constant *Val0, *Val1;
2637     SmallVector<unsigned, 4> Indices;
2638     if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2639         ParseGlobalTypeAndValue(Val0) ||
2640         ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2641         ParseGlobalTypeAndValue(Val1) ||
2642         ParseIndexList(Indices) ||
2643         ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2644       return true;
2645     if (!Val0->getType()->isAggregateType())
2646       return Error(ID.Loc, "insertvalue operand must be aggregate type");
2647     Type *IndexedType =
2648         ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2649     if (!IndexedType)
2650       return Error(ID.Loc, "invalid indices for insertvalue");
2651     if (IndexedType != Val1->getType())
2652       return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2653                                getTypeString(Val1->getType()) +
2654                                "' instead of '" + getTypeString(IndexedType) +
2655                                "'");
2656     ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2657     ID.Kind = ValID::t_Constant;
2658     return false;
2659   }
2660   case lltok::kw_icmp:
2661   case lltok::kw_fcmp: {
2662     unsigned PredVal, Opc = Lex.getUIntVal();
2663     Constant *Val0, *Val1;
2664     Lex.Lex();
2665     if (ParseCmpPredicate(PredVal, Opc) ||
2666         ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2667         ParseGlobalTypeAndValue(Val0) ||
2668         ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2669         ParseGlobalTypeAndValue(Val1) ||
2670         ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2671       return true;
2672
2673     if (Val0->getType() != Val1->getType())
2674       return Error(ID.Loc, "compare operands must have the same type");
2675
2676     CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2677
2678     if (Opc == Instruction::FCmp) {
2679       if (!Val0->getType()->isFPOrFPVectorTy())
2680         return Error(ID.Loc, "fcmp requires floating point operands");
2681       ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2682     } else {
2683       assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2684       if (!Val0->getType()->isIntOrIntVectorTy() &&
2685           !Val0->getType()->getScalarType()->isPointerTy())
2686         return Error(ID.Loc, "icmp requires pointer or integer operands");
2687       ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2688     }
2689     ID.Kind = ValID::t_Constant;
2690     return false;
2691   }
2692
2693   // Binary Operators.
2694   case lltok::kw_add:
2695   case lltok::kw_fadd:
2696   case lltok::kw_sub:
2697   case lltok::kw_fsub:
2698   case lltok::kw_mul:
2699   case lltok::kw_fmul:
2700   case lltok::kw_udiv:
2701   case lltok::kw_sdiv:
2702   case lltok::kw_fdiv:
2703   case lltok::kw_urem:
2704   case lltok::kw_srem:
2705   case lltok::kw_frem:
2706   case lltok::kw_shl:
2707   case lltok::kw_lshr:
2708   case lltok::kw_ashr: {
2709     bool NUW = false;
2710     bool NSW = false;
2711     bool Exact = false;
2712     unsigned Opc = Lex.getUIntVal();
2713     Constant *Val0, *Val1;
2714     Lex.Lex();
2715     LocTy ModifierLoc = Lex.getLoc();
2716     if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2717         Opc == Instruction::Mul || Opc == Instruction::Shl) {
2718       if (EatIfPresent(lltok::kw_nuw))
2719         NUW = true;
2720       if (EatIfPresent(lltok::kw_nsw)) {
2721         NSW = true;
2722         if (EatIfPresent(lltok::kw_nuw))
2723           NUW = true;
2724       }
2725     } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2726                Opc == Instruction::LShr || Opc == Instruction::AShr) {
2727       if (EatIfPresent(lltok::kw_exact))
2728         Exact = true;
2729     }
2730     if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2731         ParseGlobalTypeAndValue(Val0) ||
2732         ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2733         ParseGlobalTypeAndValue(Val1) ||
2734         ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2735       return true;
2736     if (Val0->getType() != Val1->getType())
2737       return Error(ID.Loc, "operands of constexpr must have same type");
2738     if (!Val0->getType()->isIntOrIntVectorTy()) {
2739       if (NUW)
2740         return Error(ModifierLoc, "nuw only applies to integer operations");
2741       if (NSW)
2742         return Error(ModifierLoc, "nsw only applies to integer operations");
2743     }
2744     // Check that the type is valid for the operator.
2745     switch (Opc) {
2746     case Instruction::Add:
2747     case Instruction::Sub:
2748     case Instruction::Mul:
2749     case Instruction::UDiv:
2750     case Instruction::SDiv:
2751     case Instruction::URem:
2752     case Instruction::SRem:
2753     case Instruction::Shl:
2754     case Instruction::AShr:
2755     case Instruction::LShr:
2756       if (!Val0->getType()->isIntOrIntVectorTy())
2757         return Error(ID.Loc, "constexpr requires integer operands");
2758       break;
2759     case Instruction::FAdd:
2760     case Instruction::FSub:
2761     case Instruction::FMul:
2762     case Instruction::FDiv:
2763     case Instruction::FRem:
2764       if (!Val0->getType()->isFPOrFPVectorTy())
2765         return Error(ID.Loc, "constexpr requires fp operands");
2766       break;
2767     default: llvm_unreachable("Unknown binary operator!");
2768     }
2769     unsigned Flags = 0;
2770     if (NUW)   Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2771     if (NSW)   Flags |= OverflowingBinaryOperator::NoSignedWrap;
2772     if (Exact) Flags |= PossiblyExactOperator::IsExact;
2773     Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2774     ID.ConstantVal = C;
2775     ID.Kind = ValID::t_Constant;
2776     return false;
2777   }
2778
2779   // Logical Operations
2780   case lltok::kw_and:
2781   case lltok::kw_or:
2782   case lltok::kw_xor: {
2783     unsigned Opc = Lex.getUIntVal();
2784     Constant *Val0, *Val1;
2785     Lex.Lex();
2786     if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2787         ParseGlobalTypeAndValue(Val0) ||
2788         ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2789         ParseGlobalTypeAndValue(Val1) ||
2790         ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2791       return true;
2792     if (Val0->getType() != Val1->getType())
2793       return Error(ID.Loc, "operands of constexpr must have same type");
2794     if (!Val0->getType()->isIntOrIntVectorTy())
2795       return Error(ID.Loc,
2796                    "constexpr requires integer or integer vector operands");
2797     ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2798     ID.Kind = ValID::t_Constant;
2799     return false;
2800   }
2801
2802   case lltok::kw_getelementptr:
2803   case lltok::kw_shufflevector:
2804   case lltok::kw_insertelement:
2805   case lltok::kw_extractelement:
2806   case lltok::kw_select: {
2807     unsigned Opc = Lex.getUIntVal();
2808     SmallVector<Constant*, 16> Elts;
2809     bool InBounds = false;
2810     Type *Ty;
2811     Lex.Lex();
2812
2813     if (Opc == Instruction::GetElementPtr)
2814       InBounds = EatIfPresent(lltok::kw_inbounds);
2815
2816     if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2817       return true;
2818
2819     LocTy ExplicitTypeLoc = Lex.getLoc();
2820     if (Opc == Instruction::GetElementPtr) {
2821       if (ParseType(Ty) ||
2822           ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2823         return true;
2824     }
2825
2826     if (ParseGlobalValueVector(Elts) ||
2827         ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2828       return true;
2829
2830     if (Opc == Instruction::GetElementPtr) {
2831       if (Elts.size() == 0 ||
2832           !Elts[0]->getType()->getScalarType()->isPointerTy())
2833         return Error(ID.Loc, "base of getelementptr must be a pointer");
2834
2835       Type *BaseType = Elts[0]->getType();
2836       auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
2837       if (Ty != BasePointerType->getElementType())
2838         return Error(
2839             ExplicitTypeLoc,
2840             "explicit pointee type doesn't match operand's pointee type");
2841
2842       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2843       for (Constant *Val : Indices) {
2844         Type *ValTy = Val->getType();
2845         if (!ValTy->getScalarType()->isIntegerTy())
2846           return Error(ID.Loc, "getelementptr index must be an integer");
2847         if (ValTy->isVectorTy() != BaseType->isVectorTy())
2848           return Error(ID.Loc, "getelementptr index type missmatch");
2849         if (ValTy->isVectorTy()) {
2850           unsigned ValNumEl = cast<VectorType>(ValTy)->getNumElements();
2851           unsigned PtrNumEl = cast<VectorType>(BaseType)->getNumElements();
2852           if (ValNumEl != PtrNumEl)
2853             return Error(
2854                 ID.Loc,
2855                 "getelementptr vector index has a wrong number of elements");
2856         }
2857       }
2858
2859       SmallPtrSet<const Type*, 4> Visited;
2860       if (!Indices.empty() && !Ty->isSized(&Visited))
2861         return Error(ID.Loc, "base element of getelementptr must be sized");
2862
2863       if (!GetElementPtrInst::getIndexedType(Ty, Indices))
2864         return Error(ID.Loc, "invalid getelementptr indices");
2865       ID.ConstantVal =
2866           ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
2867     } else if (Opc == Instruction::Select) {
2868       if (Elts.size() != 3)
2869         return Error(ID.Loc, "expected three operands to select");
2870       if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2871                                                               Elts[2]))
2872         return Error(ID.Loc, Reason);
2873       ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2874     } else if (Opc == Instruction::ShuffleVector) {
2875       if (Elts.size() != 3)
2876         return Error(ID.Loc, "expected three operands to shufflevector");
2877       if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2878         return Error(ID.Loc, "invalid operands to shufflevector");
2879       ID.ConstantVal =
2880                  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2881     } else if (Opc == Instruction::ExtractElement) {
2882       if (Elts.size() != 2)
2883         return Error(ID.Loc, "expected two operands to extractelement");
2884       if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2885         return Error(ID.Loc, "invalid extractelement operands");
2886       ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2887     } else {
2888       assert(Opc == Instruction::InsertElement && "Unknown opcode");
2889       if (Elts.size() != 3)
2890       return Error(ID.Loc, "expected three operands to insertelement");
2891       if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2892         return Error(ID.Loc, "invalid insertelement operands");
2893       ID.ConstantVal =
2894                  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2895     }
2896
2897     ID.Kind = ValID::t_Constant;
2898     return false;
2899   }
2900   }
2901
2902   Lex.Lex();
2903   return false;
2904 }
2905
2906 /// ParseGlobalValue - Parse a global value with the specified type.
2907 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2908   C = nullptr;
2909   ValID ID;
2910   Value *V = nullptr;
2911   bool Parsed = ParseValID(ID) ||
2912                 ConvertValIDToValue(Ty, ID, V, nullptr);
2913   if (V && !(C = dyn_cast<Constant>(V)))
2914     return Error(ID.Loc, "global values must be constants");
2915   return Parsed;
2916 }
2917
2918 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2919   Type *Ty = nullptr;
2920   return ParseType(Ty) ||
2921          ParseGlobalValue(Ty, V);
2922 }
2923
2924 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2925   C = nullptr;
2926
2927   LocTy KwLoc = Lex.getLoc();
2928   if (!EatIfPresent(lltok::kw_comdat))
2929     return false;
2930
2931   if (EatIfPresent(lltok::lparen)) {
2932     if (Lex.getKind() != lltok::ComdatVar)
2933       return TokError("expected comdat variable");
2934     C = getComdat(Lex.getStrVal(), Lex.getLoc());
2935     Lex.Lex();
2936     if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2937       return true;
2938   } else {
2939     if (GlobalName.empty())
2940       return TokError("comdat cannot be unnamed");
2941     C = getComdat(GlobalName, KwLoc);
2942   }
2943
2944   return false;
2945 }
2946
2947 /// ParseGlobalValueVector
2948 ///   ::= /*empty*/
2949 ///   ::= TypeAndValue (',' TypeAndValue)*
2950 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2951   // Empty list.
2952   if (Lex.getKind() == lltok::rbrace ||
2953       Lex.getKind() == lltok::rsquare ||
2954       Lex.getKind() == lltok::greater ||
2955       Lex.getKind() == lltok::rparen)
2956     return false;
2957
2958   Constant *C;
2959   if (ParseGlobalTypeAndValue(C)) return true;
2960   Elts.push_back(C);
2961
2962   while (EatIfPresent(lltok::comma)) {
2963     if (ParseGlobalTypeAndValue(C)) return true;
2964     Elts.push_back(C);
2965   }
2966
2967   return false;
2968 }
2969
2970 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
2971   SmallVector<Metadata *, 16> Elts;
2972   if (ParseMDNodeVector(Elts))
2973     return true;
2974
2975   MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
2976   return false;
2977 }
2978
2979 /// MDNode:
2980 ///  ::= !{ ... }
2981 ///  ::= !7
2982 ///  ::= !MDLocation(...)
2983 bool LLParser::ParseMDNode(MDNode *&N) {
2984   if (Lex.getKind() == lltok::MetadataVar)
2985     return ParseSpecializedMDNode(N);
2986
2987   return ParseToken(lltok::exclaim, "expected '!' here") ||
2988          ParseMDNodeTail(N);
2989 }
2990
2991 bool LLParser::ParseMDNodeTail(MDNode *&N) {
2992   // !{ ... }
2993   if (Lex.getKind() == lltok::lbrace)
2994     return ParseMDTuple(N);
2995
2996   // !42
2997   return ParseMDNodeID(N);
2998 }
2999
3000 namespace {
3001
3002 /// Structure to represent an optional metadata field.
3003 template <class FieldTy> struct MDFieldImpl {
3004   typedef MDFieldImpl ImplTy;
3005   FieldTy Val;
3006   bool Seen;
3007
3008   void assign(FieldTy Val) {
3009     Seen = true;
3010     this->Val = std::move(Val);
3011   }
3012
3013   explicit MDFieldImpl(FieldTy Default)
3014       : Val(std::move(Default)), Seen(false) {}
3015 };
3016
3017 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3018   uint64_t Max;
3019
3020   MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3021       : ImplTy(Default), Max(Max) {}
3022 };
3023 struct LineField : public MDUnsignedField {
3024   LineField() : MDUnsignedField(0, UINT32_MAX) {}
3025 };
3026 struct ColumnField : public MDUnsignedField {
3027   ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3028 };
3029 struct DwarfTagField : public MDUnsignedField {
3030   DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3031   DwarfTagField(dwarf::Tag DefaultTag)
3032       : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3033 };
3034 struct DwarfAttEncodingField : public MDUnsignedField {
3035   DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3036 };
3037 struct DwarfVirtualityField : public MDUnsignedField {
3038   DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3039 };
3040 struct DwarfLangField : public MDUnsignedField {
3041   DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3042 };
3043
3044 struct DIFlagField : public MDUnsignedField {
3045   DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3046 };
3047
3048 struct MDSignedField : public MDFieldImpl<int64_t> {
3049   int64_t Min;
3050   int64_t Max;
3051
3052   MDSignedField(int64_t Default = 0)
3053       : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3054   MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3055       : ImplTy(Default), Min(Min), Max(Max) {}
3056 };
3057
3058 struct MDBoolField : public MDFieldImpl<bool> {
3059   MDBoolField(bool Default = false) : ImplTy(Default) {}
3060 };
3061 struct MDField : public MDFieldImpl<Metadata *> {
3062   bool AllowNull;
3063
3064   MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3065 };
3066 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3067   MDConstant() : ImplTy(nullptr) {}
3068 };
3069 struct MDStringField : public MDFieldImpl<MDString *> {
3070   bool AllowEmpty;
3071   MDStringField(bool AllowEmpty = true)
3072       : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3073 };
3074 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3075   MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3076 };
3077
3078 } // end namespace
3079
3080 namespace llvm {
3081
3082 template <>
3083 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3084                             MDUnsignedField &Result) {
3085   if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3086     return TokError("expected unsigned integer");
3087
3088   auto &U = Lex.getAPSIntVal();
3089   if (U.ugt(Result.Max))
3090     return TokError("value for '" + Name + "' too large, limit is " +
3091                     Twine(Result.Max));
3092   Result.assign(U.getZExtValue());
3093   assert(Result.Val <= Result.Max && "Expected value in range");
3094   Lex.Lex();
3095   return false;
3096 }
3097
3098 template <>
3099 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3100   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3101 }
3102 template <>
3103 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3104   return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3105 }
3106
3107 template <>
3108 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3109   if (Lex.getKind() == lltok::APSInt)
3110     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3111
3112   if (Lex.getKind() != lltok::DwarfTag)
3113     return TokError("expected DWARF tag");
3114
3115   unsigned Tag = dwarf::getTag(Lex.getStrVal());
3116   if (Tag == dwarf::DW_TAG_invalid)
3117     return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3118   assert(Tag <= Result.Max && "Expected valid DWARF tag");
3119
3120   Result.assign(Tag);
3121   Lex.Lex();
3122   return false;
3123 }
3124
3125 template <>
3126 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3127                             DwarfVirtualityField &Result) {
3128   if (Lex.getKind() == lltok::APSInt)
3129     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3130
3131   if (Lex.getKind() != lltok::DwarfVirtuality)
3132     return TokError("expected DWARF virtuality code");
3133
3134   unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3135   if (!Virtuality)
3136     return TokError("invalid DWARF virtuality code" + Twine(" '") +
3137                     Lex.getStrVal() + "'");
3138   assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3139   Result.assign(Virtuality);
3140   Lex.Lex();
3141   return false;
3142 }
3143
3144 template <>
3145 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3146   if (Lex.getKind() == lltok::APSInt)
3147     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3148
3149   if (Lex.getKind() != lltok::DwarfLang)
3150     return TokError("expected DWARF language");
3151
3152   unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3153   if (!Lang)
3154     return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3155                     "'");
3156   assert(Lang <= Result.Max && "Expected valid DWARF language");
3157   Result.assign(Lang);
3158   Lex.Lex();
3159   return false;
3160 }
3161
3162 template <>
3163 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3164                             DwarfAttEncodingField &Result) {
3165   if (Lex.getKind() == lltok::APSInt)
3166     return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3167
3168   if (Lex.getKind() != lltok::DwarfAttEncoding)
3169     return TokError("expected DWARF type attribute encoding");
3170
3171   unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3172   if (!Encoding)
3173     return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3174                     Lex.getStrVal() + "'");
3175   assert(Encoding <= Result.Max && "Expected valid DWARF language");
3176   Result.assign(Encoding);
3177   Lex.Lex();
3178   return false;
3179 }
3180
3181 /// DIFlagField
3182 ///  ::= uint32
3183 ///  ::= DIFlagVector
3184 ///  ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3185 template <>
3186 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3187   assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3188
3189   // Parser for a single flag.
3190   auto parseFlag = [&](unsigned &Val) {
3191     if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3192       return ParseUInt32(Val);
3193
3194     if (Lex.getKind() != lltok::DIFlag)
3195       return TokError("expected debug info flag");
3196
3197     Val = DebugNode::getFlag(Lex.getStrVal());
3198     if (!Val)
3199       return TokError(Twine("invalid debug info flag flag '") +
3200                       Lex.getStrVal() + "'");
3201     Lex.Lex();
3202     return false;
3203   };
3204
3205   // Parse the flags and combine them together.
3206   unsigned Combined = 0;
3207   do {
3208     unsigned Val;
3209     if (parseFlag(Val))
3210       return true;
3211     Combined |= Val;
3212   } while (EatIfPresent(lltok::bar));
3213
3214   Result.assign(Combined);
3215   return false;
3216 }
3217
3218 template <>
3219 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3220                             MDSignedField &Result) {
3221   if (Lex.getKind() != lltok::APSInt)
3222     return TokError("expected signed integer");
3223
3224   auto &S = Lex.getAPSIntVal();
3225   if (S < Result.Min)
3226     return TokError("value for '" + Name + "' too small, limit is " +
3227                     Twine(Result.Min));
3228   if (S > Result.Max)
3229     return TokError("value for '" + Name + "' too large, limit is " +
3230                     Twine(Result.Max));
3231   Result.assign(S.getExtValue());
3232   assert(Result.Val >= Result.Min && "Expected value in range");
3233   assert(Result.Val <= Result.Max && "Expected value in range");
3234   Lex.Lex();
3235   return false;
3236 }
3237
3238 template <>
3239 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3240   switch (Lex.getKind()) {
3241   default:
3242     return TokError("expected 'true' or 'false'");
3243   case lltok::kw_true:
3244     Result.assign(true);
3245     break;
3246   case lltok::kw_false:
3247     Result.assign(false);
3248     break;
3249   }
3250   Lex.Lex();
3251   return false;
3252 }
3253
3254 template <>
3255 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3256   if (Lex.getKind() == lltok::kw_null) {
3257     if (!Result.AllowNull)
3258       return TokError("'" + Name + "' cannot be null");
3259     Lex.Lex();
3260     Result.assign(nullptr);
3261     return false;
3262   }
3263
3264   Metadata *MD;
3265   if (ParseMetadata(MD, nullptr))
3266     return true;
3267
3268   Result.assign(MD);
3269   return false;
3270 }
3271
3272 template <>
3273 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3274   Metadata *MD;
3275   if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3276     return true;
3277
3278   Result.assign(cast<ConstantAsMetadata>(MD));
3279   return false;
3280 }
3281
3282 template <>
3283 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3284   LocTy ValueLoc = Lex.getLoc();
3285   std::string S;
3286   if (ParseStringConstant(S))
3287     return true;
3288
3289   if (!Result.AllowEmpty && S.empty())
3290     return Error(ValueLoc, "'" + Name + "' cannot be empty");
3291
3292   Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3293   return false;
3294 }
3295
3296 template <>
3297 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3298   SmallVector<Metadata *, 4> MDs;
3299   if (ParseMDNodeVector(MDs))
3300     return true;
3301
3302   Result.assign(std::move(MDs));
3303   return false;
3304 }
3305
3306 } // end namespace llvm
3307
3308 template <class ParserTy>
3309 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3310   do {
3311     if (Lex.getKind() != lltok::LabelStr)
3312       return TokError("expected field label here");
3313
3314     if (parseField())
3315       return true;
3316   } while (EatIfPresent(lltok::comma));
3317
3318   return false;
3319 }
3320
3321 template <class ParserTy>
3322 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3323   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3324   Lex.Lex();
3325
3326   if (ParseToken(lltok::lparen, "expected '(' here"))
3327     return true;
3328   if (Lex.getKind() != lltok::rparen)
3329     if (ParseMDFieldsImplBody(parseField))
3330       return true;
3331
3332   ClosingLoc = Lex.getLoc();
3333   return ParseToken(lltok::rparen, "expected ')' here");
3334 }
3335
3336 template <class FieldTy>
3337 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3338   if (Result.Seen)
3339     return TokError("field '" + Name + "' cannot be specified more than once");
3340
3341   LocTy Loc = Lex.getLoc();
3342   Lex.Lex();
3343   return ParseMDField(Loc, Name, Result);
3344 }
3345
3346 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3347   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3348
3349 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS)                                  \
3350   if (Lex.getStrVal() == #CLASS)                                               \
3351     return Parse##CLASS(N, IsDistinct);
3352 #include "llvm/IR/Metadata.def"
3353
3354   return TokError("expected metadata type");
3355 }
3356
3357 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3358 #define NOP_FIELD(NAME, TYPE, INIT)
3359 #define REQUIRE_FIELD(NAME, TYPE, INIT)                                        \
3360   if (!NAME.Seen)                                                              \
3361     return Error(ClosingLoc, "missing required field '" #NAME "'");
3362 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT)                                    \
3363   if (Lex.getStrVal() == #NAME)                                                \
3364     return ParseMDField(#NAME, NAME);
3365 #define PARSE_MD_FIELDS()                                                      \
3366   VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD)                                \
3367   do {                                                                         \
3368     LocTy ClosingLoc;                                                          \
3369     if (ParseMDFieldsImpl([&]() -> bool {                                      \
3370       VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD)                          \
3371       return TokError(Twine("invalid field '") + Lex.getStrVal() + "'");       \
3372     }, ClosingLoc))                                                            \
3373       return true;                                                             \
3374     VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD)                                  \
3375   } while (false)
3376 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
3377   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3378
3379 /// ParseMDLocationFields:
3380 ///   ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3381 bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
3382 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3383   OPTIONAL(line, LineField, );                                                 \
3384   OPTIONAL(column, ColumnField, );                                             \
3385   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3386   OPTIONAL(inlinedAt, MDField, );
3387   PARSE_MD_FIELDS();
3388 #undef VISIT_MD_FIELDS
3389
3390   Result = GET_OR_DISTINCT(
3391       MDLocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3392   return false;
3393 }
3394
3395 /// ParseGenericDebugNode:
3396 ///   ::= !GenericDebugNode(tag: 15, header: "...", operands: {...})
3397 bool LLParser::ParseGenericDebugNode(MDNode *&Result, bool IsDistinct) {
3398 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3399   REQUIRED(tag, DwarfTagField, );                                              \
3400   OPTIONAL(header, MDStringField, );                                           \
3401   OPTIONAL(operands, MDFieldList, );
3402   PARSE_MD_FIELDS();
3403 #undef VISIT_MD_FIELDS
3404
3405   Result = GET_OR_DISTINCT(GenericDebugNode,
3406                            (Context, tag.Val, header.Val, operands.Val));
3407   return false;
3408 }
3409
3410 /// ParseMDSubrange:
3411 ///   ::= !MDSubrange(count: 30, lowerBound: 2)
3412 bool LLParser::ParseMDSubrange(MDNode *&Result, bool IsDistinct) {
3413 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3414   REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX));                         \
3415   OPTIONAL(lowerBound, MDSignedField, );
3416   PARSE_MD_FIELDS();
3417 #undef VISIT_MD_FIELDS
3418
3419   Result = GET_OR_DISTINCT(MDSubrange, (Context, count.Val, lowerBound.Val));
3420   return false;
3421 }
3422
3423 /// ParseMDEnumerator:
3424 ///   ::= !MDEnumerator(value: 30, name: "SomeKind")
3425 bool LLParser::ParseMDEnumerator(MDNode *&Result, bool IsDistinct) {
3426 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3427   REQUIRED(name, MDStringField, );                                             \
3428   REQUIRED(value, MDSignedField, );
3429   PARSE_MD_FIELDS();
3430 #undef VISIT_MD_FIELDS
3431
3432   Result = GET_OR_DISTINCT(MDEnumerator, (Context, value.Val, name.Val));
3433   return false;
3434 }
3435
3436 /// ParseMDBasicType:
3437 ///   ::= !MDBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3438 bool LLParser::ParseMDBasicType(MDNode *&Result, bool IsDistinct) {
3439 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3440   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type));                     \
3441   OPTIONAL(name, MDStringField, );                                             \
3442   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3443   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3444   OPTIONAL(encoding, DwarfAttEncodingField, );
3445   PARSE_MD_FIELDS();
3446 #undef VISIT_MD_FIELDS
3447
3448   Result = GET_OR_DISTINCT(MDBasicType, (Context, tag.Val, name.Val, size.Val,
3449                                          align.Val, encoding.Val));
3450   return false;
3451 }
3452
3453 /// ParseMDDerivedType:
3454 ///   ::= !MDDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3455 ///                      line: 7, scope: !1, baseType: !2, size: 32,
3456 ///                      align: 32, offset: 0, flags: 0, extraData: !3)
3457 bool LLParser::ParseMDDerivedType(MDNode *&Result, bool IsDistinct) {
3458 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3459   REQUIRED(tag, DwarfTagField, );                                              \
3460   OPTIONAL(name, MDStringField, );                                             \
3461   OPTIONAL(file, MDField, );                                                   \
3462   OPTIONAL(line, LineField, );                                                 \
3463   OPTIONAL(scope, MDField, );                                                  \
3464   REQUIRED(baseType, MDField, );                                               \
3465   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3466   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3467   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3468   OPTIONAL(flags, DIFlagField, );                                              \
3469   OPTIONAL(extraData, MDField, );
3470   PARSE_MD_FIELDS();
3471 #undef VISIT_MD_FIELDS
3472
3473   Result = GET_OR_DISTINCT(MDDerivedType,
3474                            (Context, tag.Val, name.Val, file.Val, line.Val,
3475                             scope.Val, baseType.Val, size.Val, align.Val,
3476                             offset.Val, flags.Val, extraData.Val));
3477   return false;
3478 }
3479
3480 bool LLParser::ParseMDCompositeType(MDNode *&Result, bool IsDistinct) {
3481 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3482   REQUIRED(tag, DwarfTagField, );                                              \
3483   OPTIONAL(name, MDStringField, );                                             \
3484   OPTIONAL(file, MDField, );                                                   \
3485   OPTIONAL(line, LineField, );                                                 \
3486   OPTIONAL(scope, MDField, );                                                  \
3487   OPTIONAL(baseType, MDField, );                                               \
3488   OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX));                            \
3489   OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX));                           \
3490   OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX));                          \
3491   OPTIONAL(flags, DIFlagField, );                                              \
3492   OPTIONAL(elements, MDField, );                                               \
3493   OPTIONAL(runtimeLang, DwarfLangField, );                                     \
3494   OPTIONAL(vtableHolder, MDField, );                                           \
3495   OPTIONAL(templateParams, MDField, );                                         \
3496   OPTIONAL(identifier, MDStringField, );
3497   PARSE_MD_FIELDS();
3498 #undef VISIT_MD_FIELDS
3499
3500   Result = GET_OR_DISTINCT(
3501       MDCompositeType,
3502       (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3503        size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3504        runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3505   return false;
3506 }
3507
3508 bool LLParser::ParseMDSubroutineType(MDNode *&Result, bool IsDistinct) {
3509 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3510   OPTIONAL(flags, DIFlagField, );                                              \
3511   REQUIRED(types, MDField, );
3512   PARSE_MD_FIELDS();
3513 #undef VISIT_MD_FIELDS
3514
3515   Result = GET_OR_DISTINCT(MDSubroutineType, (Context, flags.Val, types.Val));
3516   return false;
3517 }
3518
3519 /// ParseMDFileType:
3520 ///   ::= !MDFileType(filename: "path/to/file", directory: "/path/to/dir")
3521 bool LLParser::ParseMDFile(MDNode *&Result, bool IsDistinct) {
3522 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3523   REQUIRED(filename, MDStringField, );                                         \
3524   REQUIRED(directory, MDStringField, );
3525   PARSE_MD_FIELDS();
3526 #undef VISIT_MD_FIELDS
3527
3528   Result = GET_OR_DISTINCT(MDFile, (Context, filename.Val, directory.Val));
3529   return false;
3530 }
3531
3532 /// ParseMDCompileUnit:
3533 ///   ::= !MDCompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3534 ///                      isOptimized: true, flags: "-O2", runtimeVersion: 1,
3535 ///                      splitDebugFilename: "abc.debug", emissionKind: 1,
3536 ///                      enums: !1, retainedTypes: !2, subprograms: !3,
3537 ///                      globals: !4, imports: !5)
3538 bool LLParser::ParseMDCompileUnit(MDNode *&Result, bool IsDistinct) {
3539 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3540   REQUIRED(language, DwarfLangField, );                                        \
3541   REQUIRED(file, MDField, (/* AllowNull */ false));                            \
3542   OPTIONAL(producer, MDStringField, );                                         \
3543   OPTIONAL(isOptimized, MDBoolField, );                                        \
3544   OPTIONAL(flags, MDStringField, );                                            \
3545   OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX));                  \
3546   OPTIONAL(splitDebugFilename, MDStringField, );                               \
3547   OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX));                    \
3548   OPTIONAL(enums, MDField, );                                                  \
3549   OPTIONAL(retainedTypes, MDField, );                                          \
3550   OPTIONAL(subprograms, MDField, );                                            \
3551   OPTIONAL(globals, MDField, );                                                \
3552   OPTIONAL(imports, MDField, );
3553   PARSE_MD_FIELDS();
3554 #undef VISIT_MD_FIELDS
3555
3556   Result = GET_OR_DISTINCT(MDCompileUnit,
3557                            (Context, language.Val, file.Val, producer.Val,
3558                             isOptimized.Val, flags.Val, runtimeVersion.Val,
3559                             splitDebugFilename.Val, emissionKind.Val, enums.Val,
3560                             retainedTypes.Val, subprograms.Val, globals.Val,
3561                             imports.Val));
3562   return false;
3563 }
3564
3565 /// ParseMDSubprogram:
3566 ///   ::= !MDSubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3567 ///                     file: !1, line: 7, type: !2, isLocal: false,
3568 ///                     isDefinition: true, scopeLine: 8, containingType: !3,
3569 ///                     virtuality: DW_VIRTUALTIY_pure_virtual,
3570 ///                     virtualIndex: 10, flags: 11,
3571 ///                     isOptimized: false, function: void ()* @_Z3foov,
3572 ///                     templateParams: !4, declaration: !5, variables: !6)
3573 bool LLParser::ParseMDSubprogram(MDNode *&Result, bool IsDistinct) {
3574 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3575   OPTIONAL(scope, MDField, );                                                  \
3576   OPTIONAL(name, MDStringField, );                                             \
3577   OPTIONAL(linkageName, MDStringField, );                                      \
3578   OPTIONAL(file, MDField, );                                                   \
3579   OPTIONAL(line, LineField, );                                                 \
3580   OPTIONAL(type, MDField, );                                                   \
3581   OPTIONAL(isLocal, MDBoolField, );                                            \
3582   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
3583   OPTIONAL(scopeLine, LineField, );                                            \
3584   OPTIONAL(containingType, MDField, );                                         \
3585   OPTIONAL(virtuality, DwarfVirtualityField, );                                \
3586   OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX));                    \
3587   OPTIONAL(flags, DIFlagField, );                                              \
3588   OPTIONAL(isOptimized, MDBoolField, );                                        \
3589   OPTIONAL(function, MDConstant, );                                            \
3590   OPTIONAL(templateParams, MDField, );                                         \
3591   OPTIONAL(declaration, MDField, );                                            \
3592   OPTIONAL(variables, MDField, );
3593   PARSE_MD_FIELDS();
3594 #undef VISIT_MD_FIELDS
3595
3596   Result = GET_OR_DISTINCT(
3597       MDSubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3598                      line.Val, type.Val, isLocal.Val, isDefinition.Val,
3599                      scopeLine.Val, containingType.Val, virtuality.Val,
3600                      virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3601                      templateParams.Val, declaration.Val, variables.Val));
3602   return false;
3603 }
3604
3605 /// ParseMDLexicalBlock:
3606 ///   ::= !MDLexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3607 bool LLParser::ParseMDLexicalBlock(MDNode *&Result, bool IsDistinct) {
3608 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3609   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3610   OPTIONAL(file, MDField, );                                                   \
3611   OPTIONAL(line, LineField, );                                                 \
3612   OPTIONAL(column, ColumnField, );
3613   PARSE_MD_FIELDS();
3614 #undef VISIT_MD_FIELDS
3615
3616   Result = GET_OR_DISTINCT(
3617       MDLexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3618   return false;
3619 }
3620
3621 /// ParseMDLexicalBlockFile:
3622 ///   ::= !MDLexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3623 bool LLParser::ParseMDLexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3624 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3625   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3626   OPTIONAL(file, MDField, );                                                   \
3627   REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3628   PARSE_MD_FIELDS();
3629 #undef VISIT_MD_FIELDS
3630
3631   Result = GET_OR_DISTINCT(MDLexicalBlockFile,
3632                            (Context, scope.Val, file.Val, discriminator.Val));
3633   return false;
3634 }
3635
3636 /// ParseMDNamespace:
3637 ///   ::= !MDNamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3638 bool LLParser::ParseMDNamespace(MDNode *&Result, bool IsDistinct) {
3639 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3640   REQUIRED(scope, MDField, );                                                  \
3641   OPTIONAL(file, MDField, );                                                   \
3642   OPTIONAL(name, MDStringField, );                                             \
3643   OPTIONAL(line, LineField, );
3644   PARSE_MD_FIELDS();
3645 #undef VISIT_MD_FIELDS
3646
3647   Result = GET_OR_DISTINCT(MDNamespace,
3648                            (Context, scope.Val, file.Val, name.Val, line.Val));
3649   return false;
3650 }
3651
3652 /// ParseMDTemplateTypeParameter:
3653 ///   ::= !MDTemplateTypeParameter(name: "Ty", type: !1)
3654 bool LLParser::ParseMDTemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3655 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3656   OPTIONAL(name, MDStringField, );                                             \
3657   REQUIRED(type, MDField, );
3658   PARSE_MD_FIELDS();
3659 #undef VISIT_MD_FIELDS
3660
3661   Result =
3662       GET_OR_DISTINCT(MDTemplateTypeParameter, (Context, name.Val, type.Val));
3663   return false;
3664 }
3665
3666 /// ParseMDTemplateValueParameter:
3667 ///   ::= !MDTemplateValueParameter(tag: DW_TAG_template_value_parameter,
3668 ///                                 name: "V", type: !1, value: i32 7)
3669 bool LLParser::ParseMDTemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3670 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3671   OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter));      \
3672   OPTIONAL(name, MDStringField, );                                             \
3673   OPTIONAL(type, MDField, );                                                   \
3674   REQUIRED(value, MDField, );
3675   PARSE_MD_FIELDS();
3676 #undef VISIT_MD_FIELDS
3677
3678   Result = GET_OR_DISTINCT(MDTemplateValueParameter,
3679                            (Context, tag.Val, name.Val, type.Val, value.Val));
3680   return false;
3681 }
3682
3683 /// ParseMDGlobalVariable:
3684 ///   ::= !MDGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3685 ///                         file: !1, line: 7, type: !2, isLocal: false,
3686 ///                         isDefinition: true, variable: i32* @foo,
3687 ///                         declaration: !3)
3688 bool LLParser::ParseMDGlobalVariable(MDNode *&Result, bool IsDistinct) {
3689 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3690   REQUIRED(name, MDStringField, (/* AllowEmpty */ false));                     \
3691   OPTIONAL(scope, MDField, );                                                  \
3692   OPTIONAL(linkageName, MDStringField, );                                      \
3693   OPTIONAL(file, MDField, );                                                   \
3694   OPTIONAL(line, LineField, );                                                 \
3695   OPTIONAL(type, MDField, );                                                   \
3696   OPTIONAL(isLocal, MDBoolField, );                                            \
3697   OPTIONAL(isDefinition, MDBoolField, (true));                                 \
3698   OPTIONAL(variable, MDConstant, );                                            \
3699   OPTIONAL(declaration, MDField, );
3700   PARSE_MD_FIELDS();
3701 #undef VISIT_MD_FIELDS
3702
3703   Result = GET_OR_DISTINCT(MDGlobalVariable,
3704                            (Context, scope.Val, name.Val, linkageName.Val,
3705                             file.Val, line.Val, type.Val, isLocal.Val,
3706                             isDefinition.Val, variable.Val, declaration.Val));
3707   return false;
3708 }
3709
3710 /// ParseMDLocalVariable:
3711 ///   ::= !MDLocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
3712 ///                        file: !1, line: 7, type: !2, arg: 2, flags: 7)
3713 bool LLParser::ParseMDLocalVariable(MDNode *&Result, bool IsDistinct) {
3714 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3715   REQUIRED(tag, DwarfTagField, );                                              \
3716   REQUIRED(scope, MDField, (/* AllowNull */ false));                           \
3717   OPTIONAL(name, MDStringField, );                                             \
3718   OPTIONAL(file, MDField, );                                                   \
3719   OPTIONAL(line, LineField, );                                                 \
3720   OPTIONAL(type, MDField, );                                                   \
3721   OPTIONAL(arg, MDUnsignedField, (0, UINT8_MAX));                              \
3722   OPTIONAL(flags, DIFlagField, );
3723   PARSE_MD_FIELDS();
3724 #undef VISIT_MD_FIELDS
3725
3726   Result = GET_OR_DISTINCT(MDLocalVariable,
3727                            (Context, tag.Val, scope.Val, name.Val, file.Val,
3728                             line.Val, type.Val, arg.Val, flags.Val));
3729   return false;
3730 }
3731
3732 /// ParseMDExpression:
3733 ///   ::= !MDExpression(0, 7, -1)
3734 bool LLParser::ParseMDExpression(MDNode *&Result, bool IsDistinct) {
3735   assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3736   Lex.Lex();
3737
3738   if (ParseToken(lltok::lparen, "expected '(' here"))
3739     return true;
3740
3741   SmallVector<uint64_t, 8> Elements;
3742   if (Lex.getKind() != lltok::rparen)
3743     do {
3744       if (Lex.getKind() == lltok::DwarfOp) {
3745         if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3746           Lex.Lex();
3747           Elements.push_back(Op);
3748           continue;
3749         }
3750         return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3751       }
3752
3753       if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3754         return TokError("expected unsigned integer");
3755
3756       auto &U = Lex.getAPSIntVal();
3757       if (U.ugt(UINT64_MAX))
3758         return TokError("element too large, limit is " + Twine(UINT64_MAX));
3759       Elements.push_back(U.getZExtValue());
3760       Lex.Lex();
3761     } while (EatIfPresent(lltok::comma));
3762
3763   if (ParseToken(lltok::rparen, "expected ')' here"))
3764     return true;
3765
3766   Result = GET_OR_DISTINCT(MDExpression, (Context, Elements));
3767   return false;
3768 }
3769
3770 /// ParseMDObjCProperty:
3771 ///   ::= !MDObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3772 ///                       getter: "getFoo", attributes: 7, type: !2)
3773 bool LLParser::ParseMDObjCProperty(MDNode *&Result, bool IsDistinct) {
3774 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3775   OPTIONAL(name, MDStringField, );                                             \
3776   OPTIONAL(file, MDField, );                                                   \
3777   OPTIONAL(line, LineField, );                                                 \
3778   OPTIONAL(setter, MDStringField, );                                           \
3779   OPTIONAL(getter, MDStringField, );                                           \
3780   OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX));                      \
3781   OPTIONAL(type, MDField, );
3782   PARSE_MD_FIELDS();
3783 #undef VISIT_MD_FIELDS
3784
3785   Result = GET_OR_DISTINCT(MDObjCProperty,
3786                            (Context, name.Val, file.Val, line.Val, setter.Val,
3787                             getter.Val, attributes.Val, type.Val));
3788   return false;
3789 }
3790
3791 /// ParseMDImportedEntity:
3792 ///   ::= !MDImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3793 ///                         line: 7, name: "foo")
3794 bool LLParser::ParseMDImportedEntity(MDNode *&Result, bool IsDistinct) {
3795 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED)                                    \
3796   REQUIRED(tag, DwarfTagField, );                                              \
3797   REQUIRED(scope, MDField, );                                                  \
3798   OPTIONAL(entity, MDField, );                                                 \
3799   OPTIONAL(line, LineField, );                                                 \
3800   OPTIONAL(name, MDStringField, );
3801   PARSE_MD_FIELDS();
3802 #undef VISIT_MD_FIELDS
3803
3804   Result = GET_OR_DISTINCT(MDImportedEntity, (Context, tag.Val, scope.Val,
3805                                               entity.Val, line.Val, name.Val));
3806   return false;
3807 }
3808
3809 #undef PARSE_MD_FIELD
3810 #undef NOP_FIELD
3811 #undef REQUIRE_FIELD
3812 #undef DECLARE_FIELD
3813
3814 /// ParseMetadataAsValue
3815 ///  ::= metadata i32 %local
3816 ///  ::= metadata i32 @global
3817 ///  ::= metadata i32 7
3818 ///  ::= metadata !0
3819 ///  ::= metadata !{...}
3820 ///  ::= metadata !"string"
3821 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3822   // Note: the type 'metadata' has already been parsed.
3823   Metadata *MD;
3824   if (ParseMetadata(MD, &PFS))
3825     return true;
3826
3827   V = MetadataAsValue::get(Context, MD);
3828   return false;
3829 }
3830
3831 /// ParseValueAsMetadata
3832 ///  ::= i32 %local
3833 ///  ::= i32 @global
3834 ///  ::= i32 7
3835 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3836                                     PerFunctionState *PFS) {
3837   Type *Ty;
3838   LocTy Loc;
3839   if (ParseType(Ty, TypeMsg, Loc))
3840     return true;
3841   if (Ty->isMetadataTy())
3842     return Error(Loc, "invalid metadata-value-metadata roundtrip");
3843
3844   Value *V;
3845   if (ParseValue(Ty, V, PFS))
3846     return true;
3847
3848   MD = ValueAsMetadata::get(V);
3849   return false;
3850 }
3851
3852 /// ParseMetadata
3853 ///  ::= i32 %local
3854 ///  ::= i32 @global
3855 ///  ::= i32 7
3856 ///  ::= !42
3857 ///  ::= !{...}
3858 ///  ::= !"string"
3859 ///  ::= !MDLocation(...)
3860 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3861   if (Lex.getKind() == lltok::MetadataVar) {
3862     MDNode *N;
3863     if (ParseSpecializedMDNode(N))
3864       return true;
3865     MD = N;
3866     return false;
3867   }
3868
3869   // ValueAsMetadata:
3870   // <type> <value>
3871   if (Lex.getKind() != lltok::exclaim)
3872     return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3873
3874   // '!'.
3875   assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3876   Lex.Lex();
3877
3878   // MDString:
3879   //   ::= '!' STRINGCONSTANT
3880   if (Lex.getKind() == lltok::StringConstant) {
3881     MDString *S;
3882     if (ParseMDString(S))
3883       return true;
3884     MD = S;
3885     return false;
3886   }
3887
3888   // MDNode:
3889   // !{ ... }
3890   // !7
3891   MDNode *N;
3892   if (ParseMDNodeTail(N))
3893     return true;
3894   MD = N;
3895   return false;
3896 }
3897
3898
3899 //===----------------------------------------------------------------------===//
3900 // Function Parsing.
3901 //===----------------------------------------------------------------------===//
3902
3903 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3904                                    PerFunctionState *PFS) {
3905   if (Ty->isFunctionTy())
3906     return Error(ID.Loc, "functions are not values, refer to them as pointers");
3907
3908   switch (ID.Kind) {
3909   case ValID::t_LocalID:
3910     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3911     V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3912     return V == nullptr;
3913   case ValID::t_LocalName:
3914     if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3915     V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3916     return V == nullptr;
3917   case ValID::t_InlineAsm: {
3918     PointerType *PTy = dyn_cast<PointerType>(Ty);
3919     FunctionType *FTy =
3920       PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3921     if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3922       return Error(ID.Loc, "invalid type for inline asm constraint string");
3923     V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3924                        (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3925     return false;
3926   }
3927   case ValID::t_GlobalName:
3928     V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3929     return V == nullptr;
3930   case ValID::t_GlobalID:
3931     V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3932     return V == nullptr;
3933   case ValID::t_APSInt:
3934     if (!Ty->isIntegerTy())
3935       return Error(ID.Loc, "integer constant must have integer type");
3936     ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3937     V = ConstantInt::get(Context, ID.APSIntVal);
3938     return false;
3939   case ValID::t_APFloat:
3940     if (!Ty->isFloatingPointTy() ||
3941         !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3942       return Error(ID.Loc, "floating point constant invalid for type");
3943
3944     // The lexer has no type info, so builds all half, float, and double FP
3945     // constants as double.  Fix this here.  Long double does not need this.
3946     if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3947       bool Ignored;
3948       if (Ty->isHalfTy())
3949         ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3950                               &Ignored);
3951       else if (Ty->isFloatTy())
3952         ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3953                               &Ignored);
3954     }
3955     V = ConstantFP::get(Context, ID.APFloatVal);
3956
3957     if (V->getType() != Ty)
3958       return Error(ID.Loc, "floating point constant does not have type '" +
3959                    getTypeString(Ty) + "'");
3960
3961     return false;
3962   case ValID::t_Null:
3963     if (!Ty->isPointerTy())
3964       return Error(ID.Loc, "null must be a pointer type");
3965     V = ConstantPointerNull::get(cast<PointerType>(Ty));
3966     return false;
3967   case ValID::t_Undef:
3968     // FIXME: LabelTy should not be a first-class type.
3969     if (!Ty->isFirstClassType() || Ty->isLabelTy())
3970       return Error(ID.Loc, "invalid type for undef constant");
3971     V = UndefValue::get(Ty);
3972     return false;
3973   case ValID::t_EmptyArray:
3974     if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3975       return Error(ID.Loc, "invalid empty array initializer");
3976     V = UndefValue::get(Ty);
3977     return false;
3978   case ValID::t_Zero:
3979     // FIXME: LabelTy should not be a first-class type.
3980     if (!Ty->isFirstClassType() || Ty->isLabelTy())
3981       return Error(ID.Loc, "invalid type for null constant");
3982     V = Constant::getNullValue(Ty);
3983     return false;
3984   case ValID::t_Constant:
3985     if (ID.ConstantVal->getType() != Ty)
3986       return Error(ID.Loc, "constant expression type mismatch");
3987
3988     V = ID.ConstantVal;
3989     return false;
3990   case ValID::t_ConstantStruct:
3991   case ValID::t_PackedConstantStruct:
3992     if (StructType *ST = dyn_cast<StructType>(Ty)) {
3993       if (ST->getNumElements() != ID.UIntVal)
3994         return Error(ID.Loc,
3995                      "initializer with struct type has wrong # elements");
3996       if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3997         return Error(ID.Loc, "packed'ness of initializer and type don't match");
3998
3999       // Verify that the elements are compatible with the structtype.
4000       for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4001         if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4002           return Error(ID.Loc, "element " + Twine(i) +
4003                     " of struct initializer doesn't match struct element type");
4004
4005       V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4006                                                ID.UIntVal));
4007     } else
4008       return Error(ID.Loc, "constant expression type mismatch");
4009     return false;
4010   }
4011   llvm_unreachable("Invalid ValID");
4012 }
4013
4014 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4015   V = nullptr;
4016   ValID ID;
4017   return ParseValID(ID, PFS) ||
4018          ConvertValIDToValue(Ty, ID, V, PFS);
4019 }
4020
4021 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4022   Type *Ty = nullptr;
4023   return ParseType(Ty) ||
4024          ParseValue(Ty, V, PFS);
4025 }
4026
4027 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4028                                       PerFunctionState &PFS) {
4029   Value *V;
4030   Loc = Lex.getLoc();
4031   if (ParseTypeAndValue(V, PFS)) return true;
4032   if (!isa<BasicBlock>(V))
4033     return Error(Loc, "expected a basic block");
4034   BB = cast<BasicBlock>(V);
4035   return false;
4036 }
4037
4038
4039 /// FunctionHeader
4040 ///   ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4041 ///       OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4042 ///       OptionalAlign OptGC OptionalPrefix OptionalPrologue
4043 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4044   // Parse the linkage.
4045   LocTy LinkageLoc = Lex.getLoc();
4046   unsigned Linkage;
4047
4048   unsigned Visibility;
4049   unsigned DLLStorageClass;
4050   AttrBuilder RetAttrs;
4051   unsigned CC;
4052   Type *RetType = nullptr;
4053   LocTy RetTypeLoc = Lex.getLoc();
4054   if (ParseOptionalLinkage(Linkage) ||
4055       ParseOptionalVisibility(Visibility) ||
4056       ParseOptionalDLLStorageClass(DLLStorageClass) ||
4057       ParseOptionalCallingConv(CC) ||
4058       ParseOptionalReturnAttrs(RetAttrs) ||
4059       ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4060     return true;
4061
4062   // Verify that the linkage is ok.
4063   switch ((GlobalValue::LinkageTypes)Linkage) {
4064   case GlobalValue::ExternalLinkage:
4065     break; // always ok.
4066   case GlobalValue::ExternalWeakLinkage:
4067     if (isDefine)
4068       return Error(LinkageLoc, "invalid linkage for function definition");
4069     break;
4070   case GlobalValue::PrivateLinkage:
4071   case GlobalValue::InternalLinkage:
4072   case GlobalValue::AvailableExternallyLinkage:
4073   case GlobalValue::LinkOnceAnyLinkage:
4074   case GlobalValue::LinkOnceODRLinkage:
4075   case GlobalValue::WeakAnyLinkage:
4076   case GlobalValue::WeakODRLinkage:
4077     if (!isDefine)
4078       return Error(LinkageLoc, "invalid linkage for function declaration");
4079     break;
4080   case GlobalValue::AppendingLinkage:
4081   case GlobalValue::CommonLinkage:
4082     return Error(LinkageLoc, "invalid function linkage type");
4083   }
4084
4085   if (!isValidVisibilityForLinkage(Visibility, Linkage))
4086     return Error(LinkageLoc,
4087                  "symbol with local linkage must have default visibility");
4088
4089   if (!FunctionType::isValidReturnType(RetType))
4090     return Error(RetTypeLoc, "invalid function return type");
4091
4092   LocTy NameLoc = Lex.getLoc();
4093
4094   std::string FunctionName;
4095   if (Lex.getKind() == lltok::GlobalVar) {
4096     FunctionName = Lex.getStrVal();
4097   } else if (Lex.getKind() == lltok::GlobalID) {     // @42 is ok.
4098     unsigned NameID = Lex.getUIntVal();
4099
4100     if (NameID != NumberedVals.size())
4101       return TokError("function expected to be numbered '%" +
4102                       Twine(NumberedVals.size()) + "'");
4103   } else {
4104     return TokError("expected function name");
4105   }
4106
4107   Lex.Lex();
4108
4109   if (Lex.getKind() != lltok::lparen)
4110     return TokError("expected '(' in function argument list");
4111
4112   SmallVector<ArgInfo, 8> ArgList;
4113   bool isVarArg;
4114   AttrBuilder FuncAttrs;
4115   std::vector<unsigned> FwdRefAttrGrps;
4116   LocTy BuiltinLoc;
4117   std::string Section;
4118   unsigned Alignment;
4119   std::string GC;
4120   bool UnnamedAddr;
4121   LocTy UnnamedAddrLoc;
4122   Constant *Prefix = nullptr;
4123   Constant *Prologue = nullptr;
4124   Comdat *C;
4125
4126   if (ParseArgumentList(ArgList, isVarArg) ||
4127       ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4128                          &UnnamedAddrLoc) ||
4129       ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4130                                  BuiltinLoc) ||
4131       (EatIfPresent(lltok::kw_section) &&
4132        ParseStringConstant(Section)) ||
4133       parseOptionalComdat(FunctionName, C) ||
4134       ParseOptionalAlignment(Alignment) ||
4135       (EatIfPresent(lltok::kw_gc) &&
4136        ParseStringConstant(GC)) ||
4137       (EatIfPresent(lltok::kw_prefix) &&
4138        ParseGlobalTypeAndValue(Prefix)) ||
4139       (EatIfPresent(lltok::kw_prologue) &&
4140        ParseGlobalTypeAndValue(Prologue)))
4141     return true;
4142
4143   if (FuncAttrs.contains(Attribute::Builtin))
4144     return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4145
4146   // If the alignment was parsed as an attribute, move to the alignment field.
4147   if (FuncAttrs.hasAlignmentAttr()) {
4148     Alignment = FuncAttrs.getAlignment();
4149     FuncAttrs.removeAttribute(Attribute::Alignment);
4150   }
4151
4152   // Okay, if we got here, the function is syntactically valid.  Convert types
4153   // and do semantic checks.
4154   std::vector<Type*> ParamTypeList;
4155   SmallVector<AttributeSet, 8> Attrs;
4156
4157   if (RetAttrs.hasAttributes())
4158     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4159                                       AttributeSet::ReturnIndex,
4160                                       RetAttrs));
4161
4162   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4163     ParamTypeList.push_back(ArgList[i].Ty);
4164     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4165       AttrBuilder B(ArgList[i].Attrs, i + 1);
4166       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4167     }
4168   }
4169
4170   if (FuncAttrs.hasAttributes())
4171     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4172                                       AttributeSet::FunctionIndex,
4173                                       FuncAttrs));
4174
4175   AttributeSet PAL = AttributeSet::get(Context, Attrs);
4176
4177   if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4178     return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4179
4180   FunctionType *FT =
4181     FunctionType::get(RetType, ParamTypeList, isVarArg);
4182   PointerType *PFT = PointerType::getUnqual(FT);
4183
4184   Fn = nullptr;
4185   if (!FunctionName.empty()) {
4186     // If this was a definition of a forward reference, remove the definition
4187     // from the forward reference table and fill in the forward ref.
4188     std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4189       ForwardRefVals.find(FunctionName);
4190     if (FRVI != ForwardRefVals.end()) {
4191       Fn = M->getFunction(FunctionName);
4192       if (!Fn)
4193         return Error(FRVI->second.second, "invalid forward reference to "
4194                      "function as global value!");
4195       if (Fn->getType() != PFT)
4196         return Error(FRVI->second.second, "invalid forward reference to "
4197                      "function '" + FunctionName + "' with wrong type!");
4198
4199       ForwardRefVals.erase(FRVI);
4200     } else if ((Fn = M->getFunction(FunctionName))) {
4201       // Reject redefinitions.
4202       return Error(NameLoc, "invalid redefinition of function '" +
4203                    FunctionName + "'");
4204     } else if (M->getNamedValue(FunctionName)) {
4205       return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4206     }
4207
4208   } else {
4209     // If this is a definition of a forward referenced function, make sure the
4210     // types agree.
4211     std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4212       = ForwardRefValIDs.find(NumberedVals.size());
4213     if (I != ForwardRefValIDs.end()) {
4214       Fn = cast<Function>(I->second.first);
4215       if (Fn->getType() != PFT)
4216         return Error(NameLoc, "type of definition and forward reference of '@" +
4217                      Twine(NumberedVals.size()) + "' disagree");
4218       ForwardRefValIDs.erase(I);
4219     }
4220   }
4221
4222   if (!Fn)
4223     Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4224   else // Move the forward-reference to the correct spot in the module.
4225     M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4226
4227   if (FunctionName.empty())
4228     NumberedVals.push_back(Fn);
4229
4230   Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4231   Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4232   Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4233   Fn->setCallingConv(CC);
4234   Fn->setAttributes(PAL);
4235   Fn->setUnnamedAddr(UnnamedAddr);
4236   Fn->setAlignment(Alignment);
4237   Fn->setSection(Section);
4238   Fn->setComdat(C);
4239   if (!GC.empty()) Fn->setGC(GC.c_str());
4240   Fn->setPrefixData(Prefix);
4241   Fn->setPrologueData(Prologue);
4242   ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4243
4244   // Add all of the arguments we parsed to the function.
4245   Function::arg_iterator ArgIt = Fn->arg_begin();
4246   for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4247     // If the argument has a name, insert it into the argument symbol table.
4248     if (ArgList[i].Name.empty()) continue;
4249
4250     // Set the name, if it conflicted, it will be auto-renamed.
4251     ArgIt->setName(ArgList[i].Name);
4252
4253     if (ArgIt->getName() != ArgList[i].Name)
4254       return Error(ArgList[i].Loc, "redefinition of argument '%" +
4255                    ArgList[i].Name + "'");
4256   }
4257
4258   if (isDefine)
4259     return false;
4260
4261   // Check the declaration has no block address forward references.
4262   ValID ID;
4263   if (FunctionName.empty()) {
4264     ID.Kind = ValID::t_GlobalID;
4265     ID.UIntVal = NumberedVals.size() - 1;
4266   } else {
4267     ID.Kind = ValID::t_GlobalName;
4268     ID.StrVal = FunctionName;
4269   }
4270   auto Blocks = ForwardRefBlockAddresses.find(ID);
4271   if (Blocks != ForwardRefBlockAddresses.end())
4272     return Error(Blocks->first.Loc,
4273                  "cannot take blockaddress inside a declaration");
4274   return false;
4275 }
4276
4277 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4278   ValID ID;
4279   if (FunctionNumber == -1) {
4280     ID.Kind = ValID::t_GlobalName;
4281     ID.StrVal = F.getName();
4282   } else {
4283     ID.Kind = ValID::t_GlobalID;
4284     ID.UIntVal = FunctionNumber;
4285   }
4286
4287   auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4288   if (Blocks == P.ForwardRefBlockAddresses.end())
4289     return false;
4290
4291   for (const auto &I : Blocks->second) {
4292     const ValID &BBID = I.first;
4293     GlobalValue *GV = I.second;
4294
4295     assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4296            "Expected local id or name");
4297     BasicBlock *BB;
4298     if (BBID.Kind == ValID::t_LocalName)
4299       BB = GetBB(BBID.StrVal, BBID.Loc);
4300     else
4301       BB = GetBB(BBID.UIntVal, BBID.Loc);
4302     if (!BB)
4303       return P.Error(BBID.Loc, "referenced value is not a basic block");
4304
4305     GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4306     GV->eraseFromParent();
4307   }
4308
4309   P.ForwardRefBlockAddresses.erase(Blocks);
4310   return false;
4311 }
4312
4313 /// ParseFunctionBody
4314 ///   ::= '{' BasicBlock+ UseListOrderDirective* '}'
4315 bool LLParser::ParseFunctionBody(Function &Fn) {
4316   if (Lex.getKind() != lltok::lbrace)
4317     return TokError("expected '{' in function body");
4318   Lex.Lex();  // eat the {.
4319
4320   int FunctionNumber = -1;
4321   if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4322
4323   PerFunctionState PFS(*this, Fn, FunctionNumber);
4324
4325   // Resolve block addresses and allow basic blocks to be forward-declared
4326   // within this function.
4327   if (PFS.resolveForwardRefBlockAddresses())
4328     return true;
4329   SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4330
4331   // We need at least one basic block.
4332   if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4333     return TokError("function body requires at least one basic block");
4334
4335   while (Lex.getKind() != lltok::rbrace &&
4336          Lex.getKind() != lltok::kw_uselistorder)
4337     if (ParseBasicBlock(PFS)) return true;
4338
4339   while (Lex.getKind() != lltok::rbrace)
4340     if (ParseUseListOrder(&PFS))
4341       return true;
4342
4343   // Eat the }.
4344   Lex.Lex();
4345
4346   // Verify function is ok.
4347   return PFS.FinishFunction();
4348 }
4349
4350 /// ParseBasicBlock
4351 ///   ::= LabelStr? Instruction*
4352 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4353   // If this basic block starts out with a name, remember it.
4354   std::string Name;
4355   LocTy NameLoc = Lex.getLoc();
4356   if (Lex.getKind() == lltok::LabelStr) {
4357     Name = Lex.getStrVal();
4358     Lex.Lex();
4359   }
4360
4361   BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4362   if (!BB)
4363     return Error(NameLoc,
4364                  "unable to create block named '" + Name + "'");
4365
4366   std::string NameStr;
4367
4368   // Parse the instructions in this block until we get a terminator.
4369   Instruction *Inst;
4370   do {
4371     // This instruction may have three possibilities for a name: a) none
4372     // specified, b) name specified "%foo =", c) number specified: "%4 =".
4373     LocTy NameLoc = Lex.getLoc();
4374     int NameID = -1;
4375     NameStr = "";
4376
4377     if (Lex.getKind() == lltok::LocalVarID) {
4378       NameID = Lex.getUIntVal();
4379       Lex.Lex();
4380       if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4381         return true;
4382     } else if (Lex.getKind() == lltok::LocalVar) {
4383       NameStr = Lex.getStrVal();
4384       Lex.Lex();
4385       if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4386         return true;
4387     }
4388
4389     switch (ParseInstruction(Inst, BB, PFS)) {
4390     default: llvm_unreachable("Unknown ParseInstruction result!");
4391     case InstError: return true;
4392     case InstNormal:
4393       BB->getInstList().push_back(Inst);
4394
4395       // With a normal result, we check to see if the instruction is followed by
4396       // a comma and metadata.
4397       if (EatIfPresent(lltok::comma))
4398         if (ParseInstructionMetadata(*Inst))
4399           return true;
4400       break;
4401     case InstExtraComma:
4402       BB->getInstList().push_back(Inst);
4403
4404       // If the instruction parser ate an extra comma at the end of it, it
4405       // *must* be followed by metadata.
4406       if (ParseInstructionMetadata(*Inst))
4407         return true;
4408       break;
4409     }
4410
4411     // Set the name on the instruction.
4412     if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4413   } while (!isa<TerminatorInst>(Inst));
4414
4415   return false;
4416 }
4417
4418 //===----------------------------------------------------------------------===//
4419 // Instruction Parsing.
4420 //===----------------------------------------------------------------------===//
4421
4422 /// ParseInstruction - Parse one of the many different instructions.
4423 ///
4424 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4425                                PerFunctionState &PFS) {
4426   lltok::Kind Token = Lex.getKind();
4427   if (Token == lltok::Eof)
4428     return TokError("found end of file when expecting more instructions");
4429   LocTy Loc = Lex.getLoc();
4430   unsigned KeywordVal = Lex.getUIntVal();
4431   Lex.Lex();  // Eat the keyword.
4432
4433   switch (Token) {
4434   default:                    return Error(Loc, "expected instruction opcode");
4435   // Terminator Instructions.
4436   case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4437   case lltok::kw_ret:         return ParseRet(Inst, BB, PFS);
4438   case lltok::kw_br:          return ParseBr(Inst, PFS);
4439   case lltok::kw_switch:      return ParseSwitch(Inst, PFS);
4440   case lltok::kw_indirectbr:  return ParseIndirectBr(Inst, PFS);
4441   case lltok::kw_invoke:      return ParseInvoke(Inst, PFS);
4442   case lltok::kw_resume:      return ParseResume(Inst, PFS);
4443   // Binary Operators.
4444   case lltok::kw_add:
4445   case lltok::kw_sub:
4446   case lltok::kw_mul:
4447   case lltok::kw_shl: {
4448     bool NUW = EatIfPresent(lltok::kw_nuw);
4449     bool NSW = EatIfPresent(lltok::kw_nsw);
4450     if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4451
4452     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4453
4454     if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4455     if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4456     return false;
4457   }
4458   case lltok::kw_fadd:
4459   case lltok::kw_fsub:
4460   case lltok::kw_fmul:
4461   case lltok::kw_fdiv:
4462   case lltok::kw_frem: {
4463     FastMathFlags FMF = EatFastMathFlagsIfPresent();
4464     int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4465     if (Res != 0)
4466       return Res;
4467     if (FMF.any())
4468       Inst->setFastMathFlags(FMF);
4469     return 0;
4470   }
4471
4472   case lltok::kw_sdiv:
4473   case lltok::kw_udiv:
4474   case lltok::kw_lshr:
4475   case lltok::kw_ashr: {
4476     bool Exact = EatIfPresent(lltok::kw_exact);
4477
4478     if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4479     if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4480     return false;
4481   }
4482
4483   case lltok::kw_urem:
4484   case lltok::kw_srem:   return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4485   case lltok::kw_and:
4486   case lltok::kw_or:
4487   case lltok::kw_xor:    return ParseLogical(Inst, PFS, KeywordVal);
4488   case lltok::kw_icmp:
4489   case lltok::kw_fcmp:   return ParseCompare(Inst, PFS, KeywordVal);
4490   // Casts.
4491   case lltok::kw_trunc:
4492   case lltok::kw_zext:
4493   case lltok::kw_sext:
4494   case lltok::kw_fptrunc:
4495   case lltok::kw_fpext:
4496   case lltok::kw_bitcast:
4497   case lltok::kw_addrspacecast:
4498   case lltok::kw_uitofp:
4499   case lltok::kw_sitofp:
4500   case lltok::kw_fptoui:
4501   case lltok::kw_fptosi:
4502   case lltok::kw_inttoptr:
4503   case lltok::kw_ptrtoint:       return ParseCast(Inst, PFS, KeywordVal);
4504   // Other.
4505   case lltok::kw_select:         return ParseSelect(Inst, PFS);
4506   case lltok::kw_va_arg:         return ParseVA_Arg(Inst, PFS);
4507   case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4508   case lltok::kw_insertelement:  return ParseInsertElement(Inst, PFS);
4509   case lltok::kw_shufflevector:  return ParseShuffleVector(Inst, PFS);
4510   case lltok::kw_phi:            return ParsePHI(Inst, PFS);
4511   case lltok::kw_landingpad:     return ParseLandingPad(Inst, PFS);
4512   // Call.
4513   case lltok::kw_call:     return ParseCall(Inst, PFS, CallInst::TCK_None);
4514   case lltok::kw_tail:     return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4515   case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4516   // Memory.
4517   case lltok::kw_alloca:         return ParseAlloc(Inst, PFS);
4518   case lltok::kw_load:           return ParseLoad(Inst, PFS);
4519   case lltok::kw_store:          return ParseStore(Inst, PFS);
4520   case lltok::kw_cmpxchg:        return ParseCmpXchg(Inst, PFS);
4521   case lltok::kw_atomicrmw:      return ParseAtomicRMW(Inst, PFS);
4522   case lltok::kw_fence:          return ParseFence(Inst, PFS);
4523   case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4524   case lltok::kw_extractvalue:  return ParseExtractValue(Inst, PFS);
4525   case lltok::kw_insertvalue:   return ParseInsertValue(Inst, PFS);
4526   }
4527 }
4528
4529 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4530 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4531   if (Opc == Instruction::FCmp) {
4532     switch (Lex.getKind()) {
4533     default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4534     case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4535     case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4536     case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4537     case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4538     case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4539     case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4540     case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4541     case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4542     case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4543     case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4544     case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4545     case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4546     case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4547     case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4548     case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4549     case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4550     }
4551   } else {
4552     switch (Lex.getKind()) {
4553     default: return TokError("expected icmp predicate (e.g. 'eq')");
4554     case lltok::kw_eq:  P = CmpInst::ICMP_EQ; break;
4555     case lltok::kw_ne:  P = CmpInst::ICMP_NE; break;
4556     case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4557     case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4558     case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4559     case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4560     case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4561     case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4562     case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4563     case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4564     }
4565   }
4566   Lex.Lex();
4567   return false;
4568 }
4569
4570 //===----------------------------------------------------------------------===//
4571 // Terminator Instructions.
4572 //===----------------------------------------------------------------------===//
4573
4574 /// ParseRet - Parse a return instruction.
4575 ///   ::= 'ret' void (',' !dbg, !1)*
4576 ///   ::= 'ret' TypeAndValue (',' !dbg, !1)*
4577 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4578                         PerFunctionState &PFS) {
4579   SMLoc TypeLoc = Lex.getLoc();
4580   Type *Ty = nullptr;
4581   if (ParseType(Ty, true /*void allowed*/)) return true;
4582
4583   Type *ResType = PFS.getFunction().getReturnType();
4584
4585   if (Ty->isVoidTy()) {
4586     if (!ResType->isVoidTy())
4587       return Error(TypeLoc, "value doesn't match function result type '" +
4588                    getTypeString(ResType) + "'");
4589
4590     Inst = ReturnInst::Create(Context);
4591     return false;
4592   }
4593
4594   Value *RV;
4595   if (ParseValue(Ty, RV, PFS)) return true;
4596
4597   if (ResType != RV->getType())
4598     return Error(TypeLoc, "value doesn't match function result type '" +
4599                  getTypeString(ResType) + "'");
4600
4601   Inst = ReturnInst::Create(Context, RV);
4602   return false;
4603 }
4604
4605
4606 /// ParseBr
4607 ///   ::= 'br' TypeAndValue
4608 ///   ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4609 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4610   LocTy Loc, Loc2;
4611   Value *Op0;
4612   BasicBlock *Op1, *Op2;
4613   if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4614
4615   if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4616     Inst = BranchInst::Create(BB);
4617     return false;
4618   }
4619
4620   if (Op0->getType() != Type::getInt1Ty(Context))
4621     return Error(Loc, "branch condition must have 'i1' type");
4622
4623   if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4624       ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4625       ParseToken(lltok::comma, "expected ',' after true destination") ||
4626       ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4627     return true;
4628
4629   Inst = BranchInst::Create(Op1, Op2, Op0);
4630   return false;
4631 }
4632
4633 /// ParseSwitch
4634 ///  Instruction
4635 ///    ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4636 ///  JumpTable
4637 ///    ::= (TypeAndValue ',' TypeAndValue)*
4638 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4639   LocTy CondLoc, BBLoc;
4640   Value *Cond;
4641   BasicBlock *DefaultBB;
4642   if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4643       ParseToken(lltok::comma, "expected ',' after switch condition") ||
4644       ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4645       ParseToken(lltok::lsquare, "expected '[' with switch table"))
4646     return true;
4647
4648   if (!Cond->getType()->isIntegerTy())
4649     return Error(CondLoc, "switch condition must have integer type");
4650
4651   // Parse the jump table pairs.
4652   SmallPtrSet<Value*, 32> SeenCases;
4653   SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4654   while (Lex.getKind() != lltok::rsquare) {
4655     Value *Constant;
4656     BasicBlock *DestBB;
4657
4658     if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4659         ParseToken(lltok::comma, "expected ',' after case value") ||
4660         ParseTypeAndBasicBlock(DestBB, PFS))
4661       return true;
4662
4663     if (!SeenCases.insert(Constant).second)
4664       return Error(CondLoc, "duplicate case value in switch");
4665     if (!isa<ConstantInt>(Constant))
4666       return Error(CondLoc, "case value is not a constant integer");
4667
4668     Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4669   }
4670
4671   Lex.Lex();  // Eat the ']'.
4672
4673   SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4674   for (unsigned i = 0, e = Table.size(); i != e; ++i)
4675     SI->addCase(Table[i].first, Table[i].second);
4676   Inst = SI;
4677   return false;
4678 }
4679
4680 /// ParseIndirectBr
4681 ///  Instruction
4682 ///    ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4683 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4684   LocTy AddrLoc;
4685   Value *Address;
4686   if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4687       ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4688       ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4689     return true;
4690
4691   if (!Address->getType()->isPointerTy())
4692     return Error(AddrLoc, "indirectbr address must have pointer type");
4693
4694   // Parse the destination list.
4695   SmallVector<BasicBlock*, 16> DestList;
4696
4697   if (Lex.getKind() != lltok::rsquare) {
4698     BasicBlock *DestBB;
4699     if (ParseTypeAndBasicBlock(DestBB, PFS))
4700       return true;
4701     DestList.push_back(DestBB);
4702
4703     while (EatIfPresent(lltok::comma)) {
4704       if (ParseTypeAndBasicBlock(DestBB, PFS))
4705         return true;
4706       DestList.push_back(DestBB);
4707     }
4708   }
4709
4710   if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4711     return true;
4712
4713   IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4714   for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4715     IBI->addDestination(DestList[i]);
4716   Inst = IBI;
4717   return false;
4718 }
4719
4720
4721 /// ParseInvoke
4722 ///   ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4723 ///       OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4724 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4725   LocTy CallLoc = Lex.getLoc();
4726   AttrBuilder RetAttrs, FnAttrs;
4727   std::vector<unsigned> FwdRefAttrGrps;
4728   LocTy NoBuiltinLoc;
4729   unsigned CC;
4730   Type *RetType = nullptr;
4731   LocTy RetTypeLoc;
4732   ValID CalleeID;
4733   SmallVector<ParamInfo, 16> ArgList;
4734
4735   BasicBlock *NormalBB, *UnwindBB;
4736   if (ParseOptionalCallingConv(CC) ||
4737       ParseOptionalReturnAttrs(RetAttrs) ||
4738       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4739       ParseValID(CalleeID) ||
4740       ParseParameterList(ArgList, PFS) ||
4741       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4742                                  NoBuiltinLoc) ||
4743       ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4744       ParseTypeAndBasicBlock(NormalBB, PFS) ||
4745       ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4746       ParseTypeAndBasicBlock(UnwindBB, PFS))
4747     return true;
4748
4749   // If RetType is a non-function pointer type, then this is the short syntax
4750   // for the call, which means that RetType is just the return type.  Infer the
4751   // rest of the function argument types from the arguments that are present.
4752   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4753   if (!Ty) {
4754     // Pull out the types of all of the arguments...
4755     std::vector<Type*> ParamTypes;
4756     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4757       ParamTypes.push_back(ArgList[i].V->getType());
4758
4759     if (!FunctionType::isValidReturnType(RetType))
4760       return Error(RetTypeLoc, "Invalid result type for LLVM function");
4761
4762     Ty = FunctionType::get(RetType, ParamTypes, false);
4763   }
4764
4765   // Look up the callee.
4766   Value *Callee;
4767   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4768     return true;
4769
4770   // Set up the Attribute for the function.
4771   SmallVector<AttributeSet, 8> Attrs;
4772   if (RetAttrs.hasAttributes())
4773     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4774                                       AttributeSet::ReturnIndex,
4775                                       RetAttrs));
4776
4777   SmallVector<Value*, 8> Args;
4778
4779   // Loop through FunctionType's arguments and ensure they are specified
4780   // correctly.  Also, gather any parameter attributes.
4781   FunctionType::param_iterator I = Ty->param_begin();
4782   FunctionType::param_iterator E = Ty->param_end();
4783   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4784     Type *ExpectedTy = nullptr;
4785     if (I != E) {
4786       ExpectedTy = *I++;
4787     } else if (!Ty->isVarArg()) {
4788       return Error(ArgList[i].Loc, "too many arguments specified");
4789     }
4790
4791     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4792       return Error(ArgList[i].Loc, "argument is not of expected type '" +
4793                    getTypeString(ExpectedTy) + "'");
4794     Args.push_back(ArgList[i].V);
4795     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4796       AttrBuilder B(ArgList[i].Attrs, i + 1);
4797       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4798     }
4799   }
4800
4801   if (I != E)
4802     return Error(CallLoc, "not enough parameters specified for call");
4803
4804   if (FnAttrs.hasAttributes()) {
4805     if (FnAttrs.hasAlignmentAttr())
4806       return Error(CallLoc, "invoke instructions may not have an alignment");
4807
4808     Attrs.push_back(AttributeSet::get(RetType->getContext(),
4809                                       AttributeSet::FunctionIndex,
4810                                       FnAttrs));
4811   }
4812
4813   // Finish off the Attribute and check them
4814   AttributeSet PAL = AttributeSet::get(Context, Attrs);
4815
4816   InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
4817   II->setCallingConv(CC);
4818   II->setAttributes(PAL);
4819   ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4820   Inst = II;
4821   return false;
4822 }
4823
4824 /// ParseResume
4825 ///   ::= 'resume' TypeAndValue
4826 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4827   Value *Exn; LocTy ExnLoc;
4828   if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4829     return true;
4830
4831   ResumeInst *RI = ResumeInst::Create(Exn);
4832   Inst = RI;
4833   return false;
4834 }
4835
4836 //===----------------------------------------------------------------------===//
4837 // Binary Operators.
4838 //===----------------------------------------------------------------------===//
4839
4840 /// ParseArithmetic
4841 ///  ::= ArithmeticOps TypeAndValue ',' Value
4842 ///
4843 /// If OperandType is 0, then any FP or integer operand is allowed.  If it is 1,
4844 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4845 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4846                                unsigned Opc, unsigned OperandType) {
4847   LocTy Loc; Value *LHS, *RHS;
4848   if (ParseTypeAndValue(LHS, Loc, PFS) ||
4849       ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4850       ParseValue(LHS->getType(), RHS, PFS))
4851     return true;
4852
4853   bool Valid;
4854   switch (OperandType) {
4855   default: llvm_unreachable("Unknown operand type!");
4856   case 0: // int or FP.
4857     Valid = LHS->getType()->isIntOrIntVectorTy() ||
4858             LHS->getType()->isFPOrFPVectorTy();
4859     break;
4860   case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4861   case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4862   }
4863
4864   if (!Valid)
4865     return Error(Loc, "invalid operand type for instruction");
4866
4867   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4868   return false;
4869 }
4870
4871 /// ParseLogical
4872 ///  ::= ArithmeticOps TypeAndValue ',' Value {
4873 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4874                             unsigned Opc) {
4875   LocTy Loc; Value *LHS, *RHS;
4876   if (ParseTypeAndValue(LHS, Loc, PFS) ||
4877       ParseToken(lltok::comma, "expected ',' in logical operation") ||
4878       ParseValue(LHS->getType(), RHS, PFS))
4879     return true;
4880
4881   if (!LHS->getType()->isIntOrIntVectorTy())
4882     return Error(Loc,"instruction requires integer or integer vector operands");
4883
4884   Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4885   return false;
4886 }
4887
4888
4889 /// ParseCompare
4890 ///  ::= 'icmp' IPredicates TypeAndValue ',' Value
4891 ///  ::= 'fcmp' FPredicates TypeAndValue ',' Value
4892 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4893                             unsigned Opc) {
4894   // Parse the integer/fp comparison predicate.
4895   LocTy Loc;
4896   unsigned Pred;
4897   Value *LHS, *RHS;
4898   if (ParseCmpPredicate(Pred, Opc) ||
4899       ParseTypeAndValue(LHS, Loc, PFS) ||
4900       ParseToken(lltok::comma, "expected ',' after compare value") ||
4901       ParseValue(LHS->getType(), RHS, PFS))
4902     return true;
4903
4904   if (Opc == Instruction::FCmp) {
4905     if (!LHS->getType()->isFPOrFPVectorTy())
4906       return Error(Loc, "fcmp requires floating point operands");
4907     Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4908   } else {
4909     assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4910     if (!LHS->getType()->isIntOrIntVectorTy() &&
4911         !LHS->getType()->getScalarType()->isPointerTy())
4912       return Error(Loc, "icmp requires integer operands");
4913     Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4914   }
4915   return false;
4916 }
4917
4918 //===----------------------------------------------------------------------===//
4919 // Other Instructions.
4920 //===----------------------------------------------------------------------===//
4921
4922
4923 /// ParseCast
4924 ///   ::= CastOpc TypeAndValue 'to' Type
4925 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4926                          unsigned Opc) {
4927   LocTy Loc;
4928   Value *Op;
4929   Type *DestTy = nullptr;
4930   if (ParseTypeAndValue(Op, Loc, PFS) ||
4931       ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4932       ParseType(DestTy))
4933     return true;
4934
4935   if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4936     CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4937     return Error(Loc, "invalid cast opcode for cast from '" +
4938                  getTypeString(Op->getType()) + "' to '" +
4939                  getTypeString(DestTy) + "'");
4940   }
4941   Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4942   return false;
4943 }
4944
4945 /// ParseSelect
4946 ///   ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4947 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4948   LocTy Loc;
4949   Value *Op0, *Op1, *Op2;
4950   if (ParseTypeAndValue(Op0, Loc, PFS) ||
4951       ParseToken(lltok::comma, "expected ',' after select condition") ||
4952       ParseTypeAndValue(Op1, PFS) ||
4953       ParseToken(lltok::comma, "expected ',' after select value") ||
4954       ParseTypeAndValue(Op2, PFS))
4955     return true;
4956
4957   if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4958     return Error(Loc, Reason);
4959
4960   Inst = SelectInst::Create(Op0, Op1, Op2);
4961   return false;
4962 }
4963
4964 /// ParseVA_Arg
4965 ///   ::= 'va_arg' TypeAndValue ',' Type
4966 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4967   Value *Op;
4968   Type *EltTy = nullptr;
4969   LocTy TypeLoc;
4970   if (ParseTypeAndValue(Op, PFS) ||
4971       ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4972       ParseType(EltTy, TypeLoc))
4973     return true;
4974
4975   if (!EltTy->isFirstClassType())
4976     return Error(TypeLoc, "va_arg requires operand with first class type");
4977
4978   Inst = new VAArgInst(Op, EltTy);
4979   return false;
4980 }
4981
4982 /// ParseExtractElement
4983 ///   ::= 'extractelement' TypeAndValue ',' TypeAndValue
4984 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4985   LocTy Loc;
4986   Value *Op0, *Op1;
4987   if (ParseTypeAndValue(Op0, Loc, PFS) ||
4988       ParseToken(lltok::comma, "expected ',' after extract value") ||
4989       ParseTypeAndValue(Op1, PFS))
4990     return true;
4991
4992   if (!ExtractElementInst::isValidOperands(Op0, Op1))
4993     return Error(Loc, "invalid extractelement operands");
4994
4995   Inst = ExtractElementInst::Create(Op0, Op1);
4996   return false;
4997 }
4998
4999 /// ParseInsertElement
5000 ///   ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5001 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5002   LocTy Loc;
5003   Value *Op0, *Op1, *Op2;
5004   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5005       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5006       ParseTypeAndValue(Op1, PFS) ||
5007       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5008       ParseTypeAndValue(Op2, PFS))
5009     return true;
5010
5011   if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5012     return Error(Loc, "invalid insertelement operands");
5013
5014   Inst = InsertElementInst::Create(Op0, Op1, Op2);
5015   return false;
5016 }
5017
5018 /// ParseShuffleVector
5019 ///   ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5020 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5021   LocTy Loc;
5022   Value *Op0, *Op1, *Op2;
5023   if (ParseTypeAndValue(Op0, Loc, PFS) ||
5024       ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5025       ParseTypeAndValue(Op1, PFS) ||
5026       ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5027       ParseTypeAndValue(Op2, PFS))
5028     return true;
5029
5030   if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5031     return Error(Loc, "invalid shufflevector operands");
5032
5033   Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5034   return false;
5035 }
5036
5037 /// ParsePHI
5038 ///   ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5039 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5040   Type *Ty = nullptr;  LocTy TypeLoc;
5041   Value *Op0, *Op1;
5042
5043   if (ParseType(Ty, TypeLoc) ||
5044       ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5045       ParseValue(Ty, Op0, PFS) ||
5046       ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5047       ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5048       ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5049     return true;
5050
5051   bool AteExtraComma = false;
5052   SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5053   while (1) {
5054     PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5055
5056     if (!EatIfPresent(lltok::comma))
5057       break;
5058
5059     if (Lex.getKind() == lltok::MetadataVar) {
5060       AteExtraComma = true;
5061       break;
5062     }
5063
5064     if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5065         ParseValue(Ty, Op0, PFS) ||
5066         ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5067         ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5068         ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5069       return true;
5070   }
5071
5072   if (!Ty->isFirstClassType())
5073     return Error(TypeLoc, "phi node must have first class type");
5074
5075   PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5076   for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5077     PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5078   Inst = PN;
5079   return AteExtraComma ? InstExtraComma : InstNormal;
5080 }
5081
5082 /// ParseLandingPad
5083 ///   ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5084 /// Clause
5085 ///   ::= 'catch' TypeAndValue
5086 ///   ::= 'filter'
5087 ///   ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5088 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5089   Type *Ty = nullptr; LocTy TyLoc;
5090   Value *PersFn; LocTy PersFnLoc;
5091
5092   if (ParseType(Ty, TyLoc) ||
5093       ParseToken(lltok::kw_personality, "expected 'personality'") ||
5094       ParseTypeAndValue(PersFn, PersFnLoc, PFS))
5095     return true;
5096
5097   std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, PersFn, 0));
5098   LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5099
5100   while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5101     LandingPadInst::ClauseType CT;
5102     if (EatIfPresent(lltok::kw_catch))
5103       CT = LandingPadInst::Catch;
5104     else if (EatIfPresent(lltok::kw_filter))
5105       CT = LandingPadInst::Filter;
5106     else
5107       return TokError("expected 'catch' or 'filter' clause type");
5108
5109     Value *V;
5110     LocTy VLoc;
5111     if (ParseTypeAndValue(V, VLoc, PFS))
5112       return true;
5113
5114     // A 'catch' type expects a non-array constant. A filter clause expects an
5115     // array constant.
5116     if (CT == LandingPadInst::Catch) {
5117       if (isa<ArrayType>(V->getType()))
5118         Error(VLoc, "'catch' clause has an invalid type");
5119     } else {
5120       if (!isa<ArrayType>(V->getType()))
5121         Error(VLoc, "'filter' clause has an invalid type");
5122     }
5123
5124     Constant *CV = dyn_cast<Constant>(V);
5125     if (!CV)
5126       return Error(VLoc, "clause argument must be a constant");
5127     LP->addClause(CV);
5128   }
5129
5130   Inst = LP.release();
5131   return false;
5132 }
5133
5134 /// ParseCall
5135 ///   ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5136 ///       ParameterList OptionalAttrs
5137 ///   ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5138 ///       ParameterList OptionalAttrs
5139 ///   ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5140 ///       ParameterList OptionalAttrs
5141 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5142                          CallInst::TailCallKind TCK) {
5143   AttrBuilder RetAttrs, FnAttrs;
5144   std::vector<unsigned> FwdRefAttrGrps;
5145   LocTy BuiltinLoc;
5146   unsigned CC;
5147   Type *RetType = nullptr;
5148   LocTy RetTypeLoc;
5149   ValID CalleeID;
5150   SmallVector<ParamInfo, 16> ArgList;
5151   LocTy CallLoc = Lex.getLoc();
5152
5153   if ((TCK != CallInst::TCK_None &&
5154        ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5155       ParseOptionalCallingConv(CC) ||
5156       ParseOptionalReturnAttrs(RetAttrs) ||
5157       ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5158       ParseValID(CalleeID) ||
5159       ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5160                          PFS.getFunction().isVarArg()) ||
5161       ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5162                                  BuiltinLoc))
5163     return true;
5164
5165   // If RetType is a non-function pointer type, then this is the short syntax
5166   // for the call, which means that RetType is just the return type.  Infer the
5167   // rest of the function argument types from the arguments that are present.
5168   FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5169   if (!Ty) {
5170     // Pull out the types of all of the arguments...
5171     std::vector<Type*> ParamTypes;
5172     for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5173       ParamTypes.push_back(ArgList[i].V->getType());
5174
5175     if (!FunctionType::isValidReturnType(RetType))
5176       return Error(RetTypeLoc, "Invalid result type for LLVM function");
5177
5178     Ty = FunctionType::get(RetType, ParamTypes, false);
5179   }
5180
5181   // Look up the callee.
5182   Value *Callee;
5183   if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5184     return true;
5185
5186   // Set up the Attribute for the function.
5187   SmallVector<AttributeSet, 8> Attrs;
5188   if (RetAttrs.hasAttributes())
5189     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5190                                       AttributeSet::ReturnIndex,
5191                                       RetAttrs));
5192
5193   SmallVector<Value*, 8> Args;
5194
5195   // Loop through FunctionType's arguments and ensure they are specified
5196   // correctly.  Also, gather any parameter attributes.
5197   FunctionType::param_iterator I = Ty->param_begin();
5198   FunctionType::param_iterator E = Ty->param_end();
5199   for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5200     Type *ExpectedTy = nullptr;
5201     if (I != E) {
5202       ExpectedTy = *I++;
5203     } else if (!Ty->isVarArg()) {
5204       return Error(ArgList[i].Loc, "too many arguments specified");
5205     }
5206
5207     if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5208       return Error(ArgList[i].Loc, "argument is not of expected type '" +
5209                    getTypeString(ExpectedTy) + "'");
5210     Args.push_back(ArgList[i].V);
5211     if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5212       AttrBuilder B(ArgList[i].Attrs, i + 1);
5213       Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5214     }
5215   }
5216
5217   if (I != E)
5218     return Error(CallLoc, "not enough parameters specified for call");
5219
5220   if (FnAttrs.hasAttributes()) {
5221     if (FnAttrs.hasAlignmentAttr())
5222       return Error(CallLoc, "call instructions may not have an alignment");
5223
5224     Attrs.push_back(AttributeSet::get(RetType->getContext(),
5225                                       AttributeSet::FunctionIndex,
5226                                       FnAttrs));
5227   }
5228
5229   // Finish off the Attribute and check them
5230   AttributeSet PAL = AttributeSet::get(Context, Attrs);
5231
5232   CallInst *CI = CallInst::Create(Ty, Callee, Args);
5233   CI->setTailCallKind(TCK);
5234   CI->setCallingConv(CC);
5235   CI->setAttributes(PAL);
5236   ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5237   Inst = CI;
5238   return false;
5239 }
5240
5241 //===----------------------------------------------------------------------===//
5242 // Memory Instructions.
5243 //===----------------------------------------------------------------------===//
5244
5245 /// ParseAlloc
5246 ///   ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5247 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5248   Value *Size = nullptr;
5249   LocTy SizeLoc, TyLoc;
5250   unsigned Alignment = 0;
5251   Type *Ty = nullptr;
5252
5253   bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5254
5255   if (ParseType(Ty, TyLoc)) return true;
5256
5257   if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5258     return Error(TyLoc, "invalid type for alloca");
5259
5260   bool AteExtraComma = false;
5261   if (EatIfPresent(lltok::comma)) {
5262     if (Lex.getKind() == lltok::kw_align) {
5263       if (ParseOptionalAlignment(Alignment)) return true;
5264     } else if (Lex.getKind() == lltok::MetadataVar) {
5265       AteExtraComma = true;
5266     } else {
5267       if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5268           ParseOptionalCommaAlign(Alignment, AteExtraComma))
5269         return true;
5270     }
5271   }
5272
5273   if (Size && !Size->getType()->isIntegerTy())
5274     return Error(SizeLoc, "element count must have integer type");
5275
5276   AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5277   AI->setUsedWithInAlloca(IsInAlloca);
5278   Inst = AI;
5279   return AteExtraComma ? InstExtraComma : InstNormal;
5280 }
5281
5282 /// ParseLoad
5283 ///   ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5284 ///   ::= 'load' 'atomic' 'volatile'? TypeAndValue
5285 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
5286 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5287   Value *Val; LocTy Loc;
5288   unsigned Alignment = 0;
5289   bool AteExtraComma = false;
5290   bool isAtomic = false;
5291   AtomicOrdering Ordering = NotAtomic;
5292   SynchronizationScope Scope = CrossThread;
5293
5294   if (Lex.getKind() == lltok::kw_atomic) {
5295     isAtomic = true;
5296     Lex.Lex();
5297   }
5298
5299   bool isVolatile = false;
5300   if (Lex.getKind() == lltok::kw_volatile) {
5301     isVolatile = true;
5302     Lex.Lex();
5303   }
5304
5305   Type *Ty;
5306   LocTy ExplicitTypeLoc = Lex.getLoc();
5307   if (ParseType(Ty) ||
5308       ParseToken(lltok::comma, "expected comma after load's type") ||
5309       ParseTypeAndValue(Val, Loc, PFS) ||
5310       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5311       ParseOptionalCommaAlign(Alignment, AteExtraComma))
5312     return true;
5313
5314   if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5315     return Error(Loc, "load operand must be a pointer to a first class type");
5316   if (isAtomic && !Alignment)
5317     return Error(Loc, "atomic load must have explicit non-zero alignment");
5318   if (Ordering == Release || Ordering == AcquireRelease)
5319     return Error(Loc, "atomic load cannot use Release ordering");
5320
5321   if (Ty != cast<PointerType>(Val->getType())->getElementType())
5322     return Error(ExplicitTypeLoc,
5323                  "explicit pointee type doesn't match operand's pointee type");
5324
5325   Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5326   return AteExtraComma ? InstExtraComma : InstNormal;
5327 }
5328
5329 /// ParseStore
5330
5331 ///   ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5332 ///   ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5333 ///       'singlethread'? AtomicOrdering (',' 'align' i32)?
5334 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5335   Value *Val, *Ptr; LocTy Loc, PtrLoc;
5336   unsigned Alignment = 0;
5337   bool AteExtraComma = false;
5338   bool isAtomic = false;
5339   AtomicOrdering Ordering = NotAtomic;
5340   SynchronizationScope Scope = CrossThread;
5341
5342   if (Lex.getKind() == lltok::kw_atomic) {
5343     isAtomic = true;
5344     Lex.Lex();
5345   }
5346
5347   bool isVolatile = false;
5348   if (Lex.getKind() == lltok::kw_volatile) {
5349     isVolatile = true;
5350     Lex.Lex();
5351   }
5352
5353   if (ParseTypeAndValue(Val, Loc, PFS) ||
5354       ParseToken(lltok::comma, "expected ',' after store operand") ||
5355       ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5356       ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5357       ParseOptionalCommaAlign(Alignment, AteExtraComma))
5358     return true;
5359
5360   if (!Ptr->getType()->isPointerTy())
5361     return Error(PtrLoc, "store operand must be a pointer");
5362   if (!Val->getType()->isFirstClassType())
5363     return Error(Loc, "store operand must be a first class value");
5364   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5365     return Error(Loc, "stored value and pointer type do not match");
5366   if (isAtomic && !Alignment)
5367     return Error(Loc, "atomic store must have explicit non-zero alignment");
5368   if (Ordering == Acquire || Ordering == AcquireRelease)
5369     return Error(Loc, "atomic store cannot use Acquire ordering");
5370
5371   Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5372   return AteExtraComma ? InstExtraComma : InstNormal;
5373 }
5374
5375 /// ParseCmpXchg
5376 ///   ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5377 ///       TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5378 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5379   Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5380   bool AteExtraComma = false;
5381   AtomicOrdering SuccessOrdering = NotAtomic;
5382   AtomicOrdering FailureOrdering = NotAtomic;
5383   SynchronizationScope Scope = CrossThread;
5384   bool isVolatile = false;
5385   bool isWeak = false;
5386
5387   if (EatIfPresent(lltok::kw_weak))
5388     isWeak = true;
5389
5390   if (EatIfPresent(lltok::kw_volatile))
5391     isVolatile = true;
5392
5393   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5394       ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5395       ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5396       ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5397       ParseTypeAndValue(New, NewLoc, PFS) ||
5398       ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5399       ParseOrdering(FailureOrdering))
5400     return true;
5401
5402   if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5403     return TokError("cmpxchg cannot be unordered");
5404   if (SuccessOrdering < FailureOrdering)
5405     return TokError("cmpxchg must be at least as ordered on success as failure");
5406   if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5407     return TokError("cmpxchg failure ordering cannot include release semantics");
5408   if (!Ptr->getType()->isPointerTy())
5409     return Error(PtrLoc, "cmpxchg operand must be a pointer");
5410   if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5411     return Error(CmpLoc, "compare value and pointer type do not match");
5412   if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5413     return Error(NewLoc, "new value and pointer type do not match");
5414   if (!New->getType()->isIntegerTy())
5415     return Error(NewLoc, "cmpxchg operand must be an integer");
5416   unsigned Size = New->getType()->getPrimitiveSizeInBits();
5417   if (Size < 8 || (Size & (Size - 1)))
5418     return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5419                          " integer");
5420
5421   AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5422       Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5423   CXI->setVolatile(isVolatile);
5424   CXI->setWeak(isWeak);
5425   Inst = CXI;
5426   return AteExtraComma ? InstExtraComma : InstNormal;
5427 }
5428
5429 /// ParseAtomicRMW
5430 ///   ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5431 ///       'singlethread'? AtomicOrdering
5432 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5433   Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5434   bool AteExtraComma = false;
5435   AtomicOrdering Ordering = NotAtomic;
5436   SynchronizationScope Scope = CrossThread;
5437   bool isVolatile = false;
5438   AtomicRMWInst::BinOp Operation;
5439
5440   if (EatIfPresent(lltok::kw_volatile))
5441     isVolatile = true;
5442
5443   switch (Lex.getKind()) {
5444   default: return TokError("expected binary operation in atomicrmw");
5445   case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5446   case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5447   case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5448   case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5449   case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5450   case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5451   case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5452   case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5453   case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5454   case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5455   case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5456   }
5457   Lex.Lex();  // Eat the operation.
5458
5459   if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5460       ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5461       ParseTypeAndValue(Val, ValLoc, PFS) ||
5462       ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5463     return true;
5464
5465   if (Ordering == Unordered)
5466     return TokError("atomicrmw cannot be unordered");
5467   if (!Ptr->getType()->isPointerTy())
5468     return Error(PtrLoc, "atomicrmw operand must be a pointer");
5469   if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5470     return Error(ValLoc, "atomicrmw value and pointer type do not match");
5471   if (!Val->getType()->isIntegerTy())
5472     return Error(ValLoc, "atomicrmw operand must be an integer");
5473   unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5474   if (Size < 8 || (Size & (Size - 1)))
5475     return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5476                          " integer");
5477
5478   AtomicRMWInst *RMWI =
5479     new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5480   RMWI->setVolatile(isVolatile);
5481   Inst = RMWI;
5482   return AteExtraComma ? InstExtraComma : InstNormal;
5483 }
5484
5485 /// ParseFence
5486 ///   ::= 'fence' 'singlethread'? AtomicOrdering
5487 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5488   AtomicOrdering Ordering = NotAtomic;
5489   SynchronizationScope Scope = CrossThread;
5490   if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5491     return true;
5492
5493   if (Ordering == Unordered)
5494     return TokError("fence cannot be unordered");
5495   if (Ordering == Monotonic)
5496     return TokError("fence cannot be monotonic");
5497
5498   Inst = new FenceInst(Context, Ordering, Scope);
5499   return InstNormal;
5500 }
5501
5502 /// ParseGetElementPtr
5503 ///   ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5504 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5505   Value *Ptr = nullptr;
5506   Value *Val = nullptr;
5507   LocTy Loc, EltLoc;
5508
5509   bool InBounds = EatIfPresent(lltok::kw_inbounds);
5510
5511   Type *Ty = nullptr;
5512   LocTy ExplicitTypeLoc = Lex.getLoc();
5513   if (ParseType(Ty) ||
5514       ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5515       ParseTypeAndValue(Ptr, Loc, PFS))
5516     return true;
5517
5518   Type *BaseType = Ptr->getType();
5519   PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5520   if (!BasePointerType)
5521     return Error(Loc, "base of getelementptr must be a pointer");
5522
5523   if (Ty != BasePointerType->getElementType())
5524     return Error(ExplicitTypeLoc,
5525                  "explicit pointee type doesn't match operand's pointee type");
5526
5527   SmallVector<Value*, 16> Indices;
5528   bool AteExtraComma = false;
5529   while (EatIfPresent(lltok::comma)) {
5530     if (Lex.getKind() == lltok::MetadataVar) {
5531       AteExtraComma = true;
5532       break;
5533     }
5534     if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5535     if (!Val->getType()->getScalarType()->isIntegerTy())
5536       return Error(EltLoc, "getelementptr index must be an integer");
5537     if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5538       return Error(EltLoc, "getelementptr index type missmatch");
5539     if (Val->getType()->isVectorTy()) {
5540       unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5541       unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5542       if (ValNumEl != PtrNumEl)
5543         return Error(EltLoc,
5544           "getelementptr vector index has a wrong number of elements");
5545     }
5546     Indices.push_back(Val);
5547   }
5548
5549   SmallPtrSet<const Type*, 4> Visited;
5550   if (!Indices.empty() && !Ty->isSized(&Visited))
5551     return Error(Loc, "base element of getelementptr must be sized");
5552
5553   if (!GetElementPtrInst::getIndexedType(Ty, Indices))
5554     return Error(Loc, "invalid getelementptr indices");
5555   Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
5556   if (InBounds)
5557     cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5558   return AteExtraComma ? InstExtraComma : InstNormal;
5559 }
5560
5561 /// ParseExtractValue
5562 ///   ::= 'extractvalue' TypeAndValue (',' uint32)+
5563 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5564   Value *Val; LocTy Loc;
5565   SmallVector<unsigned, 4> Indices;
5566   bool AteExtraComma;
5567   if (ParseTypeAndValue(Val, Loc, PFS) ||
5568       ParseIndexList(Indices, AteExtraComma))
5569     return true;
5570
5571   if (!Val->getType()->isAggregateType())
5572     return Error(Loc, "extractvalue operand must be aggregate type");
5573
5574   if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5575     return Error(Loc, "invalid indices for extractvalue");
5576   Inst = ExtractValueInst::Create(Val, Indices);
5577   return AteExtraComma ? InstExtraComma : InstNormal;
5578 }
5579
5580 /// ParseInsertValue
5581 ///   ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5582 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5583   Value *Val0, *Val1; LocTy Loc0, Loc1;
5584   SmallVector<unsigned, 4> Indices;
5585   bool AteExtraComma;
5586   if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5587       ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5588       ParseTypeAndValue(Val1, Loc1, PFS) ||
5589       ParseIndexList(Indices, AteExtraComma))
5590     return true;
5591
5592   if (!Val0->getType()->isAggregateType())
5593     return Error(Loc0, "insertvalue operand must be aggregate type");
5594
5595   Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5596   if (!IndexedType)
5597     return Error(Loc0, "invalid indices for insertvalue");
5598   if (IndexedType != Val1->getType())
5599     return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5600                            getTypeString(Val1->getType()) + "' instead of '" +
5601                            getTypeString(IndexedType) + "'");
5602   Inst = InsertValueInst::Create(Val0, Val1, Indices);
5603   return AteExtraComma ? InstExtraComma : InstNormal;
5604 }
5605
5606 //===----------------------------------------------------------------------===//
5607 // Embedded metadata.
5608 //===----------------------------------------------------------------------===//
5609
5610 /// ParseMDNodeVector
5611 ///   ::= { Element (',' Element)* }
5612 /// Element
5613 ///   ::= 'null' | TypeAndValue
5614 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5615   if (ParseToken(lltok::lbrace, "expected '{' here"))
5616     return true;
5617
5618   // Check for an empty list.
5619   if (EatIfPresent(lltok::rbrace))
5620     return false;
5621
5622   do {
5623     // Null is a special case since it is typeless.
5624     if (EatIfPresent(lltok::kw_null)) {
5625       Elts.push_back(nullptr);
5626       continue;
5627     }
5628
5629     Metadata *MD;
5630     if (ParseMetadata(MD, nullptr))
5631       return true;
5632     Elts.push_back(MD);
5633   } while (EatIfPresent(lltok::comma));
5634
5635   return ParseToken(lltok::rbrace, "expected end of metadata node");
5636 }
5637
5638 //===----------------------------------------------------------------------===//
5639 // Use-list order directives.
5640 //===----------------------------------------------------------------------===//
5641 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5642                                 SMLoc Loc) {
5643   if (V->use_empty())
5644     return Error(Loc, "value has no uses");
5645
5646   unsigned NumUses = 0;
5647   SmallDenseMap<const Use *, unsigned, 16> Order;
5648   for (const Use &U : V->uses()) {
5649     if (++NumUses > Indexes.size())
5650       break;
5651     Order[&U] = Indexes[NumUses - 1];
5652   }
5653   if (NumUses < 2)
5654     return Error(Loc, "value only has one use");
5655   if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5656     return Error(Loc, "wrong number of indexes, expected " +
5657                           Twine(std::distance(V->use_begin(), V->use_end())));
5658
5659   V->sortUseList([&](const Use &L, const Use &R) {
5660     return Order.lookup(&L) < Order.lookup(&R);
5661   });
5662   return false;
5663 }
5664
5665 /// ParseUseListOrderIndexes
5666 ///   ::= '{' uint32 (',' uint32)+ '}'
5667 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5668   SMLoc Loc = Lex.getLoc();
5669   if (ParseToken(lltok::lbrace, "expected '{' here"))
5670     return true;
5671   if (Lex.getKind() == lltok::rbrace)
5672     return Lex.Error("expected non-empty list of uselistorder indexes");
5673
5674   // Use Offset, Max, and IsOrdered to check consistency of indexes.  The
5675   // indexes should be distinct numbers in the range [0, size-1], and should
5676   // not be in order.
5677   unsigned Offset = 0;
5678   unsigned Max = 0;
5679   bool IsOrdered = true;
5680   assert(Indexes.empty() && "Expected empty order vector");
5681   do {
5682     unsigned Index;
5683     if (ParseUInt32(Index))
5684       return true;
5685
5686     // Update consistency checks.
5687     Offset += Index - Indexes.size();
5688     Max = std::max(Max, Index);
5689     IsOrdered &= Index == Indexes.size();
5690
5691     Indexes.push_back(Index);
5692   } while (EatIfPresent(lltok::comma));
5693
5694   if (ParseToken(lltok::rbrace, "expected '}' here"))
5695     return true;
5696
5697   if (Indexes.size() < 2)
5698     return Error(Loc, "expected >= 2 uselistorder indexes");
5699   if (Offset != 0 || Max >= Indexes.size())
5700     return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5701   if (IsOrdered)
5702     return Error(Loc, "expected uselistorder indexes to change the order");
5703
5704   return false;
5705 }
5706
5707 /// ParseUseListOrder
5708 ///   ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5709 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5710   SMLoc Loc = Lex.getLoc();
5711   if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5712     return true;
5713
5714   Value *V;
5715   SmallVector<unsigned, 16> Indexes;
5716   if (ParseTypeAndValue(V, PFS) ||
5717       ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5718       ParseUseListOrderIndexes(Indexes))
5719     return true;
5720
5721   return sortUseListOrder(V, Indexes, Loc);
5722 }
5723
5724 /// ParseUseListOrderBB
5725 ///   ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5726 bool LLParser::ParseUseListOrderBB() {
5727   assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5728   SMLoc Loc = Lex.getLoc();
5729   Lex.Lex();
5730
5731   ValID Fn, Label;
5732   SmallVector<unsigned, 16> Indexes;
5733   if (ParseValID(Fn) ||
5734       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5735       ParseValID(Label) ||
5736       ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5737       ParseUseListOrderIndexes(Indexes))
5738     return true;
5739
5740   // Check the function.
5741   GlobalValue *GV;
5742   if (Fn.Kind == ValID::t_GlobalName)
5743     GV = M->getNamedValue(Fn.StrVal);
5744   else if (Fn.Kind == ValID::t_GlobalID)
5745     GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5746   else
5747     return Error(Fn.Loc, "expected function name in uselistorder_bb");
5748   if (!GV)
5749     return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5750   auto *F = dyn_cast<Function>(GV);
5751   if (!F)
5752     return Error(Fn.Loc, "expected function name in uselistorder_bb");
5753   if (F->isDeclaration())
5754     return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5755
5756   // Check the basic block.
5757   if (Label.Kind == ValID::t_LocalID)
5758     return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5759   if (Label.Kind != ValID::t_LocalName)
5760     return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5761   Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5762   if (!V)
5763     return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5764   if (!isa<BasicBlock>(V))
5765     return Error(Label.Loc, "expected basic block in uselistorder_bb");
5766
5767   return sortUseListOrder(V, Indexes, Loc);
5768 }