LLVM  16.0.0git
LLParser.cpp
Go to the documentation of this file.
1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the parser class for .ll files.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/LLToken.h"
22 #include "llvm/IR/Argument.h"
23 #include "llvm/IR/AutoUpgrade.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/Comdat.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/Value.h"
43 #include "llvm/Support/Casting.h"
48 #include <algorithm>
49 #include <cassert>
50 #include <cstring>
51 #include <vector>
52 
53 using namespace llvm;
54 
55 static std::string getTypeString(Type *T) {
56  std::string Result;
57  raw_string_ostream Tmp(Result);
58  Tmp << *T;
59  return Tmp.str();
60 }
61 
63  while (true) {
64  lltok::Kind K = L.Lex();
65  // LLLexer will set the opaque pointers option in LLVMContext if it sees an
66  // explicit "ptr".
67  if (K == lltok::star || K == lltok::Error || K == lltok::Eof ||
68  isa_and_nonnull<PointerType>(L.getTyVal())) {
69  if (K == lltok::star)
70  C.setOpaquePointers(false);
71  return;
72  }
73  }
74 }
75 
76 /// Run: module ::= toplevelentity*
78  DataLayoutCallbackTy DataLayoutCallback) {
79  // If we haven't decided on whether or not we're using opaque pointers, do a
80  // quick lex over the tokens to see if we explicitly construct any typed or
81  // opaque pointer types.
82  // Don't bail out on an error so we do the same work in the parsing below
83  // regardless of if --opaque-pointers is set.
84  if (!Context.hasSetOpaquePointersValue())
85  setContextOpaquePointers(OPLex, Context);
86 
87  // Prime the lexer.
88  Lex.Lex();
89 
90  if (Context.shouldDiscardValueNames())
91  return error(
92  Lex.getLoc(),
93  "Can't read textual IR with a Context that discards named Values");
94 
95  if (M) {
96  if (parseTargetDefinitions())
97  return true;
98 
99  if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple()))
100  M->setDataLayout(*LayoutOverride);
101  }
102 
103  return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
104  validateEndOfIndex();
105 }
106 
108  const SlotMapping *Slots) {
109  restoreParsingState(Slots);
110  Lex.Lex();
111 
112  Type *Ty = nullptr;
113  if (parseType(Ty) || parseConstantValue(Ty, C))
114  return true;
115  if (Lex.getKind() != lltok::Eof)
116  return error(Lex.getLoc(), "expected end of string");
117  return false;
118 }
119 
120 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
121  const SlotMapping *Slots) {
122  restoreParsingState(Slots);
123  Lex.Lex();
124 
125  Read = 0;
126  SMLoc Start = Lex.getLoc();
127  Ty = nullptr;
128  if (parseType(Ty))
129  return true;
130  SMLoc End = Lex.getLoc();
131  Read = End.getPointer() - Start.getPointer();
132 
133  return false;
134 }
135 
136 void LLParser::restoreParsingState(const SlotMapping *Slots) {
137  if (!Slots)
138  return;
139  NumberedVals = Slots->GlobalValues;
140  NumberedMetadata = Slots->MetadataNodes;
141  for (const auto &I : Slots->NamedTypes)
142  NamedTypes.insert(
143  std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
144  for (const auto &I : Slots->Types)
145  NumberedTypes.insert(
146  std::make_pair(I.first, std::make_pair(I.second, LocTy())));
147 }
148 
149 /// validateEndOfModule - Do final validity and basic correctness checks at the
150 /// end of the module.
151 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
152  if (!M)
153  return false;
154  // Handle any function attribute group forward references.
155  for (const auto &RAG : ForwardRefAttrGroups) {
156  Value *V = RAG.first;
157  const std::vector<unsigned> &Attrs = RAG.second;
158  AttrBuilder B(Context);
159 
160  for (const auto &Attr : Attrs) {
161  auto R = NumberedAttrBuilders.find(Attr);
162  if (R != NumberedAttrBuilders.end())
163  B.merge(R->second);
164  }
165 
166  if (Function *Fn = dyn_cast<Function>(V)) {
167  AttributeList AS = Fn->getAttributes();
168  AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
169  AS = AS.removeFnAttributes(Context);
170 
171  FnAttrs.merge(B);
172 
173  // If the alignment was parsed as an attribute, move to the alignment
174  // field.
175  if (FnAttrs.hasAlignmentAttr()) {
176  Fn->setAlignment(FnAttrs.getAlignment());
177  FnAttrs.removeAttribute(Attribute::Alignment);
178  }
179 
180  AS = AS.addFnAttributes(Context, FnAttrs);
181  Fn->setAttributes(AS);
182  } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
183  AttributeList AS = CI->getAttributes();
184  AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
185  AS = AS.removeFnAttributes(Context);
186  FnAttrs.merge(B);
187  AS = AS.addFnAttributes(Context, FnAttrs);
188  CI->setAttributes(AS);
189  } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
190  AttributeList AS = II->getAttributes();
191  AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
192  AS = AS.removeFnAttributes(Context);
193  FnAttrs.merge(B);
194  AS = AS.addFnAttributes(Context, FnAttrs);
195  II->setAttributes(AS);
196  } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
197  AttributeList AS = CBI->getAttributes();
198  AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
199  AS = AS.removeFnAttributes(Context);
200  FnAttrs.merge(B);
201  AS = AS.addFnAttributes(Context, FnAttrs);
202  CBI->setAttributes(AS);
203  } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
204  AttrBuilder Attrs(M->getContext(), GV->getAttributes());
205  Attrs.merge(B);
206  GV->setAttributes(AttributeSet::get(Context,Attrs));
207  } else {
208  llvm_unreachable("invalid object with forward attribute group reference");
209  }
210  }
211 
212  // If there are entries in ForwardRefBlockAddresses at this point, the
213  // function was never defined.
214  if (!ForwardRefBlockAddresses.empty())
215  return error(ForwardRefBlockAddresses.begin()->first.Loc,
216  "expected function name in blockaddress");
217 
218  auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
219  GlobalValue *FwdRef) {
220  GlobalValue *GV = nullptr;
221  if (GVRef.Kind == ValID::t_GlobalName) {
222  GV = M->getNamedValue(GVRef.StrVal);
223  } else if (GVRef.UIntVal < NumberedVals.size()) {
224  GV = dyn_cast<GlobalValue>(NumberedVals[GVRef.UIntVal]);
225  }
226 
227  if (!GV)
228  return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
229  "' referenced by dso_local_equivalent");
230 
231  if (!GV->getValueType()->isFunctionTy())
232  return error(GVRef.Loc,
233  "expected a function, alias to function, or ifunc "
234  "in dso_local_equivalent");
235 
236  auto *Equiv = DSOLocalEquivalent::get(GV);
237  FwdRef->replaceAllUsesWith(Equiv);
238  FwdRef->eraseFromParent();
239  return false;
240  };
241 
242  // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
243  // point, they are references after the function was defined. Resolve those
244  // now.
245  for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
246  if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
247  return true;
248  }
249  for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
250  if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
251  return true;
252  }
253  ForwardRefDSOLocalEquivalentNames.clear();
254  ForwardRefDSOLocalEquivalentNames.clear();
255 
256  for (const auto &NT : NumberedTypes)
257  if (NT.second.second.isValid())
258  return error(NT.second.second,
259  "use of undefined type '%" + Twine(NT.first) + "'");
260 
261  for (StringMap<std::pair<Type*, LocTy> >::iterator I =
262  NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
263  if (I->second.second.isValid())
264  return error(I->second.second,
265  "use of undefined type named '" + I->getKey() + "'");
266 
267  if (!ForwardRefComdats.empty())
268  return error(ForwardRefComdats.begin()->second,
269  "use of undefined comdat '$" +
270  ForwardRefComdats.begin()->first + "'");
271 
272  if (!ForwardRefVals.empty())
273  return error(ForwardRefVals.begin()->second.second,
274  "use of undefined value '@" + ForwardRefVals.begin()->first +
275  "'");
276 
277  if (!ForwardRefValIDs.empty())
278  return error(ForwardRefValIDs.begin()->second.second,
279  "use of undefined value '@" +
280  Twine(ForwardRefValIDs.begin()->first) + "'");
281 
282  if (!ForwardRefMDNodes.empty())
283  return error(ForwardRefMDNodes.begin()->second.second,
284  "use of undefined metadata '!" +
285  Twine(ForwardRefMDNodes.begin()->first) + "'");
286 
287  // Resolve metadata cycles.
288  for (auto &N : NumberedMetadata) {
289  if (N.second && !N.second->isResolved())
290  N.second->resolveCycles();
291  }
292 
293  for (auto *Inst : InstsWithTBAATag) {
294  MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
295  assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
296  auto *UpgradedMD = UpgradeTBAANode(*MD);
297  if (MD != UpgradedMD)
298  Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
299  }
300 
301  // Look for intrinsic functions and CallInst that need to be upgraded. We use
302  // make_early_inc_range here because we may remove some functions.
305 
306  // Some types could be renamed during loading if several modules are
307  // loaded in the same LLVMContext (LTO scenario). In this case we should
308  // remangle intrinsics names as well.
309  for (Function &F : llvm::make_early_inc_range(*M)) {
310  if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) {
311  F.replaceAllUsesWith(*Remangled);
312  F.eraseFromParent();
313  }
314  }
315 
316  if (UpgradeDebugInfo)
318 
319  UpgradeModuleFlags(*M);
321 
322  if (!Slots)
323  return false;
324  // Initialize the slot mapping.
325  // Because by this point we've parsed and validated everything, we can "steal"
326  // the mapping from LLParser as it doesn't need it anymore.
327  Slots->GlobalValues = std::move(NumberedVals);
328  Slots->MetadataNodes = std::move(NumberedMetadata);
329  for (const auto &I : NamedTypes)
330  Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
331  for (const auto &I : NumberedTypes)
332  Slots->Types.insert(std::make_pair(I.first, I.second.first));
333 
334  return false;
335 }
336 
337 /// Do final validity and basic correctness checks at the end of the index.
338 bool LLParser::validateEndOfIndex() {
339  if (!Index)
340  return false;
341 
342  if (!ForwardRefValueInfos.empty())
343  return error(ForwardRefValueInfos.begin()->second.front().second,
344  "use of undefined summary '^" +
345  Twine(ForwardRefValueInfos.begin()->first) + "'");
346 
347  if (!ForwardRefAliasees.empty())
348  return error(ForwardRefAliasees.begin()->second.front().second,
349  "use of undefined summary '^" +
350  Twine(ForwardRefAliasees.begin()->first) + "'");
351 
352  if (!ForwardRefTypeIds.empty())
353  return error(ForwardRefTypeIds.begin()->second.front().second,
354  "use of undefined type id summary '^" +
355  Twine(ForwardRefTypeIds.begin()->first) + "'");
356 
357  return false;
358 }
359 
360 //===----------------------------------------------------------------------===//
361 // Top-Level Entities
362 //===----------------------------------------------------------------------===//
363 
364 bool LLParser::parseTargetDefinitions() {
365  while (true) {
366  switch (Lex.getKind()) {
367  case lltok::kw_target:
368  if (parseTargetDefinition())
369  return true;
370  break;
372  if (parseSourceFileName())
373  return true;
374  break;
375  default:
376  return false;
377  }
378  }
379 }
380 
381 bool LLParser::parseTopLevelEntities() {
382  // If there is no Module, then parse just the summary index entries.
383  if (!M) {
384  while (true) {
385  switch (Lex.getKind()) {
386  case lltok::Eof:
387  return false;
388  case lltok::SummaryID:
389  if (parseSummaryEntry())
390  return true;
391  break;
393  if (parseSourceFileName())
394  return true;
395  break;
396  default:
397  // Skip everything else
398  Lex.Lex();
399  }
400  }
401  }
402  while (true) {
403  switch (Lex.getKind()) {
404  default:
405  return tokError("expected top-level entity");
406  case lltok::Eof: return false;
407  case lltok::kw_declare:
408  if (parseDeclare())
409  return true;
410  break;
411  case lltok::kw_define:
412  if (parseDefine())
413  return true;
414  break;
415  case lltok::kw_module:
416  if (parseModuleAsm())
417  return true;
418  break;
419  case lltok::LocalVarID:
420  if (parseUnnamedType())
421  return true;
422  break;
423  case lltok::LocalVar:
424  if (parseNamedType())
425  return true;
426  break;
427  case lltok::GlobalID:
428  if (parseUnnamedGlobal())
429  return true;
430  break;
431  case lltok::GlobalVar:
432  if (parseNamedGlobal())
433  return true;
434  break;
435  case lltok::ComdatVar: if (parseComdat()) return true; break;
436  case lltok::exclaim:
437  if (parseStandaloneMetadata())
438  return true;
439  break;
440  case lltok::SummaryID:
441  if (parseSummaryEntry())
442  return true;
443  break;
444  case lltok::MetadataVar:
445  if (parseNamedMetadata())
446  return true;
447  break;
449  if (parseUnnamedAttrGrp())
450  return true;
451  break;
453  if (parseUseListOrder())
454  return true;
455  break;
457  if (parseUseListOrderBB())
458  return true;
459  break;
460  }
461  }
462 }
463 
464 /// toplevelentity
465 /// ::= 'module' 'asm' STRINGCONSTANT
466 bool LLParser::parseModuleAsm() {
467  assert(Lex.getKind() == lltok::kw_module);
468  Lex.Lex();
469 
470  std::string AsmStr;
471  if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
472  parseStringConstant(AsmStr))
473  return true;
474 
475  M->appendModuleInlineAsm(AsmStr);
476  return false;
477 }
478 
479 /// toplevelentity
480 /// ::= 'target' 'triple' '=' STRINGCONSTANT
481 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
482 bool LLParser::parseTargetDefinition() {
483  assert(Lex.getKind() == lltok::kw_target);
484  std::string Str;
485  switch (Lex.Lex()) {
486  default:
487  return tokError("unknown target property");
488  case lltok::kw_triple:
489  Lex.Lex();
490  if (parseToken(lltok::equal, "expected '=' after target triple") ||
491  parseStringConstant(Str))
492  return true;
493  M->setTargetTriple(Str);
494  return false;
496  Lex.Lex();
497  if (parseToken(lltok::equal, "expected '=' after target datalayout"))
498  return true;
499  LocTy Loc = Lex.getLoc();
500  if (parseStringConstant(Str))
501  return true;
503  if (!MaybeDL)
504  return error(Loc, toString(MaybeDL.takeError()));
505  M->setDataLayout(MaybeDL.get());
506  return false;
507  }
508 }
509 
510 /// toplevelentity
511 /// ::= 'source_filename' '=' STRINGCONSTANT
512 bool LLParser::parseSourceFileName() {
514  Lex.Lex();
515  if (parseToken(lltok::equal, "expected '=' after source_filename") ||
516  parseStringConstant(SourceFileName))
517  return true;
518  if (M)
519  M->setSourceFileName(SourceFileName);
520  return false;
521 }
522 
523 /// parseUnnamedType:
524 /// ::= LocalVarID '=' 'type' type
525 bool LLParser::parseUnnamedType() {
526  LocTy TypeLoc = Lex.getLoc();
527  unsigned TypeID = Lex.getUIntVal();
528  Lex.Lex(); // eat LocalVarID;
529 
530  if (parseToken(lltok::equal, "expected '=' after name") ||
531  parseToken(lltok::kw_type, "expected 'type' after '='"))
532  return true;
533 
534  Type *Result = nullptr;
535  if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
536  return true;
537 
538  if (!isa<StructType>(Result)) {
539  std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
540  if (Entry.first)
541  return error(TypeLoc, "non-struct types may not be recursive");
542  Entry.first = Result;
543  Entry.second = SMLoc();
544  }
545 
546  return false;
547 }
548 
549 /// toplevelentity
550 /// ::= LocalVar '=' 'type' type
551 bool LLParser::parseNamedType() {
552  std::string Name = Lex.getStrVal();
553  LocTy NameLoc = Lex.getLoc();
554  Lex.Lex(); // eat LocalVar.
555 
556  if (parseToken(lltok::equal, "expected '=' after name") ||
557  parseToken(lltok::kw_type, "expected 'type' after name"))
558  return true;
559 
560  Type *Result = nullptr;
561  if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
562  return true;
563 
564  if (!isa<StructType>(Result)) {
565  std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
566  if (Entry.first)
567  return error(NameLoc, "non-struct types may not be recursive");
568  Entry.first = Result;
569  Entry.second = SMLoc();
570  }
571 
572  return false;
573 }
574 
575 /// toplevelentity
576 /// ::= 'declare' FunctionHeader
577 bool LLParser::parseDeclare() {
578  assert(Lex.getKind() == lltok::kw_declare);
579  Lex.Lex();
580 
581  std::vector<std::pair<unsigned, MDNode *>> MDs;
582  while (Lex.getKind() == lltok::MetadataVar) {
583  unsigned MDK;
584  MDNode *N;
585  if (parseMetadataAttachment(MDK, N))
586  return true;
587  MDs.push_back({MDK, N});
588  }
589 
590  Function *F;
591  if (parseFunctionHeader(F, false))
592  return true;
593  for (auto &MD : MDs)
594  F->addMetadata(MD.first, *MD.second);
595  return false;
596 }
597 
598 /// toplevelentity
599 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
600 bool LLParser::parseDefine() {
601  assert(Lex.getKind() == lltok::kw_define);
602  Lex.Lex();
603 
604  Function *F;
605  return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
606  parseFunctionBody(*F);
607 }
608 
609 /// parseGlobalType
610 /// ::= 'constant'
611 /// ::= 'global'
612 bool LLParser::parseGlobalType(bool &IsConstant) {
613  if (Lex.getKind() == lltok::kw_constant)
614  IsConstant = true;
615  else if (Lex.getKind() == lltok::kw_global)
616  IsConstant = false;
617  else {
618  IsConstant = false;
619  return tokError("expected 'global' or 'constant'");
620  }
621  Lex.Lex();
622  return false;
623 }
624 
625 bool LLParser::parseOptionalUnnamedAddr(
626  GlobalVariable::UnnamedAddr &UnnamedAddr) {
627  if (EatIfPresent(lltok::kw_unnamed_addr))
628  UnnamedAddr = GlobalValue::UnnamedAddr::Global;
629  else if (EatIfPresent(lltok::kw_local_unnamed_addr))
630  UnnamedAddr = GlobalValue::UnnamedAddr::Local;
631  else
632  UnnamedAddr = GlobalValue::UnnamedAddr::None;
633  return false;
634 }
635 
636 /// parseUnnamedGlobal:
637 /// OptionalVisibility (ALIAS | IFUNC) ...
638 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
639 /// OptionalDLLStorageClass
640 /// ... -> global variable
641 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
642 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
643 /// OptionalVisibility
644 /// OptionalDLLStorageClass
645 /// ... -> global variable
646 bool LLParser::parseUnnamedGlobal() {
647  unsigned VarID = NumberedVals.size();
648  std::string Name;
649  LocTy NameLoc = Lex.getLoc();
650 
651  // Handle the GlobalID form.
652  if (Lex.getKind() == lltok::GlobalID) {
653  if (Lex.getUIntVal() != VarID)
654  return error(Lex.getLoc(),
655  "variable expected to be numbered '%" + Twine(VarID) + "'");
656  Lex.Lex(); // eat GlobalID;
657 
658  if (parseToken(lltok::equal, "expected '=' after name"))
659  return true;
660  }
661 
662  bool HasLinkage;
663  unsigned Linkage, Visibility, DLLStorageClass;
664  bool DSOLocal;
666  GlobalVariable::UnnamedAddr UnnamedAddr;
667  if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
668  DSOLocal) ||
669  parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
670  return true;
671 
672  switch (Lex.getKind()) {
673  default:
674  return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
675  DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
676  case lltok::kw_alias:
677  case lltok::kw_ifunc:
678  return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility,
679  DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
680  }
681 }
682 
683 /// parseNamedGlobal:
684 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
685 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
686 /// OptionalVisibility OptionalDLLStorageClass
687 /// ... -> global variable
688 bool LLParser::parseNamedGlobal() {
689  assert(Lex.getKind() == lltok::GlobalVar);
690  LocTy NameLoc = Lex.getLoc();
691  std::string Name = Lex.getStrVal();
692  Lex.Lex();
693 
694  bool HasLinkage;
695  unsigned Linkage, Visibility, DLLStorageClass;
696  bool DSOLocal;
698  GlobalVariable::UnnamedAddr UnnamedAddr;
699  if (parseToken(lltok::equal, "expected '=' in global variable") ||
700  parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
701  DSOLocal) ||
702  parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
703  return true;
704 
705  switch (Lex.getKind()) {
706  default:
707  return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
708  DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
709  case lltok::kw_alias:
710  case lltok::kw_ifunc:
711  return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility,
712  DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
713  }
714 }
715 
716 bool LLParser::parseComdat() {
717  assert(Lex.getKind() == lltok::ComdatVar);
718  std::string Name = Lex.getStrVal();
719  LocTy NameLoc = Lex.getLoc();
720  Lex.Lex();
721 
722  if (parseToken(lltok::equal, "expected '=' here"))
723  return true;
724 
725  if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
726  return tokError("expected comdat type");
727 
729  switch (Lex.getKind()) {
730  default:
731  return tokError("unknown selection kind");
732  case lltok::kw_any:
733  SK = Comdat::Any;
734  break;
736  SK = Comdat::ExactMatch;
737  break;
738  case lltok::kw_largest:
739  SK = Comdat::Largest;
740  break;
743  break;
744  case lltok::kw_samesize:
745  SK = Comdat::SameSize;
746  break;
747  }
748  Lex.Lex();
749 
750  // See if the comdat was forward referenced, if so, use the comdat.
751  Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
753  if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
754  return error(NameLoc, "redefinition of comdat '$" + Name + "'");
755 
756  Comdat *C;
757  if (I != ComdatSymTab.end())
758  C = &I->second;
759  else
760  C = M->getOrInsertComdat(Name);
761  C->setSelectionKind(SK);
762 
763  return false;
764 }
765 
766 // MDString:
767 // ::= '!' STRINGCONSTANT
768 bool LLParser::parseMDString(MDString *&Result) {
769  std::string Str;
770  if (parseStringConstant(Str))
771  return true;
772  Result = MDString::get(Context, Str);
773  return false;
774 }
775 
776 // MDNode:
777 // ::= '!' MDNodeNumber
778 bool LLParser::parseMDNodeID(MDNode *&Result) {
779  // !{ ..., !42, ... }
780  LocTy IDLoc = Lex.getLoc();
781  unsigned MID = 0;
782  if (parseUInt32(MID))
783  return true;
784 
785  // If not a forward reference, just return it now.
786  if (NumberedMetadata.count(MID)) {
787  Result = NumberedMetadata[MID];
788  return false;
789  }
790 
791  // Otherwise, create MDNode forward reference.
792  auto &FwdRef = ForwardRefMDNodes[MID];
793  FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
794 
795  Result = FwdRef.first.get();
796  NumberedMetadata[MID].reset(Result);
797  return false;
798 }
799 
800 /// parseNamedMetadata:
801 /// !foo = !{ !1, !2 }
802 bool LLParser::parseNamedMetadata() {
804  std::string Name = Lex.getStrVal();
805  Lex.Lex();
806 
807  if (parseToken(lltok::equal, "expected '=' here") ||
808  parseToken(lltok::exclaim, "Expected '!' here") ||
809  parseToken(lltok::lbrace, "Expected '{' here"))
810  return true;
811 
813  if (Lex.getKind() != lltok::rbrace)
814  do {
815  MDNode *N = nullptr;
816  // parse DIExpressions inline as a special case. They are still MDNodes,
817  // so they can still appear in named metadata. Remove this logic if they
818  // become plain Metadata.
819  if (Lex.getKind() == lltok::MetadataVar &&
820  Lex.getStrVal() == "DIExpression") {
821  if (parseDIExpression(N, /*IsDistinct=*/false))
822  return true;
823  // DIArgLists should only appear inline in a function, as they may
824  // contain LocalAsMetadata arguments which require a function context.
825  } else if (Lex.getKind() == lltok::MetadataVar &&
826  Lex.getStrVal() == "DIArgList") {
827  return tokError("found DIArgList outside of function");
828  } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
829  parseMDNodeID(N)) {
830  return true;
831  }
832  NMD->addOperand(N);
833  } while (EatIfPresent(lltok::comma));
834 
835  return parseToken(lltok::rbrace, "expected end of metadata node");
836 }
837 
838 /// parseStandaloneMetadata:
839 /// !42 = !{...}
840 bool LLParser::parseStandaloneMetadata() {
841  assert(Lex.getKind() == lltok::exclaim);
842  Lex.Lex();
843  unsigned MetadataID = 0;
844 
845  MDNode *Init;
846  if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
847  return true;
848 
849  // Detect common error, from old metadata syntax.
850  if (Lex.getKind() == lltok::Type)
851  return tokError("unexpected type in metadata definition");
852 
853  bool IsDistinct = EatIfPresent(lltok::kw_distinct);
854  if (Lex.getKind() == lltok::MetadataVar) {
855  if (parseSpecializedMDNode(Init, IsDistinct))
856  return true;
857  } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
858  parseMDTuple(Init, IsDistinct))
859  return true;
860 
861  // See if this was forward referenced, if so, handle it.
862  auto FI = ForwardRefMDNodes.find(MetadataID);
863  if (FI != ForwardRefMDNodes.end()) {
864  FI->second.first->replaceAllUsesWith(Init);
865  ForwardRefMDNodes.erase(FI);
866 
867  assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
868  } else {
869  if (NumberedMetadata.count(MetadataID))
870  return tokError("Metadata id is already used");
871  NumberedMetadata[MetadataID].reset(Init);
872  }
873 
874  return false;
875 }
876 
877 // Skips a single module summary entry.
878 bool LLParser::skipModuleSummaryEntry() {
879  // Each module summary entry consists of a tag for the entry
880  // type, followed by a colon, then the fields which may be surrounded by
881  // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
882  // support is in place we will look for the tokens corresponding to the
883  // expected tags.
884  if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
885  Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
886  Lex.getKind() != lltok::kw_blockcount)
887  return tokError(
888  "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
889  "start of summary entry");
890  if (Lex.getKind() == lltok::kw_flags)
891  return parseSummaryIndexFlags();
892  if (Lex.getKind() == lltok::kw_blockcount)
893  return parseBlockCount();
894  Lex.Lex();
895  if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
896  parseToken(lltok::lparen, "expected '(' at start of summary entry"))
897  return true;
898  // Now walk through the parenthesized entry, until the number of open
899  // parentheses goes back down to 0 (the first '(' was parsed above).
900  unsigned NumOpenParen = 1;
901  do {
902  switch (Lex.getKind()) {
903  case lltok::lparen:
904  NumOpenParen++;
905  break;
906  case lltok::rparen:
907  NumOpenParen--;
908  break;
909  case lltok::Eof:
910  return tokError("found end of file while parsing summary entry");
911  default:
912  // Skip everything in between parentheses.
913  break;
914  }
915  Lex.Lex();
916  } while (NumOpenParen > 0);
917  return false;
918 }
919 
920 /// SummaryEntry
921 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
922 bool LLParser::parseSummaryEntry() {
923  assert(Lex.getKind() == lltok::SummaryID);
924  unsigned SummaryID = Lex.getUIntVal();
925 
926  // For summary entries, colons should be treated as distinct tokens,
927  // not an indication of the end of a label token.
928  Lex.setIgnoreColonInIdentifiers(true);
929 
930  Lex.Lex();
931  if (parseToken(lltok::equal, "expected '=' here"))
932  return true;
933 
934  // If we don't have an index object, skip the summary entry.
935  if (!Index)
936  return skipModuleSummaryEntry();
937 
938  bool result = false;
939  switch (Lex.getKind()) {
940  case lltok::kw_gv:
941  result = parseGVEntry(SummaryID);
942  break;
943  case lltok::kw_module:
944  result = parseModuleEntry(SummaryID);
945  break;
946  case lltok::kw_typeid:
947  result = parseTypeIdEntry(SummaryID);
948  break;
950  result = parseTypeIdCompatibleVtableEntry(SummaryID);
951  break;
952  case lltok::kw_flags:
953  result = parseSummaryIndexFlags();
954  break;
956  result = parseBlockCount();
957  break;
958  default:
959  result = error(Lex.getLoc(), "unexpected summary kind");
960  break;
961  }
962  Lex.setIgnoreColonInIdentifiers(false);
963  return result;
964 }
965 
966 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
969 }
970 static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L) {
973 }
974 
975 // If there was an explicit dso_local, update GV. In the absence of an explicit
976 // dso_local we keep the default value.
977 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
978  if (DSOLocal)
979  GV.setDSOLocal(true);
980 }
981 
982 static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1,
983  Type *Ty2) {
984  std::string ErrString;
985  raw_string_ostream ErrOS(ErrString);
986  ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")";
987  return ErrOS.str();
988 }
989 
990 /// parseAliasOrIFunc:
991 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
992 /// OptionalVisibility OptionalDLLStorageClass
993 /// OptionalThreadLocal OptionalUnnamedAddr
994 /// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
995 ///
996 /// AliaseeOrResolver
997 /// ::= TypeAndValue
998 ///
999 /// SymbolAttrs
1000 /// ::= ',' 'partition' StringConstant
1001 ///
1002 /// Everything through OptionalUnnamedAddr has already been parsed.
1003 ///
1004 bool LLParser::parseAliasOrIFunc(const std::string &Name, LocTy NameLoc,
1005  unsigned L, unsigned Visibility,
1006  unsigned DLLStorageClass, bool DSOLocal,
1008  GlobalVariable::UnnamedAddr UnnamedAddr) {
1009  bool IsAlias;
1010  if (Lex.getKind() == lltok::kw_alias)
1011  IsAlias = true;
1012  else if (Lex.getKind() == lltok::kw_ifunc)
1013  IsAlias = false;
1014  else
1015  llvm_unreachable("Not an alias or ifunc!");
1016  Lex.Lex();
1017 
1019 
1020  if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1021  return error(NameLoc, "invalid linkage type for alias");
1022 
1023  if (!isValidVisibilityForLinkage(Visibility, L))
1024  return error(NameLoc,
1025  "symbol with local linkage must have default visibility");
1026 
1027  if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1028  return error(NameLoc,
1029  "symbol with local linkage cannot have a DLL storage class");
1030 
1031  Type *Ty;
1032  LocTy ExplicitTypeLoc = Lex.getLoc();
1033  if (parseType(Ty) ||
1034  parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1035  return true;
1036 
1037  Constant *Aliasee;
1038  LocTy AliaseeLoc = Lex.getLoc();
1039  if (Lex.getKind() != lltok::kw_bitcast &&
1040  Lex.getKind() != lltok::kw_getelementptr &&
1041  Lex.getKind() != lltok::kw_addrspacecast &&
1042  Lex.getKind() != lltok::kw_inttoptr) {
1043  if (parseGlobalTypeAndValue(Aliasee))
1044  return true;
1045  } else {
1046  // The bitcast dest type is not present, it is implied by the dest type.
1047  ValID ID;
1048  if (parseValID(ID, /*PFS=*/nullptr))
1049  return true;
1050  if (ID.Kind != ValID::t_Constant)
1051  return error(AliaseeLoc, "invalid aliasee");
1052  Aliasee = ID.ConstantVal;
1053  }
1054 
1055  Type *AliaseeType = Aliasee->getType();
1056  auto *PTy = dyn_cast<PointerType>(AliaseeType);
1057  if (!PTy)
1058  return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1059  unsigned AddrSpace = PTy->getAddressSpace();
1060 
1061  if (IsAlias) {
1062  if (!PTy->isOpaqueOrPointeeTypeMatches(Ty))
1063  return error(
1064  ExplicitTypeLoc,
1066  "explicit pointee type doesn't match operand's pointee type", Ty,
1067  PTy->getNonOpaquePointerElementType()));
1068  } else {
1069  if (!PTy->isOpaque() &&
1070  !PTy->getNonOpaquePointerElementType()->isFunctionTy())
1071  return error(ExplicitTypeLoc,
1072  "explicit pointee type should be a function type");
1073  }
1074 
1075  GlobalValue *GVal = nullptr;
1076 
1077  // See if the alias was forward referenced, if so, prepare to replace the
1078  // forward reference.
1079  if (!Name.empty()) {
1080  auto I = ForwardRefVals.find(Name);
1081  if (I != ForwardRefVals.end()) {
1082  GVal = I->second.first;
1083  ForwardRefVals.erase(Name);
1084  } else if (M->getNamedValue(Name)) {
1085  return error(NameLoc, "redefinition of global '@" + Name + "'");
1086  }
1087  } else {
1088  auto I = ForwardRefValIDs.find(NumberedVals.size());
1089  if (I != ForwardRefValIDs.end()) {
1090  GVal = I->second.first;
1091  ForwardRefValIDs.erase(I);
1092  }
1093  }
1094 
1095  // Okay, create the alias/ifunc but do not insert it into the module yet.
1096  std::unique_ptr<GlobalAlias> GA;
1097  std::unique_ptr<GlobalIFunc> GI;
1098  GlobalValue *GV;
1099  if (IsAlias) {
1100  GA.reset(GlobalAlias::create(Ty, AddrSpace,
1102  Aliasee, /*Parent*/ nullptr));
1103  GV = GA.get();
1104  } else {
1105  GI.reset(GlobalIFunc::create(Ty, AddrSpace,
1107  Aliasee, /*Parent*/ nullptr));
1108  GV = GI.get();
1109  }
1110  GV->setThreadLocalMode(TLM);
1113  GV->setUnnamedAddr(UnnamedAddr);
1114  maybeSetDSOLocal(DSOLocal, *GV);
1115 
1116  // At this point we've parsed everything except for the IndirectSymbolAttrs.
1117  // Now parse them if there are any.
1118  while (Lex.getKind() == lltok::comma) {
1119  Lex.Lex();
1120 
1121  if (Lex.getKind() == lltok::kw_partition) {
1122  Lex.Lex();
1123  GV->setPartition(Lex.getStrVal());
1124  if (parseToken(lltok::StringConstant, "expected partition string"))
1125  return true;
1126  } else {
1127  return tokError("unknown alias or ifunc property!");
1128  }
1129  }
1130 
1131  if (Name.empty())
1132  NumberedVals.push_back(GV);
1133 
1134  if (GVal) {
1135  // Verify that types agree.
1136  if (GVal->getType() != GV->getType())
1137  return error(
1138  ExplicitTypeLoc,
1139  "forward reference and definition of alias have different types");
1140 
1141  // If they agree, just RAUW the old value with the alias and remove the
1142  // forward ref info.
1143  GVal->replaceAllUsesWith(GV);
1144  GVal->eraseFromParent();
1145  }
1146 
1147  // Insert into the module, we know its name won't collide now.
1148  if (IsAlias)
1149  M->getAliasList().push_back(GA.release());
1150  else
1151  M->getIFuncList().push_back(GI.release());
1152  assert(GV->getName() == Name && "Should not be a name conflict!");
1153 
1154  return false;
1155 }
1156 
1158  switch (Kind) {
1161  case lltok::kw_sanitize_memtag:
1163  return true;
1164  default:
1165  return false;
1166  }
1167 }
1168 
1169 bool LLParser::parseSanitizer(GlobalVariable *GV) {
1172  if (GV->hasSanitizerMetadata())
1173  Meta = GV->getSanitizerMetadata();
1174 
1175  switch (Lex.getKind()) {
1177  Meta.NoAddress = true;
1178  break;
1180  Meta.NoHWAddress = true;
1181  break;
1182  case lltok::kw_sanitize_memtag:
1183  Meta.Memtag = true;
1184  break;
1186  Meta.IsDynInit = true;
1187  break;
1188  default:
1189  return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1190  }
1191  GV->setSanitizerMetadata(Meta);
1192  Lex.Lex();
1193  return false;
1194 }
1195 
1196 /// parseGlobal
1197 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1198 /// OptionalVisibility OptionalDLLStorageClass
1199 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1200 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1201 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1202 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1203 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1204 /// Const OptionalAttrs
1205 ///
1206 /// Everything up to and including OptionalUnnamedAddr has been parsed
1207 /// already.
1208 ///
1209 bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1210  unsigned Linkage, bool HasLinkage,
1211  unsigned Visibility, unsigned DLLStorageClass,
1212  bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1213  GlobalVariable::UnnamedAddr UnnamedAddr) {
1214  if (!isValidVisibilityForLinkage(Visibility, Linkage))
1215  return error(NameLoc,
1216  "symbol with local linkage must have default visibility");
1217 
1218  if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1219  return error(NameLoc,
1220  "symbol with local linkage cannot have a DLL storage class");
1221 
1222  unsigned AddrSpace;
1223  bool IsConstant, IsExternallyInitialized;
1224  LocTy IsExternallyInitializedLoc;
1225  LocTy TyLoc;
1226 
1227  Type *Ty = nullptr;
1228  if (parseOptionalAddrSpace(AddrSpace) ||
1229  parseOptionalToken(lltok::kw_externally_initialized,
1230  IsExternallyInitialized,
1231  &IsExternallyInitializedLoc) ||
1232  parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1233  return true;
1234 
1235  // If the linkage is specified and is external, then no initializer is
1236  // present.
1237  Constant *Init = nullptr;
1238  if (!HasLinkage ||
1241  if (parseGlobalValue(Ty, Init))
1242  return true;
1243  }
1244 
1246  return error(TyLoc, "invalid type for global variable");
1247 
1248  GlobalValue *GVal = nullptr;
1249 
1250  // See if the global was forward referenced, if so, use the global.
1251  if (!Name.empty()) {
1252  auto I = ForwardRefVals.find(Name);
1253  if (I != ForwardRefVals.end()) {
1254  GVal = I->second.first;
1255  ForwardRefVals.erase(I);
1256  } else if (M->getNamedValue(Name)) {
1257  return error(NameLoc, "redefinition of global '@" + Name + "'");
1258  }
1259  } else {
1260  auto I = ForwardRefValIDs.find(NumberedVals.size());
1261  if (I != ForwardRefValIDs.end()) {
1262  GVal = I->second.first;
1263  ForwardRefValIDs.erase(I);
1264  }
1265  }
1266 
1267  GlobalVariable *GV = new GlobalVariable(
1268  *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1269  GlobalVariable::NotThreadLocal, AddrSpace);
1270 
1271  if (Name.empty())
1272  NumberedVals.push_back(GV);
1273 
1274  // Set the parsed properties on the global.
1275  if (Init)
1276  GV->setInitializer(Init);
1277  GV->setConstant(IsConstant);
1279  maybeSetDSOLocal(DSOLocal, *GV);
1282  GV->setExternallyInitialized(IsExternallyInitialized);
1283  GV->setThreadLocalMode(TLM);
1284  GV->setUnnamedAddr(UnnamedAddr);
1285 
1286  if (GVal) {
1287  if (GVal->getType() != Ty->getPointerTo(AddrSpace))
1288  return error(
1289  TyLoc,
1290  "forward reference and definition of global have different types");
1291 
1292  GVal->replaceAllUsesWith(GV);
1293  GVal->eraseFromParent();
1294  }
1295 
1296  // parse attributes on the global.
1297  while (Lex.getKind() == lltok::comma) {
1298  Lex.Lex();
1299 
1300  if (Lex.getKind() == lltok::kw_section) {
1301  Lex.Lex();
1302  GV->setSection(Lex.getStrVal());
1303  if (parseToken(lltok::StringConstant, "expected global section string"))
1304  return true;
1305  } else if (Lex.getKind() == lltok::kw_partition) {
1306  Lex.Lex();
1307  GV->setPartition(Lex.getStrVal());
1308  if (parseToken(lltok::StringConstant, "expected partition string"))
1309  return true;
1310  } else if (Lex.getKind() == lltok::kw_align) {
1311  MaybeAlign Alignment;
1312  if (parseOptionalAlignment(Alignment))
1313  return true;
1314  GV->setAlignment(Alignment);
1315  } else if (Lex.getKind() == lltok::MetadataVar) {
1316  if (parseGlobalObjectMetadataAttachment(*GV))
1317  return true;
1318  } else if (isSanitizer(Lex.getKind())) {
1319  if (parseSanitizer(GV))
1320  return true;
1321  } else {
1322  Comdat *C;
1323  if (parseOptionalComdat(Name, C))
1324  return true;
1325  if (C)
1326  GV->setComdat(C);
1327  else
1328  return tokError("unknown global variable property!");
1329  }
1330  }
1331 
1333  LocTy BuiltinLoc;
1334  std::vector<unsigned> FwdRefAttrGrps;
1335  if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1336  return true;
1337  if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1338  GV->setAttributes(AttributeSet::get(Context, Attrs));
1339  ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1340  }
1341 
1342  return false;
1343 }
1344 
1345 /// parseUnnamedAttrGrp
1346 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1347 bool LLParser::parseUnnamedAttrGrp() {
1349  LocTy AttrGrpLoc = Lex.getLoc();
1350  Lex.Lex();
1351 
1352  if (Lex.getKind() != lltok::AttrGrpID)
1353  return tokError("expected attribute group id");
1354 
1355  unsigned VarID = Lex.getUIntVal();
1356  std::vector<unsigned> unused;
1357  LocTy BuiltinLoc;
1358  Lex.Lex();
1359 
1360  if (parseToken(lltok::equal, "expected '=' here") ||
1361  parseToken(lltok::lbrace, "expected '{' here"))
1362  return true;
1363 
1364  auto R = NumberedAttrBuilders.find(VarID);
1365  if (R == NumberedAttrBuilders.end())
1366  R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1367 
1368  if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1369  parseToken(lltok::rbrace, "expected end of attribute group"))
1370  return true;
1371 
1372  if (!R->second.hasAttributes())
1373  return error(AttrGrpLoc, "attribute group has no attributes");
1374 
1375  return false;
1376 }
1377 
1379  switch (Kind) {
1380 #define GET_ATTR_NAMES
1381 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1382  case lltok::kw_##DISPLAY_NAME: \
1383  return Attribute::ENUM_NAME;
1384 #include "llvm/IR/Attributes.inc"
1385  default:
1386  return Attribute::None;
1387  }
1388 }
1389 
1390 bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1391  bool InAttrGroup) {
1392  if (Attribute::isTypeAttrKind(Attr))
1393  return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1394 
1395  switch (Attr) {
1396  case Attribute::Alignment: {
1397  MaybeAlign Alignment;
1398  if (InAttrGroup) {
1399  uint32_t Value = 0;
1400  Lex.Lex();
1401  if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1402  return true;
1403  Alignment = Align(Value);
1404  } else {
1405  if (parseOptionalAlignment(Alignment, true))
1406  return true;
1407  }
1408  B.addAlignmentAttr(Alignment);
1409  return false;
1410  }
1411  case Attribute::StackAlignment: {
1412  unsigned Alignment;
1413  if (InAttrGroup) {
1414  Lex.Lex();
1415  if (parseToken(lltok::equal, "expected '=' here") ||
1416  parseUInt32(Alignment))
1417  return true;
1418  } else {
1419  if (parseOptionalStackAlignment(Alignment))
1420  return true;
1421  }
1422  B.addStackAlignmentAttr(Alignment);
1423  return false;
1424  }
1425  case Attribute::AllocSize: {
1426  unsigned ElemSizeArg;
1427  Optional<unsigned> NumElemsArg;
1428  if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1429  return true;
1430  B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1431  return false;
1432  }
1433  case Attribute::VScaleRange: {
1434  unsigned MinValue, MaxValue;
1435  if (parseVScaleRangeArguments(MinValue, MaxValue))
1436  return true;
1437  B.addVScaleRangeAttr(MinValue,
1438  MaxValue > 0 ? MaxValue : Optional<unsigned>());
1439  return false;
1440  }
1441  case Attribute::Dereferenceable: {
1442  uint64_t Bytes;
1443  if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1444  return true;
1445  B.addDereferenceableAttr(Bytes);
1446  return false;
1447  }
1448  case Attribute::DereferenceableOrNull: {
1449  uint64_t Bytes;
1450  if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1451  return true;
1452  B.addDereferenceableOrNullAttr(Bytes);
1453  return false;
1454  }
1455  case Attribute::UWTable: {
1456  UWTableKind Kind;
1457  if (parseOptionalUWTableKind(Kind))
1458  return true;
1459  B.addUWTableAttr(Kind);
1460  return false;
1461  }
1462  case Attribute::AllocKind: {
1464  if (parseAllocKind(Kind))
1465  return true;
1466  B.addAllocKindAttr(Kind);
1467  return false;
1468  }
1469  default:
1470  B.addAttribute(Attr);
1471  Lex.Lex();
1472  return false;
1473  }
1474 }
1475 
1476 /// parseFnAttributeValuePairs
1477 /// ::= <attr> | <attr> '=' <value>
1478 bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1479  std::vector<unsigned> &FwdRefAttrGrps,
1480  bool InAttrGrp, LocTy &BuiltinLoc) {
1481  bool HaveError = false;
1482 
1483  B.clear();
1484 
1485  while (true) {
1486  lltok::Kind Token = Lex.getKind();
1487  if (Token == lltok::rbrace)
1488  return HaveError; // Finished.
1489 
1490  if (Token == lltok::StringConstant) {
1491  if (parseStringAttribute(B))
1492  return true;
1493  continue;
1494  }
1495 
1496  if (Token == lltok::AttrGrpID) {
1497  // Allow a function to reference an attribute group:
1498  //
1499  // define void @foo() #1 { ... }
1500  if (InAttrGrp) {
1501  HaveError |= error(
1502  Lex.getLoc(),
1503  "cannot have an attribute group reference in an attribute group");
1504  } else {
1505  // Save the reference to the attribute group. We'll fill it in later.
1506  FwdRefAttrGrps.push_back(Lex.getUIntVal());
1507  }
1508  Lex.Lex();
1509  continue;
1510  }
1511 
1512  SMLoc Loc = Lex.getLoc();
1513  if (Token == lltok::kw_builtin)
1514  BuiltinLoc = Loc;
1515 
1516  Attribute::AttrKind Attr = tokenToAttribute(Token);
1517  if (Attr == Attribute::None) {
1518  if (!InAttrGrp)
1519  return HaveError;
1520  return error(Lex.getLoc(), "unterminated attribute group");
1521  }
1522 
1523  if (parseEnumAttribute(Attr, B, InAttrGrp))
1524  return true;
1525 
1526  // As a hack, we allow function alignment to be initially parsed as an
1527  // attribute on a function declaration/definition or added to an attribute
1528  // group and later moved to the alignment field.
1529  if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1530  HaveError |= error(Loc, "this attribute does not apply to functions");
1531  }
1532 }
1533 
1534 //===----------------------------------------------------------------------===//
1535 // GlobalValue Reference/Resolution Routines.
1536 //===----------------------------------------------------------------------===//
1537 
1539  // For opaque pointers, the used global type does not matter. We will later
1540  // RAUW it with a global/function of the correct type.
1541  if (PTy->isOpaque())
1542  return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1543  GlobalValue::ExternalWeakLinkage, nullptr, "",
1545  PTy->getAddressSpace());
1546 
1547  Type *ElemTy = PTy->getNonOpaquePointerElementType();
1548  if (auto *FT = dyn_cast<FunctionType>(ElemTy))
1550  PTy->getAddressSpace(), "", M);
1551  else
1552  return new GlobalVariable(
1553  *M, ElemTy, false, GlobalValue::ExternalWeakLinkage, nullptr, "",
1555 }
1556 
1557 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1558  Value *Val) {
1559  Type *ValTy = Val->getType();
1560  if (ValTy == Ty)
1561  return Val;
1562  if (Ty->isLabelTy())
1563  error(Loc, "'" + Name + "' is not a basic block");
1564  else
1565  error(Loc, "'" + Name + "' defined with type '" +
1566  getTypeString(Val->getType()) + "' but expected '" +
1567  getTypeString(Ty) + "'");
1568  return nullptr;
1569 }
1570 
1571 /// getGlobalVal - Get a value with the specified name or ID, creating a
1572 /// forward reference record if needed. This can return null if the value
1573 /// exists but does not have the right type.
1574 GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1575  LocTy Loc) {
1576  PointerType *PTy = dyn_cast<PointerType>(Ty);
1577  if (!PTy) {
1578  error(Loc, "global variable reference must have pointer type");
1579  return nullptr;
1580  }
1581 
1582  // Look this name up in the normal function symbol table.
1583  GlobalValue *Val =
1584  cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1585 
1586  // If this is a forward reference for the value, see if we already created a
1587  // forward ref record.
1588  if (!Val) {
1589  auto I = ForwardRefVals.find(Name);
1590  if (I != ForwardRefVals.end())
1591  Val = I->second.first;
1592  }
1593 
1594  // If we have the value in the symbol table or fwd-ref table, return it.
1595  if (Val)
1596  return cast_or_null<GlobalValue>(
1597  checkValidVariableType(Loc, "@" + Name, Ty, Val));
1598 
1599  // Otherwise, create a new forward reference for this value and remember it.
1600  GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1601  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1602  return FwdVal;
1603 }
1604 
1605 GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1606  PointerType *PTy = dyn_cast<PointerType>(Ty);
1607  if (!PTy) {
1608  error(Loc, "global variable reference must have pointer type");
1609  return nullptr;
1610  }
1611 
1612  GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1613 
1614  // If this is a forward reference for the value, see if we already created a
1615  // forward ref record.
1616  if (!Val) {
1617  auto I = ForwardRefValIDs.find(ID);
1618  if (I != ForwardRefValIDs.end())
1619  Val = I->second.first;
1620  }
1621 
1622  // If we have the value in the symbol table or fwd-ref table, return it.
1623  if (Val)
1624  return cast_or_null<GlobalValue>(
1625  checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1626 
1627  // Otherwise, create a new forward reference for this value and remember it.
1628  GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1629  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1630  return FwdVal;
1631 }
1632 
1633 //===----------------------------------------------------------------------===//
1634 // Comdat Reference/Resolution Routines.
1635 //===----------------------------------------------------------------------===//
1636 
1637 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1638  // Look this name up in the comdat symbol table.
1639  Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1641  if (I != ComdatSymTab.end())
1642  return &I->second;
1643 
1644  // Otherwise, create a new forward reference for this value and remember it.
1645  Comdat *C = M->getOrInsertComdat(Name);
1646  ForwardRefComdats[Name] = Loc;
1647  return C;
1648 }
1649 
1650 //===----------------------------------------------------------------------===//
1651 // Helper Routines.
1652 //===----------------------------------------------------------------------===//
1653 
1654 /// parseToken - If the current token has the specified kind, eat it and return
1655 /// success. Otherwise, emit the specified error and return failure.
1656 bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1657  if (Lex.getKind() != T)
1658  return tokError(ErrMsg);
1659  Lex.Lex();
1660  return false;
1661 }
1662 
1663 /// parseStringConstant
1664 /// ::= StringConstant
1665 bool LLParser::parseStringConstant(std::string &Result) {
1666  if (Lex.getKind() != lltok::StringConstant)
1667  return tokError("expected string constant");
1668  Result = Lex.getStrVal();
1669  Lex.Lex();
1670  return false;
1671 }
1672 
1673 /// parseUInt32
1674 /// ::= uint32
1675 bool LLParser::parseUInt32(uint32_t &Val) {
1676  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1677  return tokError("expected integer");
1678  uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1679  if (Val64 != unsigned(Val64))
1680  return tokError("expected 32-bit integer (too large)");
1681  Val = Val64;
1682  Lex.Lex();
1683  return false;
1684 }
1685 
1686 /// parseUInt64
1687 /// ::= uint64
1688 bool LLParser::parseUInt64(uint64_t &Val) {
1689  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1690  return tokError("expected integer");
1691  Val = Lex.getAPSIntVal().getLimitedValue();
1692  Lex.Lex();
1693  return false;
1694 }
1695 
1696 /// parseTLSModel
1697 /// := 'localdynamic'
1698 /// := 'initialexec'
1699 /// := 'localexec'
1700 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1701  switch (Lex.getKind()) {
1702  default:
1703  return tokError("expected localdynamic, initialexec or localexec");
1706  break;
1707  case lltok::kw_initialexec:
1709  break;
1710  case lltok::kw_localexec:
1712  break;
1713  }
1714 
1715  Lex.Lex();
1716  return false;
1717 }
1718 
1719 /// parseOptionalThreadLocal
1720 /// := /*empty*/
1721 /// := 'thread_local'
1722 /// := 'thread_local' '(' tlsmodel ')'
1723 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1725  if (!EatIfPresent(lltok::kw_thread_local))
1726  return false;
1727 
1729  if (Lex.getKind() == lltok::lparen) {
1730  Lex.Lex();
1731  return parseTLSModel(TLM) ||
1732  parseToken(lltok::rparen, "expected ')' after thread local model");
1733  }
1734  return false;
1735 }
1736 
1737 /// parseOptionalAddrSpace
1738 /// := /*empty*/
1739 /// := 'addrspace' '(' uint32 ')'
1740 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1741  AddrSpace = DefaultAS;
1742  if (!EatIfPresent(lltok::kw_addrspace))
1743  return false;
1744  return parseToken(lltok::lparen, "expected '(' in address space") ||
1745  parseUInt32(AddrSpace) ||
1746  parseToken(lltok::rparen, "expected ')' in address space");
1747 }
1748 
1749 /// parseStringAttribute
1750 /// := StringConstant
1751 /// := StringConstant '=' StringConstant
1752 bool LLParser::parseStringAttribute(AttrBuilder &B) {
1753  std::string Attr = Lex.getStrVal();
1754  Lex.Lex();
1755  std::string Val;
1756  if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1757  return true;
1758  B.addAttribute(Attr, Val);
1759  return false;
1760 }
1761 
1762 /// Parse a potentially empty list of parameter or return attributes.
1763 bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1764  bool HaveError = false;
1765 
1766  B.clear();
1767 
1768  while (true) {
1769  lltok::Kind Token = Lex.getKind();
1770  if (Token == lltok::StringConstant) {
1771  if (parseStringAttribute(B))
1772  return true;
1773  continue;
1774  }
1775 
1776  SMLoc Loc = Lex.getLoc();
1777  Attribute::AttrKind Attr = tokenToAttribute(Token);
1778  if (Attr == Attribute::None)
1779  return HaveError;
1780 
1781  if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
1782  return true;
1783 
1784  if (IsParam && !Attribute::canUseAsParamAttr(Attr))
1785  HaveError |= error(Loc, "this attribute does not apply to parameters");
1786  if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
1787  HaveError |= error(Loc, "this attribute does not apply to return values");
1788  }
1789 }
1790 
1791 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1792  HasLinkage = true;
1793  switch (Kind) {
1794  default:
1795  HasLinkage = false;
1797  case lltok::kw_private:
1799  case lltok::kw_internal:
1801  case lltok::kw_weak:
1803  case lltok::kw_weak_odr:
1805  case lltok::kw_linkonce:
1811  case lltok::kw_appending:
1813  case lltok::kw_common:
1815  case lltok::kw_extern_weak:
1817  case lltok::kw_external:
1819  }
1820 }
1821 
1822 /// parseOptionalLinkage
1823 /// ::= /*empty*/
1824 /// ::= 'private'
1825 /// ::= 'internal'
1826 /// ::= 'weak'
1827 /// ::= 'weak_odr'
1828 /// ::= 'linkonce'
1829 /// ::= 'linkonce_odr'
1830 /// ::= 'available_externally'
1831 /// ::= 'appending'
1832 /// ::= 'common'
1833 /// ::= 'extern_weak'
1834 /// ::= 'external'
1835 bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1836  unsigned &Visibility,
1837  unsigned &DLLStorageClass, bool &DSOLocal) {
1838  Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1839  if (HasLinkage)
1840  Lex.Lex();
1841  parseOptionalDSOLocal(DSOLocal);
1842  parseOptionalVisibility(Visibility);
1843  parseOptionalDLLStorageClass(DLLStorageClass);
1844 
1845  if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1846  return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1847  }
1848 
1849  return false;
1850 }
1851 
1852 void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
1853  switch (Lex.getKind()) {
1854  default:
1855  DSOLocal = false;
1856  break;
1857  case lltok::kw_dso_local:
1858  DSOLocal = true;
1859  Lex.Lex();
1860  break;
1862  DSOLocal = false;
1863  Lex.Lex();
1864  break;
1865  }
1866 }
1867 
1868 /// parseOptionalVisibility
1869 /// ::= /*empty*/
1870 /// ::= 'default'
1871 /// ::= 'hidden'
1872 /// ::= 'protected'
1873 ///
1874 void LLParser::parseOptionalVisibility(unsigned &Res) {
1875  switch (Lex.getKind()) {
1876  default:
1878  return;
1879  case lltok::kw_default:
1881  break;
1882  case lltok::kw_hidden:
1884  break;
1885  case lltok::kw_protected:
1887  break;
1888  }
1889  Lex.Lex();
1890 }
1891 
1892 /// parseOptionalDLLStorageClass
1893 /// ::= /*empty*/
1894 /// ::= 'dllimport'
1895 /// ::= 'dllexport'
1896 ///
1897 void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
1898  switch (Lex.getKind()) {
1899  default:
1901  return;
1902  case lltok::kw_dllimport:
1904  break;
1905  case lltok::kw_dllexport:
1907  break;
1908  }
1909  Lex.Lex();
1910 }
1911 
1912 /// parseOptionalCallingConv
1913 /// ::= /*empty*/
1914 /// ::= 'ccc'
1915 /// ::= 'fastcc'
1916 /// ::= 'intel_ocl_bicc'
1917 /// ::= 'coldcc'
1918 /// ::= 'cfguard_checkcc'
1919 /// ::= 'x86_stdcallcc'
1920 /// ::= 'x86_fastcallcc'
1921 /// ::= 'x86_thiscallcc'
1922 /// ::= 'x86_vectorcallcc'
1923 /// ::= 'arm_apcscc'
1924 /// ::= 'arm_aapcscc'
1925 /// ::= 'arm_aapcs_vfpcc'
1926 /// ::= 'aarch64_vector_pcs'
1927 /// ::= 'aarch64_sve_vector_pcs'
1928 /// ::= 'aarch64_sme_preservemost_from_x0'
1929 /// ::= 'aarch64_sme_preservemost_from_x2'
1930 /// ::= 'msp430_intrcc'
1931 /// ::= 'avr_intrcc'
1932 /// ::= 'avr_signalcc'
1933 /// ::= 'ptx_kernel'
1934 /// ::= 'ptx_device'
1935 /// ::= 'spir_func'
1936 /// ::= 'spir_kernel'
1937 /// ::= 'x86_64_sysvcc'
1938 /// ::= 'win64cc'
1939 /// ::= 'webkit_jscc'
1940 /// ::= 'anyregcc'
1941 /// ::= 'preserve_mostcc'
1942 /// ::= 'preserve_allcc'
1943 /// ::= 'ghccc'
1944 /// ::= 'swiftcc'
1945 /// ::= 'swifttailcc'
1946 /// ::= 'x86_intrcc'
1947 /// ::= 'hhvmcc'
1948 /// ::= 'hhvm_ccc'
1949 /// ::= 'cxx_fast_tlscc'
1950 /// ::= 'amdgpu_vs'
1951 /// ::= 'amdgpu_ls'
1952 /// ::= 'amdgpu_hs'
1953 /// ::= 'amdgpu_es'
1954 /// ::= 'amdgpu_gs'
1955 /// ::= 'amdgpu_ps'
1956 /// ::= 'amdgpu_cs'
1957 /// ::= 'amdgpu_kernel'
1958 /// ::= 'tailcc'
1959 /// ::= 'cc' UINT
1960 ///
1961 bool LLParser::parseOptionalCallingConv(unsigned &CC) {
1962  switch (Lex.getKind()) {
1963  default: CC = CallingConv::C; return false;
1964  case lltok::kw_ccc: CC = CallingConv::C; break;
1965  case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1966  case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1979  break;
1982  break;
1985  break;
1995  case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1997  case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2000  case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2001  case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2004  case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
2005  case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
2016  case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2017  case lltok::kw_cc: {
2018  Lex.Lex();
2019  return parseUInt32(CC);
2020  }
2021  }
2022 
2023  Lex.Lex();
2024  return false;
2025 }
2026 
2027 /// parseMetadataAttachment
2028 /// ::= !dbg !42
2029 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2030  assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2031 
2032  std::string Name = Lex.getStrVal();
2033  Kind = M->getMDKindID(Name);
2034  Lex.Lex();
2035 
2036  return parseMDNode(MD);
2037 }
2038 
2039 /// parseInstructionMetadata
2040 /// ::= !dbg !42 (',' !dbg !57)*
2041 bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2042  do {
2043  if (Lex.getKind() != lltok::MetadataVar)
2044  return tokError("expected metadata after comma");
2045 
2046  unsigned MDK;
2047  MDNode *N;
2048  if (parseMetadataAttachment(MDK, N))
2049  return true;
2050 
2051  Inst.setMetadata(MDK, N);
2052  if (MDK == LLVMContext::MD_tbaa)
2053  InstsWithTBAATag.push_back(&Inst);
2054 
2055  // If this is the end of the list, we're done.
2056  } while (EatIfPresent(lltok::comma));
2057  return false;
2058 }
2059 
2060 /// parseGlobalObjectMetadataAttachment
2061 /// ::= !dbg !57
2062 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2063  unsigned MDK;
2064  MDNode *N;
2065  if (parseMetadataAttachment(MDK, N))
2066  return true;
2067 
2068  GO.addMetadata(MDK, *N);
2069  return false;
2070 }
2071 
2072 /// parseOptionalFunctionMetadata
2073 /// ::= (!dbg !57)*
2074 bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2075  while (Lex.getKind() == lltok::MetadataVar)
2076  if (parseGlobalObjectMetadataAttachment(F))
2077  return true;
2078  return false;
2079 }
2080 
2081 /// parseOptionalAlignment
2082 /// ::= /* empty */
2083 /// ::= 'align' 4
2084 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2085  Alignment = None;
2086  if (!EatIfPresent(lltok::kw_align))
2087  return false;
2088  LocTy AlignLoc = Lex.getLoc();
2089  uint64_t Value = 0;
2090 
2091  LocTy ParenLoc = Lex.getLoc();
2092  bool HaveParens = false;
2093  if (AllowParens) {
2094  if (EatIfPresent(lltok::lparen))
2095  HaveParens = true;
2096  }
2097 
2098  if (parseUInt64(Value))
2099  return true;
2100 
2101  if (HaveParens && !EatIfPresent(lltok::rparen))
2102  return error(ParenLoc, "expected ')'");
2103 
2104  if (!isPowerOf2_64(Value))
2105  return error(AlignLoc, "alignment is not a power of two");
2107  return error(AlignLoc, "huge alignments are not supported yet");
2108  Alignment = Align(Value);
2109  return false;
2110 }
2111 
2112 /// parseOptionalDerefAttrBytes
2113 /// ::= /* empty */
2114 /// ::= AttrKind '(' 4 ')'
2115 ///
2116 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2117 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2118  uint64_t &Bytes) {
2119  assert((AttrKind == lltok::kw_dereferenceable ||
2120  AttrKind == lltok::kw_dereferenceable_or_null) &&
2121  "contract!");
2122 
2123  Bytes = 0;
2124  if (!EatIfPresent(AttrKind))
2125  return false;
2126  LocTy ParenLoc = Lex.getLoc();
2127  if (!EatIfPresent(lltok::lparen))
2128  return error(ParenLoc, "expected '('");
2129  LocTy DerefLoc = Lex.getLoc();
2130  if (parseUInt64(Bytes))
2131  return true;
2132  ParenLoc = Lex.getLoc();
2133  if (!EatIfPresent(lltok::rparen))
2134  return error(ParenLoc, "expected ')'");
2135  if (!Bytes)
2136  return error(DerefLoc, "dereferenceable bytes must be non-zero");
2137  return false;
2138 }
2139 
2140 bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2141  Lex.Lex();
2143  if (!EatIfPresent(lltok::lparen))
2144  return false;
2145  LocTy KindLoc = Lex.getLoc();
2146  if (Lex.getKind() == lltok::kw_sync)
2148  else if (Lex.getKind() == lltok::kw_async)
2150  else
2151  return error(KindLoc, "expected unwind table kind");
2152  Lex.Lex();
2153  return parseToken(lltok::rparen, "expected ')'");
2154 }
2155 
2156 bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2157  Lex.Lex();
2158  LocTy ParenLoc = Lex.getLoc();
2159  if (!EatIfPresent(lltok::lparen))
2160  return error(ParenLoc, "expected '('");
2161  LocTy KindLoc = Lex.getLoc();
2162  std::string Arg;
2163  if (parseStringConstant(Arg))
2164  return error(KindLoc, "expected allockind value");
2165  for (StringRef A : llvm::split(Arg, ",")) {
2166  if (A == "alloc") {
2168  } else if (A == "realloc") {
2170  } else if (A == "free") {
2172  } else if (A == "uninitialized") {
2174  } else if (A == "zeroed") {
2176  } else if (A == "aligned") {
2178  } else {
2179  return error(KindLoc, Twine("unknown allockind ") + A);
2180  }
2181  }
2182  ParenLoc = Lex.getLoc();
2183  if (!EatIfPresent(lltok::rparen))
2184  return error(ParenLoc, "expected ')'");
2185  if (Kind == AllocFnKind::Unknown)
2186  return error(KindLoc, "expected allockind value");
2187  return false;
2188 }
2189 
2190 /// parseOptionalCommaAlign
2191 /// ::=
2192 /// ::= ',' align 4
2193 ///
2194 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2195 /// end.
2196 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2197  bool &AteExtraComma) {
2198  AteExtraComma = false;
2199  while (EatIfPresent(lltok::comma)) {
2200  // Metadata at the end is an early exit.
2201  if (Lex.getKind() == lltok::MetadataVar) {
2202  AteExtraComma = true;
2203  return false;
2204  }
2205 
2206  if (Lex.getKind() != lltok::kw_align)
2207  return error(Lex.getLoc(), "expected metadata or 'align'");
2208 
2209  if (parseOptionalAlignment(Alignment))
2210  return true;
2211  }
2212 
2213  return false;
2214 }
2215 
2216 /// parseOptionalCommaAddrSpace
2217 /// ::=
2218 /// ::= ',' addrspace(1)
2219 ///
2220 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2221 /// end.
2222 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2223  bool &AteExtraComma) {
2224  AteExtraComma = false;
2225  while (EatIfPresent(lltok::comma)) {
2226  // Metadata at the end is an early exit.
2227  if (Lex.getKind() == lltok::MetadataVar) {
2228  AteExtraComma = true;
2229  return false;
2230  }
2231 
2232  Loc = Lex.getLoc();
2233  if (Lex.getKind() != lltok::kw_addrspace)
2234  return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2235 
2236  if (parseOptionalAddrSpace(AddrSpace))
2237  return true;
2238  }
2239 
2240  return false;
2241 }
2242 
2243 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2244  Optional<unsigned> &HowManyArg) {
2245  Lex.Lex();
2246 
2247  auto StartParen = Lex.getLoc();
2248  if (!EatIfPresent(lltok::lparen))
2249  return error(StartParen, "expected '('");
2250 
2251  if (parseUInt32(BaseSizeArg))
2252  return true;
2253 
2254  if (EatIfPresent(lltok::comma)) {
2255  auto HowManyAt = Lex.getLoc();
2256  unsigned HowMany;
2257  if (parseUInt32(HowMany))
2258  return true;
2259  if (HowMany == BaseSizeArg)
2260  return error(HowManyAt,
2261  "'allocsize' indices can't refer to the same parameter");
2262  HowManyArg = HowMany;
2263  } else
2264  HowManyArg = None;
2265 
2266  auto EndParen = Lex.getLoc();
2267  if (!EatIfPresent(lltok::rparen))
2268  return error(EndParen, "expected ')'");
2269  return false;
2270 }
2271 
2272 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2273  unsigned &MaxValue) {
2274  Lex.Lex();
2275 
2276  auto StartParen = Lex.getLoc();
2277  if (!EatIfPresent(lltok::lparen))
2278  return error(StartParen, "expected '('");
2279 
2280  if (parseUInt32(MinValue))
2281  return true;
2282 
2283  if (EatIfPresent(lltok::comma)) {
2284  if (parseUInt32(MaxValue))
2285  return true;
2286  } else
2287  MaxValue = MinValue;
2288 
2289  auto EndParen = Lex.getLoc();
2290  if (!EatIfPresent(lltok::rparen))
2291  return error(EndParen, "expected ')'");
2292  return false;
2293 }
2294 
2295 /// parseScopeAndOrdering
2296 /// if isAtomic: ::= SyncScope? AtomicOrdering
2297 /// else: ::=
2298 ///
2299 /// This sets Scope and Ordering to the parsed values.
2300 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2301  AtomicOrdering &Ordering) {
2302  if (!IsAtomic)
2303  return false;
2304 
2305  return parseScope(SSID) || parseOrdering(Ordering);
2306 }
2307 
2308 /// parseScope
2309 /// ::= syncscope("singlethread" | "<target scope>")?
2310 ///
2311 /// This sets synchronization scope ID to the ID of the parsed value.
2312 bool LLParser::parseScope(SyncScope::ID &SSID) {
2313  SSID = SyncScope::System;
2314  if (EatIfPresent(lltok::kw_syncscope)) {
2315  auto StartParenAt = Lex.getLoc();
2316  if (!EatIfPresent(lltok::lparen))
2317  return error(StartParenAt, "Expected '(' in syncscope");
2318 
2319  std::string SSN;
2320  auto SSNAt = Lex.getLoc();
2321  if (parseStringConstant(SSN))
2322  return error(SSNAt, "Expected synchronization scope name");
2323 
2324  auto EndParenAt = Lex.getLoc();
2325  if (!EatIfPresent(lltok::rparen))
2326  return error(EndParenAt, "Expected ')' in syncscope");
2327 
2328  SSID = Context.getOrInsertSyncScopeID(SSN);
2329  }
2330 
2331  return false;
2332 }
2333 
2334 /// parseOrdering
2335 /// ::= AtomicOrdering
2336 ///
2337 /// This sets Ordering to the parsed value.
2338 bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2339  switch (Lex.getKind()) {
2340  default:
2341  return tokError("Expected ordering on atomic instruction");
2342  case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2343  case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2344  // Not specified yet:
2345  // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2346  case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2347  case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2348  case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2349  case lltok::kw_seq_cst:
2351  break;
2352  }
2353  Lex.Lex();
2354  return false;
2355 }
2356 
2357 /// parseOptionalStackAlignment
2358 /// ::= /* empty */
2359 /// ::= 'alignstack' '(' 4 ')'
2360 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2361  Alignment = 0;
2362  if (!EatIfPresent(lltok::kw_alignstack))
2363  return false;
2364  LocTy ParenLoc = Lex.getLoc();
2365  if (!EatIfPresent(lltok::lparen))
2366  return error(ParenLoc, "expected '('");
2367  LocTy AlignLoc = Lex.getLoc();
2368  if (parseUInt32(Alignment))
2369  return true;
2370  ParenLoc = Lex.getLoc();
2371  if (!EatIfPresent(lltok::rparen))
2372  return error(ParenLoc, "expected ')'");
2373  if (!isPowerOf2_32(Alignment))
2374  return error(AlignLoc, "stack alignment is not a power of two");
2375  return false;
2376 }
2377 
2378 /// parseIndexList - This parses the index list for an insert/extractvalue
2379 /// instruction. This sets AteExtraComma in the case where we eat an extra
2380 /// comma at the end of the line and find that it is followed by metadata.
2381 /// Clients that don't allow metadata can call the version of this function that
2382 /// only takes one argument.
2383 ///
2384 /// parseIndexList
2385 /// ::= (',' uint32)+
2386 ///
2387 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2388  bool &AteExtraComma) {
2389  AteExtraComma = false;
2390 
2391  if (Lex.getKind() != lltok::comma)
2392  return tokError("expected ',' as start of index list");
2393 
2394  while (EatIfPresent(lltok::comma)) {
2395  if (Lex.getKind() == lltok::MetadataVar) {
2396  if (Indices.empty())
2397  return tokError("expected index");
2398  AteExtraComma = true;
2399  return false;
2400  }
2401  unsigned Idx = 0;
2402  if (parseUInt32(Idx))
2403  return true;
2404  Indices.push_back(Idx);
2405  }
2406 
2407  return false;
2408 }
2409 
2410 //===----------------------------------------------------------------------===//
2411 // Type Parsing.
2412 //===----------------------------------------------------------------------===//
2413 
2414 /// parseType - parse a type.
2415 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2416  SMLoc TypeLoc = Lex.getLoc();
2417  switch (Lex.getKind()) {
2418  default:
2419  return tokError(Msg);
2420  case lltok::Type:
2421  // Type ::= 'float' | 'void' (etc)
2422  Result = Lex.getTyVal();
2423  Lex.Lex();
2424 
2425  // Handle "ptr" opaque pointer type.
2426  //
2427  // Type ::= ptr ('addrspace' '(' uint32 ')')?
2428  if (Result->isOpaquePointerTy()) {
2429  unsigned AddrSpace;
2430  if (parseOptionalAddrSpace(AddrSpace))
2431  return true;
2432  Result = PointerType::get(getContext(), AddrSpace);
2433 
2434  // Give a nice error for 'ptr*'.
2435  if (Lex.getKind() == lltok::star)
2436  return tokError("ptr* is invalid - use ptr instead");
2437 
2438  // Fall through to parsing the type suffixes only if this 'ptr' is a
2439  // function return. Otherwise, return success, implicitly rejecting other
2440  // suffixes.
2441  if (Lex.getKind() != lltok::lparen)
2442  return false;
2443  }
2444  break;
2445  case lltok::lbrace:
2446  // Type ::= StructType
2447  if (parseAnonStructType(Result, false))
2448  return true;
2449  break;
2450  case lltok::lsquare:
2451  // Type ::= '[' ... ']'
2452  Lex.Lex(); // eat the lsquare.
2453  if (parseArrayVectorType(Result, false))
2454  return true;
2455  break;
2456  case lltok::less: // Either vector or packed struct.
2457  // Type ::= '<' ... '>'
2458  Lex.Lex();
2459  if (Lex.getKind() == lltok::lbrace) {
2460  if (parseAnonStructType(Result, true) ||
2461  parseToken(lltok::greater, "expected '>' at end of packed struct"))
2462  return true;
2463  } else if (parseArrayVectorType(Result, true))
2464  return true;
2465  break;
2466  case lltok::LocalVar: {
2467  // Type ::= %foo
2468  std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2469 
2470  // If the type hasn't been defined yet, create a forward definition and
2471  // remember where that forward def'n was seen (in case it never is defined).
2472  if (!Entry.first) {
2473  Entry.first = StructType::create(Context, Lex.getStrVal());
2474  Entry.second = Lex.getLoc();
2475  }
2476  Result = Entry.first;
2477  Lex.Lex();
2478  break;
2479  }
2480 
2481  case lltok::LocalVarID: {
2482  // Type ::= %4
2483  std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2484 
2485  // If the type hasn't been defined yet, create a forward definition and
2486  // remember where that forward def'n was seen (in case it never is defined).
2487  if (!Entry.first) {
2488  Entry.first = StructType::create(Context);
2489  Entry.second = Lex.getLoc();
2490  }
2491  Result = Entry.first;
2492  Lex.Lex();
2493  break;
2494  }
2495  }
2496 
2497  // parse the type suffixes.
2498  while (true) {
2499  switch (Lex.getKind()) {
2500  // End of type.
2501  default:
2502  if (!AllowVoid && Result->isVoidTy())
2503  return error(TypeLoc, "void type only allowed for function results");
2504  return false;
2505 
2506  // Type ::= Type '*'
2507  case lltok::star:
2508  if (Result->isLabelTy())
2509  return tokError("basic block pointers are invalid");
2510  if (Result->isVoidTy())
2511  return tokError("pointers to void are invalid - use i8* instead");
2512  if (!PointerType::isValidElementType(Result))
2513  return tokError("pointer to this type is invalid");
2514  Result = PointerType::getUnqual(Result);
2515  Lex.Lex();
2516  break;
2517 
2518  // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2519  case lltok::kw_addrspace: {
2520  if (Result->isLabelTy())
2521  return tokError("basic block pointers are invalid");
2522  if (Result->isVoidTy())
2523  return tokError("pointers to void are invalid; use i8* instead");
2524  if (!PointerType::isValidElementType(Result))
2525  return tokError("pointer to this type is invalid");
2526  unsigned AddrSpace;
2527  if (parseOptionalAddrSpace(AddrSpace) ||
2528  parseToken(lltok::star, "expected '*' in address space"))
2529  return true;
2530 
2531  Result = PointerType::get(Result, AddrSpace);
2532  break;
2533  }
2534 
2535  /// Types '(' ArgTypeListI ')' OptFuncAttrs
2536  case lltok::lparen:
2537  if (parseFunctionType(Result))
2538  return true;
2539  break;
2540  }
2541  }
2542 }
2543 
2544 /// parseParameterList
2545 /// ::= '(' ')'
2546 /// ::= '(' Arg (',' Arg)* ')'
2547 /// Arg
2548 /// ::= Type OptionalAttributes Value OptionalAttributes
2549 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2550  PerFunctionState &PFS, bool IsMustTailCall,
2551  bool InVarArgsFunc) {
2552  if (parseToken(lltok::lparen, "expected '(' in call"))
2553  return true;
2554 
2555  while (Lex.getKind() != lltok::rparen) {
2556  // If this isn't the first argument, we need a comma.
2557  if (!ArgList.empty() &&
2558  parseToken(lltok::comma, "expected ',' in argument list"))
2559  return true;
2560 
2561  // parse an ellipsis if this is a musttail call in a variadic function.
2562  if (Lex.getKind() == lltok::dotdotdot) {
2563  const char *Msg = "unexpected ellipsis in argument list for ";
2564  if (!IsMustTailCall)
2565  return tokError(Twine(Msg) + "non-musttail call");
2566  if (!InVarArgsFunc)
2567  return tokError(Twine(Msg) + "musttail call in non-varargs function");
2568  Lex.Lex(); // Lex the '...', it is purely for readability.
2569  return parseToken(lltok::rparen, "expected ')' at end of argument list");
2570  }
2571 
2572  // parse the argument.
2573  LocTy ArgLoc;
2574  Type *ArgTy = nullptr;
2575  Value *V;
2576  if (parseType(ArgTy, ArgLoc))
2577  return true;
2578 
2579  AttrBuilder ArgAttrs(M->getContext());
2580 
2581  if (ArgTy->isMetadataTy()) {
2582  if (parseMetadataAsValue(V, PFS))
2583  return true;
2584  } else {
2585  // Otherwise, handle normal operands.
2586  if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2587  return true;
2588  }
2589  ArgList.push_back(ParamInfo(
2590  ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2591  }
2592 
2593  if (IsMustTailCall && InVarArgsFunc)
2594  return tokError("expected '...' at end of argument list for musttail call "
2595  "in varargs function");
2596 
2597  Lex.Lex(); // Lex the ')'.
2598  return false;
2599 }
2600 
2601 /// parseRequiredTypeAttr
2602 /// ::= attrname(<ty>)
2603 bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
2604  Attribute::AttrKind AttrKind) {
2605  Type *Ty = nullptr;
2606  if (!EatIfPresent(AttrToken))
2607  return true;
2608  if (!EatIfPresent(lltok::lparen))
2609  return error(Lex.getLoc(), "expected '('");
2610  if (parseType(Ty))
2611  return true;
2612  if (!EatIfPresent(lltok::rparen))
2613  return error(Lex.getLoc(), "expected ')'");
2614 
2615  B.addTypeAttr(AttrKind, Ty);
2616  return false;
2617 }
2618 
2619 /// parseOptionalOperandBundles
2620 /// ::= /*empty*/
2621 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2622 ///
2623 /// OperandBundle
2624 /// ::= bundle-tag '(' ')'
2625 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2626 ///
2627 /// bundle-tag ::= String Constant
2628 bool LLParser::parseOptionalOperandBundles(
2629  SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2630  LocTy BeginLoc = Lex.getLoc();
2631  if (!EatIfPresent(lltok::lsquare))
2632  return false;
2633 
2634  while (Lex.getKind() != lltok::rsquare) {
2635  // If this isn't the first operand bundle, we need a comma.
2636  if (!BundleList.empty() &&
2637  parseToken(lltok::comma, "expected ',' in input list"))
2638  return true;
2639 
2640  std::string Tag;
2641  if (parseStringConstant(Tag))
2642  return true;
2643 
2644  if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
2645  return true;
2646 
2647  std::vector<Value *> Inputs;
2648  while (Lex.getKind() != lltok::rparen) {
2649  // If this isn't the first input, we need a comma.
2650  if (!Inputs.empty() &&
2651  parseToken(lltok::comma, "expected ',' in input list"))
2652  return true;
2653 
2654  Type *Ty = nullptr;
2655  Value *Input = nullptr;
2656  if (parseType(Ty) || parseValue(Ty, Input, PFS))
2657  return true;
2658  Inputs.push_back(Input);
2659  }
2660 
2661  BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2662 
2663  Lex.Lex(); // Lex the ')'.
2664  }
2665 
2666  if (BundleList.empty())
2667  return error(BeginLoc, "operand bundle set must not be empty");
2668 
2669  Lex.Lex(); // Lex the ']'.
2670  return false;
2671 }
2672 
2673 /// parseArgumentList - parse the argument list for a function type or function
2674 /// prototype.
2675 /// ::= '(' ArgTypeListI ')'
2676 /// ArgTypeListI
2677 /// ::= /*empty*/
2678 /// ::= '...'
2679 /// ::= ArgTypeList ',' '...'
2680 /// ::= ArgType (',' ArgType)*
2681 ///
2682 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2683  bool &IsVarArg) {
2684  unsigned CurValID = 0;
2685  IsVarArg = false;
2686  assert(Lex.getKind() == lltok::lparen);
2687  Lex.Lex(); // eat the (.
2688 
2689  if (Lex.getKind() == lltok::rparen) {
2690  // empty
2691  } else if (Lex.getKind() == lltok::dotdotdot) {
2692  IsVarArg = true;
2693  Lex.Lex();
2694  } else {
2695  LocTy TypeLoc = Lex.getLoc();
2696  Type *ArgTy = nullptr;
2698  std::string Name;
2699 
2700  if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2701  return true;
2702 
2703  if (ArgTy->isVoidTy())
2704  return error(TypeLoc, "argument can not have void type");
2705 
2706  if (Lex.getKind() == lltok::LocalVar) {
2707  Name = Lex.getStrVal();
2708  Lex.Lex();
2709  } else if (Lex.getKind() == lltok::LocalVarID) {
2710  if (Lex.getUIntVal() != CurValID)
2711  return error(TypeLoc, "argument expected to be numbered '%" +
2712  Twine(CurValID) + "'");
2713  ++CurValID;
2714  Lex.Lex();
2715  }
2716 
2718  return error(TypeLoc, "invalid type for function argument");
2719 
2720  ArgList.emplace_back(TypeLoc, ArgTy,
2721  AttributeSet::get(ArgTy->getContext(), Attrs),
2722  std::move(Name));
2723 
2724  while (EatIfPresent(lltok::comma)) {
2725  // Handle ... at end of arg list.
2726  if (EatIfPresent(lltok::dotdotdot)) {
2727  IsVarArg = true;
2728  break;
2729  }
2730 
2731  // Otherwise must be an argument type.
2732  TypeLoc = Lex.getLoc();
2733  if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2734  return true;
2735 
2736  if (ArgTy->isVoidTy())
2737  return error(TypeLoc, "argument can not have void type");
2738 
2739  if (Lex.getKind() == lltok::LocalVar) {
2740  Name = Lex.getStrVal();
2741  Lex.Lex();
2742  } else {
2743  if (Lex.getKind() == lltok::LocalVarID) {
2744  if (Lex.getUIntVal() != CurValID)
2745  return error(TypeLoc, "argument expected to be numbered '%" +
2746  Twine(CurValID) + "'");
2747  Lex.Lex();
2748  }
2749  ++CurValID;
2750  Name = "";
2751  }
2752 
2753  if (!ArgTy->isFirstClassType())
2754  return error(TypeLoc, "invalid type for function argument");
2755 
2756  ArgList.emplace_back(TypeLoc, ArgTy,
2757  AttributeSet::get(ArgTy->getContext(), Attrs),
2758  std::move(Name));
2759  }
2760  }
2761 
2762  return parseToken(lltok::rparen, "expected ')' at end of argument list");
2763 }
2764 
2765 /// parseFunctionType
2766 /// ::= Type ArgumentList OptionalAttrs
2767 bool LLParser::parseFunctionType(Type *&Result) {
2768  assert(Lex.getKind() == lltok::lparen);
2769 
2770  if (!FunctionType::isValidReturnType(Result))
2771  return tokError("invalid function return type");
2772 
2773  SmallVector<ArgInfo, 8> ArgList;
2774  bool IsVarArg;
2775  if (parseArgumentList(ArgList, IsVarArg))
2776  return true;
2777 
2778  // Reject names on the arguments lists.
2779  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2780  if (!ArgList[i].Name.empty())
2781  return error(ArgList[i].Loc, "argument name invalid in function type");
2782  if (ArgList[i].Attrs.hasAttributes())
2783  return error(ArgList[i].Loc,
2784  "argument attributes invalid in function type");
2785  }
2786 
2787  SmallVector<Type*, 16> ArgListTy;
2788  for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2789  ArgListTy.push_back(ArgList[i].Ty);
2790 
2791  Result = FunctionType::get(Result, ArgListTy, IsVarArg);
2792  return false;
2793 }
2794 
2795 /// parseAnonStructType - parse an anonymous struct type, which is inlined into
2796 /// other structs.
2797 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
2798  SmallVector<Type*, 8> Elts;
2799  if (parseStructBody(Elts))
2800  return true;
2801 
2802  Result = StructType::get(Context, Elts, Packed);
2803  return false;
2804 }
2805 
2806 /// parseStructDefinition - parse a struct in a 'type' definition.
2807 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
2808  std::pair<Type *, LocTy> &Entry,
2809  Type *&ResultTy) {
2810  // If the type was already defined, diagnose the redefinition.
2811  if (Entry.first && !Entry.second.isValid())
2812  return error(TypeLoc, "redefinition of type");
2813 
2814  // If we have opaque, just return without filling in the definition for the
2815  // struct. This counts as a definition as far as the .ll file goes.
2816  if (EatIfPresent(lltok::kw_opaque)) {
2817  // This type is being defined, so clear the location to indicate this.
2818  Entry.second = SMLoc();
2819 
2820  // If this type number has never been uttered, create it.
2821  if (!Entry.first)
2822  Entry.first = StructType::create(Context, Name);
2823  ResultTy = Entry.first;
2824  return false;
2825  }
2826 
2827  // If the type starts with '<', then it is either a packed struct or a vector.
2828  bool isPacked = EatIfPresent(lltok::less);
2829 
2830  // If we don't have a struct, then we have a random type alias, which we
2831  // accept for compatibility with old files. These types are not allowed to be
2832  // forward referenced and not allowed to be recursive.
2833  if (Lex.getKind() != lltok::lbrace) {
2834  if (Entry.first)
2835  return error(TypeLoc, "forward references to non-struct type");
2836 
2837  ResultTy = nullptr;
2838  if (isPacked)
2839  return parseArrayVectorType(ResultTy, true);
2840  return parseType(ResultTy);
2841  }
2842 
2843  // This type is being defined, so clear the location to indicate this.
2844  Entry.second = SMLoc();
2845 
2846  // If this type number has never been uttered, create it.
2847  if (!Entry.first)
2848  Entry.first = StructType::create(Context, Name);
2849 
2850  StructType *STy = cast<StructType>(Entry.first);
2851 
2852  SmallVector<Type*, 8> Body;
2853  if (parseStructBody(Body) ||
2854  (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
2855  return true;
2856 
2857  STy->setBody(Body, isPacked);
2858  ResultTy = STy;
2859  return false;
2860 }
2861 
2862 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2863 /// StructType
2864 /// ::= '{' '}'
2865 /// ::= '{' Type (',' Type)* '}'
2866 /// ::= '<' '{' '}' '>'
2867 /// ::= '<' '{' Type (',' Type)* '}' '>'
2868 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
2869  assert(Lex.getKind() == lltok::lbrace);
2870  Lex.Lex(); // Consume the '{'
2871 
2872  // Handle the empty struct.
2873  if (EatIfPresent(lltok::rbrace))
2874  return false;
2875 
2876  LocTy EltTyLoc = Lex.getLoc();
2877  Type *Ty = nullptr;
2878  if (parseType(Ty))
2879  return true;
2880  Body.push_back(Ty);
2881 
2883  return error(EltTyLoc, "invalid element type for struct");
2884 
2885  while (EatIfPresent(lltok::comma)) {
2886  EltTyLoc = Lex.getLoc();
2887  if (parseType(Ty))
2888  return true;
2889 
2891  return error(EltTyLoc, "invalid element type for struct");
2892 
2893  Body.push_back(Ty);
2894  }
2895 
2896  return parseToken(lltok::rbrace, "expected '}' at end of struct");
2897 }
2898 
2899 /// parseArrayVectorType - parse an array or vector type, assuming the first
2900 /// token has already been consumed.
2901 /// Type
2902 /// ::= '[' APSINTVAL 'x' Types ']'
2903 /// ::= '<' APSINTVAL 'x' Types '>'
2904 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
2905 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
2906  bool Scalable = false;
2907 
2908  if (IsVector && Lex.getKind() == lltok::kw_vscale) {
2909  Lex.Lex(); // consume the 'vscale'
2910  if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
2911  return true;
2912 
2913  Scalable = true;
2914  }
2915 
2916  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2917  Lex.getAPSIntVal().getBitWidth() > 64)
2918  return tokError("expected number in address space");
2919 
2920  LocTy SizeLoc = Lex.getLoc();
2922  Lex.Lex();
2923 
2924  if (parseToken(lltok::kw_x, "expected 'x' after element count"))
2925  return true;
2926 
2927  LocTy TypeLoc = Lex.getLoc();
2928  Type *EltTy = nullptr;
2929  if (parseType(EltTy))
2930  return true;
2931 
2932  if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
2933  "expected end of sequential type"))
2934  return true;
2935 
2936  if (IsVector) {
2937  if (Size == 0)
2938  return error(SizeLoc, "zero element vector is illegal");
2939  if ((unsigned)Size != Size)
2940  return error(SizeLoc, "size too large for vector");
2941  if (!VectorType::isValidElementType(EltTy))
2942  return error(TypeLoc, "invalid vector element type");
2943  Result = VectorType::get(EltTy, unsigned(Size), Scalable);
2944  } else {
2945  if (!ArrayType::isValidElementType(EltTy))
2946  return error(TypeLoc, "invalid array element type");
2947  Result = ArrayType::get(EltTy, Size);
2948  }
2949  return false;
2950 }
2951 
2952 //===----------------------------------------------------------------------===//
2953 // Function Semantic Analysis.
2954 //===----------------------------------------------------------------------===//
2955 
2956 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2957  int functionNumber)
2958  : P(p), F(f), FunctionNumber(functionNumber) {
2959 
2960  // Insert unnamed arguments into the NumberedVals list.
2961  for (Argument &A : F.args())
2962  if (!A.hasName())
2963  NumberedVals.push_back(&A);
2964 }
2965 
2966 LLParser::PerFunctionState::~PerFunctionState() {
2967  // If there were any forward referenced non-basicblock values, delete them.
2968 
2969  for (const auto &P : ForwardRefVals) {
2970  if (isa<BasicBlock>(P.second.first))
2971  continue;
2972  P.second.first->replaceAllUsesWith(
2973  UndefValue::get(P.second.first->getType()));
2974  P.second.first->deleteValue();
2975  }
2976 
2977  for (const auto &P : ForwardRefValIDs) {
2978  if (isa<BasicBlock>(P.second.first))
2979  continue;
2980  P.second.first->replaceAllUsesWith(
2981  UndefValue::get(P.second.first->getType()));
2982  P.second.first->deleteValue();
2983  }
2984 }
2985 
2986 bool LLParser::PerFunctionState::finishFunction() {
2987  if (!ForwardRefVals.empty())
2988  return P.error(ForwardRefVals.begin()->second.second,
2989  "use of undefined value '%" + ForwardRefVals.begin()->first +
2990  "'");
2991  if (!ForwardRefValIDs.empty())
2992  return P.error(ForwardRefValIDs.begin()->second.second,
2993  "use of undefined value '%" +
2994  Twine(ForwardRefValIDs.begin()->first) + "'");
2995  return false;
2996 }
2997 
2998 /// getVal - Get a value with the specified name or ID, creating a
2999 /// forward reference record if needed. This can return null if the value
3000 /// exists but does not have the right type.
3001 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3002  LocTy Loc) {
3003  // Look this name up in the normal function symbol table.
3004  Value *Val = F.getValueSymbolTable()->lookup(Name);
3005 
3006  // If this is a forward reference for the value, see if we already created a
3007  // forward ref record.
3008  if (!Val) {
3009  auto I = ForwardRefVals.find(Name);
3010  if (I != ForwardRefVals.end())
3011  Val = I->second.first;
3012  }
3013 
3014  // If we have the value in the symbol table or fwd-ref table, return it.
3015  if (Val)
3016  return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3017 
3018  // Don't make placeholders with invalid type.
3019  if (!Ty->isFirstClassType()) {
3020  P.error(Loc, "invalid use of a non-first-class type");
3021  return nullptr;
3022  }
3023 
3024  // Otherwise, create a new forward reference for this value and remember it.
3025  Value *FwdVal;
3026  if (Ty->isLabelTy()) {
3027  FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3028  } else {
3029  FwdVal = new Argument(Ty, Name);
3030  }
3031 
3032  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3033  return FwdVal;
3034 }
3035 
3036 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3037  // Look this name up in the normal function symbol table.
3038  Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
3039 
3040  // If this is a forward reference for the value, see if we already created a
3041  // forward ref record.
3042  if (!Val) {
3043  auto I = ForwardRefValIDs.find(ID);
3044  if (I != ForwardRefValIDs.end())
3045  Val = I->second.first;
3046  }
3047 
3048  // If we have the value in the symbol table or fwd-ref table, return it.
3049  if (Val)
3050  return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3051 
3052  if (!Ty->isFirstClassType()) {
3053  P.error(Loc, "invalid use of a non-first-class type");
3054  return nullptr;
3055  }
3056 
3057  // Otherwise, create a new forward reference for this value and remember it.
3058  Value *FwdVal;
3059  if (Ty->isLabelTy()) {
3060  FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3061  } else {
3062  FwdVal = new Argument(Ty);
3063  }
3064 
3065  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3066  return FwdVal;
3067 }
3068 
3069 /// setInstName - After an instruction is parsed and inserted into its
3070 /// basic block, this installs its name.
3071 bool LLParser::PerFunctionState::setInstName(int NameID,
3072  const std::string &NameStr,
3073  LocTy NameLoc, Instruction *Inst) {
3074  // If this instruction has void type, it cannot have a name or ID specified.
3075  if (Inst->getType()->isVoidTy()) {
3076  if (NameID != -1 || !NameStr.empty())
3077  return P.error(NameLoc, "instructions returning void cannot have a name");
3078  return false;
3079  }
3080 
3081  // If this was a numbered instruction, verify that the instruction is the
3082  // expected value and resolve any forward references.
3083  if (NameStr.empty()) {
3084  // If neither a name nor an ID was specified, just use the next ID.
3085  if (NameID == -1)
3086  NameID = NumberedVals.size();
3087 
3088  if (unsigned(NameID) != NumberedVals.size())
3089  return P.error(NameLoc, "instruction expected to be numbered '%" +
3090  Twine(NumberedVals.size()) + "'");
3091 
3092  auto FI = ForwardRefValIDs.find(NameID);
3093  if (FI != ForwardRefValIDs.end()) {
3094  Value *Sentinel = FI->second.first;
3095  if (Sentinel->getType() != Inst->getType())
3096  return P.error(NameLoc, "instruction forward referenced with type '" +
3097  getTypeString(FI->second.first->getType()) +
3098  "'");
3099 
3100  Sentinel->replaceAllUsesWith(Inst);
3101  Sentinel->deleteValue();
3102  ForwardRefValIDs.erase(FI);
3103  }
3104 
3105  NumberedVals.push_back(Inst);
3106  return false;
3107  }
3108 
3109  // Otherwise, the instruction had a name. Resolve forward refs and set it.
3110  auto FI = ForwardRefVals.find(NameStr);
3111  if (FI != ForwardRefVals.end()) {
3112  Value *Sentinel = FI->second.first;
3113  if (Sentinel->getType() != Inst->getType())
3114  return P.error(NameLoc, "instruction forward referenced with type '" +
3115  getTypeString(FI->second.first->getType()) +
3116  "'");
3117 
3118  Sentinel->replaceAllUsesWith(Inst);
3119  Sentinel->deleteValue();
3120  ForwardRefVals.erase(FI);
3121  }
3122 
3123  // Set the name on the instruction.
3124  Inst->setName(NameStr);
3125 
3126  if (Inst->getName() != NameStr)
3127  return P.error(NameLoc, "multiple definition of local value named '" +
3128  NameStr + "'");
3129  return false;
3130 }
3131 
3132 /// getBB - Get a basic block with the specified name or ID, creating a
3133 /// forward reference record if needed.
3134 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3135  LocTy Loc) {
3136  return dyn_cast_or_null<BasicBlock>(
3137  getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3138 }
3139 
3140 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3141  return dyn_cast_or_null<BasicBlock>(
3142  getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3143 }
3144 
3145 /// defineBB - Define the specified basic block, which is either named or
3146 /// unnamed. If there is an error, this returns null otherwise it returns
3147 /// the block being defined.
3148 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3149  int NameID, LocTy Loc) {
3150  BasicBlock *BB;
3151  if (Name.empty()) {
3152  if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3153  P.error(Loc, "label expected to be numbered '" +
3154  Twine(NumberedVals.size()) + "'");
3155  return nullptr;
3156  }
3157  BB = getBB(NumberedVals.size(), Loc);
3158  if (!BB) {
3159  P.error(Loc, "unable to create block numbered '" +
3160  Twine(NumberedVals.size()) + "'");
3161  return nullptr;
3162  }
3163  } else {
3164  BB = getBB(Name, Loc);
3165  if (!BB) {
3166  P.error(Loc, "unable to create block named '" + Name + "'");
3167  return nullptr;
3168  }
3169  }
3170 
3171  // Move the block to the end of the function. Forward ref'd blocks are
3172  // inserted wherever they happen to be referenced.
3173  F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
3174 
3175  // Remove the block from forward ref sets.
3176  if (Name.empty()) {
3177  ForwardRefValIDs.erase(NumberedVals.size());
3178  NumberedVals.push_back(BB);
3179  } else {
3180  // BB forward references are already in the function symbol table.
3181  ForwardRefVals.erase(Name);
3182  }
3183 
3184  return BB;
3185 }
3186 
3187 //===----------------------------------------------------------------------===//
3188 // Constants.
3189 //===----------------------------------------------------------------------===//
3190 
3191 /// parseValID - parse an abstract value that doesn't necessarily have a
3192 /// type implied. For example, if we parse "4" we don't know what integer type
3193 /// it has. The value will later be combined with its type and checked for
3194 /// basic correctness. PFS is used to convert function-local operands of
3195 /// metadata (since metadata operands are not just parsed here but also
3196 /// converted to values). PFS can be null when we are not parsing metadata
3197 /// values inside a function.
3198 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3199  ID.Loc = Lex.getLoc();
3200  switch (Lex.getKind()) {
3201  default:
3202  return tokError("expected value token");
3203  case lltok::GlobalID: // @42
3204  ID.UIntVal = Lex.getUIntVal();
3205  ID.Kind = ValID::t_GlobalID;
3206  break;
3207  case lltok::GlobalVar: // @foo
3208  ID.StrVal = Lex.getStrVal();
3209  ID.Kind = ValID::t_GlobalName;
3210  break;
3211  case lltok::LocalVarID: // %42
3212  ID.UIntVal = Lex.getUIntVal();
3213  ID.Kind = ValID::t_LocalID;
3214  break;
3215  case lltok::LocalVar: // %foo
3216  ID.StrVal = Lex.getStrVal();
3217  ID.Kind = ValID::t_LocalName;
3218  break;
3219  case lltok::APSInt:
3220  ID.APSIntVal = Lex.getAPSIntVal();
3221  ID.Kind = ValID::t_APSInt;
3222  break;
3223  case lltok::APFloat:
3224  ID.APFloatVal = Lex.getAPFloatVal();
3225  ID.Kind = ValID::t_APFloat;
3226  break;
3227  case lltok::kw_true:
3228  ID.ConstantVal = ConstantInt::getTrue(Context);
3229  ID.Kind = ValID::t_Constant;
3230  break;
3231  case lltok::kw_false:
3232  ID.ConstantVal = ConstantInt::getFalse(Context);
3233  ID.Kind = ValID::t_Constant;
3234  break;
3235  case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3236  case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3237  case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3238  case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3239  case lltok::kw_none: ID.Kind = ValID::t_None; break;
3240 
3241  case lltok::lbrace: {
3242  // ValID ::= '{' ConstVector '}'
3243  Lex.Lex();
3245  if (parseGlobalValueVector(Elts) ||
3246  parseToken(lltok::rbrace, "expected end of struct constant"))
3247  return true;
3248 
3249  ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3250  ID.UIntVal = Elts.size();
3251  memcpy(ID.ConstantStructElts.get(), Elts.data(),
3252  Elts.size() * sizeof(Elts[0]));
3253  ID.Kind = ValID::t_ConstantStruct;
3254  return false;
3255  }
3256  case lltok::less: {
3257  // ValID ::= '<' ConstVector '>' --> Vector.
3258  // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3259  Lex.Lex();
3260  bool isPackedStruct = EatIfPresent(lltok::lbrace);
3261 
3263  LocTy FirstEltLoc = Lex.getLoc();
3264  if (parseGlobalValueVector(Elts) ||
3265  (isPackedStruct &&
3266  parseToken(lltok::rbrace, "expected end of packed struct")) ||
3267  parseToken(lltok::greater, "expected end of constant"))
3268  return true;
3269 
3270  if (isPackedStruct) {
3271  ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3272  memcpy(ID.ConstantStructElts.get(), Elts.data(),
3273  Elts.size() * sizeof(Elts[0]));
3274  ID.UIntVal = Elts.size();
3276  return false;
3277  }
3278 
3279  if (Elts.empty())
3280  return error(ID.Loc, "constant vector must not be empty");
3281 
3282  if (!Elts[0]->getType()->isIntegerTy() &&
3283  !Elts[0]->getType()->isFloatingPointTy() &&
3284  !Elts[0]->getType()->isPointerTy())
3285  return error(
3286  FirstEltLoc,
3287  "vector elements must have integer, pointer or floating point type");
3288 
3289  // Verify that all the vector elements have the same type.
3290  for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3291  if (Elts[i]->getType() != Elts[0]->getType())
3292  return error(FirstEltLoc, "vector element #" + Twine(i) +
3293  " is not of type '" +
3294  getTypeString(Elts[0]->getType()));
3295 
3296  ID.ConstantVal = ConstantVector::get(Elts);
3297  ID.Kind = ValID::t_Constant;
3298  return false;
3299  }
3300  case lltok::lsquare: { // Array Constant
3301  Lex.Lex();
3303  LocTy FirstEltLoc = Lex.getLoc();
3304  if (parseGlobalValueVector(Elts) ||
3305  parseToken(lltok::rsquare, "expected end of array constant"))
3306  return true;
3307 
3308  // Handle empty element.
3309  if (Elts.empty()) {
3310  // Use undef instead of an array because it's inconvenient to determine
3311  // the element type at this point, there being no elements to examine.
3312  ID.Kind = ValID::t_EmptyArray;
3313  return false;
3314  }
3315 
3316  if (!Elts[0]->getType()->isFirstClassType())
3317  return error(FirstEltLoc, "invalid array element type: " +
3318  getTypeString(Elts[0]->getType()));
3319 
3320  ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3321 
3322  // Verify all elements are correct type!
3323  for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3324  if (Elts[i]->getType() != Elts[0]->getType())
3325  return error(FirstEltLoc, "array element #" + Twine(i) +
3326  " is not of type '" +
3327  getTypeString(Elts[0]->getType()));
3328  }
3329 
3330  ID.ConstantVal = ConstantArray::get(ATy, Elts);
3331  ID.Kind = ValID::t_Constant;
3332  return false;
3333  }
3334  case lltok::kw_c: // c "foo"
3335  Lex.Lex();
3336  ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3337  false);
3338  if (parseToken(lltok::StringConstant, "expected string"))
3339  return true;
3340  ID.Kind = ValID::t_Constant;
3341  return false;
3342 
3343  case lltok::kw_asm: {
3344  // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3345  // STRINGCONSTANT
3346  bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3347  Lex.Lex();
3348  if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3349  parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3350  parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3351  parseOptionalToken(lltok::kw_unwind, CanThrow) ||
3352  parseStringConstant(ID.StrVal) ||
3353  parseToken(lltok::comma, "expected comma in inline asm expression") ||
3354  parseToken(lltok::StringConstant, "expected constraint string"))
3355  return true;
3356  ID.StrVal2 = Lex.getStrVal();
3357  ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
3358  (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
3359  ID.Kind = ValID::t_InlineAsm;
3360  return false;
3361  }
3362 
3363  case lltok::kw_blockaddress: {
3364  // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3365  Lex.Lex();
3366 
3367  ValID Fn, Label;
3368 
3369  if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3370  parseValID(Fn, PFS) ||
3371  parseToken(lltok::comma,
3372  "expected comma in block address expression") ||
3373  parseValID(Label, PFS) ||
3374  parseToken(lltok::rparen, "expected ')' in block address expression"))
3375  return true;
3376 
3377  if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3378  return error(Fn.Loc, "expected function name in blockaddress");
3379  if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3380  return error(Label.Loc, "expected basic block name in blockaddress");
3381 
3382  // Try to find the function (but skip it if it's forward-referenced).
3383  GlobalValue *GV = nullptr;
3384  if (Fn.Kind == ValID::t_GlobalID) {
3385  if (Fn.UIntVal < NumberedVals.size())
3386  GV = NumberedVals[Fn.UIntVal];
3387  } else if (!ForwardRefVals.count(Fn.StrVal)) {
3388  GV = M->getNamedValue(Fn.StrVal);
3389  }
3390  Function *F = nullptr;
3391  if (GV) {
3392  // Confirm that it's actually a function with a definition.
3393  if (!isa<Function>(GV))
3394  return error(Fn.Loc, "expected function name in blockaddress");
3395  F = cast<Function>(GV);
3396  if (F->isDeclaration())
3397  return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3398  }
3399 
3400  if (!F) {
3401  // Make a global variable as a placeholder for this reference.
3402  GlobalValue *&FwdRef =
3403  ForwardRefBlockAddresses.insert(std::make_pair(
3404  std::move(Fn),
3405  std::map<ValID, GlobalValue *>()))
3406  .first->second.insert(std::make_pair(std::move(Label), nullptr))
3407  .first->second;
3408  if (!FwdRef) {
3409  unsigned FwdDeclAS;
3410  if (ExpectedTy) {
3411  // If we know the type that the blockaddress is being assigned to,
3412  // we can use the address space of that type.
3413  if (!ExpectedTy->isPointerTy())
3414  return error(ID.Loc,
3415  "type of blockaddress must be a pointer and not '" +
3416  getTypeString(ExpectedTy) + "'");
3417  FwdDeclAS = ExpectedTy->getPointerAddressSpace();
3418  } else if (PFS) {
3419  // Otherwise, we default the address space of the current function.
3420  FwdDeclAS = PFS->getFunction().getAddressSpace();
3421  } else {
3422  llvm_unreachable("Unknown address space for blockaddress");
3423  }
3424  FwdRef = new GlobalVariable(
3425  *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
3426  nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
3427  }
3428 
3429  ID.ConstantVal = FwdRef;
3430  ID.Kind = ValID::t_Constant;
3431  return false;
3432  }
3433 
3434  // We found the function; now find the basic block. Don't use PFS, since we
3435  // might be inside a constant expression.
3436  BasicBlock *BB;
3437  if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3438  if (Label.Kind == ValID::t_LocalID)
3439  BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3440  else
3441  BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3442  if (!BB)
3443  return error(Label.Loc, "referenced value is not a basic block");
3444  } else {
3445  if (Label.Kind == ValID::t_LocalID)
3446  return error(Label.Loc, "cannot take address of numeric label after "
3447  "the function is defined");
3448  BB = dyn_cast_or_null<BasicBlock>(
3449  F->getValueSymbolTable()->lookup(Label.StrVal));
3450  if (!BB)
3451  return error(Label.Loc, "referenced value is not a basic block");
3452  }
3453 
3454  ID.ConstantVal = BlockAddress::get(F, BB);
3455  ID.Kind = ValID::t_Constant;
3456  return false;
3457  }
3458 
3460  // ValID ::= 'dso_local_equivalent' @foo
3461  Lex.Lex();
3462 
3463  ValID Fn;
3464 
3465  if (parseValID(Fn, PFS))
3466  return true;
3467 
3468  if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3469  return error(Fn.Loc,
3470  "expected global value name in dso_local_equivalent");
3471 
3472  // Try to find the function (but skip it if it's forward-referenced).
3473  GlobalValue *GV = nullptr;
3474  if (Fn.Kind == ValID::t_GlobalID) {
3475  if (Fn.UIntVal < NumberedVals.size())
3476  GV = NumberedVals[Fn.UIntVal];
3477  } else if (!ForwardRefVals.count(Fn.StrVal)) {
3478  GV = M->getNamedValue(Fn.StrVal);
3479  }
3480 
3481  if (!GV) {
3482  // Make a placeholder global variable as a placeholder for this reference.
3483  auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
3484  ? ForwardRefDSOLocalEquivalentIDs
3485  : ForwardRefDSOLocalEquivalentNames;
3486  GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn, nullptr).first->second;
3487  if (!FwdRef) {
3488  FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3489  GlobalValue::InternalLinkage, nullptr, "",
3490  nullptr, GlobalValue::NotThreadLocal);
3491  }
3492 
3493  ID.ConstantVal = FwdRef;
3494  ID.Kind = ValID::t_Constant;
3495  return false;
3496  }
3497 
3498  if (!GV->getValueType()->isFunctionTy())
3499  return error(Fn.Loc, "expected a function, alias to function, or ifunc "
3500  "in dso_local_equivalent");
3501 
3502  ID.ConstantVal = DSOLocalEquivalent::get(GV);
3503  ID.Kind = ValID::t_Constant;
3504  return false;
3505  }
3506 
3507  case lltok::kw_no_cfi: {
3508  // ValID ::= 'no_cfi' @foo
3509  Lex.Lex();
3510 
3511  if (parseValID(ID, PFS))
3512  return true;
3513 
3514  if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
3515  return error(ID.Loc, "expected global value name in no_cfi");
3516 
3517  ID.NoCFI = true;
3518  return false;
3519  }
3520 
3521  case lltok::kw_trunc:
3522  case lltok::kw_zext:
3523  case lltok::kw_sext:
3524  case lltok::kw_fptrunc:
3525  case lltok::kw_fpext:
3526  case lltok::kw_bitcast:
3528  case lltok::kw_uitofp:
3529  case lltok::kw_sitofp:
3530  case lltok::kw_fptoui:
3531  case lltok::kw_fptosi:
3532  case lltok::kw_inttoptr:
3533  case lltok::kw_ptrtoint: {
3534  unsigned Opc = Lex.getUIntVal();
3535  Type *DestTy = nullptr;
3536  Constant *SrcVal;
3537  Lex.Lex();
3538  if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3539  parseGlobalTypeAndValue(SrcVal) ||
3540  parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3541  parseType(DestTy) ||
3542  parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3543  return true;
3544  if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3545  return error(ID.Loc, "invalid cast opcode for cast from '" +
3546  getTypeString(SrcVal->getType()) + "' to '" +
3547  getTypeString(DestTy) + "'");
3548  ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3549  SrcVal, DestTy);
3550  ID.Kind = ValID::t_Constant;
3551  return false;
3552  }
3554  return error(ID.Loc, "extractvalue constexprs are no longer supported");
3555  case lltok::kw_insertvalue:
3556  return error(ID.Loc, "insertvalue constexprs are no longer supported");
3557  case lltok::kw_udiv:
3558  return error(ID.Loc, "udiv constexprs are no longer supported");
3559  case lltok::kw_sdiv:
3560  return error(ID.Loc, "sdiv constexprs are no longer supported");
3561  case lltok::kw_urem:
3562  return error(ID.Loc, "urem constexprs are no longer supported");
3563  case lltok::kw_srem:
3564  return error(ID.Loc, "srem constexprs are no longer supported");
3565  case lltok::kw_fadd:
3566  return error(ID.Loc, "fadd constexprs are no longer supported");
3567  case lltok::kw_fsub:
3568  return error(ID.Loc, "fsub constexprs are no longer supported");
3569  case lltok::kw_fmul:
3570  return error(ID.Loc, "fmul constexprs are no longer supported");
3571  case lltok::kw_fdiv:
3572  return error(ID.Loc, "fdiv constexprs are no longer supported");
3573  case lltok::kw_frem:
3574  return error(ID.Loc, "frem constexprs are no longer supported");
3575  case lltok::kw_fneg:
3576  return error(ID.Loc, "fneg constexprs are no longer supported");
3577  case lltok::kw_icmp:
3578  case lltok::kw_fcmp: {
3579  unsigned PredVal, Opc = Lex.getUIntVal();
3580  Constant *Val0, *Val1;
3581  Lex.Lex();
3582  if (parseCmpPredicate(PredVal, Opc) ||
3583  parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3584  parseGlobalTypeAndValue(Val0) ||
3585  parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3586  parseGlobalTypeAndValue(Val1) ||
3587  parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3588  return true;
3589 
3590  if (Val0->getType() != Val1->getType())
3591  return error(ID.Loc, "compare operands must have the same type");
3592 
3593  CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3594 
3595  if (Opc == Instruction::FCmp) {
3596  if (!Val0->getType()->isFPOrFPVectorTy())
3597  return error(ID.Loc, "fcmp requires floating point operands");
3598  ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3599  } else {
3600  assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3601  if (!Val0->getType()->isIntOrIntVectorTy() &&
3602  !Val0->getType()->isPtrOrPtrVectorTy())
3603  return error(ID.Loc, "icmp requires pointer or integer operands");
3604  ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3605  }
3606  ID.Kind = ValID::t_Constant;
3607  return false;
3608  }
3609 
3610  // Binary Operators.
3611  case lltok::kw_add:
3612  case lltok::kw_sub:
3613  case lltok::kw_mul:
3614  case lltok::kw_shl:
3615  case lltok::kw_lshr:
3616  case lltok::kw_ashr: {
3617  bool NUW = false;
3618  bool NSW = false;
3619  bool Exact = false;
3620  unsigned Opc = Lex.getUIntVal();
3621  Constant *Val0, *Val1;
3622  Lex.Lex();
3623  if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3624  Opc == Instruction::Mul || Opc == Instruction::Shl) {
3625  if (EatIfPresent(lltok::kw_nuw))
3626  NUW = true;
3627  if (EatIfPresent(lltok::kw_nsw)) {
3628  NSW = true;
3629  if (EatIfPresent(lltok::kw_nuw))
3630  NUW = true;
3631  }
3632  } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3633  Opc == Instruction::LShr || Opc == Instruction::AShr) {
3634  if (EatIfPresent(lltok::kw_exact))
3635  Exact = true;
3636  }
3637  if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3638  parseGlobalTypeAndValue(Val0) ||
3639  parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3640  parseGlobalTypeAndValue(Val1) ||
3641  parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3642  return true;
3643  if (Val0->getType() != Val1->getType())
3644  return error(ID.Loc, "operands of constexpr must have same type");
3645  // Check that the type is valid for the operator.
3646  switch (Opc) {
3647  case Instruction::Add:
3648  case Instruction::Sub:
3649  case Instruction::Mul:
3650  case Instruction::UDiv:
3651  case Instruction::SDiv:
3652  case Instruction::URem:
3653  case Instruction::SRem:
3654  case Instruction::Shl:
3655  case Instruction::AShr:
3656  case Instruction::LShr:
3657  if (!Val0->getType()->isIntOrIntVectorTy())
3658  return error(ID.Loc, "constexpr requires integer operands");
3659  break;
3660  case Instruction::FAdd:
3661  case Instruction::FSub:
3662  case Instruction::FMul:
3663  case Instruction::FDiv:
3664  case Instruction::FRem:
3665  if (!Val0->getType()->isFPOrFPVectorTy())
3666  return error(ID.Loc, "constexpr requires fp operands");
3667  break;
3668  default: llvm_unreachable("Unknown binary operator!");
3669  }
3670  unsigned Flags = 0;
3672  if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3673  if (Exact) Flags |= PossiblyExactOperator::IsExact;
3674  Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3675  ID.ConstantVal = C;
3676  ID.Kind = ValID::t_Constant;
3677  return false;
3678  }
3679 
3680  // Logical Operations
3681  case lltok::kw_and:
3682  case lltok::kw_or:
3683  case lltok::kw_xor: {
3684  unsigned Opc = Lex.getUIntVal();
3685  Constant *Val0, *Val1;
3686  Lex.Lex();
3687  if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3688  parseGlobalTypeAndValue(Val0) ||
3689  parseToken(lltok::comma, "expected comma in logical constantexpr") ||
3690  parseGlobalTypeAndValue(Val1) ||
3691  parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3692  return true;
3693  if (Val0->getType() != Val1->getType())
3694  return error(ID.Loc, "operands of constexpr must have same type");
3695  if (!Val0->getType()->isIntOrIntVectorTy())
3696  return error(ID.Loc,
3697  "constexpr requires integer or integer vector operands");
3698  ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3699  ID.Kind = ValID::t_Constant;
3700  return false;
3701  }
3702 
3707  case lltok::kw_select: {
3708  unsigned Opc = Lex.getUIntVal();
3710  bool InBounds = false;
3711  Type *Ty;
3712  Lex.Lex();
3713 
3714  if (Opc == Instruction::GetElementPtr)
3715  InBounds = EatIfPresent(lltok::kw_inbounds);
3716 
3717  if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
3718  return true;
3719 
3720  LocTy ExplicitTypeLoc = Lex.getLoc();
3721  if (Opc == Instruction::GetElementPtr) {
3722  if (parseType(Ty) ||
3723  parseToken(lltok::comma, "expected comma after getelementptr's type"))
3724  return true;
3725  }
3726 
3727  Optional<unsigned> InRangeOp;
3728  if (parseGlobalValueVector(
3729  Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3730  parseToken(lltok::rparen, "expected ')' in constantexpr"))
3731  return true;
3732 
3733  if (Opc == Instruction::GetElementPtr) {
3734  if (Elts.size() == 0 ||
3735  !Elts[0]->getType()->isPtrOrPtrVectorTy())
3736  return error(ID.Loc, "base of getelementptr must be a pointer");
3737 
3738  Type *BaseType = Elts[0]->getType();
3739  auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3740  if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
3741  return error(
3742  ExplicitTypeLoc,
3744  "explicit pointee type doesn't match operand's pointee type",
3745  Ty, BasePointerType->getNonOpaquePointerElementType()));
3746  }
3747 
3748  unsigned GEPWidth =
3749  BaseType->isVectorTy()
3750  ? cast<FixedVectorType>(BaseType)->getNumElements()
3751  : 0;
3752 
3753  ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3754  for (Constant *Val : Indices) {
3755  Type *ValTy = Val->getType();
3756  if (!ValTy->isIntOrIntVectorTy())
3757  return error(ID.Loc, "getelementptr index must be an integer");
3758  if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
3759  unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
3760  if (GEPWidth && (ValNumEl != GEPWidth))
3761  return error(
3762  ID.Loc,
3763  "getelementptr vector index has a wrong number of elements");
3764  // GEPWidth may have been unknown because the base is a scalar,
3765  // but it is known now.
3766  GEPWidth = ValNumEl;
3767  }
3768  }
3769 
3770  SmallPtrSet<Type*, 4> Visited;
3771  if (!Indices.empty() && !Ty->isSized(&Visited))
3772  return error(ID.Loc, "base element of getelementptr must be sized");
3773 
3774  if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3775  return error(ID.Loc, "invalid getelementptr indices");
3776 
3777  if (InRangeOp) {
3778  if (*InRangeOp == 0)
3779  return error(ID.Loc,
3780  "inrange keyword may not appear on pointer operand");
3781  --*InRangeOp;
3782  }
3783 
3784  ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3785  InBounds, InRangeOp);
3786  } else if (Opc == Instruction::Select) {
3787  if (Elts.size() != 3)
3788  return error(ID.Loc, "expected three operands to select");
3789  if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3790  Elts[2]))
3791  return error(ID.Loc, Reason);
3792  ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3793  } else if (Opc == Instruction::ShuffleVector) {
3794  if (Elts.size() != 3)
3795  return error(ID.Loc, "expected three operands to shufflevector");
3796  if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3797  return error(ID.Loc, "invalid operands to shufflevector");
3799  ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
3800  ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
3801  } else if (Opc == Instruction::ExtractElement) {
3802  if (Elts.size() != 2)
3803  return error(ID.Loc, "expected two operands to extractelement");
3804  if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3805  return error(ID.Loc, "invalid extractelement operands");
3806  ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3807  } else {
3808  assert(Opc == Instruction::InsertElement && "Unknown opcode");
3809  if (Elts.size() != 3)
3810  return error(ID.Loc, "expected three operands to insertelement");
3811  if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3812  return error(ID.Loc, "invalid insertelement operands");
3813  ID.ConstantVal =
3814  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3815  }
3816 
3817  ID.Kind = ValID::t_Constant;
3818  return false;
3819  }
3820  }
3821 
3822  Lex.Lex();
3823  return false;
3824 }
3825 
3826 /// parseGlobalValue - parse a global value with the specified type.
3827 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
3828  C = nullptr;
3829  ValID ID;
3830  Value *V = nullptr;
3831  bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
3832  convertValIDToValue(Ty, ID, V, nullptr);
3833  if (V && !(C = dyn_cast<Constant>(V)))
3834  return error(ID.Loc, "global values must be constants");
3835  return Parsed;
3836 }
3837 
3838 bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
3839  Type *Ty = nullptr;
3840  return parseType(Ty) || parseGlobalValue(Ty, V);
3841 }
3842 
3843 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3844  C = nullptr;
3845 
3846  LocTy KwLoc = Lex.getLoc();
3847  if (!EatIfPresent(lltok::kw_comdat))
3848  return false;
3849 
3850  if (EatIfPresent(lltok::lparen)) {
3851  if (Lex.getKind() != lltok::ComdatVar)
3852  return tokError("expected comdat variable");
3853  C = getComdat(Lex.getStrVal(), Lex.getLoc());
3854  Lex.Lex();
3855  if (parseToken(lltok::rparen, "expected ')' after comdat var"))
3856  return true;
3857  } else {
3858  if (GlobalName.empty())
3859  return tokError("comdat cannot be unnamed");
3860  C = getComdat(std::string(GlobalName), KwLoc);
3861  }
3862 
3863  return false;
3864 }
3865 
3866 /// parseGlobalValueVector
3867 /// ::= /*empty*/
3868 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3869 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3870  Optional<unsigned> *InRangeOp) {
3871  // Empty list.
3872  if (Lex.getKind() == lltok::rbrace ||
3873  Lex.getKind() == lltok::rsquare ||
3874  Lex.getKind() == lltok::greater ||
3875  Lex.getKind() == lltok::rparen)
3876  return false;
3877 
3878  do {
3879  if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3880  *InRangeOp = Elts.size();
3881 
3882  Constant *C;
3883  if (parseGlobalTypeAndValue(C))
3884  return true;
3885  Elts.push_back(C);
3886  } while (EatIfPresent(lltok::comma));
3887 
3888  return false;
3889 }
3890 
3891 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
3893  if (parseMDNodeVector(Elts))
3894  return true;
3895 
3896  MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3897  return false;
3898 }
3899 
3900 /// MDNode:
3901 /// ::= !{ ... }
3902 /// ::= !7
3903 /// ::= !DILocation(...)
3904 bool LLParser::parseMDNode(MDNode *&N) {
3905  if (Lex.getKind() == lltok::MetadataVar)
3906  return parseSpecializedMDNode(N);
3907 
3908  return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
3909 }
3910 
3911 bool LLParser::parseMDNodeTail(MDNode *&N) {
3912  // !{ ... }
3913  if (Lex.getKind() == lltok::lbrace)
3914  return parseMDTuple(N);
3915 
3916  // !42
3917  return parseMDNodeID(N);
3918 }
3919 
3920 namespace {
3921 
3922 /// Structure to represent an optional metadata field.
3923 template <class FieldTy> struct MDFieldImpl {
3924  typedef MDFieldImpl ImplTy;
3925  FieldTy Val;
3926  bool Seen;
3927 
3928  void assign(FieldTy Val) {
3929  Seen = true;
3930  this->Val = std::move(Val);
3931  }
3932 
3933  explicit MDFieldImpl(FieldTy Default)
3934  : Val(std::move(Default)), Seen(false) {}
3935 };
3936 
3937 /// Structure to represent an optional metadata field that
3938 /// can be of either type (A or B) and encapsulates the
3939 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3940 /// to reimplement the specifics for representing each Field.
3941 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3942  typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3943  FieldTypeA A;
3944  FieldTypeB B;
3945  bool Seen;
3946 
3947  enum {
3948  IsInvalid = 0,
3949  IsTypeA = 1,
3950  IsTypeB = 2
3951  } WhatIs;
3952 
3953  void assign(FieldTypeA A) {
3954  Seen = true;
3955  this->A = std::move(A);
3956  WhatIs = IsTypeA;
3957  }
3958 
3959  void assign(FieldTypeB B) {
3960  Seen = true;
3961  this->B = std::move(B);
3962  WhatIs = IsTypeB;
3963  }
3964 
3965  explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3966  : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3967  WhatIs(IsInvalid) {}
3968 };
3969 
3970 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3971  uint64_t Max;
3972 
3973  MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3974  : ImplTy(Default), Max(Max) {}
3975 };
3976 
3977 struct LineField : public MDUnsignedField {
3978  LineField() : MDUnsignedField(0, UINT32_MAX) {}
3979 };
3980 
3981 struct ColumnField : public MDUnsignedField {
3982  ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3983 };
3984 
3985 struct DwarfTagField : public MDUnsignedField {
3986  DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3987  DwarfTagField(dwarf::Tag DefaultTag)
3988  : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3989 };
3990 
3991 struct DwarfMacinfoTypeField : public MDUnsignedField {
3992  DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3993  DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3994  : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3995 };
3996 
3997 struct DwarfAttEncodingField : public MDUnsignedField {
3998  DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3999 };
4000 
4001 struct DwarfVirtualityField : public MDUnsignedField {
4002  DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4003 };
4004 
4005 struct DwarfLangField : public MDUnsignedField {
4006  DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4007 };
4008 
4009 struct DwarfCCField : public MDUnsignedField {
4010  DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4011 };
4012 
4013 struct EmissionKindField : public MDUnsignedField {
4014  EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4015 };
4016 
4017 struct NameTableKindField : public MDUnsignedField {
4018  NameTableKindField()
4019  : MDUnsignedField(
4020  0, (unsigned)
4021  DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4022 };
4023 
4024 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4025  DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4026 };
4027 
4028 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4029  DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4030 };
4031 
4032 struct MDAPSIntField : public MDFieldImpl<APSInt> {
4033  MDAPSIntField() : ImplTy(APSInt()) {}
4034 };
4035 
4036 struct MDSignedField : public MDFieldImpl<int64_t> {
4037  int64_t Min = INT64_MIN;
4038  int64_t Max = INT64_MAX;
4039 
4040  MDSignedField(int64_t Default = 0)
4041  : ImplTy(Default) {}
4042  MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4043  : ImplTy(Default), Min(Min), Max(Max) {}
4044 };
4045 
4046 struct MDBoolField : public MDFieldImpl<bool> {
4047  MDBoolField(bool Default = false) : ImplTy(Default) {}
4048 };
4049 
4050 struct MDField : public MDFieldImpl<Metadata *> {
4051  bool AllowNull;
4052 
4053  MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4054 };
4055 
4056 struct MDStringField : public MDFieldImpl<MDString *> {
4057  bool AllowEmpty;
4058  MDStringField(bool AllowEmpty = true)
4059  : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4060 };
4061 
4062 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4063  MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4064 };
4065 
4066 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4067  ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4068 };
4069 
4070 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4071  MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4072  : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4073 
4074  MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4075  bool AllowNull = true)
4076  : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4077 
4078  bool isMDSignedField() const { return WhatIs == IsTypeA; }
4079  bool isMDField() const { return WhatIs == IsTypeB; }
4080  int64_t getMDSignedValue() const {
4081  assert(isMDSignedField() && "Wrong field type");
4082  return A.Val;
4083  }
4084  Metadata *getMDFieldValue() const {
4085  assert(isMDField() && "Wrong field type");
4086  return B.Val;
4087  }
4088 };
4089 
4090 } // end anonymous namespace
4091 
4092 namespace llvm {
4093 
4094 template <>
4095 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4096  if (Lex.getKind() != lltok::APSInt)
4097  return tokError("expected integer");
4098 
4099  Result.assign(Lex.getAPSIntVal());
4100  Lex.Lex();
4101  return false;
4102 }
4103 
4104 template <>
4105 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4106  MDUnsignedField &Result) {
4107  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4108  return tokError("expected unsigned integer");
4109 
4110  auto &U = Lex.getAPSIntVal();
4111  if (U.ugt(Result.Max))
4112  return tokError("value for '" + Name + "' too large, limit is " +
4113  Twine(Result.Max));
4114  Result.assign(U.getZExtValue());
4115  assert(Result.Val <= Result.Max && "Expected value in range");
4116  Lex.Lex();
4117  return false;
4118 }
4119 
4120 template <>
4121 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4122  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4123 }
4124 template <>
4125 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4126  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4127 }
4128 
4129 template <>
4130 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4131  if (Lex.getKind() == lltok::APSInt)
4132  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4133 
4134  if (Lex.getKind() != lltok::DwarfTag)
4135  return tokError("expected DWARF tag");
4136 
4137  unsigned Tag = dwarf::getTag(Lex.getStrVal());
4138  if (Tag == dwarf::DW_TAG_invalid)
4139  return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4140  assert(Tag <= Result.Max && "Expected valid DWARF tag");
4141 
4142  Result.assign(Tag);
4143  Lex.Lex();
4144  return false;
4145 }
4146 
4147 template <>
4148 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4149  DwarfMacinfoTypeField &Result) {
4150  if (Lex.getKind() == lltok::APSInt)
4151  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4152 
4153  if (Lex.getKind() != lltok::DwarfMacinfo)
4154  return tokError("expected DWARF macinfo type");
4155 
4156  unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4157  if (Macinfo == dwarf::DW_MACINFO_invalid)
4158  return tokError("invalid DWARF macinfo type" + Twine(" '") +
4159  Lex.getStrVal() + "'");
4160  assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4161 
4162  Result.assign(Macinfo);
4163  Lex.Lex();
4164  return false;
4165 }
4166 
4167 template <>
4168 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4169  DwarfVirtualityField &Result) {
4170  if (Lex.getKind() == lltok::APSInt)
4171  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4172 
4173  if (Lex.getKind() != lltok::DwarfVirtuality)
4174  return tokError("expected DWARF virtuality code");
4175 
4176  unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4177  if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4178  return tokError("invalid DWARF virtuality code" + Twine(" '") +
4179  Lex.getStrVal() + "'");
4180  assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4181  Result.assign(Virtuality);
4182  Lex.Lex();
4183  return false;
4184 }
4185 
4186 template <>
4187 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4188  if (Lex.getKind() == lltok::APSInt)
4189  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4190 
4191  if (Lex.getKind() != lltok::DwarfLang)
4192  return tokError("expected DWARF language");
4193 
4194  unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4195  if (!Lang)
4196  return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4197  "'");
4198  assert(Lang <= Result.Max && "Expected valid DWARF language");
4199  Result.assign(Lang);
4200  Lex.Lex();
4201  return false;
4202 }
4203 
4204 template <>
4205 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4206  if (Lex.getKind() == lltok::APSInt)
4207  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4208 
4209  if (Lex.getKind() != lltok::DwarfCC)
4210  return tokError("expected DWARF calling convention");
4211 
4212  unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4213  if (!CC)
4214  return tokError("invalid DWARF calling convention" + Twine(" '") +
4215  Lex.getStrVal() + "'");
4216  assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4217  Result.assign(CC);
4218  Lex.Lex();
4219  return false;
4220 }
4221 
4222 template <>
4223 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4224  EmissionKindField &Result) {
4225  if (Lex.getKind() == lltok::APSInt)
4226  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4227 
4228  if (Lex.getKind() != lltok::EmissionKind)
4229  return tokError("expected emission kind");
4230 
4232  if (!Kind)
4233  return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4234  "'");
4235  assert(*Kind <= Result.Max && "Expected valid emission kind");
4236  Result.assign(*Kind);
4237  Lex.Lex();
4238  return false;
4239 }
4240 
4241 template <>
4242 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4243  NameTableKindField &Result) {
4244  if (Lex.getKind() == lltok::APSInt)
4245  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4246 
4247  if (Lex.getKind() != lltok::NameTableKind)
4248  return tokError("expected nameTable kind");
4249 
4251  if (!Kind)
4252  return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4253  "'");
4254  assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4255  Result.assign((unsigned)*Kind);
4256  Lex.Lex();
4257  return false;
4258 }
4259 
4260 template <>
4261 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4262  DwarfAttEncodingField &Result) {
4263  if (Lex.getKind() == lltok::APSInt)
4264  return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4265 
4266  if (Lex.getKind() != lltok::DwarfAttEncoding)
4267  return tokError("expected DWARF type attribute encoding");
4268 
4269  unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4270  if (!Encoding)
4271  return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4272  Lex.getStrVal() + "'");
4273  assert(Encoding <= Result.Max && "Expected valid DWARF language");
4274  Result.assign(Encoding);
4275  Lex.Lex();
4276  return false;
4277 }
4278 
4279 /// DIFlagField
4280 /// ::= uint32
4281 /// ::= DIFlagVector
4282 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4283 template <>
4284 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4285 
4286  // parser for a single flag.
4287  auto parseFlag = [&](DINode::DIFlags &Val) {
4288  if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4289  uint32_t TempVal = static_cast<uint32_t>(Val);
4290  bool Res = parseUInt32(TempVal);
4291  Val = static_cast<DINode::DIFlags>(TempVal);
4292  return Res;
4293  }
4294 
4295  if (Lex.getKind() != lltok::DIFlag)
4296  return tokError("expected debug info flag");
4297 
4298  Val = DINode::getFlag(Lex.getStrVal());
4299  if (!Val)
4300  return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
4301  "'");
4302  Lex.Lex();
4303  return false;
4304  };
4305 
4306  // parse the flags and combine them together.
4307  DINode::DIFlags Combined = DINode::FlagZero;
4308  do {
4309  DINode::DIFlags Val;
4310  if (parseFlag(Val))
4311  return true;
4312  Combined |= Val;
4313  } while (EatIfPresent(lltok::bar));
4314 
4315  Result.assign(Combined);
4316  return false;
4317 }
4318 
4319 /// DISPFlagField
4320 /// ::= uint32
4321 /// ::= DISPFlagVector
4322 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4323 template <>
4324 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4325 
4326  // parser for a single flag.
4327  auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4328  if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4329  uint32_t TempVal = static_cast<uint32_t>(Val);
4330  bool Res = parseUInt32(TempVal);
4331  Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4332  return Res;
4333  }
4334 
4335  if (Lex.getKind() != lltok::DISPFlag)
4336  return tokError("expected debug info flag");
4337 
4338  Val = DISubprogram::getFlag(Lex.getStrVal());
4339  if (!Val)
4340  return tokError(Twine("invalid subprogram debug info flag '") +
4341  Lex.getStrVal() + "'");
4342  Lex.Lex();
4343  return false;
4344  };
4345 
4346  // parse the flags and combine them together.
4347  DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4348  do {
4350  if (parseFlag(Val))
4351  return true;
4352  Combined |= Val;
4353  } while (EatIfPresent(lltok::bar));
4354 
4355  Result.assign(Combined);
4356  return false;
4357 }
4358 
4359 template <>
4360 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4361  if (Lex.getKind() != lltok::APSInt)
4362  return tokError("expected signed integer");
4363 
4364  auto &S = Lex.getAPSIntVal();
4365  if (S < Result.Min)
4366  return tokError("value for '" + Name + "' too small, limit is " +
4367  Twine(Result.Min));
4368  if (S > Result.Max)
4369  return tokError("value for '" + Name + "' too large, limit is " +
4370  Twine(Result.Max));
4371  Result.assign(S.getExtValue());
4372  assert(Result.Val >= Result.Min && "Expected value in range");
4373  assert(Result.Val <= Result.Max && "Expected value in range");
4374  Lex.Lex();
4375  return false;
4376 }
4377 
4378 template <>
4379 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4380  switch (Lex.getKind()) {
4381  default:
4382  return tokError("expected 'true' or 'false'");
4383  case lltok::kw_true:
4384  Result.assign(true);
4385  break;
4386  case lltok::kw_false:
4387  Result.assign(false);
4388  break;
4389  }
4390  Lex.Lex();
4391  return false;
4392 }
4393 
4394 template <>
4395 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4396  if (Lex.getKind() == lltok::kw_null) {
4397  if (!Result.AllowNull)
4398  return tokError("'" + Name + "' cannot be null");
4399  Lex.Lex();
4400  Result.assign(nullptr);
4401  return false;
4402  }
4403 
4404  Metadata *MD;
4405  if (parseMetadata(MD, nullptr))
4406  return true;
4407 
4408  Result.assign(MD);
4409  return false;
4410 }
4411 
4412 template <>
4413 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4414  MDSignedOrMDField &Result) {
4415  // Try to parse a signed int.
4416  if (Lex.getKind() == lltok::APSInt) {
4417  MDSignedField Res = Result.A;
4418  if (!parseMDField(Loc, Name, Res)) {
4419  Result.assign(Res);
4420  return false;
4421  }
4422  return true;
4423  }
4424 
4425  // Otherwise, try to parse as an MDField.
4426  MDField Res = Result.B;
4427  if (!parseMDField(Loc, Name, Res)) {
4428  Result.assign(Res);
4429  return false;
4430  }
4431 
4432  return true;
4433 }
4434 
4435 template <>
4436 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4437  LocTy ValueLoc = Lex.getLoc();
4438  std::string S;
4439  if (parseStringConstant(S))
4440  return true;
4441 
4442  if (!Result.AllowEmpty && S.empty())
4443  return error(ValueLoc, "'" + Name + "' cannot be empty");
4444 
4445  Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4446  return false;
4447 }
4448 
4449 template <>
4450 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4452  if (parseMDNodeVector(MDs))
4453  return true;
4454 
4455  Result.assign(std::move(MDs));
4456  return false;
4457 }
4458 
4459 template <>
4460 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4461  ChecksumKindField &Result) {
4464 
4465  if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4466  return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4467  "'");
4468 
4469  Result.assign(*CSKind);
4470  Lex.Lex();
4471  return false;
4472 }
4473 
4474 } // end namespace llvm
4475 
4476 template <class ParserTy>
4477 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4478  do {
4479  if (Lex.getKind() != lltok::LabelStr)
4480  return tokError("expected field label here");
4481 
4482  if (ParseField())
4483  return true;
4484  } while (EatIfPresent(lltok::comma));
4485 
4486  return false;
4487 }
4488 
4489 template <class ParserTy>
4490 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4491  assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4492  Lex.Lex();
4493 
4494  if (parseToken(lltok::lparen, "expected '(' here"))
4495  return true;
4496  if (Lex.getKind() != lltok::rparen)
4497  if (parseMDFieldsImplBody(ParseField))
4498  return true;
4499 
4500  ClosingLoc = Lex.getLoc();
4501  return parseToken(lltok::rparen, "expected ')' here");
4502 }
4503 
4504 template <class FieldTy>
4505 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4506  if (Result.Seen)
4507  return tokError("field '" + Name + "' cannot be specified more than once");
4508 
4509  LocTy Loc = Lex.getLoc();
4510  Lex.Lex();
4511  return parseMDField(Loc, Name, Result);
4512 }
4513 
4514 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4515  assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4516 
4517 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4518  if (Lex.getStrVal() == #CLASS) \
4519  return parse##CLASS(N, IsDistinct);
4520 #include "llvm/IR/Metadata.def"
4521 
4522  return tokError("expected metadata type");
4523 }
4524 
4525 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4526 #define NOP_FIELD(NAME, TYPE, INIT)
4527 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4528  if (!NAME.Seen) \
4529  return error(ClosingLoc, "missing required field '" #NAME "'");
4530 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4531  if (Lex.getStrVal() == #NAME) \
4532  return parseMDField(#NAME, NAME);
4533 #define PARSE_MD_FIELDS() \
4534  VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4535  do { \
4536  LocTy ClosingLoc; \
4537  if (parseMDFieldsImpl( \
4538  [&]() -> bool { \
4539  VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4540  return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4541  "'"); \
4542  }, \
4543  ClosingLoc)) \
4544  return true; \
4545  VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4546  } while (false)
4547 #define GET_OR_DISTINCT(CLASS, ARGS) \
4548  (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4549 
4550 /// parseDILocationFields:
4551 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4552 /// isImplicitCode: true)
4553 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4554 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4555  OPTIONAL(line, LineField, ); \
4556  OPTIONAL(column, ColumnField, ); \
4557  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4558  OPTIONAL(inlinedAt, MDField, ); \
4559  OPTIONAL(isImplicitCode, MDBoolField, (false));
4560  PARSE_MD_FIELDS();
4561 #undef VISIT_MD_FIELDS
4562 
4563  Result =
4564  GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4565  inlinedAt.Val, isImplicitCode.Val));
4566  return false;
4567 }
4568 
4569 /// parseGenericDINode:
4570 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4571 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4572 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4573  REQUIRED(tag, DwarfTagField, ); \
4574  OPTIONAL(header, MDStringField, ); \
4575  OPTIONAL(operands, MDFieldList, );
4576  PARSE_MD_FIELDS();
4577 #undef VISIT_MD_FIELDS
4578 
4580  (Context, tag.Val, header.Val, operands.Val));
4581  return false;
4582 }
4583 
4584 /// parseDISubrange:
4585 /// ::= !DISubrange(count: 30, lowerBound: 2)
4586 /// ::= !DISubrange(count: !node, lowerBound: 2)
4587 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4588 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4589 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4590  OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4591  OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4592  OPTIONAL(upperBound, MDSignedOrMDField, ); \
4593  OPTIONAL(stride, MDSignedOrMDField, );
4594  PARSE_MD_FIELDS();
4595 #undef VISIT_MD_FIELDS
4596 
4597  Metadata *Count = nullptr;
4598  Metadata *LowerBound = nullptr;
4599  Metadata *UpperBound = nullptr;
4600  Metadata *Stride = nullptr;
4601 
4602  auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4603  if (Bound.isMDSignedField())
4605  Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4606  if (Bound.isMDField())
4607  return Bound.getMDFieldValue();
4608  return nullptr;
4609  };
4610 
4611  Count = convToMetadata(count);
4612  LowerBound = convToMetadata(lowerBound);
4613  UpperBound = convToMetadata(upperBound);
4614  Stride = convToMetadata(stride);
4615 
4617  (Context, Count, LowerBound, UpperBound, Stride));
4618 
4619  return false;
4620 }
4621 
4622 /// parseDIGenericSubrange:
4623 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4624 /// !node3)
4625 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4626 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4627  OPTIONAL(count, MDSignedOrMDField, ); \
4628  OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4629  OPTIONAL(upperBound, MDSignedOrMDField, ); \
4630  OPTIONAL(stride, MDSignedOrMDField, );
4631  PARSE_MD_FIELDS();
4632 #undef VISIT_MD_FIELDS
4633 
4634  auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4635  if (Bound.isMDSignedField())
4636  return DIExpression::get(
4637  Context, {dwarf::DW_OP_consts,
4638  static_cast<uint64_t>(Bound.getMDSignedValue())});
4639  if (Bound.isMDField())
4640  return Bound.getMDFieldValue();
4641  return nullptr;
4642  };
4643 
4644  Metadata *Count = ConvToMetadata(count);
4645  Metadata *LowerBound = ConvToMetadata(lowerBound);
4646  Metadata *UpperBound = ConvToMetadata(upperBound);
4647  Metadata *Stride = ConvToMetadata(stride);
4648 
4650  (Context, Count, LowerBound, UpperBound, Stride));
4651 
4652  return false;
4653 }
4654 
4655 /// parseDIEnumerator:
4656 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4657 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4658 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4659  REQUIRED(name, MDStringField, ); \
4660  REQUIRED(value, MDAPSIntField, ); \
4661  OPTIONAL(isUnsigned, MDBoolField, (false));
4662  PARSE_MD_FIELDS();
4663 #undef VISIT_MD_FIELDS
4664 
4665  if (isUnsigned.Val && value.Val.isNegative())
4666  return tokError("unsigned enumerator with negative value");
4667 
4668  APSInt Value(value.Val);
4669  // Add a leading zero so that unsigned values with the msb set are not
4670  // mistaken for negative values when used for signed enumerators.
4671  if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
4672  Value = Value.zext(Value.getBitWidth() + 1);
4673 
4674  Result =
4675  GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4676 
4677  return false;
4678 }
4679 
4680 /// parseDIBasicType:
4681 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4682 /// encoding: DW_ATE_encoding, flags: 0)
4683 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
4684 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4685  OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4686  OPTIONAL(name, MDStringField, ); \
4687  OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4688  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4689  OPTIONAL(encoding, DwarfAttEncodingField, ); \
4690  OPTIONAL(flags, DIFlagField, );
4691  PARSE_MD_FIELDS();
4692 #undef VISIT_MD_FIELDS
4693 
4694  Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4695  align.Val, encoding.Val, flags.Val));
4696  return false;
4697 }
4698 
4699 /// parseDIStringType:
4700 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
4701 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
4702 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4703  OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
4704  OPTIONAL(name, MDStringField, ); \
4705  OPTIONAL(stringLength, MDField, ); \
4706  OPTIONAL(stringLengthExpression, MDField, ); \
4707  OPTIONAL(stringLocationExpression, MDField, ); \
4708  OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4709  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4710  OPTIONAL(encoding, DwarfAttEncodingField, );
4711  PARSE_MD_FIELDS();
4712 #undef VISIT_MD_FIELDS
4713 
4715  DIStringType,
4716  (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
4717  stringLocationExpression.Val, size.Val, align.Val, encoding.Val));
4718  return false;
4719 }
4720 
4721 /// parseDIDerivedType:
4722 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4723 /// line: 7, scope: !1, baseType: !2, size: 32,
4724 /// align: 32, offset: 0, flags: 0, extraData: !3,
4725 /// dwarfAddressSpace: 3)
4726 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4727 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4728  REQUIRED(tag, DwarfTagField, ); \
4729  OPTIONAL(name, MDStringField, ); \
4730  OPTIONAL(file, MDField, ); \
4731  OPTIONAL(line, LineField, ); \
4732  OPTIONAL(scope, MDField, ); \
4733  REQUIRED(baseType, MDField, ); \
4734  OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4735  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4736  OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4737  OPTIONAL(flags, DIFlagField, ); \
4738  OPTIONAL(extraData, MDField, ); \
4739  OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
4740  OPTIONAL(annotations, MDField, );
4741  PARSE_MD_FIELDS();
4742 #undef VISIT_MD_FIELDS
4743 
4744  Optional<unsigned> DWARFAddressSpace;
4745  if (dwarfAddressSpace.Val != UINT32_MAX)
4746  DWARFAddressSpace = dwarfAddressSpace.Val;
4747 
4749  (Context, tag.Val, name.Val, file.Val, line.Val,
4750  scope.Val, baseType.Val, size.Val, align.Val,
4751  offset.Val, DWARFAddressSpace, flags.Val,
4752  extraData.Val, annotations.Val));
4753  return false;
4754 }
4755 
4756 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
4757 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4758  REQUIRED(tag, DwarfTagField, ); \
4759  OPTIONAL(name, MDStringField, ); \
4760  OPTIONAL(file, MDField, ); \
4761  OPTIONAL(line, LineField, ); \
4762  OPTIONAL(scope, MDField, ); \
4763  OPTIONAL(baseType, MDField, ); \
4764  OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4765  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4766  OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4767  OPTIONAL(flags, DIFlagField, ); \
4768  OPTIONAL(elements, MDField, ); \
4769  OPTIONAL(runtimeLang, DwarfLangField, ); \
4770  OPTIONAL(vtableHolder, MDField, ); \
4771  OPTIONAL(templateParams, MDField, ); \
4772  OPTIONAL(identifier, MDStringField, ); \
4773  OPTIONAL(discriminator, MDField, ); \
4774  OPTIONAL(dataLocation, MDField, ); \
4775  OPTIONAL(associated, MDField, ); \
4776  OPTIONAL(allocated, MDField, ); \
4777  OPTIONAL(rank, MDSignedOrMDField, ); \
4778  OPTIONAL(annotations, MDField, );
4779  PARSE_MD_FIELDS();
4780 #undef VISIT_MD_FIELDS
4781 
4782  Metadata *Rank = nullptr;
4783  if (rank.isMDSignedField())
4785  Type::getInt64Ty(Context), rank.getMDSignedValue()));
4786  else if (rank.isMDField())
4787  Rank = rank.getMDFieldValue();
4788 
4789  // If this has an identifier try to build an ODR type.
4790  if (identifier.Val)
4791  if (auto *CT = DICompositeType::buildODRType(
4792  Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4793  scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4794  elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
4795  discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4796  Rank, annotations.Val)) {
4797  Result = CT;
4798  return false;
4799  }
4800 
4801  // Create a new node, and save it in the context if it belongs in the type
4802  // map.
4805  (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4806  size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4807  runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4808  discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
4809  annotations.Val));
4810  return false;
4811 }
4812 
4813 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4814 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4815  OPTIONAL(flags, DIFlagField, ); \
4816  OPTIONAL(cc, DwarfCCField, ); \
4817  REQUIRED(types, MDField, );
4818  PARSE_MD_FIELDS();
4819 #undef VISIT_MD_FIELDS
4820 
4822  (Context, flags.Val, cc.Val, types.Val));
4823  return false;
4824 }
4825 
4826 /// parseDIFileType:
4827 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4828 /// checksumkind: CSK_MD5,
4829 /// checksum: "000102030405060708090a0b0c0d0e0f",
4830 /// source: "source file contents")
4831 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
4832  // The default constructed value for checksumkind is required, but will never
4833  // be used, as the parser checks if the field was actually Seen before using
4834  // the Val.
4835 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4836  REQUIRED(filename, MDStringField, ); \
4837  REQUIRED(directory, MDStringField, ); \
4838  OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4839  OPTIONAL(checksum, MDStringField, ); \
4840  OPTIONAL(source, MDStringField, );
4841  PARSE_MD_FIELDS();
4842 #undef VISIT_MD_FIELDS
4843 
4845  if (checksumkind.Seen && checksum.Seen)
4846  OptChecksum.emplace(checksumkind.Val, checksum.Val);
4847  else if (checksumkind.Seen || checksum.Seen)
4848  return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4849 
4850  Optional<MDString *> OptSource;
4851  if (source.Seen)
4852  OptSource = source.Val;
4853  Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4854  OptChecksum, OptSource));
4855  return false;
4856 }
4857 
4858 /// parseDICompileUnit:
4859 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4860 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4861 /// splitDebugFilename: "abc.debug",
4862 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4863 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
4864 /// sysroot: "/", sdk: "MacOSX.sdk")
4865 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4866  if (!IsDistinct)
4867  return Lex.Error("missing 'distinct', required for !DICompileUnit");
4868 
4869 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4870  REQUIRED(language, DwarfLangField, ); \
4871  REQUIRED(file, MDField, (/* AllowNull */ false)); \
4872  OPTIONAL(producer, MDStringField, ); \
4873  OPTIONAL(isOptimized, MDBoolField, ); \
4874  OPTIONAL(flags, MDStringField, ); \
4875  OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4876  OPTIONAL(splitDebugFilename, MDStringField, ); \
4877  OPTIONAL(emissionKind, EmissionKindField, ); \
4878  OPTIONAL(enums, MDField, ); \
4879  OPTIONAL(retainedTypes, MDField, ); \
4880  OPTIONAL(globals, MDField, ); \
4881  OPTIONAL(imports, MDField, ); \
4882  OPTIONAL(macros, MDField, ); \
4883  OPTIONAL(dwoId, MDUnsignedField, ); \
4884  OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4885  OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4886  OPTIONAL(nameTableKind, NameTableKindField, ); \
4887  OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
4888  OPTIONAL(sysroot, MDStringField, ); \
4889  OPTIONAL(sdk, MDStringField, );
4890  PARSE_MD_FIELDS();
4891 #undef VISIT_MD_FIELDS
4892 
4894  Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4895  runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4896  retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4897  splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4898  rangesBaseAddress.Val, sysroot.Val, sdk.Val);
4899  return false;
4900 }
4901 
4902 /// parseDISubprogram:
4903 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4904 /// file: !1, line: 7, type: !2, isLocal: false,
4905 /// isDefinition: true, scopeLine: 8, containingType: !3,
4906 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4907 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4908 /// spFlags: 10, isOptimized: false, templateParams: !4,
4909 /// declaration: !5, retainedNodes: !6, thrownTypes: !7,
4910 /// annotations: !8)
4911 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
4912  auto Loc = Lex.getLoc();
4913 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4914  OPTIONAL(scope, MDField, ); \
4915  OPTIONAL(name, MDStringField, ); \
4916  OPTIONAL(linkageName, MDStringField, ); \
4917  OPTIONAL(file, MDField, ); \
4918  OPTIONAL(line, LineField, ); \
4919  OPTIONAL(type, MDField, ); \
4920  OPTIONAL(isLocal, MDBoolField, ); \
4921  OPTIONAL(isDefinition, MDBoolField, (true)); \
4922  OPTIONAL(scopeLine, LineField, ); \
4923  OPTIONAL(containingType, MDField, ); \
4924  OPTIONAL(virtuality, DwarfVirtualityField, ); \
4925  OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4926  OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4927  OPTIONAL(flags, DIFlagField, ); \
4928  OPTIONAL(spFlags, DISPFlagField, ); \
4929  OPTIONAL(isOptimized, MDBoolField, ); \
4930  OPTIONAL(unit, MDField, ); \
4931  OPTIONAL(templateParams, MDField, ); \
4932  OPTIONAL(declaration, MDField, ); \
4933  OPTIONAL(retainedNodes, MDField, ); \
4934  OPTIONAL(thrownTypes, MDField, ); \
4935  OPTIONAL(annotations, MDField, ); \
4936  OPTIONAL(targetFuncName, MDStringField, );
4937  PARSE_MD_FIELDS();
4938 #undef VISIT_MD_FIELDS
4939 
4940  // An explicit spFlags field takes precedence over individual fields in
4941  // older IR versions.
4942  DISubprogram::DISPFlags SPFlags =
4943  spFlags.Seen ? spFlags.Val
4944  : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4945  isOptimized.Val, virtuality.Val);
4946  if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4947  return Lex.Error(
4948  Loc,
4949  "missing 'distinct', required for !DISubprogram that is a Definition");
4951  DISubprogram,
4952  (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4953  type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4954  thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
4955  declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
4956  targetFuncName.Val));
4957  return false;
4958 }
4959 
4960 /// parseDILexicalBlock:
4961 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4962 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4963 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4964  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4965  OPTIONAL(file, MDField, ); \
4966  OPTIONAL(line, LineField, ); \
4967  OPTIONAL(column, ColumnField, );
4968  PARSE_MD_FIELDS();
4969 #undef VISIT_MD_FIELDS
4970 
4972  DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4973  return false;
4974 }
4975 
4976 /// parseDILexicalBlockFile:
4977 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4978 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4979 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4980  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4981  OPTIONAL(file, MDField, ); \
4982  REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4983  PARSE_MD_FIELDS();
4984 #undef VISIT_MD_FIELDS
4985 
4987  (Context, scope.Val, file.Val, discriminator.Val));
4988  return false;
4989 }
4990 
4991 /// parseDICommonBlock:
4992 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4993 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4994 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4995  REQUIRED(scope, MDField, ); \
4996  OPTIONAL(declaration, MDField, ); \
4997  OPTIONAL(name, MDStringField, ); \
4998  OPTIONAL(file, MDField, ); \
4999  OPTIONAL(line, LineField, );
5000  PARSE_MD_FIELDS();
5001 #undef VISIT_MD_FIELDS
5002 
5004  (Context, scope.Val, declaration.Val, name.Val,
5005  file.Val, line.Val));
5006  return false;
5007 }
5008 
5009 /// parseDINamespace:
5010 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
5011 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
5012 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5013  REQUIRED(scope, MDField, ); \
5014  OPTIONAL(name, MDStringField, ); \
5015  OPTIONAL(exportSymbols, MDBoolField, );
5016  PARSE_MD_FIELDS();
5017 #undef VISIT_MD_FIELDS
5018 
5020  (Context, scope.Val, name.Val, exportSymbols.Val));
5021  return false;
5022 }
5023 
5024 /// parseDIMacro:
5025 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5026 /// "SomeValue")
5027 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
5028 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5029  REQUIRED(type, DwarfMacinfoTypeField, ); \
5030  OPTIONAL(line, LineField, ); \
5031  REQUIRED(name, MDStringField, ); \
5032  OPTIONAL(value, MDStringField, );
5033  PARSE_MD_FIELDS();
5034 #undef VISIT_MD_FIELDS
5035 
5037  (Context, type.Val, line.Val, name.Val, value.Val));
5038  return false;
5039 }
5040 
5041 /// parseDIMacroFile:
5042 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
5043 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
5044 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5045  OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5046  OPTIONAL(line, LineField, ); \
5047  REQUIRED(file, MDField, ); \
5048  OPTIONAL(nodes, MDField, );
5049  PARSE_MD_FIELDS();
5050 #undef VISIT_MD_FIELDS
5051 
5053  (Context, type.Val, line.Val, file.Val, nodes.Val));
5054  return false;
5055 }
5056 
5057 /// parseDIModule:
5058 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5059 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5060 /// file: !1, line: 4, isDecl: false)
5061 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5062 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5063  REQUIRED(scope, MDField, ); \
5064  REQUIRED(name, MDStringField, ); \
5065  OPTIONAL(configMacros, MDStringField, ); \
5066  OPTIONAL(includePath, MDStringField, ); \
5067  OPTIONAL(apinotes, MDStringField, ); \
5068  OPTIONAL(file, MDField, ); \
5069  OPTIONAL(line, LineField, ); \
5070  OPTIONAL(isDecl, MDBoolField, );
5071  PARSE_MD_FIELDS();
5072 #undef VISIT_MD_FIELDS
5073 
5074  Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5075  configMacros.Val, includePath.Val,
5076  apinotes.Val, line.Val, isDecl.Val));
5077  return false;
5078 }
5079 
5080 /// parseDITemplateTypeParameter:
5081 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5082 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5083 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5084  OPTIONAL(name, MDStringField, ); \
5085  REQUIRED(type, MDField, ); \
5086  OPTIONAL(defaulted, MDBoolField, );
5087  PARSE_MD_FIELDS();
5088 #undef VISIT_MD_FIELDS
5089 
5091  (Context, name.Val, type.Val, defaulted.Val));
5092  return false;
5093 }
5094 
5095 /// parseDITemplateValueParameter:
5096 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5097 /// name: "V", type: !1, defaulted: false,
5098 /// value: i32 7)
5099 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5100 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5101  OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5102  OPTIONAL(name, MDStringField, ); \
5103  OPTIONAL(type, MDField, ); \
5104  OPTIONAL(defaulted, MDBoolField, ); \
5105  REQUIRED(value, MDField, );
5106 
5107  PARSE_MD_FIELDS();
5108 #undef VISIT_MD_FIELDS
5109 
5112  (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5113  return false;
5114 }
5115 
5116 /// parseDIGlobalVariable:
5117 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5118 /// file: !1, line: 7, type: !2, isLocal: false,
5119 /// isDefinition: true, templateParams: !3,
5120 /// declaration: !4, align: 8)
5121 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5122 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5123  OPTIONAL(name, MDStringField, (/* AllowEmpty */ false)); \
5124  OPTIONAL(scope, MDField, ); \
5125  OPTIONAL(linkageName, MDStringField, ); \
5126  OPTIONAL(file, MDField, ); \
5127  OPTIONAL(line, LineField, ); \
5128  OPTIONAL(type, MDField, ); \
5129  OPTIONAL(isLocal, MDBoolField, ); \
5130  OPTIONAL(isDefinition, MDBoolField, (true)); \
5131  OPTIONAL(templateParams, MDField, ); \
5132  OPTIONAL(declaration, MDField, ); \
5133  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5134  OPTIONAL(annotations, MDField, );
5135  PARSE_MD_FIELDS();
5136 #undef VISIT_MD_FIELDS
5137 
5138  Result =
5140  (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5141  line.Val, type.Val, isLocal.Val, isDefinition.Val,
5142  declaration.Val, templateParams.Val, align.Val,
5143  annotations.Val));
5144  return false;
5145 }
5146 
5147 /// parseDILocalVariable:
5148 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5149 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5150 /// align: 8)
5151 /// ::= !DILocalVariable(scope: !0, name: "foo",
5152 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5153 /// align: 8)
5154 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5155 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5156  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5157  OPTIONAL(name, MDStringField, ); \
5158  OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5159  OPTIONAL(file, MDField, ); \
5160  OPTIONAL(line, LineField, ); \
5161  OPTIONAL(type, MDField, ); \
5162  OPTIONAL(flags, DIFlagField, ); \
5163  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5164  OPTIONAL(annotations, MDField, );
5165  PARSE_MD_FIELDS();
5166 #undef VISIT_MD_FIELDS
5167 
5169  (Context, scope.Val, name.Val, file.Val, line.Val,
5170  type.Val, arg.Val, flags.Val, align.Val,
5171  annotations.Val));
5172  return false;
5173 }
5174 
5175 /// parseDILabel:
5176 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5177 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5178 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5179  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5180  REQUIRED(name, MDStringField, ); \
5181  REQUIRED(file, MDField, ); \
5182  REQUIRED(line, LineField, );
5183  PARSE_MD_FIELDS();
5184 #undef VISIT_MD_FIELDS
5185 
5187  (Context, scope.Val, name.Val, file.Val, line.Val));
5188  return false;
5189 }
5190 
5191 /// parseDIExpression:
5192 /// ::= !DIExpression(0, 7, -1)
5193 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5194  assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5195  Lex.Lex();
5196 
5197  if (parseToken(lltok::lparen, "expected '(' here"))
5198  return true;
5199 
5200  SmallVector<uint64_t, 8> Elements;
5201  if (Lex.getKind() != lltok::rparen)
5202  do {
5203  if (Lex.getKind() == lltok::DwarfOp) {
5204  if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5205  Lex.Lex();
5206  Elements.push_back(Op);
5207  continue;
5208  }
5209  return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5210  }
5211 
5212  if (Lex.getKind() == lltok::DwarfAttEncoding) {
5213  if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5214  Lex.Lex();
5215  Elements.push_back(Op);
5216  continue;
5217  }
5218  return tokError(Twine("invalid DWARF attribute encoding '") +
5219  Lex.getStrVal() + "'");
5220  }
5221 
5222  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5223  return tokError("expected unsigned integer");
5224 
5225  auto &U = Lex.getAPSIntVal();
5226  if (U.ugt(UINT64_MAX))
5227  return tokError("element too large, limit is " + Twine(UINT64_MAX));
5228  Elements.push_back(U.getZExtValue());
5229  Lex.Lex();
5230  } while (EatIfPresent(lltok::comma));
5231 
5232  if (parseToken(lltok::rparen, "expected ')' here"))
5233  return true;
5234 
5235  Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5236  return false;
5237 }
5238 
5239 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) {
5240  return parseDIArgList(Result, IsDistinct, nullptr);
5241 }
5242 /// ParseDIArgList:
5243 /// ::= !DIArgList(i32 7, i64 %0)
5244 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct,
5245  PerFunctionState *PFS) {
5246  assert(PFS && "Expected valid function state");
5247  assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5248  Lex.Lex();
5249 
5250  if (parseToken(lltok::lparen, "expected '(' here"))
5251  return true;
5252 
5254  if (Lex.