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