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