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