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