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