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