LLVM  10.0.0
LLParser.cpp
Go to the documentation of this file.
1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the parser class for .ll files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "LLParser.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/IR/Argument.h"
22 #include "llvm/IR/AutoUpgrade.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Comdat.h"
26 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalIFunc.h"
31 #include "llvm/IR/GlobalObject.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/IR/Value.h"
43 #include "llvm/Support/Casting.h"
48 #include <algorithm>
49 #include <cassert>
50 #include <cstring>
51 #include <iterator>
52 #include <vector>
53 
54 using namespace llvm;
55 
56 static std::string getTypeString(Type *T) {
57  std::string Result;
58  raw_string_ostream Tmp(Result);
59  Tmp << *T;
60  return Tmp.str();
61 }
62 
63 /// Run: module ::= toplevelentity*
64 bool LLParser::Run() {
65  // Prime the lexer.
66  Lex.Lex();
67 
68  if (Context.shouldDiscardValueNames())
69  return Error(
70  Lex.getLoc(),
71  "Can't read textual IR with a Context that discards named Values");
72 
73  return ParseTopLevelEntities() || ValidateEndOfModule() ||
74  ValidateEndOfIndex();
75 }
76 
78  const SlotMapping *Slots) {
79  restoreParsingState(Slots);
80  Lex.Lex();
81 
82  Type *Ty = nullptr;
83  if (ParseType(Ty) || parseConstantValue(Ty, C))
84  return true;
85  if (Lex.getKind() != lltok::Eof)
86  return Error(Lex.getLoc(), "expected end of string");
87  return false;
88 }
89 
90 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
91  const SlotMapping *Slots) {
92  restoreParsingState(Slots);
93  Lex.Lex();
94 
95  Read = 0;
96  SMLoc Start = Lex.getLoc();
97  Ty = nullptr;
98  if (ParseType(Ty))
99  return true;
100  SMLoc End = Lex.getLoc();
101  Read = End.getPointer() - Start.getPointer();
102 
103  return false;
104 }
105 
106 void LLParser::restoreParsingState(const SlotMapping *Slots) {
107  if (!Slots)
108  return;
109  NumberedVals = Slots->GlobalValues;
110  NumberedMetadata = Slots->MetadataNodes;
111  for (const auto &I : Slots->NamedTypes)
112  NamedTypes.insert(
113  std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
114  for (const auto &I : Slots->Types)
115  NumberedTypes.insert(
116  std::make_pair(I.first, std::make_pair(I.second, LocTy())));
117 }
118 
119 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
120 /// module.
121 bool LLParser::ValidateEndOfModule() {
122  if (!M)
123  return false;
124  // Handle any function attribute group forward references.
125  for (const auto &RAG : ForwardRefAttrGroups) {
126  Value *V = RAG.first;
127  const std::vector<unsigned> &Attrs = RAG.second;
128  AttrBuilder B;
129 
130  for (const auto &Attr : Attrs)
131  B.merge(NumberedAttrBuilders[Attr]);
132 
133  if (Function *Fn = dyn_cast<Function>(V)) {
134  AttributeList AS = Fn->getAttributes();
135  AttrBuilder FnAttrs(AS.getFnAttributes());
137 
138  FnAttrs.merge(B);
139 
140  // If the alignment was parsed as an attribute, move to the alignment
141  // field.
142  if (FnAttrs.hasAlignmentAttr()) {
143  Fn->setAlignment(FnAttrs.getAlignment());
144  FnAttrs.removeAttribute(Attribute::Alignment);
145  }
146 
148  AttributeSet::get(Context, FnAttrs));
149  Fn->setAttributes(AS);
150  } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
151  AttributeList AS = CI->getAttributes();
152  AttrBuilder FnAttrs(AS.getFnAttributes());
154  FnAttrs.merge(B);
156  AttributeSet::get(Context, FnAttrs));
157  CI->setAttributes(AS);
158  } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
159  AttributeList AS = II->getAttributes();
160  AttrBuilder FnAttrs(AS.getFnAttributes());
162  FnAttrs.merge(B);
164  AttributeSet::get(Context, FnAttrs));
165  II->setAttributes(AS);
166  } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
167  AttributeList AS = CBI->getAttributes();
168  AttrBuilder FnAttrs(AS.getFnAttributes());
170  FnAttrs.merge(B);
172  AttributeSet::get(Context, FnAttrs));
173  CBI->setAttributes(AS);
174  } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
175  AttrBuilder Attrs(GV->getAttributes());
176  Attrs.merge(B);
177  GV->setAttributes(AttributeSet::get(Context,Attrs));
178  } else {
179  llvm_unreachable("invalid object with forward attribute group reference");
180  }
181  }
182 
183  // If there are entries in ForwardRefBlockAddresses at this point, the
184  // function was never defined.
185  if (!ForwardRefBlockAddresses.empty())
186  return Error(ForwardRefBlockAddresses.begin()->first.Loc,
187  "expected function name in blockaddress");
188 
189  for (const auto &NT : NumberedTypes)
190  if (NT.second.second.isValid())
191  return Error(NT.second.second,
192  "use of undefined type '%" + Twine(NT.first) + "'");
193 
194  for (StringMap<std::pair<Type*, LocTy> >::iterator I =
195  NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
196  if (I->second.second.isValid())
197  return Error(I->second.second,
198  "use of undefined type named '" + I->getKey() + "'");
199 
200  if (!ForwardRefComdats.empty())
201  return Error(ForwardRefComdats.begin()->second,
202  "use of undefined comdat '$" +
203  ForwardRefComdats.begin()->first + "'");
204 
205  if (!ForwardRefVals.empty())
206  return Error(ForwardRefVals.begin()->second.second,
207  "use of undefined value '@" + ForwardRefVals.begin()->first +
208  "'");
209 
210  if (!ForwardRefValIDs.empty())
211  return Error(ForwardRefValIDs.begin()->second.second,
212  "use of undefined value '@" +
213  Twine(ForwardRefValIDs.begin()->first) + "'");
214 
215  if (!ForwardRefMDNodes.empty())
216  return Error(ForwardRefMDNodes.begin()->second.second,
217  "use of undefined metadata '!" +
218  Twine(ForwardRefMDNodes.begin()->first) + "'");
219 
220  // Resolve metadata cycles.
221  for (auto &N : NumberedMetadata) {
222  if (N.second && !N.second->isResolved())
223  N.second->resolveCycles();
224  }
225 
226  for (auto *Inst : InstsWithTBAATag) {
227  MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
228  assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
229  auto *UpgradedMD = UpgradeTBAANode(*MD);
230  if (MD != UpgradedMD)
231  Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
232  }
233 
234  // Look for intrinsic functions and CallInst that need to be upgraded
235  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
236  UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
237 
238  // Some types could be renamed during loading if several modules are
239  // loaded in the same LLVMContext (LTO scenario). In this case we should
240  // remangle intrinsics names as well.
241  for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
242  Function *F = &*FI++;
243  if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
244  F->replaceAllUsesWith(Remangled.getValue());
245  F->eraseFromParent();
246  }
247  }
248 
249  if (UpgradeDebugInfo)
251 
252  UpgradeModuleFlags(*M);
254 
255  if (!Slots)
256  return false;
257  // Initialize the slot mapping.
258  // Because by this point we've parsed and validated everything, we can "steal"
259  // the mapping from LLParser as it doesn't need it anymore.
260  Slots->GlobalValues = std::move(NumberedVals);
261  Slots->MetadataNodes = std::move(NumberedMetadata);
262  for (const auto &I : NamedTypes)
263  Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
264  for (const auto &I : NumberedTypes)
265  Slots->Types.insert(std::make_pair(I.first, I.second.first));
266 
267  return false;
268 }
269 
270 /// Do final validity and sanity checks at the end of the index.
271 bool LLParser::ValidateEndOfIndex() {
272  if (!Index)
273  return false;
274 
275  if (!ForwardRefValueInfos.empty())
276  return Error(ForwardRefValueInfos.begin()->second.front().second,
277  "use of undefined summary '^" +
278  Twine(ForwardRefValueInfos.begin()->first) + "'");
279 
280  if (!ForwardRefAliasees.empty())
281  return Error(ForwardRefAliasees.begin()->second.front().second,
282  "use of undefined summary '^" +
283  Twine(ForwardRefAliasees.begin()->first) + "'");
284 
285  if (!ForwardRefTypeIds.empty())
286  return Error(ForwardRefTypeIds.begin()->second.front().second,
287  "use of undefined type id summary '^" +
288  Twine(ForwardRefTypeIds.begin()->first) + "'");
289 
290  return false;
291 }
292 
293 //===----------------------------------------------------------------------===//
294 // Top-Level Entities
295 //===----------------------------------------------------------------------===//
296 
297 bool LLParser::ParseTopLevelEntities() {
298  // If there is no Module, then parse just the summary index entries.
299  if (!M) {
300  while (true) {
301  switch (Lex.getKind()) {
302  case lltok::Eof:
303  return false;
304  case lltok::SummaryID:
305  if (ParseSummaryEntry())
306  return true;
307  break;
309  if (ParseSourceFileName())
310  return true;
311  break;
312  default:
313  // Skip everything else
314  Lex.Lex();
315  }
316  }
317  }
318  while (true) {
319  switch (Lex.getKind()) {
320  default: return TokError("expected top-level entity");
321  case lltok::Eof: return false;
322  case lltok::kw_declare: if (ParseDeclare()) return true; break;
323  case lltok::kw_define: if (ParseDefine()) return true; break;
324  case lltok::kw_module: if (ParseModuleAsm()) return true; break;
325  case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
327  if (ParseSourceFileName())
328  return true;
329  break;
330  case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
331  case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
332  case lltok::LocalVar: if (ParseNamedType()) return true; break;
333  case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
334  case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
335  case lltok::ComdatVar: if (parseComdat()) return true; break;
336  case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
337  case lltok::SummaryID:
338  if (ParseSummaryEntry())
339  return true;
340  break;
341  case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
342  case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
343  case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
345  if (ParseUseListOrderBB())
346  return true;
347  break;
348  }
349  }
350 }
351 
352 /// toplevelentity
353 /// ::= 'module' 'asm' STRINGCONSTANT
354 bool LLParser::ParseModuleAsm() {
355  assert(Lex.getKind() == lltok::kw_module);
356  Lex.Lex();
357 
358  std::string AsmStr;
359  if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
360  ParseStringConstant(AsmStr)) return true;
361 
362  M->appendModuleInlineAsm(AsmStr);
363  return false;
364 }
365 
366 /// toplevelentity
367 /// ::= 'target' 'triple' '=' STRINGCONSTANT
368 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
369 bool LLParser::ParseTargetDefinition() {
370  assert(Lex.getKind() == lltok::kw_target);
371  std::string Str;
372  switch (Lex.Lex()) {
373  default: return TokError("unknown target property");
374  case lltok::kw_triple:
375  Lex.Lex();
376  if (ParseToken(lltok::equal, "expected '=' after target triple") ||
377  ParseStringConstant(Str))
378  return true;
379  M->setTargetTriple(Str);
380  return false;
382  Lex.Lex();
383  if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
384  ParseStringConstant(Str))
385  return true;
386  if (DataLayoutStr.empty())
387  M->setDataLayout(Str);
388  return false;
389  }
390 }
391 
392 /// toplevelentity
393 /// ::= 'source_filename' '=' STRINGCONSTANT
394 bool LLParser::ParseSourceFileName() {
396  Lex.Lex();
397  if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
398  ParseStringConstant(SourceFileName))
399  return true;
400  if (M)
401  M->setSourceFileName(SourceFileName);
402  return false;
403 }
404 
405 /// toplevelentity
406 /// ::= 'deplibs' '=' '[' ']'
407 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
408 /// FIXME: Remove in 4.0. Currently parse, but ignore.
409 bool LLParser::ParseDepLibs() {
410  assert(Lex.getKind() == lltok::kw_deplibs);
411  Lex.Lex();
412  if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
413  ParseToken(lltok::lsquare, "expected '=' after deplibs"))
414  return true;
415 
416  if (EatIfPresent(lltok::rsquare))
417  return false;
418 
419  do {
420  std::string Str;
421  if (ParseStringConstant(Str)) return true;
422  } while (EatIfPresent(lltok::comma));
423 
424  return ParseToken(lltok::rsquare, "expected ']' at end of list");
425 }
426 
427 /// ParseUnnamedType:
428 /// ::= LocalVarID '=' 'type' type
429 bool LLParser::ParseUnnamedType() {
430  LocTy TypeLoc = Lex.getLoc();
431  unsigned TypeID = Lex.getUIntVal();
432  Lex.Lex(); // eat LocalVarID;
433 
434  if (ParseToken(lltok::equal, "expected '=' after name") ||
435  ParseToken(lltok::kw_type, "expected 'type' after '='"))
436  return true;
437 
438  Type *Result = nullptr;
439  if (ParseStructDefinition(TypeLoc, "",
440  NumberedTypes[TypeID], Result)) return true;
441 
442  if (!isa<StructType>(Result)) {
443  std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
444  if (Entry.first)
445  return Error(TypeLoc, "non-struct types may not be recursive");
446  Entry.first = Result;
447  Entry.second = SMLoc();
448  }
449 
450  return false;
451 }
452 
453 /// toplevelentity
454 /// ::= LocalVar '=' 'type' type
455 bool LLParser::ParseNamedType() {
456  std::string Name = Lex.getStrVal();
457  LocTy NameLoc = Lex.getLoc();
458  Lex.Lex(); // eat LocalVar.
459 
460  if (ParseToken(lltok::equal, "expected '=' after name") ||
461  ParseToken(lltok::kw_type, "expected 'type' after name"))
462  return true;
463 
464  Type *Result = nullptr;
465  if (ParseStructDefinition(NameLoc, Name,
466  NamedTypes[Name], Result)) return true;
467 
468  if (!isa<StructType>(Result)) {
469  std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
470  if (Entry.first)
471  return Error(NameLoc, "non-struct types may not be recursive");
472  Entry.first = Result;
473  Entry.second = SMLoc();
474  }
475 
476  return false;
477 }
478 
479 /// toplevelentity
480 /// ::= 'declare' FunctionHeader
481 bool LLParser::ParseDeclare() {
482  assert(Lex.getKind() == lltok::kw_declare);
483  Lex.Lex();
484 
485  std::vector<std::pair<unsigned, MDNode *>> MDs;
486  while (Lex.getKind() == lltok::MetadataVar) {
487  unsigned MDK;
488  MDNode *N;
489  if (ParseMetadataAttachment(MDK, N))
490  return true;
491  MDs.push_back({MDK, N});
492  }
493 
494  Function *F;
495  if (ParseFunctionHeader(F, false))
496  return true;
497  for (auto &MD : MDs)
498  F->addMetadata(MD.first, *MD.second);
499  return false;
500 }
501 
502 /// toplevelentity
503 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
504 bool LLParser::ParseDefine() {
505  assert(Lex.getKind() == lltok::kw_define);
506  Lex.Lex();
507 
508  Function *F;
509  return ParseFunctionHeader(F, true) ||
510  ParseOptionalFunctionMetadata(*F) ||
511  ParseFunctionBody(*F);
512 }
513 
514 /// ParseGlobalType
515 /// ::= 'constant'
516 /// ::= 'global'
517 bool LLParser::ParseGlobalType(bool &IsConstant) {
518  if (Lex.getKind() == lltok::kw_constant)
519  IsConstant = true;
520  else if (Lex.getKind() == lltok::kw_global)
521  IsConstant = false;
522  else {
523  IsConstant = false;
524  return TokError("expected 'global' or 'constant'");
525  }
526  Lex.Lex();
527  return false;
528 }
529 
530 bool LLParser::ParseOptionalUnnamedAddr(
531  GlobalVariable::UnnamedAddr &UnnamedAddr) {
532  if (EatIfPresent(lltok::kw_unnamed_addr))
533  UnnamedAddr = GlobalValue::UnnamedAddr::Global;
534  else if (EatIfPresent(lltok::kw_local_unnamed_addr))
535  UnnamedAddr = GlobalValue::UnnamedAddr::Local;
536  else
537  UnnamedAddr = GlobalValue::UnnamedAddr::None;
538  return false;
539 }
540 
541 /// ParseUnnamedGlobal:
542 /// OptionalVisibility (ALIAS | IFUNC) ...
543 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
544 /// OptionalDLLStorageClass
545 /// ... -> global variable
546 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
547 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
548 /// OptionalDLLStorageClass
549 /// ... -> global variable
550 bool LLParser::ParseUnnamedGlobal() {
551  unsigned VarID = NumberedVals.size();
552  std::string Name;
553  LocTy NameLoc = Lex.getLoc();
554 
555  // Handle the GlobalID form.
556  if (Lex.getKind() == lltok::GlobalID) {
557  if (Lex.getUIntVal() != VarID)
558  return Error(Lex.getLoc(), "variable expected to be numbered '%" +
559  Twine(VarID) + "'");
560  Lex.Lex(); // eat GlobalID;
561 
562  if (ParseToken(lltok::equal, "expected '=' after name"))
563  return true;
564  }
565 
566  bool HasLinkage;
567  unsigned Linkage, Visibility, DLLStorageClass;
568  bool DSOLocal;
570  GlobalVariable::UnnamedAddr UnnamedAddr;
571  if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
572  DSOLocal) ||
573  ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
574  return true;
575 
576  if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
577  return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
578  DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
579 
580  return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
581  DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
582 }
583 
584 /// ParseNamedGlobal:
585 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
586 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
587 /// OptionalVisibility OptionalDLLStorageClass
588 /// ... -> global variable
589 bool LLParser::ParseNamedGlobal() {
590  assert(Lex.getKind() == lltok::GlobalVar);
591  LocTy NameLoc = Lex.getLoc();
592  std::string Name = Lex.getStrVal();
593  Lex.Lex();
594 
595  bool HasLinkage;
596  unsigned Linkage, Visibility, DLLStorageClass;
597  bool DSOLocal;
599  GlobalVariable::UnnamedAddr UnnamedAddr;
600  if (ParseToken(lltok::equal, "expected '=' in global variable") ||
601  ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
602  DSOLocal) ||
603  ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
604  return true;
605 
606  if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
607  return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
608  DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
609 
610  return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
611  DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
612 }
613 
614 bool LLParser::parseComdat() {
615  assert(Lex.getKind() == lltok::ComdatVar);
616  std::string Name = Lex.getStrVal();
617  LocTy NameLoc = Lex.getLoc();
618  Lex.Lex();
619 
620  if (ParseToken(lltok::equal, "expected '=' here"))
621  return true;
622 
623  if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
624  return TokError("expected comdat type");
625 
627  switch (Lex.getKind()) {
628  default:
629  return TokError("unknown selection kind");
630  case lltok::kw_any:
631  SK = Comdat::Any;
632  break;
634  SK = Comdat::ExactMatch;
635  break;
636  case lltok::kw_largest:
637  SK = Comdat::Largest;
638  break;
641  break;
642  case lltok::kw_samesize:
643  SK = Comdat::SameSize;
644  break;
645  }
646  Lex.Lex();
647 
648  // See if the comdat was forward referenced, if so, use the comdat.
649  Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
650  Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
651  if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
652  return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
653 
654  Comdat *C;
655  if (I != ComdatSymTab.end())
656  C = &I->second;
657  else
658  C = M->getOrInsertComdat(Name);
659  C->setSelectionKind(SK);
660 
661  return false;
662 }
663 
664 // MDString:
665 // ::= '!' STRINGCONSTANT
666 bool LLParser::ParseMDString(MDString *&Result) {
667  std::string Str;
668  if (ParseStringConstant(Str)) return true;
669  Result = MDString::get(Context, Str);
670  return false;
671 }
672 
673 // MDNode:
674 // ::= '!' MDNodeNumber
675 bool LLParser::ParseMDNodeID(MDNode *&Result) {
676  // !{ ..., !42, ... }
677  LocTy IDLoc = Lex.getLoc();
678  unsigned MID = 0;
679  if (ParseUInt32(MID))
680  return true;
681 
682  // If not a forward reference, just return it now.
683  if (NumberedMetadata.count(MID)) {
684  Result = NumberedMetadata[MID];
685  return false;
686  }
687 
688  // Otherwise, create MDNode forward reference.
689  auto &FwdRef = ForwardRefMDNodes[MID];
690  FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
691 
692  Result = FwdRef.first.get();
693  NumberedMetadata[MID].reset(Result);
694  return false;
695 }
696 
697 /// ParseNamedMetadata:
698 /// !foo = !{ !1, !2 }
699 bool LLParser::ParseNamedMetadata() {
701  std::string Name = Lex.getStrVal();
702  Lex.Lex();
703 
704  if (ParseToken(lltok::equal, "expected '=' here") ||
705  ParseToken(lltok::exclaim, "Expected '!' here") ||
706  ParseToken(lltok::lbrace, "Expected '{' here"))
707  return true;
708 
709  NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
710  if (Lex.getKind() != lltok::rbrace)
711  do {
712  MDNode *N = nullptr;
713  // Parse DIExpressions inline as a special case. They are still MDNodes,
714  // so they can still appear in named metadata. Remove this logic if they
715  // become plain Metadata.
716  if (Lex.getKind() == lltok::MetadataVar &&
717  Lex.getStrVal() == "DIExpression") {
718  if (ParseDIExpression(N, /*IsDistinct=*/false))
719  return true;
720  } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
721  ParseMDNodeID(N)) {
722  return true;
723  }
724  NMD->addOperand(N);
725  } while (EatIfPresent(lltok::comma));
726 
727  return ParseToken(lltok::rbrace, "expected end of metadata node");
728 }
729 
730 /// ParseStandaloneMetadata:
731 /// !42 = !{...}
732 bool LLParser::ParseStandaloneMetadata() {
733  assert(Lex.getKind() == lltok::exclaim);
734  Lex.Lex();
735  unsigned MetadataID = 0;
736 
737  MDNode *Init;
738  if (ParseUInt32(MetadataID) ||
739  ParseToken(lltok::equal, "expected '=' here"))
740  return true;
741 
742  // Detect common error, from old metadata syntax.
743  if (Lex.getKind() == lltok::Type)
744  return TokError("unexpected type in metadata definition");
745 
746  bool IsDistinct = EatIfPresent(lltok::kw_distinct);
747  if (Lex.getKind() == lltok::MetadataVar) {
748  if (ParseSpecializedMDNode(Init, IsDistinct))
749  return true;
750  } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
751  ParseMDTuple(Init, IsDistinct))
752  return true;
753 
754  // See if this was forward referenced, if so, handle it.
755  auto FI = ForwardRefMDNodes.find(MetadataID);
756  if (FI != ForwardRefMDNodes.end()) {
757  FI->second.first->replaceAllUsesWith(Init);
758  ForwardRefMDNodes.erase(FI);
759 
760  assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
761  } else {
762  if (NumberedMetadata.count(MetadataID))
763  return TokError("Metadata id is already used");
764  NumberedMetadata[MetadataID].reset(Init);
765  }
766 
767  return false;
768 }
769 
770 // Skips a single module summary entry.
771 bool LLParser::SkipModuleSummaryEntry() {
772  // Each module summary entry consists of a tag for the entry
773  // type, followed by a colon, then the fields surrounded by nested sets of
774  // parentheses. The "tag:" looks like a Label. Once parsing support is
775  // in place we will look for the tokens corresponding to the expected tags.
776  if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
777  Lex.getKind() != lltok::kw_typeid)
778  return TokError(
779  "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
780  Lex.Lex();
781  if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
782  ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
783  return true;
784  // Now walk through the parenthesized entry, until the number of open
785  // parentheses goes back down to 0 (the first '(' was parsed above).
786  unsigned NumOpenParen = 1;
787  do {
788  switch (Lex.getKind()) {
789  case lltok::lparen:
790  NumOpenParen++;
791  break;
792  case lltok::rparen:
793  NumOpenParen--;
794  break;
795  case lltok::Eof:
796  return TokError("found end of file while parsing summary entry");
797  default:
798  // Skip everything in between parentheses.
799  break;
800  }
801  Lex.Lex();
802  } while (NumOpenParen > 0);
803  return false;
804 }
805 
806 /// SummaryEntry
807 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
808 bool LLParser::ParseSummaryEntry() {
809  assert(Lex.getKind() == lltok::SummaryID);
810  unsigned SummaryID = Lex.getUIntVal();
811 
812  // For summary entries, colons should be treated as distinct tokens,
813  // not an indication of the end of a label token.
814  Lex.setIgnoreColonInIdentifiers(true);
815 
816  Lex.Lex();
817  if (ParseToken(lltok::equal, "expected '=' here"))
818  return true;
819 
820  // If we don't have an index object, skip the summary entry.
821  if (!Index)
822  return SkipModuleSummaryEntry();
823 
824  bool result = false;
825  switch (Lex.getKind()) {
826  case lltok::kw_gv:
827  result = ParseGVEntry(SummaryID);
828  break;
829  case lltok::kw_module:
830  result = ParseModuleEntry(SummaryID);
831  break;
832  case lltok::kw_typeid:
833  result = ParseTypeIdEntry(SummaryID);
834  break;
836  result = ParseTypeIdCompatibleVtableEntry(SummaryID);
837  break;
838  default:
839  result = Error(Lex.getLoc(), "unexpected summary kind");
840  break;
841  }
842  Lex.setIgnoreColonInIdentifiers(false);
843  return result;
844 }
845 
846 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
849 }
850 
851 // If there was an explicit dso_local, update GV. In the absence of an explicit
852 // dso_local we keep the default value.
853 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
854  if (DSOLocal)
855  GV.setDSOLocal(true);
856 }
857 
858 /// parseIndirectSymbol:
859 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
860 /// OptionalVisibility OptionalDLLStorageClass
861 /// OptionalThreadLocal OptionalUnnamedAddr
862 /// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
863 ///
864 /// IndirectSymbol
865 /// ::= TypeAndValue
866 ///
867 /// IndirectSymbolAttr
868 /// ::= ',' 'partition' StringConstant
869 ///
870 /// Everything through OptionalUnnamedAddr has already been parsed.
871 ///
872 bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
873  unsigned L, unsigned Visibility,
874  unsigned DLLStorageClass, bool DSOLocal,
876  GlobalVariable::UnnamedAddr UnnamedAddr) {
877  bool IsAlias;
878  if (Lex.getKind() == lltok::kw_alias)
879  IsAlias = true;
880  else if (Lex.getKind() == lltok::kw_ifunc)
881  IsAlias = false;
882  else
883  llvm_unreachable("Not an alias or ifunc!");
884  Lex.Lex();
885 
887 
888  if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
889  return Error(NameLoc, "invalid linkage type for alias");
890 
891  if (!isValidVisibilityForLinkage(Visibility, L))
892  return Error(NameLoc,
893  "symbol with local linkage must have default visibility");
894 
895  Type *Ty;
896  LocTy ExplicitTypeLoc = Lex.getLoc();
897  if (ParseType(Ty) ||
898  ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
899  return true;
900 
901  Constant *Aliasee;
902  LocTy AliaseeLoc = Lex.getLoc();
903  if (Lex.getKind() != lltok::kw_bitcast &&
904  Lex.getKind() != lltok::kw_getelementptr &&
905  Lex.getKind() != lltok::kw_addrspacecast &&
906  Lex.getKind() != lltok::kw_inttoptr) {
907  if (ParseGlobalTypeAndValue(Aliasee))
908  return true;
909  } else {
910  // The bitcast dest type is not present, it is implied by the dest type.
911  ValID ID;
912  if (ParseValID(ID))
913  return true;
914  if (ID.Kind != ValID::t_Constant)
915  return Error(AliaseeLoc, "invalid aliasee");
916  Aliasee = ID.ConstantVal;
917  }
918 
919  Type *AliaseeType = Aliasee->getType();
920  auto *PTy = dyn_cast<PointerType>(AliaseeType);
921  if (!PTy)
922  return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
923  unsigned AddrSpace = PTy->getAddressSpace();
924 
925  if (IsAlias && Ty != PTy->getElementType())
926  return Error(
927  ExplicitTypeLoc,
928  "explicit pointee type doesn't match operand's pointee type");
929 
930  if (!IsAlias && !PTy->getElementType()->isFunctionTy())
931  return Error(
932  ExplicitTypeLoc,
933  "explicit pointee type should be a function type");
934 
935  GlobalValue *GVal = nullptr;
936 
937  // See if the alias was forward referenced, if so, prepare to replace the
938  // forward reference.
939  if (!Name.empty()) {
940  GVal = M->getNamedValue(Name);
941  if (GVal) {
942  if (!ForwardRefVals.erase(Name))
943  return Error(NameLoc, "redefinition of global '@" + Name + "'");
944  }
945  } else {
946  auto I = ForwardRefValIDs.find(NumberedVals.size());
947  if (I != ForwardRefValIDs.end()) {
948  GVal = I->second.first;
949  ForwardRefValIDs.erase(I);
950  }
951  }
952 
953  // Okay, create the alias but do not insert it into the module yet.
954  std::unique_ptr<GlobalIndirectSymbol> GA;
955  if (IsAlias)
956  GA.reset(GlobalAlias::create(Ty, AddrSpace,
958  Aliasee, /*Parent*/ nullptr));
959  else
960  GA.reset(GlobalIFunc::create(Ty, AddrSpace,
962  Aliasee, /*Parent*/ nullptr));
963  GA->setThreadLocalMode(TLM);
964  GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
965  GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
966  GA->setUnnamedAddr(UnnamedAddr);
967  maybeSetDSOLocal(DSOLocal, *GA);
968 
969  // At this point we've parsed everything except for the IndirectSymbolAttrs.
970  // Now parse them if there are any.
971  while (Lex.getKind() == lltok::comma) {
972  Lex.Lex();
973 
974  if (Lex.getKind() == lltok::kw_partition) {
975  Lex.Lex();
976  GA->setPartition(Lex.getStrVal());
977  if (ParseToken(lltok::StringConstant, "expected partition string"))
978  return true;
979  } else {
980  return TokError("unknown alias or ifunc property!");
981  }
982  }
983 
984  if (Name.empty())
985  NumberedVals.push_back(GA.get());
986 
987  if (GVal) {
988  // Verify that types agree.
989  if (GVal->getType() != GA->getType())
990  return Error(
991  ExplicitTypeLoc,
992  "forward reference and definition of alias have different types");
993 
994  // If they agree, just RAUW the old value with the alias and remove the
995  // forward ref info.
996  GVal->replaceAllUsesWith(GA.get());
997  GVal->eraseFromParent();
998  }
999 
1000  // Insert into the module, we know its name won't collide now.
1001  if (IsAlias)
1002  M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
1003  else
1004  M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
1005  assert(GA->getName() == Name && "Should not be a name conflict!");
1006 
1007  // The module owns this now
1008  GA.release();
1009 
1010  return false;
1011 }
1012 
1013 /// ParseGlobal
1014 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1015 /// OptionalVisibility OptionalDLLStorageClass
1016 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1017 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1018 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1019 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1020 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1021 /// Const OptionalAttrs
1022 ///
1023 /// Everything up to and including OptionalUnnamedAddr has been parsed
1024 /// already.
1025 ///
1026 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
1027  unsigned Linkage, bool HasLinkage,
1028  unsigned Visibility, unsigned DLLStorageClass,
1029  bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1030  GlobalVariable::UnnamedAddr UnnamedAddr) {
1031  if (!isValidVisibilityForLinkage(Visibility, Linkage))
1032  return Error(NameLoc,
1033  "symbol with local linkage must have default visibility");
1034 
1035  unsigned AddrSpace;
1036  bool IsConstant, IsExternallyInitialized;
1037  LocTy IsExternallyInitializedLoc;
1038  LocTy TyLoc;
1039 
1040  Type *Ty = nullptr;
1041  if (ParseOptionalAddrSpace(AddrSpace) ||
1042  ParseOptionalToken(lltok::kw_externally_initialized,
1043  IsExternallyInitialized,
1044  &IsExternallyInitializedLoc) ||
1045  ParseGlobalType(IsConstant) ||
1046  ParseType(Ty, TyLoc))
1047  return true;
1048 
1049  // If the linkage is specified and is external, then no initializer is
1050  // present.
1051  Constant *Init = nullptr;
1052  if (!HasLinkage ||
1054  (GlobalValue::LinkageTypes)Linkage)) {
1055  if (ParseGlobalValue(Ty, Init))
1056  return true;
1057  }
1058 
1060  return Error(TyLoc, "invalid type for global variable");
1061 
1062  GlobalValue *GVal = nullptr;
1063 
1064  // See if the global was forward referenced, if so, use the global.
1065  if (!Name.empty()) {
1066  GVal = M->getNamedValue(Name);
1067  if (GVal) {
1068  if (!ForwardRefVals.erase(Name))
1069  return Error(NameLoc, "redefinition of global '@" + Name + "'");
1070  }
1071  } else {
1072  auto I = ForwardRefValIDs.find(NumberedVals.size());
1073  if (I != ForwardRefValIDs.end()) {
1074  GVal = I->second.first;
1075  ForwardRefValIDs.erase(I);
1076  }
1077  }
1078 
1079  GlobalVariable *GV;
1080  if (!GVal) {
1081  GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1083  AddrSpace);
1084  } else {
1085  if (GVal->getValueType() != Ty)
1086  return Error(TyLoc,
1087  "forward reference and definition of global have different types");
1088 
1089  GV = cast<GlobalVariable>(GVal);
1090 
1091  // Move the forward-reference to the correct spot in the module.
1092  M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1093  }
1094 
1095  if (Name.empty())
1096  NumberedVals.push_back(GV);
1097 
1098  // Set the parsed properties on the global.
1099  if (Init)
1100  GV->setInitializer(Init);
1101  GV->setConstant(IsConstant);
1102  GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1103  maybeSetDSOLocal(DSOLocal, *GV);
1106  GV->setExternallyInitialized(IsExternallyInitialized);
1107  GV->setThreadLocalMode(TLM);
1108  GV->setUnnamedAddr(UnnamedAddr);
1109 
1110  // Parse attributes on the global.
1111  while (Lex.getKind() == lltok::comma) {
1112  Lex.Lex();
1113 
1114  if (Lex.getKind() == lltok::kw_section) {
1115  Lex.Lex();
1116  GV->setSection(Lex.getStrVal());
1117  if (ParseToken(lltok::StringConstant, "expected global section string"))
1118  return true;
1119  } else if (Lex.getKind() == lltok::kw_partition) {
1120  Lex.Lex();
1121  GV->setPartition(Lex.getStrVal());
1122  if (ParseToken(lltok::StringConstant, "expected partition string"))
1123  return true;
1124  } else if (Lex.getKind() == lltok::kw_align) {
1125  MaybeAlign Alignment;
1126  if (ParseOptionalAlignment(Alignment)) return true;
1127  GV->setAlignment(Alignment);
1128  } else if (Lex.getKind() == lltok::MetadataVar) {
1129  if (ParseGlobalObjectMetadataAttachment(*GV))
1130  return true;
1131  } else {
1132  Comdat *C;
1133  if (parseOptionalComdat(Name, C))
1134  return true;
1135  if (C)
1136  GV->setComdat(C);
1137  else
1138  return TokError("unknown global variable property!");
1139  }
1140  }
1141 
1143  LocTy BuiltinLoc;
1144  std::vector<unsigned> FwdRefAttrGrps;
1145  if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1146  return true;
1147  if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1148  GV->setAttributes(AttributeSet::get(Context, Attrs));
1149  ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1150  }
1151 
1152  return false;
1153 }
1154 
1155 /// ParseUnnamedAttrGrp
1156 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1157 bool LLParser::ParseUnnamedAttrGrp() {
1159  LocTy AttrGrpLoc = Lex.getLoc();
1160  Lex.Lex();
1161 
1162  if (Lex.getKind() != lltok::AttrGrpID)
1163  return TokError("expected attribute group id");
1164 
1165  unsigned VarID = Lex.getUIntVal();
1166  std::vector<unsigned> unused;
1167  LocTy BuiltinLoc;
1168  Lex.Lex();
1169 
1170  if (ParseToken(lltok::equal, "expected '=' here") ||
1171  ParseToken(lltok::lbrace, "expected '{' here") ||
1172  ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1173  BuiltinLoc) ||
1174  ParseToken(lltok::rbrace, "expected end of attribute group"))
1175  return true;
1176 
1177  if (!NumberedAttrBuilders[VarID].hasAttributes())
1178  return Error(AttrGrpLoc, "attribute group has no attributes");
1179 
1180  return false;
1181 }
1182 
1183 /// ParseFnAttributeValuePairs
1184 /// ::= <attr> | <attr> '=' <value>
1185 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1186  std::vector<unsigned> &FwdRefAttrGrps,
1187  bool inAttrGrp, LocTy &BuiltinLoc) {
1188  bool HaveError = false;
1189 
1190  B.clear();
1191 
1192  while (true) {
1193  lltok::Kind Token = Lex.getKind();
1194  if (Token == lltok::kw_builtin)
1195  BuiltinLoc = Lex.getLoc();
1196  switch (Token) {
1197  default:
1198  if (!inAttrGrp) return HaveError;
1199  return Error(Lex.getLoc(), "unterminated attribute group");
1200  case lltok::rbrace:
1201  // Finished.
1202  return false;
1203 
1204  case lltok::AttrGrpID: {
1205  // Allow a function to reference an attribute group:
1206  //
1207  // define void @foo() #1 { ... }
1208  if (inAttrGrp)
1209  HaveError |=
1210  Error(Lex.getLoc(),
1211  "cannot have an attribute group reference in an attribute group");
1212 
1213  unsigned AttrGrpNum = Lex.getUIntVal();
1214  if (inAttrGrp) break;
1215 
1216  // Save the reference to the attribute group. We'll fill it in later.
1217  FwdRefAttrGrps.push_back(AttrGrpNum);
1218  break;
1219  }
1220  // Target-dependent attributes:
1221  case lltok::StringConstant: {
1222  if (ParseStringAttribute(B))
1223  return true;
1224  continue;
1225  }
1226 
1227  // Target-independent attributes:
1228  case lltok::kw_align: {
1229  // As a hack, we allow function alignment to be initially parsed as an
1230  // attribute on a function declaration/definition or added to an attribute
1231  // group and later moved to the alignment field.
1232  MaybeAlign Alignment;
1233  if (inAttrGrp) {
1234  Lex.Lex();
1235  uint32_t Value = 0;
1236  if (ParseToken(lltok::equal, "expected '=' here") || ParseUInt32(Value))
1237  return true;
1238  Alignment = Align(Value);
1239  } else {
1240  if (ParseOptionalAlignment(Alignment))
1241  return true;
1242  }
1243  B.addAlignmentAttr(Alignment);
1244  continue;
1245  }
1246  case lltok::kw_alignstack: {
1247  unsigned Alignment;
1248  if (inAttrGrp) {
1249  Lex.Lex();
1250  if (ParseToken(lltok::equal, "expected '=' here") ||
1251  ParseUInt32(Alignment))
1252  return true;
1253  } else {
1254  if (ParseOptionalStackAlignment(Alignment))
1255  return true;
1256  }
1257  B.addStackAlignmentAttr(Alignment);
1258  continue;
1259  }
1260  case lltok::kw_allocsize: {
1261  unsigned ElemSizeArg;
1262  Optional<unsigned> NumElemsArg;
1263  // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1264  if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1265  return true;
1266  B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1267  continue;
1268  }
1269  case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1270  case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1271  case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1275  B.addAttribute(Attribute::InaccessibleMemOnly); break;
1277  B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1278  case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1280  case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1281  case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1282  case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1283  case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1284  case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
1286  B.addAttribute(Attribute::NoImplicitFloat); break;
1287  case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1288  case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1289  case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1290  case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1291  case lltok::kw_nosync: B.addAttribute(Attribute::NoSync); break;
1292  case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
1293  case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1294  case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1296  B.addAttribute(Attribute::OptForFuzzing); break;
1297  case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1298  case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1299  case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1300  case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1302  B.addAttribute(Attribute::ReturnsTwice); break;
1303  case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1304  case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1305  case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1306  case lltok::kw_sspstrong:
1307  B.addAttribute(Attribute::StackProtectStrong); break;
1308  case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1310  B.addAttribute(Attribute::ShadowCallStack); break;
1312  B.addAttribute(Attribute::SanitizeAddress); break;
1314  B.addAttribute(Attribute::SanitizeHWAddress); break;
1316  B.addAttribute(Attribute::SanitizeMemTag); break;
1318  B.addAttribute(Attribute::SanitizeThread); break;
1320  B.addAttribute(Attribute::SanitizeMemory); break;
1322  B.addAttribute(Attribute::SpeculativeLoadHardening);
1323  break;
1324  case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1325  case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1326  case lltok::kw_willreturn: B.addAttribute(Attribute::WillReturn); break;
1327  case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1328 
1329  // Error handling.
1330  case lltok::kw_inreg:
1331  case lltok::kw_signext:
1332  case lltok::kw_zeroext:
1333  HaveError |=
1334  Error(Lex.getLoc(),
1335  "invalid use of attribute on a function");
1336  break;
1337  case lltok::kw_byval:
1340  case lltok::kw_inalloca:
1341  case lltok::kw_nest:
1342  case lltok::kw_noalias:
1343  case lltok::kw_nocapture:
1344  case lltok::kw_nonnull:
1345  case lltok::kw_returned:
1346  case lltok::kw_sret:
1347  case lltok::kw_swifterror:
1348  case lltok::kw_swiftself:
1349  case lltok::kw_immarg:
1350  HaveError |=
1351  Error(Lex.getLoc(),
1352  "invalid use of parameter-only attribute on a function");
1353  break;
1354  }
1355 
1356  Lex.Lex();
1357  }
1358 }
1359 
1360 //===----------------------------------------------------------------------===//
1361 // GlobalValue Reference/Resolution Routines.
1362 //===----------------------------------------------------------------------===//
1363 
1365  const std::string &Name) {
1366  if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1368  PTy->getAddressSpace(), Name, M);
1369  else
1370  return new GlobalVariable(*M, PTy->getElementType(), false,
1373  PTy->getAddressSpace());
1374 }
1375 
1376 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1377  Value *Val, bool IsCall) {
1378  if (Val->getType() == Ty)
1379  return Val;
1380  // For calls we also accept variables in the program address space.
1381  Type *SuggestedTy = Ty;
1382  if (IsCall && isa<PointerType>(Ty)) {
1383  Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1385  SuggestedTy = TyInProgAS;
1386  if (Val->getType() == TyInProgAS)
1387  return Val;
1388  }
1389  if (Ty->isLabelTy())
1390  Error(Loc, "'" + Name + "' is not a basic block");
1391  else
1392  Error(Loc, "'" + Name + "' defined with type '" +
1393  getTypeString(Val->getType()) + "' but expected '" +
1394  getTypeString(SuggestedTy) + "'");
1395  return nullptr;
1396 }
1397 
1398 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1399 /// forward reference record if needed. This can return null if the value
1400 /// exists but does not have the right type.
1401 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1402  LocTy Loc, bool IsCall) {
1403  PointerType *PTy = dyn_cast<PointerType>(Ty);
1404  if (!PTy) {
1405  Error(Loc, "global variable reference must have pointer type");
1406  return nullptr;
1407  }
1408 
1409  // Look this name up in the normal function symbol table.
1410  GlobalValue *Val =
1411  cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1412 
1413  // If this is a forward reference for the value, see if we already created a
1414  // forward ref record.
1415  if (!Val) {
1416  auto I = ForwardRefVals.find(Name);
1417  if (I != ForwardRefVals.end())
1418  Val = I->second.first;
1419  }
1420 
1421  // If we have the value in the symbol table or fwd-ref table, return it.
1422  if (Val)
1423  return cast_or_null<GlobalValue>(
1424  checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1425 
1426  // Otherwise, create a new forward reference for this value and remember it.
1427  GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1428  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1429  return FwdVal;
1430 }
1431 
1432 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1433  bool IsCall) {
1434  PointerType *PTy = dyn_cast<PointerType>(Ty);
1435  if (!PTy) {
1436  Error(Loc, "global variable reference must have pointer type");
1437  return nullptr;
1438  }
1439 
1440  GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1441 
1442  // If this is a forward reference for the value, see if we already created a
1443  // forward ref record.
1444  if (!Val) {
1445  auto I = ForwardRefValIDs.find(ID);
1446  if (I != ForwardRefValIDs.end())
1447  Val = I->second.first;
1448  }
1449 
1450  // If we have the value in the symbol table or fwd-ref table, return it.
1451  if (Val)
1452  return cast_or_null<GlobalValue>(
1453  checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1454 
1455  // Otherwise, create a new forward reference for this value and remember it.
1456  GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1457  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1458  return FwdVal;
1459 }
1460 
1461 //===----------------------------------------------------------------------===//
1462 // Comdat Reference/Resolution Routines.
1463 //===----------------------------------------------------------------------===//
1464 
1465 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1466  // Look this name up in the comdat symbol table.
1467  Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1468  Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1469  if (I != ComdatSymTab.end())
1470  return &I->second;
1471 
1472  // Otherwise, create a new forward reference for this value and remember it.
1473  Comdat *C = M->getOrInsertComdat(Name);
1474  ForwardRefComdats[Name] = Loc;
1475  return C;
1476 }
1477 
1478 //===----------------------------------------------------------------------===//
1479 // Helper Routines.
1480 //===----------------------------------------------------------------------===//
1481 
1482 /// ParseToken - If the current token has the specified kind, eat it and return
1483 /// success. Otherwise, emit the specified error and return failure.
1484 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1485  if (Lex.getKind() != T)
1486  return TokError(ErrMsg);
1487  Lex.Lex();
1488  return false;
1489 }
1490 
1491 /// ParseStringConstant
1492 /// ::= StringConstant
1493 bool LLParser::ParseStringConstant(std::string &Result) {
1494  if (Lex.getKind() != lltok::StringConstant)
1495  return TokError("expected string constant");
1496  Result = Lex.getStrVal();
1497  Lex.Lex();
1498  return false;
1499 }
1500 
1501 /// ParseUInt32
1502 /// ::= uint32
1503 bool LLParser::ParseUInt32(uint32_t &Val) {
1504  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1505  return TokError("expected integer");
1506  uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1507  if (Val64 != unsigned(Val64))
1508  return TokError("expected 32-bit integer (too large)");
1509  Val = Val64;
1510  Lex.Lex();
1511  return false;
1512 }
1513 
1514 /// ParseUInt64
1515 /// ::= uint64
1516 bool LLParser::ParseUInt64(uint64_t &Val) {
1517  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1518  return TokError("expected integer");
1519  Val = Lex.getAPSIntVal().getLimitedValue();
1520  Lex.Lex();
1521  return false;
1522 }
1523 
1524 /// ParseTLSModel
1525 /// := 'localdynamic'
1526 /// := 'initialexec'
1527 /// := 'localexec'
1528 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1529  switch (Lex.getKind()) {
1530  default:
1531  return TokError("expected localdynamic, initialexec or localexec");
1534  break;
1535  case lltok::kw_initialexec:
1537  break;
1538  case lltok::kw_localexec:
1540  break;
1541  }
1542 
1543  Lex.Lex();
1544  return false;
1545 }
1546 
1547 /// ParseOptionalThreadLocal
1548 /// := /*empty*/
1549 /// := 'thread_local'
1550 /// := 'thread_local' '(' tlsmodel ')'
1551 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1553  if (!EatIfPresent(lltok::kw_thread_local))
1554  return false;
1555 
1557  if (Lex.getKind() == lltok::lparen) {
1558  Lex.Lex();
1559  return ParseTLSModel(TLM) ||
1560  ParseToken(lltok::rparen, "expected ')' after thread local model");
1561  }
1562  return false;
1563 }
1564 
1565 /// ParseOptionalAddrSpace
1566 /// := /*empty*/
1567 /// := 'addrspace' '(' uint32 ')'
1568 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1569  AddrSpace = DefaultAS;
1570  if (!EatIfPresent(lltok::kw_addrspace))
1571  return false;
1572  return ParseToken(lltok::lparen, "expected '(' in address space") ||
1573  ParseUInt32(AddrSpace) ||
1574  ParseToken(lltok::rparen, "expected ')' in address space");
1575 }
1576 
1577 /// ParseStringAttribute
1578 /// := StringConstant
1579 /// := StringConstant '=' StringConstant
1580 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1581  std::string Attr = Lex.getStrVal();
1582  Lex.Lex();
1583  std::string Val;
1584  if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1585  return true;
1586  B.addAttribute(Attr, Val);
1587  return false;
1588 }
1589 
1590 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1591 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1592  bool HaveError = false;
1593 
1594  B.clear();
1595 
1596  while (true) {
1597  lltok::Kind Token = Lex.getKind();
1598  switch (Token) {
1599  default: // End of attributes.
1600  return HaveError;
1601  case lltok::StringConstant: {
1602  if (ParseStringAttribute(B))
1603  return true;
1604  continue;
1605  }
1606  case lltok::kw_align: {
1607  MaybeAlign Alignment;
1608  if (ParseOptionalAlignment(Alignment))
1609  return true;
1610  B.addAlignmentAttr(Alignment);
1611  continue;
1612  }
1613  case lltok::kw_byval: {
1614  Type *Ty;
1615  if (ParseByValWithOptionalType(Ty))
1616  return true;
1617  B.addByValAttr(Ty);
1618  continue;
1619  }
1621  uint64_t Bytes;
1622  if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1623  return true;
1624  B.addDereferenceableAttr(Bytes);
1625  continue;
1626  }
1628  uint64_t Bytes;
1629  if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1630  return true;
1632  continue;
1633  }
1634  case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1635  case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1636  case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1638  case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1639  case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
1640  case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1641  case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1642  case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1643  case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1644  case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1645  case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1646  case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1647  case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1648  case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1649  case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1650  case lltok::kw_immarg: B.addAttribute(Attribute::ImmArg); break;
1651 
1652  case lltok::kw_alignstack:
1654  case lltok::kw_argmemonly:
1655  case lltok::kw_builtin:
1656  case lltok::kw_inlinehint:
1657  case lltok::kw_jumptable:
1658  case lltok::kw_minsize:
1659  case lltok::kw_naked:
1660  case lltok::kw_nobuiltin:
1661  case lltok::kw_noduplicate:
1663  case lltok::kw_noinline:
1664  case lltok::kw_nonlazybind:
1665  case lltok::kw_noredzone:
1666  case lltok::kw_noreturn:
1667  case lltok::kw_nocf_check:
1668  case lltok::kw_nounwind:
1670  case lltok::kw_optnone:
1671  case lltok::kw_optsize:
1679  case lltok::kw_ssp:
1680  case lltok::kw_sspreq:
1681  case lltok::kw_sspstrong:
1682  case lltok::kw_safestack:
1684  case lltok::kw_strictfp:
1685  case lltok::kw_uwtable:
1686  HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1687  break;
1688  }
1689 
1690  Lex.Lex();
1691  }
1692 }
1693 
1694 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1695 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1696  bool HaveError = false;
1697 
1698  B.clear();
1699 
1700  while (true) {
1701  lltok::Kind Token = Lex.getKind();
1702  switch (Token) {
1703  default: // End of attributes.
1704  return HaveError;
1705  case lltok::StringConstant: {
1706  if (ParseStringAttribute(B))
1707  return true;
1708  continue;
1709  }
1711  uint64_t Bytes;
1712  if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1713  return true;
1714  B.addDereferenceableAttr(Bytes);
1715  continue;
1716  }
1718  uint64_t Bytes;
1719  if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1720  return true;
1722  continue;
1723  }
1724  case lltok::kw_align: {
1725  MaybeAlign Alignment;
1726  if (ParseOptionalAlignment(Alignment))
1727  return true;
1728  B.addAlignmentAttr(Alignment);
1729  continue;
1730  }
1731  case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1733  case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1734  case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1735  case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1736 
1737  // Error handling.
1738  case lltok::kw_byval:
1739  case lltok::kw_inalloca:
1740  case lltok::kw_nest:
1741  case lltok::kw_nocapture:
1742  case lltok::kw_returned:
1743  case lltok::kw_sret:
1744  case lltok::kw_swifterror:
1745  case lltok::kw_swiftself:
1746  case lltok::kw_immarg:
1747  HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1748  break;
1749 
1750  case lltok::kw_alignstack:
1752  case lltok::kw_argmemonly:
1753  case lltok::kw_builtin:
1754  case lltok::kw_cold:
1755  case lltok::kw_inlinehint:
1756  case lltok::kw_jumptable:
1757  case lltok::kw_minsize:
1758  case lltok::kw_naked:
1759  case lltok::kw_nobuiltin:
1760  case lltok::kw_noduplicate:
1762  case lltok::kw_noinline:
1763  case lltok::kw_nonlazybind:
1764  case lltok::kw_noredzone:
1765  case lltok::kw_noreturn:
1766  case lltok::kw_nocf_check:
1767  case lltok::kw_nounwind:
1769  case lltok::kw_optnone:
1770  case lltok::kw_optsize:
1778  case lltok::kw_ssp:
1779  case lltok::kw_sspreq:
1780  case lltok::kw_sspstrong:
1781  case lltok::kw_safestack:
1783  case lltok::kw_strictfp:
1784  case lltok::kw_uwtable:
1785  HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1786  break;
1787 
1788  case lltok::kw_readnone:
1789  case lltok::kw_readonly:
1790  HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1791  }
1792 
1793  Lex.Lex();
1794  }
1795 }
1796 
1797 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1798  HasLinkage = true;
1799  switch (Kind) {
1800  default:
1801  HasLinkage = false;
1803  case lltok::kw_private:
1805  case lltok::kw_internal:
1807  case lltok::kw_weak:
1809  case lltok::kw_weak_odr:
1811  case lltok::kw_linkonce:
1817  case lltok::kw_appending:
1819  case lltok::kw_common:
1821  case lltok::kw_extern_weak:
1823  case lltok::kw_external:
1825  }
1826 }
1827 
1828 /// ParseOptionalLinkage
1829 /// ::= /*empty*/
1830 /// ::= 'private'
1831 /// ::= 'internal'
1832 /// ::= 'weak'
1833 /// ::= 'weak_odr'
1834 /// ::= 'linkonce'
1835 /// ::= 'linkonce_odr'
1836 /// ::= 'available_externally'
1837 /// ::= 'appending'
1838 /// ::= 'common'
1839 /// ::= 'extern_weak'
1840 /// ::= 'external'
1841 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1842  unsigned &Visibility,
1843  unsigned &DLLStorageClass,
1844  bool &DSOLocal) {
1845  Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1846  if (HasLinkage)
1847  Lex.Lex();
1848  ParseOptionalDSOLocal(DSOLocal);
1849  ParseOptionalVisibility(Visibility);
1850  ParseOptionalDLLStorageClass(DLLStorageClass);
1851 
1852  if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1853  return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1854  }
1855 
1856  return false;
1857 }
1858 
1859 void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1860  switch (Lex.getKind()) {
1861  default:
1862  DSOLocal = false;
1863  break;
1864  case lltok::kw_dso_local:
1865  DSOLocal = true;
1866  Lex.Lex();
1867  break;
1869  DSOLocal = false;
1870  Lex.Lex();
1871  break;
1872  }
1873 }
1874 
1875 /// ParseOptionalVisibility
1876 /// ::= /*empty*/
1877 /// ::= 'default'
1878 /// ::= 'hidden'
1879 /// ::= 'protected'
1880 ///
1881 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1882  switch (Lex.getKind()) {
1883  default:
1885  return;
1886  case lltok::kw_default:
1888  break;
1889  case lltok::kw_hidden:
1891  break;
1892  case lltok::kw_protected:
1894  break;
1895  }
1896  Lex.Lex();
1897 }
1898 
1899 /// ParseOptionalDLLStorageClass
1900 /// ::= /*empty*/
1901 /// ::= 'dllimport'
1902 /// ::= 'dllexport'
1903 ///
1904 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1905  switch (Lex.getKind()) {
1906  default:
1908  return;
1909  case lltok::kw_dllimport:
1911  break;
1912  case lltok::kw_dllexport:
1914  break;
1915  }
1916  Lex.Lex();
1917 }
1918 
1919 /// ParseOptionalCallingConv
1920 /// ::= /*empty*/
1921 /// ::= 'ccc'
1922 /// ::= 'fastcc'
1923 /// ::= 'intel_ocl_bicc'
1924 /// ::= 'coldcc'
1925 /// ::= 'cfguard_checkcc'
1926 /// ::= 'x86_stdcallcc'
1927 /// ::= 'x86_fastcallcc'
1928 /// ::= 'x86_thiscallcc'
1929 /// ::= 'x86_vectorcallcc'
1930 /// ::= 'arm_apcscc'
1931 /// ::= 'arm_aapcscc'
1932 /// ::= 'arm_aapcs_vfpcc'
1933 /// ::= 'aarch64_vector_pcs'
1934 /// ::= 'aarch64_sve_vector_pcs'
1935 /// ::= 'msp430_intrcc'
1936 /// ::= 'avr_intrcc'
1937 /// ::= 'avr_signalcc'
1938 /// ::= 'ptx_kernel'
1939 /// ::= 'ptx_device'
1940 /// ::= 'spir_func'
1941 /// ::= 'spir_kernel'
1942 /// ::= 'x86_64_sysvcc'
1943 /// ::= 'win64cc'
1944 /// ::= 'webkit_jscc'
1945 /// ::= 'anyregcc'
1946 /// ::= 'preserve_mostcc'
1947 /// ::= 'preserve_allcc'
1948 /// ::= 'ghccc'
1949 /// ::= 'swiftcc'
1950 /// ::= 'x86_intrcc'
1951 /// ::= 'hhvmcc'
1952 /// ::= 'hhvm_ccc'
1953 /// ::= 'cxx_fast_tlscc'
1954 /// ::= 'amdgpu_vs'
1955 /// ::= 'amdgpu_ls'
1956 /// ::= 'amdgpu_hs'
1957 /// ::= 'amdgpu_es'
1958 /// ::= 'amdgpu_gs'
1959 /// ::= 'amdgpu_ps'
1960 /// ::= 'amdgpu_cs'
1961 /// ::= 'amdgpu_kernel'
1962 /// ::= 'tailcc'
1963 /// ::= 'cc' UINT
1964 ///
1965 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1966  switch (Lex.getKind()) {
1967  default: CC = CallingConv::C; return false;
1968  case lltok::kw_ccc: CC = CallingConv::C; break;
1969  case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1970  case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1977  case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1983  break;
1985  case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1990  case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1993  case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1995  case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1998  case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1999  case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2000  case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
2001  case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
2002  case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
2004  case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
2005  case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
2006  case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
2007  case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
2008  case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
2009  case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
2010  case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
2012  case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2013  case lltok::kw_cc: {
2014  Lex.Lex();
2015  return ParseUInt32(CC);
2016  }
2017  }
2018 
2019  Lex.Lex();
2020  return false;
2021 }
2022 
2023 /// ParseMetadataAttachment
2024 /// ::= !dbg !42
2025 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2026  assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2027 
2028  std::string Name = Lex.getStrVal();
2029  Kind = M->getMDKindID(Name);
2030  Lex.Lex();
2031 
2032  return ParseMDNode(MD);
2033 }
2034 
2035 /// ParseInstructionMetadata
2036 /// ::= !dbg !42 (',' !dbg !57)*
2037 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
2038  do {
2039  if (Lex.getKind() != lltok::MetadataVar)
2040  return TokError("expected metadata after comma");
2041 
2042  unsigned MDK;
2043  MDNode *N;
2044  if (ParseMetadataAttachment(MDK, N))
2045  return true;
2046 
2047  Inst.setMetadata(MDK, N);
2048  if (MDK == LLVMContext::MD_tbaa)
2049  InstsWithTBAATag.push_back(&Inst);
2050 
2051  // If this is the end of the list, we're done.
2052  } while (EatIfPresent(lltok::comma));
2053  return false;
2054 }
2055 
2056 /// ParseGlobalObjectMetadataAttachment
2057 /// ::= !dbg !57
2058 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2059  unsigned MDK;
2060  MDNode *N;
2061  if (ParseMetadataAttachment(MDK, N))
2062  return true;
2063 
2064  GO.addMetadata(MDK, *N);
2065  return false;
2066 }
2067 
2068 /// ParseOptionalFunctionMetadata
2069 /// ::= (!dbg !57)*
2070 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
2071  while (Lex.getKind() == lltok::MetadataVar)
2072  if (ParseGlobalObjectMetadataAttachment(F))
2073  return true;
2074  return false;
2075 }
2076 
2077 /// ParseOptionalAlignment
2078 /// ::= /* empty */
2079 /// ::= 'align' 4
2080 bool LLParser::ParseOptionalAlignment(MaybeAlign &Alignment) {
2081  Alignment = None;
2082  if (!EatIfPresent(lltok::kw_align))
2083  return false;
2084  LocTy AlignLoc = Lex.getLoc();
2085  uint32_t Value = 0;
2086  if (ParseUInt32(Value))
2087  return true;
2088  if (!isPowerOf2_32(Value))
2089  return Error(AlignLoc, "alignment is not a power of two");
2090  if (Value > Value::MaximumAlignment)
2091  return Error(AlignLoc, "huge alignments are not supported yet");
2092  Alignment = Align(Value);
2093  return false;
2094 }
2095 
2096 /// ParseOptionalDerefAttrBytes
2097 /// ::= /* empty */
2098 /// ::= AttrKind '(' 4 ')'
2099 ///
2100 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2101 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2102  uint64_t &Bytes) {
2103  assert((AttrKind == lltok::kw_dereferenceable ||
2104  AttrKind == lltok::kw_dereferenceable_or_null) &&
2105  "contract!");
2106 
2107  Bytes = 0;
2108  if (!EatIfPresent(AttrKind))
2109  return false;
2110  LocTy ParenLoc = Lex.getLoc();
2111  if (!EatIfPresent(lltok::lparen))
2112  return Error(ParenLoc, "expected '('");
2113  LocTy DerefLoc = Lex.getLoc();
2114  if (ParseUInt64(Bytes)) return true;
2115  ParenLoc = Lex.getLoc();
2116  if (!EatIfPresent(lltok::rparen))
2117  return Error(ParenLoc, "expected ')'");
2118  if (!Bytes)
2119  return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2120  return false;
2121 }
2122 
2123 /// ParseOptionalCommaAlign
2124 /// ::=
2125 /// ::= ',' align 4
2126 ///
2127 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2128 /// end.
2129 bool LLParser::ParseOptionalCommaAlign(MaybeAlign &Alignment,
2130  bool &AteExtraComma) {
2131  AteExtraComma = false;
2132  while (EatIfPresent(lltok::comma)) {
2133  // Metadata at the end is an early exit.
2134  if (Lex.getKind() == lltok::MetadataVar) {
2135  AteExtraComma = true;
2136  return false;
2137  }
2138 
2139  if (Lex.getKind() != lltok::kw_align)
2140  return Error(Lex.getLoc(), "expected metadata or 'align'");
2141 
2142  if (ParseOptionalAlignment(Alignment)) return true;
2143  }
2144 
2145  return false;
2146 }
2147 
2148 /// ParseOptionalCommaAddrSpace
2149 /// ::=
2150 /// ::= ',' addrspace(1)
2151 ///
2152 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2153 /// end.
2154 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2155  LocTy &Loc,
2156  bool &AteExtraComma) {
2157  AteExtraComma = false;
2158  while (EatIfPresent(lltok::comma)) {
2159  // Metadata at the end is an early exit.
2160  if (Lex.getKind() == lltok::MetadataVar) {
2161  AteExtraComma = true;
2162  return false;
2163  }
2164 
2165  Loc = Lex.getLoc();
2166  if (Lex.getKind() != lltok::kw_addrspace)
2167  return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2168 
2169  if (ParseOptionalAddrSpace(AddrSpace))
2170  return true;
2171  }
2172 
2173  return false;
2174 }
2175 
2176 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2177  Optional<unsigned> &HowManyArg) {
2178  Lex.Lex();
2179 
2180  auto StartParen = Lex.getLoc();
2181  if (!EatIfPresent(lltok::lparen))
2182  return Error(StartParen, "expected '('");
2183 
2184  if (ParseUInt32(BaseSizeArg))
2185  return true;
2186 
2187  if (EatIfPresent(lltok::comma)) {
2188  auto HowManyAt = Lex.getLoc();
2189  unsigned HowMany;
2190  if (ParseUInt32(HowMany))
2191  return true;
2192  if (HowMany == BaseSizeArg)
2193  return Error(HowManyAt,
2194  "'allocsize' indices can't refer to the same parameter");
2195  HowManyArg = HowMany;
2196  } else
2197  HowManyArg = None;
2198 
2199  auto EndParen = Lex.getLoc();
2200  if (!EatIfPresent(lltok::rparen))
2201  return Error(EndParen, "expected ')'");
2202  return false;
2203 }
2204 
2205 /// ParseScopeAndOrdering
2206 /// if isAtomic: ::= SyncScope? AtomicOrdering
2207 /// else: ::=
2208 ///
2209 /// This sets Scope and Ordering to the parsed values.
2210 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
2211  AtomicOrdering &Ordering) {
2212  if (!isAtomic)
2213  return false;
2214 
2215  return ParseScope(SSID) || ParseOrdering(Ordering);
2216 }
2217 
2218 /// ParseScope
2219 /// ::= syncscope("singlethread" | "<target scope>")?
2220 ///
2221 /// This sets synchronization scope ID to the ID of the parsed value.
2222 bool LLParser::ParseScope(SyncScope::ID &SSID) {
2223  SSID = SyncScope::System;
2224  if (EatIfPresent(lltok::kw_syncscope)) {
2225  auto StartParenAt = Lex.getLoc();
2226  if (!EatIfPresent(lltok::lparen))
2227  return Error(StartParenAt, "Expected '(' in syncscope");
2228 
2229  std::string SSN;
2230  auto SSNAt = Lex.getLoc();
2231  if (ParseStringConstant(SSN))
2232  return Error(SSNAt, "Expected synchronization scope name");
2233 
2234  auto EndParenAt = Lex.getLoc();
2235  if (!EatIfPresent(lltok::rparen))
2236  return Error(EndParenAt, "Expected ')' in syncscope");
2237 
2238  SSID = Context.getOrInsertSyncScopeID(SSN);
2239  }
2240 
2241  return false;
2242 }
2243 
2244 /// ParseOrdering
2245 /// ::= AtomicOrdering
2246 ///
2247 /// This sets Ordering to the parsed value.
2248 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
2249  switch (Lex.getKind()) {
2250  default: return TokError("Expected ordering on atomic instruction");
2251  case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2252  case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2253  // Not specified yet:
2254  // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2255  case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2256  case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2257  case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2258  case lltok::kw_seq_cst:
2260  break;
2261  }
2262  Lex.Lex();
2263  return false;
2264 }
2265 
2266 /// ParseOptionalStackAlignment
2267 /// ::= /* empty */
2268 /// ::= 'alignstack' '(' 4 ')'
2269 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2270  Alignment = 0;
2271  if (!EatIfPresent(lltok::kw_alignstack))
2272  return false;
2273  LocTy ParenLoc = Lex.getLoc();
2274  if (!EatIfPresent(lltok::lparen))
2275  return Error(ParenLoc, "expected '('");
2276  LocTy AlignLoc = Lex.getLoc();
2277  if (ParseUInt32(Alignment)) return true;
2278  ParenLoc = Lex.getLoc();
2279  if (!EatIfPresent(lltok::rparen))
2280  return Error(ParenLoc, "expected ')'");
2281  if (!isPowerOf2_32(Alignment))
2282  return Error(AlignLoc, "stack alignment is not a power of two");
2283  return false;
2284 }
2285 
2286 /// ParseIndexList - This parses the index list for an insert/extractvalue
2287 /// instruction. This sets AteExtraComma in the case where we eat an extra
2288 /// comma at the end of the line and find that it is followed by metadata.
2289 /// Clients that don't allow metadata can call the version of this function that
2290 /// only takes one argument.
2291 ///
2292 /// ParseIndexList
2293 /// ::= (',' uint32)+
2294 ///
2295 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2296  bool &AteExtraComma) {
2297  AteExtraComma = false;
2298 
2299  if (Lex.getKind() != lltok::comma)
2300  return TokError("expected ',' as start of index list");
2301 
2302  while (EatIfPresent(lltok::comma)) {
2303  if (Lex.getKind() == lltok::MetadataVar) {
2304  if (Indices.empty()) return TokError("expected index");
2305  AteExtraComma = true;
2306  return false;
2307  }
2308  unsigned Idx = 0;
2309  if (ParseUInt32(Idx)) return true;
2310  Indices.push_back(Idx);
2311  }
2312 
2313  return false;
2314 }
2315 
2316 //===----------------------------------------------------------------------===//
2317 // Type Parsing.
2318 //===----------------------------------------------------------------------===//
2319 
2320 /// ParseType - Parse a type.
2321 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2322  SMLoc TypeLoc = Lex.getLoc();
2323  switch (Lex.getKind()) {
2324  default:
2325  return TokError(Msg);
2326  case lltok::Type:
2327  // Type ::= 'float' | 'void' (etc)
2328  Result = Lex.getTyVal();
2329  Lex.Lex();
2330  break;
2331  case lltok::lbrace:
2332  // Type ::= StructType
2333  if (ParseAnonStructType(Result, false))
2334  return true;
2335  break;
2336  case lltok::lsquare:
2337  // Type ::= '[' ... ']'
2338  Lex.Lex(); // eat the lsquare.
2339  if (ParseArrayVectorType(Result, false))
2340  return true;
2341  break;
2342  case lltok::less: // Either vector or packed struct.
2343  // Type ::= '<' ... '>'
2344  Lex.Lex();
2345  if (Lex.getKind() == lltok::lbrace) {
2346  if (ParseAnonStructType(Result, true) ||
2347  ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2348  return true;
2349  } else if (ParseArrayVectorType(Result, true))
2350  return true;
2351  break;
2352  case lltok::LocalVar: {
2353  // Type ::= %foo
2354  std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2355 
2356  // If the type hasn't been defined yet, create a forward definition and
2357  // remember where that forward def'n was seen (in case it never is defined).
2358  if (!Entry.first) {
2359  Entry.first = StructType::create(Context, Lex.getStrVal());
2360  Entry.second = Lex.getLoc();
2361  }
2362  Result = Entry.first;
2363  Lex.Lex();
2364  break;
2365  }
2366 
2367  case lltok::LocalVarID: {
2368  // Type ::= %4
2369  std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2370 
2371  // If the type hasn't been defined yet, create a forward definition and
2372  // remember where that forward def'n was seen (in case it never is defined).
2373  if (!Entry.first) {
2374  Entry.first = StructType::create(Context);
2375  Entry.second = Lex.getLoc();
2376  }
2377  Result = Entry.first;
2378  Lex.Lex();
2379  break;
2380  }
2381  }
2382 
2383  // Parse the type suffixes.
2384  while (true) {
2385  switch (Lex.getKind()) {
2386  // End of type.
2387  default:
2388  if (!AllowVoid && Result->isVoidTy())
2389  return Error(TypeLoc, "void type only allowed for function results");
2390  return false;
2391 
2392  // Type ::= Type '*'
2393  case lltok::star:
2394  if (Result->isLabelTy())
2395  return TokError("basic block pointers are invalid");
2396  if (Result->isVoidTy())
2397  return TokError("pointers to void are invalid - use i8* instead");
2398  if (!PointerType::isValidElementType(Result))
2399  return TokError("pointer to this type is invalid");
2400  Result = PointerType::getUnqual(Result);
2401  Lex.Lex();
2402  break;
2403 
2404  // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2405  case lltok::kw_addrspace: {
2406  if (Result->isLabelTy())
2407  return TokError("basic block pointers are invalid");
2408  if (Result->isVoidTy())
2409  return TokError("pointers to void are invalid; use i8* instead");
2410  if (!PointerType::isValidElementType(Result))
2411  return TokError("pointer to this type is invalid");
2412  unsigned AddrSpace;
2413  if (ParseOptionalAddrSpace(AddrSpace) ||
2414  ParseToken(lltok::star, "expected '*' in address space"))
2415  return true;
2416 
2417  Result = PointerType::get(Result, AddrSpace);
2418  break;
2419  }
2420 
2421  /// Types '(' ArgTypeListI ')' OptFuncAttrs
2422  case lltok::lparen:
2423  if (ParseFunctionType(Result))
2424  return true;
2425  break;
2426  }
2427  }
2428 }
2429 
2430 /// ParseParameterList
2431 /// ::= '(' ')'
2432 /// ::= '(' Arg (',' Arg)* ')'
2433 /// Arg
2434 /// ::= Type OptionalAttributes Value OptionalAttributes
2435 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2436  PerFunctionState &PFS, bool IsMustTailCall,
2437  bool InVarArgsFunc) {
2438  if (ParseToken(lltok::lparen, "expected '(' in call"))
2439  return true;
2440 
2441  while (Lex.getKind() != lltok::rparen) {
2442  // If this isn't the first argument, we need a comma.
2443  if (!ArgList.empty() &&
2444  ParseToken(lltok::comma, "expected ',' in argument list"))
2445  return true;
2446 
2447  // Parse an ellipsis if this is a musttail call in a variadic function.
2448  if (Lex.getKind() == lltok::dotdotdot) {
2449  const char *Msg = "unexpected ellipsis in argument list for ";
2450  if (!IsMustTailCall)
2451  return TokError(Twine(Msg) + "non-musttail call");
2452  if (!InVarArgsFunc)
2453  return TokError(Twine(Msg) + "musttail call in non-varargs function");
2454  Lex.Lex(); // Lex the '...', it is purely for readability.
2455  return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2456  }
2457 
2458  // Parse the argument.
2459  LocTy ArgLoc;
2460  Type *ArgTy = nullptr;
2461  AttrBuilder ArgAttrs;
2462  Value *V;
2463  if (ParseType(ArgTy, ArgLoc))
2464  return true;
2465 
2466  if (ArgTy->isMetadataTy()) {
2467  if (ParseMetadataAsValue(V, PFS))
2468  return true;
2469  } else {
2470  // Otherwise, handle normal operands.
2471  if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2472  return true;
2473  }
2474  ArgList.push_back(ParamInfo(
2475  ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2476  }
2477 
2478  if (IsMustTailCall && InVarArgsFunc)
2479  return TokError("expected '...' at end of argument list for musttail call "
2480  "in varargs function");
2481 
2482  Lex.Lex(); // Lex the ')'.
2483  return false;
2484 }
2485 
2486 /// ParseByValWithOptionalType
2487 /// ::= byval
2488 /// ::= byval(<ty>)
2489 bool LLParser::ParseByValWithOptionalType(Type *&Result) {
2490  Result = nullptr;
2491  if (!EatIfPresent(lltok::kw_byval))
2492  return true;
2493  if (!EatIfPresent(lltok::lparen))
2494  return false;
2495  if (ParseType(Result))
2496  return true;
2497  if (!EatIfPresent(lltok::rparen))
2498  return Error(Lex.getLoc(), "expected ')'");
2499  return false;
2500 }
2501 
2502 /// ParseOptionalOperandBundles
2503 /// ::= /*empty*/
2504 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2505 ///
2506 /// OperandBundle
2507 /// ::= bundle-tag '(' ')'
2508 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2509 ///
2510 /// bundle-tag ::= String Constant
2511 bool LLParser::ParseOptionalOperandBundles(
2512  SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2513  LocTy BeginLoc = Lex.getLoc();
2514  if (!EatIfPresent(lltok::lsquare))
2515  return false;
2516 
2517  while (Lex.getKind() != lltok::rsquare) {
2518  // If this isn't the first operand bundle, we need a comma.
2519  if (!BundleList.empty() &&
2520  ParseToken(lltok::comma, "expected ',' in input list"))
2521  return true;
2522 
2523  std::string Tag;
2524  if (ParseStringConstant(Tag))
2525  return true;
2526 
2527  if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2528  return true;
2529 
2530  std::vector<Value *> Inputs;
2531  while (Lex.getKind() != lltok::rparen) {
2532  // If this isn't the first input, we need a comma.
2533  if (!Inputs.empty() &&
2534  ParseToken(lltok::comma, "expected ',' in input list"))
2535  return true;
2536 
2537  Type *Ty = nullptr;
2538  Value *Input = nullptr;
2539  if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2540  return true;
2541  Inputs.push_back(Input);
2542  }
2543 
2544  BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2545 
2546  Lex.Lex(); // Lex the ')'.
2547  }
2548 
2549  if (BundleList.empty())
2550  return Error(BeginLoc, "operand bundle set must not be empty");
2551 
2552  Lex.Lex(); // Lex the ']'.
2553  return false;
2554 }
2555 
2556 /// ParseArgumentList - Parse the argument list for a function type or function
2557 /// prototype.
2558 /// ::= '(' ArgTypeListI ')'
2559 /// ArgTypeListI
2560 /// ::= /*empty*/
2561 /// ::= '...'
2562 /// ::= ArgTypeList ',' '...'
2563 /// ::= ArgType (',' ArgType)*
2564 ///
2565 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2566  bool &isVarArg){
2567  unsigned CurValID = 0;
2568  isVarArg = false;
2569  assert(Lex.getKind() == lltok::lparen);
2570  Lex.Lex(); // eat the (.
2571 
2572  if (Lex.getKind() == lltok::rparen) {
2573  // empty
2574  } else if (Lex.getKind() == lltok::dotdotdot) {
2575  isVarArg = true;
2576  Lex.Lex();
2577  } else {
2578  LocTy TypeLoc = Lex.getLoc();
2579  Type *ArgTy = nullptr;
2581  std::string Name;
2582 
2583  if (ParseType(ArgTy) ||
2584  ParseOptionalParamAttrs(Attrs)) return true;
2585 
2586  if (ArgTy->isVoidTy())
2587  return Error(TypeLoc, "argument can not have void type");
2588 
2589  if (Lex.getKind() == lltok::LocalVar) {
2590  Name = Lex.getStrVal();
2591  Lex.Lex();
2592  } else if (Lex.getKind() == lltok::LocalVarID) {
2593  if (Lex.getUIntVal() != CurValID)
2594  return Error(TypeLoc, "argument expected to be numbered '%" +
2595  Twine(CurValID) + "'");
2596  ++CurValID;
2597  Lex.Lex();
2598  }
2599 
2601  return Error(TypeLoc, "invalid type for function argument");
2602 
2603  ArgList.emplace_back(TypeLoc, ArgTy,
2604  AttributeSet::get(ArgTy->getContext(), Attrs),
2605  std::move(Name));
2606 
2607  while (EatIfPresent(lltok::comma)) {
2608  // Handle ... at end of arg list.
2609  if (EatIfPresent(lltok::dotdotdot)) {
2610  isVarArg = true;
2611  break;
2612  }
2613 
2614  // Otherwise must be an argument type.
2615  TypeLoc = Lex.getLoc();
2616  if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2617 
2618  if (ArgTy->isVoidTy())
2619  return Error(TypeLoc, "argument can not have void type");
2620 
2621  if (Lex.getKind() == lltok::LocalVar) {
2622  Name = Lex.getStrVal();
2623  Lex.Lex();
2624  } else {
2625  if (Lex.getKind() == lltok::LocalVarID) {
2626  if (Lex.getUIntVal() != CurValID)
2627  return Error(TypeLoc, "argument expected to be numbered '%" +
2628  Twine(CurValID) + "'");
2629  Lex.Lex();
2630  }
2631  ++CurValID;
2632  Name = "";
2633  }
2634 
2635  if (!ArgTy->isFirstClassType())
2636  return Error(TypeLoc, "invalid type for function argument");
2637 
2638  ArgList.emplace_back(TypeLoc, ArgTy,
2639  AttributeSet::get(ArgTy->getContext(), Attrs),
2640  std::move(Name));
2641  }
2642  }
2643 
2644  return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2645 }
2646 
2647 /// ParseFunctionType
2648 /// ::= Type ArgumentList OptionalAttrs
2649 bool LLParser::ParseFunctionType(Type *&Result) {
2650  assert(Lex.getKind() == lltok::lparen);
2651 
2652  if (!FunctionType::isValidReturnType(Result))
2653  return TokError("invalid function return type");
2654 
2655  SmallVector<ArgInfo, 8> ArgList;
2656  bool isVarArg;
2657  if (ParseArgumentList(ArgList, isVarArg))
2658  return true;
2659 
2660  // Reject names on the arguments lists.
2661  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2662  if (!ArgList[i].Name.empty())
2663  return Error(ArgList[i].Loc, "argument name invalid in function type");
2664  if (ArgList[i].Attrs.hasAttributes())
2665  return Error(ArgList[i].Loc,
2666  "argument attributes invalid in function type");
2667  }
2668 
2669  SmallVector<Type*, 16> ArgListTy;
2670  for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2671  ArgListTy.push_back(ArgList[i].Ty);
2672 
2673  Result = FunctionType::get(Result, ArgListTy, isVarArg);
2674  return false;
2675 }
2676 
2677 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2678 /// other structs.
2679 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2680  SmallVector<Type*, 8> Elts;
2681  if (ParseStructBody(Elts)) return true;
2682 
2683  Result = StructType::get(Context, Elts, Packed);
2684  return false;
2685 }
2686 
2687 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2688 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2689  std::pair<Type*, LocTy> &Entry,
2690  Type *&ResultTy) {
2691  // If the type was already defined, diagnose the redefinition.
2692  if (Entry.first && !Entry.second.isValid())
2693  return Error(TypeLoc, "redefinition of type");
2694 
2695  // If we have opaque, just return without filling in the definition for the
2696  // struct. This counts as a definition as far as the .ll file goes.
2697  if (EatIfPresent(lltok::kw_opaque)) {
2698  // This type is being defined, so clear the location to indicate this.
2699  Entry.second = SMLoc();
2700 
2701  // If this type number has never been uttered, create it.
2702  if (!Entry.first)
2703  Entry.first = StructType::create(Context, Name);
2704  ResultTy = Entry.first;
2705  return false;
2706  }
2707 
2708  // If the type starts with '<', then it is either a packed struct or a vector.
2709  bool isPacked = EatIfPresent(lltok::less);
2710 
2711  // If we don't have a struct, then we have a random type alias, which we
2712  // accept for compatibility with old files. These types are not allowed to be
2713  // forward referenced and not allowed to be recursive.
2714  if (Lex.getKind() != lltok::lbrace) {
2715  if (Entry.first)
2716  return Error(TypeLoc, "forward references to non-struct type");
2717 
2718  ResultTy = nullptr;
2719  if (isPacked)
2720  return ParseArrayVectorType(ResultTy, true);
2721  return ParseType(ResultTy);
2722  }
2723 
2724  // This type is being defined, so clear the location to indicate this.
2725  Entry.second = SMLoc();
2726 
2727  // If this type number has never been uttered, create it.
2728  if (!Entry.first)
2729  Entry.first = StructType::create(Context, Name);
2730 
2731  StructType *STy = cast<StructType>(Entry.first);
2732 
2733  SmallVector<Type*, 8> Body;
2734  if (ParseStructBody(Body) ||
2735  (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2736  return true;
2737 
2738  STy->setBody(Body, isPacked);
2739  ResultTy = STy;
2740  return false;
2741 }
2742 
2743 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2744 /// StructType
2745 /// ::= '{' '}'
2746 /// ::= '{' Type (',' Type)* '}'
2747 /// ::= '<' '{' '}' '>'
2748 /// ::= '<' '{' Type (',' Type)* '}' '>'
2749 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2750  assert(Lex.getKind() == lltok::lbrace);
2751  Lex.Lex(); // Consume the '{'
2752 
2753  // Handle the empty struct.
2754  if (EatIfPresent(lltok::rbrace))
2755  return false;
2756 
2757  LocTy EltTyLoc = Lex.getLoc();
2758  Type *Ty = nullptr;
2759  if (ParseType(Ty)) return true;
2760  Body.push_back(Ty);
2761 
2763  return Error(EltTyLoc, "invalid element type for struct");
2764 
2765  while (EatIfPresent(lltok::comma)) {
2766  EltTyLoc = Lex.getLoc();
2767  if (ParseType(Ty)) return true;
2768 
2770  return Error(EltTyLoc, "invalid element type for struct");
2771 
2772  Body.push_back(Ty);
2773  }
2774 
2775  return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2776 }
2777 
2778 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2779 /// token has already been consumed.
2780 /// Type
2781 /// ::= '[' APSINTVAL 'x' Types ']'
2782 /// ::= '<' APSINTVAL 'x' Types '>'
2783 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
2784 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2785  bool Scalable = false;
2786 
2787  if (isVector && Lex.getKind() == lltok::kw_vscale) {
2788  Lex.Lex(); // consume the 'vscale'
2789  if (ParseToken(lltok::kw_x, "expected 'x' after vscale"))
2790  return true;
2791 
2792  Scalable = true;
2793  }
2794 
2795  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2796  Lex.getAPSIntVal().getBitWidth() > 64)
2797  return TokError("expected number in address space");
2798 
2799  LocTy SizeLoc = Lex.getLoc();
2800  uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2801  Lex.Lex();
2802 
2803  if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2804  return true;
2805 
2806  LocTy TypeLoc = Lex.getLoc();
2807  Type *EltTy = nullptr;
2808  if (ParseType(EltTy)) return true;
2809 
2810  if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2811  "expected end of sequential type"))
2812  return true;
2813 
2814  if (isVector) {
2815  if (Size == 0)
2816  return Error(SizeLoc, "zero element vector is illegal");
2817  if ((unsigned)Size != Size)
2818  return Error(SizeLoc, "size too large for vector");
2819  if (!VectorType::isValidElementType(EltTy))
2820  return Error(TypeLoc, "invalid vector element type");
2821  Result = VectorType::get(EltTy, unsigned(Size), Scalable);
2822  } else {
2823  if (!ArrayType::isValidElementType(EltTy))
2824  return Error(TypeLoc, "invalid array element type");
2825  Result = ArrayType::get(EltTy, Size);
2826  }
2827  return false;
2828 }
2829 
2830 //===----------------------------------------------------------------------===//
2831 // Function Semantic Analysis.
2832 //===----------------------------------------------------------------------===//
2833 
2834 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2835  int functionNumber)
2836  : P(p), F(f), FunctionNumber(functionNumber) {
2837 
2838  // Insert unnamed arguments into the NumberedVals list.
2839  for (Argument &A : F.args())
2840  if (!A.hasName())
2841  NumberedVals.push_back(&A);
2842 }
2843 
2844 LLParser::PerFunctionState::~PerFunctionState() {
2845  // If there were any forward referenced non-basicblock values, delete them.
2846 
2847  for (const auto &P : ForwardRefVals) {
2848  if (isa<BasicBlock>(P.second.first))
2849  continue;
2850  P.second.first->replaceAllUsesWith(
2851  UndefValue::get(P.second.first->getType()));
2852  P.second.first->deleteValue();
2853  }
2854 
2855  for (const auto &P : ForwardRefValIDs) {
2856  if (isa<BasicBlock>(P.second.first))
2857  continue;
2858  P.second.first->replaceAllUsesWith(
2859  UndefValue::get(P.second.first->getType()));
2860  P.second.first->deleteValue();
2861  }
2862 }
2863 
2864 bool LLParser::PerFunctionState::FinishFunction() {
2865  if (!ForwardRefVals.empty())
2866  return P.Error(ForwardRefVals.begin()->second.second,
2867  "use of undefined value '%" + ForwardRefVals.begin()->first +
2868  "'");
2869  if (!ForwardRefValIDs.empty())
2870  return P.Error(ForwardRefValIDs.begin()->second.second,
2871  "use of undefined value '%" +
2872  Twine(ForwardRefValIDs.begin()->first) + "'");
2873  return false;
2874 }
2875 
2876 /// GetVal - Get a value with the specified name or ID, creating a
2877 /// forward reference record if needed. This can return null if the value
2878 /// exists but does not have the right type.
2879 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2880  LocTy Loc, bool IsCall) {
2881  // Look this name up in the normal function symbol table.
2882  Value *Val = F.getValueSymbolTable()->lookup(Name);
2883 
2884  // If this is a forward reference for the value, see if we already created a
2885  // forward ref record.
2886  if (!Val) {
2887  auto I = ForwardRefVals.find(Name);
2888  if (I != ForwardRefVals.end())
2889  Val = I->second.first;
2890  }
2891 
2892  // If we have the value in the symbol table or fwd-ref table, return it.
2893  if (Val)
2894  return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
2895 
2896  // Don't make placeholders with invalid type.
2897  if (!Ty->isFirstClassType()) {
2898  P.Error(Loc, "invalid use of a non-first-class type");
2899  return nullptr;
2900  }
2901 
2902  // Otherwise, create a new forward reference for this value and remember it.
2903  Value *FwdVal;
2904  if (Ty->isLabelTy()) {
2905  FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2906  } else {
2907  FwdVal = new Argument(Ty, Name);
2908  }
2909 
2910  ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2911  return FwdVal;
2912 }
2913 
2914 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2915  bool IsCall) {
2916  // Look this name up in the normal function symbol table.
2917  Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2918 
2919  // If this is a forward reference for the value, see if we already created a
2920  // forward ref record.
2921  if (!Val) {
2922  auto I = ForwardRefValIDs.find(ID);
2923  if (I != ForwardRefValIDs.end())
2924  Val = I->second.first;
2925  }
2926 
2927  // If we have the value in the symbol table or fwd-ref table, return it.
2928  if (Val)
2929  return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
2930 
2931  if (!Ty->isFirstClassType()) {
2932  P.Error(Loc, "invalid use of a non-first-class type");
2933  return nullptr;
2934  }
2935 
2936  // Otherwise, create a new forward reference for this value and remember it.
2937  Value *FwdVal;
2938  if (Ty->isLabelTy()) {
2939  FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2940  } else {
2941  FwdVal = new Argument(Ty);
2942  }
2943 
2944  ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2945  return FwdVal;
2946 }
2947 
2948 /// SetInstName - After an instruction is parsed and inserted into its
2949 /// basic block, this installs its name.
2950 bool LLParser::PerFunctionState::SetInstName(int NameID,
2951  const std::string &NameStr,
2952  LocTy NameLoc, Instruction *Inst) {
2953  // If this instruction has void type, it cannot have a name or ID specified.
2954  if (Inst->getType()->isVoidTy()) {
2955  if (NameID != -1 || !NameStr.empty())
2956  return P.Error(NameLoc, "instructions returning void cannot have a name");
2957  return false;
2958  }
2959 
2960  // If this was a numbered instruction, verify that the instruction is the
2961  // expected value and resolve any forward references.
2962  if (NameStr.empty()) {
2963  // If neither a name nor an ID was specified, just use the next ID.
2964  if (NameID == -1)
2965  NameID = NumberedVals.size();
2966 
2967  if (unsigned(NameID) != NumberedVals.size())
2968  return P.Error(NameLoc, "instruction expected to be numbered '%" +
2969  Twine(NumberedVals.size()) + "'");
2970 
2971  auto FI = ForwardRefValIDs.find(NameID);
2972  if (FI != ForwardRefValIDs.end()) {
2973  Value *Sentinel = FI->second.first;
2974  if (Sentinel->getType() != Inst->getType())
2975  return P.Error(NameLoc, "instruction forward referenced with type '" +
2976  getTypeString(FI->second.first->getType()) + "'");
2977 
2978  Sentinel->replaceAllUsesWith(Inst);
2979  Sentinel->deleteValue();
2980  ForwardRefValIDs.erase(FI);
2981  }
2982 
2983  NumberedVals.push_back(Inst);
2984  return false;
2985  }
2986 
2987  // Otherwise, the instruction had a name. Resolve forward refs and set it.
2988  auto FI = ForwardRefVals.find(NameStr);
2989  if (FI != ForwardRefVals.end()) {
2990  Value *Sentinel = FI->second.first;
2991  if (Sentinel->getType() != Inst->getType())
2992  return P.Error(NameLoc, "instruction forward referenced with type '" +
2993  getTypeString(FI->second.first->getType()) + "'");
2994 
2995  Sentinel->replaceAllUsesWith(Inst);
2996  Sentinel->deleteValue();
2997  ForwardRefVals.erase(FI);
2998  }
2999 
3000  // Set the name on the instruction.
3001  Inst->setName(NameStr);
3002 
3003  if (Inst->getName() != NameStr)
3004  return P.Error(NameLoc, "multiple definition of local value named '" +
3005  NameStr + "'");
3006  return false;
3007 }
3008 
3009 /// GetBB - Get a basic block with the specified name or ID, creating a
3010 /// forward reference record if needed.
3011 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
3012  LocTy Loc) {
3013  return dyn_cast_or_null<BasicBlock>(
3014  GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
3015 }
3016 
3017 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
3018  return dyn_cast_or_null<BasicBlock>(
3019  GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
3020 }
3021 
3022 /// DefineBB - Define the specified basic block, which is either named or
3023 /// unnamed. If there is an error, this returns null otherwise it returns
3024 /// the block being defined.
3025 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
3026  int NameID, LocTy Loc) {
3027  BasicBlock *BB;
3028  if (Name.empty()) {
3029  if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3030  P.Error(Loc, "label expected to be numbered '" +
3031  Twine(NumberedVals.size()) + "'");
3032  return nullptr;
3033  }
3034  BB = GetBB(NumberedVals.size(), Loc);
3035  if (!BB) {
3036  P.Error(Loc, "unable to create block numbered '" +
3037  Twine(NumberedVals.size()) + "'");
3038  return nullptr;
3039  }
3040  } else {
3041  BB = GetBB(Name, Loc);
3042  if (!BB) {
3043  P.Error(Loc, "unable to create block named '" + Name + "'");
3044  return nullptr;
3045  }
3046  }
3047 
3048  // Move the block to the end of the function. Forward ref'd blocks are
3049  // inserted wherever they happen to be referenced.
3050  F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
3051 
3052  // Remove the block from forward ref sets.
3053  if (Name.empty()) {
3054  ForwardRefValIDs.erase(NumberedVals.size());
3055  NumberedVals.push_back(BB);
3056  } else {
3057  // BB forward references are already in the function symbol table.
3058  ForwardRefVals.erase(Name);
3059  }
3060 
3061  return BB;
3062 }
3063 
3064 //===----------------------------------------------------------------------===//
3065 // Constants.
3066 //===----------------------------------------------------------------------===//
3067 
3068 /// ParseValID - Parse an abstract value that doesn't necessarily have a
3069 /// type implied. For example, if we parse "4" we don't know what integer type
3070 /// it has. The value will later be combined with its type and checked for
3071 /// sanity. PFS is used to convert function-local operands of metadata (since
3072 /// metadata operands are not just parsed here but also converted to values).
3073 /// PFS can be null when we are not parsing metadata values inside a function.
3074 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
3075  ID.Loc = Lex.getLoc();
3076  switch (Lex.getKind()) {
3077  default: return TokError("expected value token");
3078  case lltok::GlobalID: // @42
3079  ID.UIntVal = Lex.getUIntVal();
3080  ID.Kind = ValID::t_GlobalID;
3081  break;
3082  case lltok::GlobalVar: // @foo
3083  ID.StrVal = Lex.getStrVal();
3085  break;
3086  case lltok::LocalVarID: // %42
3087  ID.UIntVal = Lex.getUIntVal();
3088  ID.Kind = ValID::t_LocalID;
3089  break;
3090  case lltok::LocalVar: // %foo
3091  ID.StrVal = Lex.getStrVal();
3092  ID.Kind = ValID::t_LocalName;
3093  break;
3094  case lltok::APSInt:
3095  ID.APSIntVal = Lex.getAPSIntVal();
3096  ID.Kind = ValID::t_APSInt;
3097  break;
3098  case lltok::APFloat:
3099  ID.APFloatVal = Lex.getAPFloatVal();
3100  ID.Kind = ValID::t_APFloat;
3101  break;
3102  case lltok::kw_true:
3103  ID.ConstantVal = ConstantInt::getTrue(Context);
3104  ID.Kind = ValID::t_Constant;
3105  break;
3106  case lltok::kw_false:
3107  ID.ConstantVal = ConstantInt::getFalse(Context);
3108  ID.Kind = ValID::t_Constant;
3109  break;
3110  case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3111  case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3112  case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3113  case lltok::kw_none: ID.Kind = ValID::t_None; break;
3114 
3115  case lltok::lbrace: {
3116  // ValID ::= '{' ConstVector '}'
3117  Lex.Lex();
3119  if (ParseGlobalValueVector(Elts) ||
3120  ParseToken(lltok::rbrace, "expected end of struct constant"))
3121  return true;
3122 
3123  ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3124  ID.UIntVal = Elts.size();
3125  memcpy(ID.ConstantStructElts.get(), Elts.data(),
3126  Elts.size() * sizeof(Elts[0]));
3128  return false;
3129  }
3130  case lltok::less: {
3131  // ValID ::= '<' ConstVector '>' --> Vector.
3132  // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3133  Lex.Lex();
3134  bool isPackedStruct = EatIfPresent(lltok::lbrace);
3135 
3137  LocTy FirstEltLoc = Lex.getLoc();
3138  if (ParseGlobalValueVector(Elts) ||
3139  (isPackedStruct &&
3140  ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3141  ParseToken(lltok::greater, "expected end of constant"))
3142  return true;
3143 
3144  if (isPackedStruct) {
3145  ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3146  memcpy(ID.ConstantStructElts.get(), Elts.data(),
3147  Elts.size() * sizeof(Elts[0]));
3148  ID.UIntVal = Elts.size();
3150  return false;
3151  }
3152 
3153  if (Elts.empty())
3154  return Error(ID.Loc, "constant vector must not be empty");
3155 
3156  if (!Elts[0]->getType()->isIntegerTy() &&
3157  !Elts[0]->getType()->isFloatingPointTy() &&
3158  !Elts[0]->getType()->isPointerTy())
3159  return Error(FirstEltLoc,
3160  "vector elements must have integer, pointer or floating point type");
3161 
3162  // Verify that all the vector elements have the same type.
3163  for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3164  if (Elts[i]->getType() != Elts[0]->getType())
3165  return Error(FirstEltLoc,
3166  "vector element #" + Twine(i) +
3167  " is not of type '" + getTypeString(Elts[0]->getType()));
3168 
3169  ID.ConstantVal = ConstantVector::get(Elts);
3170  ID.Kind = ValID::t_Constant;
3171  return false;
3172  }
3173  case lltok::lsquare: { // Array Constant
3174  Lex.Lex();
3176  LocTy FirstEltLoc = Lex.getLoc();
3177  if (ParseGlobalValueVector(Elts) ||
3178  ParseToken(lltok::rsquare, "expected end of array constant"))
3179  return true;
3180 
3181  // Handle empty element.
3182  if (Elts.empty()) {
3183  // Use undef instead of an array because it's inconvenient to determine
3184  // the element type at this point, there being no elements to examine.
3186  return false;
3187  }
3188 
3189  if (!Elts[0]->getType()->isFirstClassType())
3190  return Error(FirstEltLoc, "invalid array element type: " +
3191  getTypeString(Elts[0]->getType()));
3192 
3193  ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3194 
3195  // Verify all elements are correct type!
3196  for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3197  if (Elts[i]->getType() != Elts[0]->getType())
3198  return Error(FirstEltLoc,
3199  "array element #" + Twine(i) +
3200  " is not of type '" + getTypeString(Elts[0]->getType()));
3201  }
3202 
3203  ID.ConstantVal = ConstantArray::get(ATy, Elts);
3204  ID.Kind = ValID::t_Constant;
3205  return false;
3206  }
3207  case lltok::kw_c: // c "foo"
3208  Lex.Lex();
3210  false);
3211  if (ParseToken(lltok::StringConstant, "expected string")) return true;
3212  ID.Kind = ValID::t_Constant;
3213  return false;
3214 
3215  case lltok::kw_asm: {
3216  // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3217  // STRINGCONSTANT
3218  bool HasSideEffect, AlignStack, AsmDialect;
3219  Lex.Lex();
3220  if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3221  ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3222  ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3223  ParseStringConstant(ID.StrVal) ||
3224  ParseToken(lltok::comma, "expected comma in inline asm expression") ||
3225  ParseToken(lltok::StringConstant, "expected constraint string"))
3226  return true;
3227  ID.StrVal2 = Lex.getStrVal();
3228  ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
3229  (unsigned(AsmDialect)<<2);
3230  ID.Kind = ValID::t_InlineAsm;
3231  return false;
3232  }
3233 
3234  case lltok::kw_blockaddress: {
3235  // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3236  Lex.Lex();
3237 
3238  ValID Fn, Label;
3239 
3240  if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3241  ParseValID(Fn) ||
3242  ParseToken(lltok::comma, "expected comma in block address expression")||
3243  ParseValID(Label) ||
3244  ParseToken(lltok::rparen, "expected ')' in block address expression"))
3245  return true;
3246 
3247  if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3248  return Error(Fn.Loc, "expected function name in blockaddress");
3249  if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3250  return Error(Label.Loc, "expected basic block name in blockaddress");
3251 
3252  // Try to find the function (but skip it if it's forward-referenced).
3253  GlobalValue *GV = nullptr;
3254  if (Fn.Kind == ValID::t_GlobalID) {
3255  if (Fn.UIntVal < NumberedVals.size())
3256  GV = NumberedVals[Fn.UIntVal];
3257  } else if (!ForwardRefVals.count(Fn.StrVal)) {
3258  GV = M->getNamedValue(Fn.StrVal);
3259  }
3260  Function *F = nullptr;
3261  if (GV) {
3262  // Confirm that it's actually a function with a definition.
3263  if (!isa<Function>(GV))
3264  return Error(Fn.Loc, "expected function name in blockaddress");
3265  F = cast<Function>(GV);
3266  if (F->isDeclaration())
3267  return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3268  }
3269 
3270  if (!F) {
3271  // Make a global variable as a placeholder for this reference.
3272  GlobalValue *&FwdRef =
3273  ForwardRefBlockAddresses.insert(std::make_pair(
3274  std::move(Fn),
3275  std::map<ValID, GlobalValue *>()))
3276  .first->second.insert(std::make_pair(std::move(Label), nullptr))
3277  .first->second;
3278  if (!FwdRef)
3279  FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3280  GlobalValue::InternalLinkage, nullptr, "");
3281  ID.ConstantVal = FwdRef;
3282  ID.Kind = ValID::t_Constant;
3283  return false;
3284  }
3285 
3286  // We found the function; now find the basic block. Don't use PFS, since we
3287  // might be inside a constant expression.
3288  BasicBlock *BB;
3289  if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3290  if (Label.Kind == ValID::t_LocalID)
3291  BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3292  else
3293  BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3294  if (!BB)
3295  return Error(Label.Loc, "referenced value is not a basic block");
3296  } else {
3297  if (Label.Kind == ValID::t_LocalID)
3298  return Error(Label.Loc, "cannot take address of numeric label after "
3299  "the function is defined");
3300  BB = dyn_cast_or_null<BasicBlock>(
3301  F->getValueSymbolTable()->lookup(Label.StrVal));
3302  if (!BB)
3303  return Error(Label.Loc, "referenced value is not a basic block");
3304  }
3305 
3306  ID.ConstantVal = BlockAddress::get(F, BB);
3307  ID.Kind = ValID::t_Constant;
3308  return false;
3309  }
3310 
3311  case lltok::kw_trunc:
3312  case lltok::kw_zext:
3313  case lltok::kw_sext:
3314  case lltok::kw_fptrunc:
3315  case lltok::kw_fpext:
3316  case lltok::kw_bitcast:
3318  case lltok::kw_uitofp:
3319  case lltok::kw_sitofp:
3320  case lltok::kw_fptoui:
3321  case lltok::kw_fptosi:
3322  case lltok::kw_inttoptr:
3323  case lltok::kw_ptrtoint: {
3324  unsigned Opc = Lex.getUIntVal();
3325  Type *DestTy = nullptr;
3326  Constant *SrcVal;
3327  Lex.Lex();
3328  if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3329  ParseGlobalTypeAndValue(SrcVal) ||
3330  ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3331  ParseType(DestTy) ||
3332  ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3333  return true;
3334  if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3335  return Error(ID.Loc, "invalid cast opcode for cast from '" +
3336  getTypeString(SrcVal->getType()) + "' to '" +
3337  getTypeString(DestTy) + "'");
3339  SrcVal, DestTy);
3340  ID.Kind = ValID::t_Constant;
3341  return false;
3342  }
3343  case lltok::kw_extractvalue: {
3344  Lex.Lex();
3345  Constant *Val;
3346  SmallVector<unsigned, 4> Indices;
3347  if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3348  ParseGlobalTypeAndValue(Val) ||
3349  ParseIndexList(Indices) ||
3350  ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3351  return true;
3352 
3353  if (!Val->getType()->isAggregateType())
3354  return Error(ID.Loc, "extractvalue operand must be aggregate type");
3355  if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3356  return Error(ID.Loc, "invalid indices for extractvalue");
3357  ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3358  ID.Kind = ValID::t_Constant;
3359  return false;
3360  }
3361  case lltok::kw_insertvalue: {
3362  Lex.Lex();
3363  Constant *Val0, *Val1;
3364  SmallVector<unsigned, 4> Indices;
3365  if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3366  ParseGlobalTypeAndValue(Val0) ||
3367  ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3368  ParseGlobalTypeAndValue(Val1) ||
3369  ParseIndexList(Indices) ||
3370  ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3371  return true;
3372  if (!Val0->getType()->isAggregateType())
3373  return Error(ID.Loc, "insertvalue operand must be aggregate type");
3374  Type *IndexedType =
3375  ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3376  if (!IndexedType)
3377  return Error(ID.Loc, "invalid indices for insertvalue");
3378  if (IndexedType != Val1->getType())
3379  return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3380  getTypeString(Val1->getType()) +
3381  "' instead of '" + getTypeString(IndexedType) +
3382  "'");
3383  ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3384  ID.Kind = ValID::t_Constant;
3385  return false;
3386  }
3387  case lltok::kw_icmp:
3388  case lltok::kw_fcmp: {
3389  unsigned PredVal, Opc = Lex.getUIntVal();
3390  Constant *Val0, *Val1;
3391  Lex.Lex();
3392  if (ParseCmpPredicate(PredVal, Opc) ||
3393  ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3394  ParseGlobalTypeAndValue(Val0) ||
3395  ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3396  ParseGlobalTypeAndValue(Val1) ||
3397  ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3398  return true;
3399 
3400  if (Val0->getType() != Val1->getType())
3401  return Error(ID.Loc, "compare operands must have the same type");
3402 
3403  CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3404 
3405  if (Opc == Instruction::FCmp) {
3406  if (!Val0->getType()->isFPOrFPVectorTy())
3407  return Error(ID.Loc, "fcmp requires floating point operands");
3408  ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3409  } else {
3410  assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3411  if (!Val0->getType()->isIntOrIntVectorTy() &&
3412  !Val0->getType()->isPtrOrPtrVectorTy())
3413  return Error(ID.Loc, "icmp requires pointer or integer operands");
3414  ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3415  }
3416  ID.Kind = ValID::t_Constant;
3417  return false;
3418  }
3419 
3420  // Unary Operators.
3421  case lltok::kw_fneg: {
3422  unsigned Opc = Lex.getUIntVal();
3423  Constant *Val;
3424  Lex.Lex();
3425  if (ParseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3426  ParseGlobalTypeAndValue(Val) ||
3427  ParseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3428  return true;
3429 
3430  // Check that the type is valid for the operator.
3431  switch (Opc) {
3432  case Instruction::FNeg:
3433  if (!Val->getType()->isFPOrFPVectorTy())
3434  return Error(ID.Loc, "constexpr requires fp operands");
3435  break;
3436  default: llvm_unreachable("Unknown unary operator!");
3437  }
3438  unsigned Flags = 0;
3439  Constant *C = ConstantExpr::get(Opc, Val, Flags);
3440  ID.ConstantVal = C;
3441  ID.Kind = ValID::t_Constant;
3442  return false;
3443  }
3444  // Binary Operators.
3445  case lltok::kw_add:
3446  case lltok::kw_fadd:
3447  case lltok::kw_sub:
3448  case lltok::kw_fsub:
3449  case lltok::kw_mul:
3450  case lltok::kw_fmul:
3451  case lltok::kw_udiv:
3452  case lltok::kw_sdiv:
3453  case lltok::kw_fdiv:
3454  case lltok::kw_urem:
3455  case lltok::kw_srem:
3456  case lltok::kw_frem:
3457  case lltok::kw_shl:
3458  case lltok::kw_lshr:
3459  case lltok::kw_ashr: {
3460  bool NUW = false;
3461  bool NSW = false;
3462  bool Exact = false;
3463  unsigned Opc = Lex.getUIntVal();
3464  Constant *Val0, *Val1;
3465  Lex.Lex();
3466  if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3467  Opc == Instruction::Mul || Opc == Instruction::Shl) {
3468  if (EatIfPresent(lltok::kw_nuw))
3469  NUW = true;
3470  if (EatIfPresent(lltok::kw_nsw)) {
3471  NSW = true;
3472  if (EatIfPresent(lltok::kw_nuw))
3473  NUW = true;
3474  }
3475  } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3476  Opc == Instruction::LShr || Opc == Instruction::AShr) {
3477  if (EatIfPresent(lltok::kw_exact))
3478  Exact = true;
3479  }
3480  if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3481  ParseGlobalTypeAndValue(Val0) ||
3482  ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3483  ParseGlobalTypeAndValue(Val1) ||
3484  ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3485  return true;
3486  if (Val0->getType() != Val1->getType())
3487  return Error(ID.Loc, "operands of constexpr must have same type");
3488  // Check that the type is valid for the operator.
3489  switch (Opc) {
3490  case Instruction::Add:
3491  case Instruction::Sub:
3492  case Instruction::Mul:
3493  case Instruction::UDiv:
3494  case Instruction::SDiv:
3495  case Instruction::URem:
3496  case Instruction::SRem:
3497  case Instruction::Shl:
3498  case Instruction::AShr:
3499  case Instruction::LShr:
3500  if (!Val0->getType()->isIntOrIntVectorTy())
3501  return Error(ID.Loc, "constexpr requires integer operands");
3502  break;
3503  case Instruction::FAdd:
3504  case Instruction::FSub:
3505  case Instruction::FMul:
3506  case Instruction::FDiv:
3507  case Instruction::FRem:
3508  if (!Val0->getType()->isFPOrFPVectorTy())
3509  return Error(ID.Loc, "constexpr requires fp operands");
3510  break;
3511  default: llvm_unreachable("Unknown binary operator!");
3512  }
3513  unsigned Flags = 0;
3515  if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3516  if (Exact) Flags |= PossiblyExactOperator::IsExact;
3517  Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3518  ID.ConstantVal = C;
3519  ID.Kind = ValID::t_Constant;
3520  return false;
3521  }
3522 
3523  // Logical Operations
3524  case lltok::kw_and:
3525  case lltok::kw_or:
3526  case lltok::kw_xor: {
3527  unsigned Opc = Lex.getUIntVal();
3528  Constant *Val0, *Val1;
3529  Lex.Lex();
3530  if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3531  ParseGlobalTypeAndValue(Val0) ||
3532  ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3533  ParseGlobalTypeAndValue(Val1) ||
3534  ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3535  return true;
3536  if (Val0->getType() != Val1->getType())
3537  return Error(ID.Loc, "operands of constexpr must have same type");
3538  if (!Val0->getType()->isIntOrIntVectorTy())
3539  return Error(ID.Loc,
3540  "constexpr requires integer or integer vector operands");
3541  ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3542  ID.Kind = ValID::t_Constant;
3543  return false;
3544  }
3545 
3550  case lltok::kw_select: {
3551  unsigned Opc = Lex.getUIntVal();
3553  bool InBounds = false;
3554  Type *Ty;
3555  Lex.Lex();
3556 
3557  if (Opc == Instruction::GetElementPtr)
3558  InBounds = EatIfPresent(lltok::kw_inbounds);
3559 
3560  if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3561  return true;
3562 
3563  LocTy ExplicitTypeLoc = Lex.getLoc();
3564  if (Opc == Instruction::GetElementPtr) {
3565  if (ParseType(Ty) ||
3566  ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3567  return true;
3568  }
3569 
3570  Optional<unsigned> InRangeOp;
3571  if (ParseGlobalValueVector(
3572  Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3573  ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3574  return true;
3575 
3576  if (Opc == Instruction::GetElementPtr) {
3577  if (Elts.size() == 0 ||
3578  !Elts[0]->getType()->isPtrOrPtrVectorTy())
3579  return Error(ID.Loc, "base of getelementptr must be a pointer");
3580 
3581  Type *BaseType = Elts[0]->getType();
3582  auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3583  if (Ty != BasePointerType->getElementType())
3584  return Error(
3585  ExplicitTypeLoc,
3586  "explicit pointee type doesn't match operand's pointee type");
3587 
3588  unsigned GEPWidth =
3589  BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3590 
3591  ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3592  for (Constant *Val : Indices) {
3593  Type *ValTy = Val->getType();
3594  if (!ValTy->isIntOrIntVectorTy())
3595  return Error(ID.Loc, "getelementptr index must be an integer");
3596  if (ValTy->isVectorTy()) {
3597  unsigned ValNumEl = ValTy->getVectorNumElements();
3598  if (GEPWidth && (ValNumEl != GEPWidth))
3599  return Error(
3600  ID.Loc,
3601  "getelementptr vector index has a wrong number of elements");
3602  // GEPWidth may have been unknown because the base is a scalar,
3603  // but it is known now.
3604  GEPWidth = ValNumEl;
3605  }
3606  }
3607 
3608  SmallPtrSet<Type*, 4> Visited;
3609  if (!Indices.empty() && !Ty->isSized(&Visited))
3610  return Error(ID.Loc, "base element of getelementptr must be sized");
3611 
3612  if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3613  return Error(ID.Loc, "invalid getelementptr indices");
3614 
3615  if (InRangeOp) {
3616  if (*InRangeOp == 0)
3617  return Error(ID.Loc,
3618  "inrange keyword may not appear on pointer operand");
3619  --*InRangeOp;
3620  }
3621 
3622  ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3623  InBounds, InRangeOp);
3624  } else if (Opc == Instruction::Select) {
3625  if (Elts.size() != 3)
3626  return Error(ID.Loc, "expected three operands to select");
3627  if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3628  Elts[2]))
3629  return Error(ID.Loc, Reason);
3630  ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3631  } else if (Opc == Instruction::ShuffleVector) {
3632  if (Elts.size() != 3)
3633  return Error(ID.Loc, "expected three operands to shufflevector");
3634  if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3635  return Error(ID.Loc, "invalid operands to shufflevector");
3636  ID.ConstantVal =
3637  ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3638  } else if (Opc == Instruction::ExtractElement) {
3639  if (Elts.size() != 2)
3640  return Error(ID.Loc, "expected two operands to extractelement");
3641  if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3642  return Error(ID.Loc, "invalid extractelement operands");
3643  ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3644  } else {
3645  assert(Opc == Instruction::InsertElement && "Unknown opcode");
3646  if (Elts.size() != 3)
3647  return Error(ID.Loc, "expected three operands to insertelement");
3648  if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3649  return Error(ID.Loc, "invalid insertelement operands");
3650  ID.ConstantVal =
3651  ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3652  }
3653 
3654  ID.Kind = ValID::t_Constant;
3655  return false;
3656  }
3657  }
3658 
3659  Lex.Lex();
3660  return false;
3661 }
3662 
3663 /// ParseGlobalValue - Parse a global value with the specified type.
3664 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3665  C = nullptr;
3666  ValID ID;
3667  Value *V = nullptr;
3668  bool Parsed = ParseValID(ID) ||
3669  ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3670  if (V && !(C = dyn_cast<Constant>(V)))
3671  return Error(ID.Loc, "global values must be constants");
3672  return Parsed;
3673 }
3674 
3675 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3676  Type *Ty = nullptr;
3677  return ParseType(Ty) ||
3678  ParseGlobalValue(Ty, V);
3679 }
3680 
3681 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3682  C = nullptr;
3683 
3684  LocTy KwLoc = Lex.getLoc();
3685  if (!EatIfPresent(lltok::kw_comdat))
3686  return false;
3687 
3688  if (EatIfPresent(lltok::lparen)) {
3689  if (Lex.getKind() != lltok::ComdatVar)
3690  return TokError("expected comdat variable");
3691  C = getComdat(Lex.getStrVal(), Lex.getLoc());
3692  Lex.Lex();
3693  if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3694  return true;
3695  } else {
3696  if (GlobalName.empty())
3697  return TokError("comdat cannot be unnamed");
3698  C = getComdat(GlobalName, KwLoc);
3699  }
3700 
3701  return false;
3702 }
3703 
3704 /// ParseGlobalValueVector
3705 /// ::= /*empty*/
3706 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3707 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3708  Optional<unsigned> *InRangeOp) {
3709  // Empty list.
3710  if (Lex.getKind() == lltok::rbrace ||
3711  Lex.getKind() == lltok::rsquare ||
3712  Lex.getKind() == lltok::greater ||
3713  Lex.getKind() == lltok::rparen)
3714  return false;
3715 
3716  do {
3717  if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3718  *InRangeOp = Elts.size();
3719 
3720  Constant *C;
3721  if (ParseGlobalTypeAndValue(C)) return true;
3722  Elts.push_back(C);
3723  } while (EatIfPresent(lltok::comma));
3724 
3725  return false;
3726 }
3727 
3728 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3730  if (ParseMDNodeVector(Elts))
3731  return true;
3732 
3733  MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3734  return false;
3735 }
3736 
3737 /// MDNode:
3738 /// ::= !{ ... }
3739 /// ::= !7
3740 /// ::= !DILocation(...)
3741 bool LLParser::ParseMDNode(MDNode *&N) {
3742  if (Lex.getKind() == lltok::MetadataVar)
3743  return ParseSpecializedMDNode(N);
3744 
3745  return ParseToken(lltok::exclaim, "expected '!' here") ||
3746  ParseMDNodeTail(N);
3747 }
3748 
3749 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3750  // !{ ... }
3751  if (Lex.getKind() == lltok::lbrace)
3752  return ParseMDTuple(N);
3753 
3754  // !42
3755  return ParseMDNodeID(N);
3756 }
3757 
3758 namespace {
3759 
3760 /// Structure to represent an optional metadata field.
3761 template <class FieldTy> struct MDFieldImpl {
3762  typedef MDFieldImpl ImplTy;
3763  FieldTy Val;
3764  bool Seen;
3765 
3766  void assign(FieldTy Val) {
3767  Seen = true;
3768  this->Val = std::move(Val);
3769  }
3770 
3771  explicit MDFieldImpl(FieldTy Default)
3772  : Val(std::move(Default)), Seen(false) {}
3773 };
3774 
3775 /// Structure to represent an optional metadata field that
3776 /// can be of either type (A or B) and encapsulates the
3777 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3778 /// to reimplement the specifics for representing each Field.
3779 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3780  typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3781  FieldTypeA A;
3782  FieldTypeB B;
3783  bool Seen;
3784 
3785  enum {
3786  IsInvalid = 0,
3787  IsTypeA = 1,
3788  IsTypeB = 2
3789  } WhatIs;
3790 
3791  void assign(FieldTypeA A) {
3792  Seen = true;
3793  this->A = std::move(A);
3794  WhatIs = IsTypeA;
3795  }
3796 
3797  void assign(FieldTypeB B) {
3798  Seen = true;
3799  this->B = std::move(B);
3800  WhatIs = IsTypeB;
3801  }
3802 
3803  explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3804  : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3805  WhatIs(IsInvalid) {}
3806 };
3807 
3808 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3809  uint64_t Max;
3810 
3811  MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3812  : ImplTy(Default), Max(Max) {}
3813 };
3814 
3815 struct LineField : public MDUnsignedField {
3816  LineField() : MDUnsignedField(0, UINT32_MAX) {}
3817 };
3818 
3819 struct ColumnField : public MDUnsignedField {
3820  ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3821 };
3822 
3823 struct DwarfTagField : public MDUnsignedField {
3824  DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3825  DwarfTagField(dwarf::Tag DefaultTag)
3826  : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3827 };
3828 
3829 struct DwarfMacinfoTypeField : public MDUnsignedField {
3830  DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3831  DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3832  : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3833 };
3834 
3835 struct DwarfAttEncodingField : public MDUnsignedField {
3836  DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3837 };
3838 
3839 struct DwarfVirtualityField : public MDUnsignedField {
3840  DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3841 };
3842 
3843 struct DwarfLangField : public MDUnsignedField {
3844  DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3845 };
3846 
3847 struct DwarfCCField : public MDUnsignedField {
3848  DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3849 };
3850 
3851 struct EmissionKindField : public MDUnsignedField {
3852  EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3853 };
3854 
3855 struct NameTableKindField : public MDUnsignedField {
3856  NameTableKindField()
3857  : MDUnsignedField(
3858  0, (unsigned)
3860 };
3861 
3862 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3863  DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3864 };
3865 
3866 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3867  DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3868 };
3869 
3870 struct MDSignedField : public MDFieldImpl<int64_t> {
3871  int64_t Min;
3872  int64_t Max;
3873 
3874  MDSignedField(int64_t Default = 0)
3875  : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3876  MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3877  : ImplTy(Default), Min(Min), Max(Max) {}
3878 };
3879 
3880 struct MDBoolField : public MDFieldImpl<bool> {
3881  MDBoolField(bool Default = false) : ImplTy(Default) {}
3882 };
3883 
3884 struct MDField : public MDFieldImpl<Metadata *> {
3885  bool AllowNull;
3886 
3887  MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3888 };
3889 
3890 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3891  MDConstant() : ImplTy(nullptr) {}
3892 };
3893 
3894 struct MDStringField : public MDFieldImpl<MDString *> {
3895  bool AllowEmpty;
3896  MDStringField(bool AllowEmpty = true)
3897  : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3898 };
3899 
3900 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3901  MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3902 };
3903 
3904 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3905  ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3906 };
3907 
3908 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3909  MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3910  : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3911 
3912  MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3913  bool AllowNull = true)
3914  : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3915 
3916  bool isMDSignedField() const { return WhatIs == IsTypeA; }
3917  bool isMDField() const { return WhatIs == IsTypeB; }
3918  int64_t getMDSignedValue() const {
3919  assert(isMDSignedField() && "Wrong field type");
3920  return A.Val;
3921  }
3922  Metadata *getMDFieldValue() const {
3923  assert(isMDField() && "Wrong field type");
3924  return B.Val;
3925  }
3926 };
3927 
3928 struct MDSignedOrUnsignedField
3929  : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3930  MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3931 
3932  bool isMDSignedField() const { return WhatIs == IsTypeA; }
3933  bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3934  int64_t getMDSignedValue() const {
3935  assert(isMDSignedField() && "Wrong field type");
3936  return A.Val;
3937  }
3938  uint64_t getMDUnsignedValue() const {
3939  assert(isMDUnsignedField() && "Wrong field type");
3940  return B.Val;
3941  }
3942 };
3943 
3944 } // end anonymous namespace
3945 
3946 namespace llvm {
3947 
3948 template <>
3949 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3950  MDUnsignedField &Result) {
3951  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3952  return TokError("expected unsigned integer");
3953 
3954  auto &U = Lex.getAPSIntVal();
3955  if (U.ugt(Result.Max))
3956  return TokError("value for '" + Name + "' too large, limit is " +
3957  Twine(Result.Max));
3958  Result.assign(U.getZExtValue());
3959  assert(Result.Val <= Result.Max && "Expected value in range");
3960  Lex.Lex();
3961  return false;
3962 }
3963 
3964 template <>
3965 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3966  return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3967 }
3968 template <>
3969 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3970  return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3971 }
3972 
3973 template <>
3974 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3975  if (Lex.getKind() == lltok::APSInt)
3976  return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3977 
3978  if (Lex.getKind() != lltok::DwarfTag)
3979  return TokError("expected DWARF tag");
3980 
3981  unsigned Tag = dwarf::getTag(Lex.getStrVal());
3982  if (Tag == dwarf::DW_TAG_invalid)
3983  return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3984  assert(Tag <= Result.Max && "Expected valid DWARF tag");
3985 
3986  Result.assign(Tag);
3987  Lex.Lex();
3988  return false;
3989 }
3990 
3991 template <>
3992 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3993  DwarfMacinfoTypeField &Result) {
3994  if (Lex.getKind() == lltok::APSInt)
3995  return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3996 
3997  if (Lex.getKind() != lltok::DwarfMacinfo)
3998  return TokError("expected DWARF macinfo type");
3999 
4000  unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4001  if (Macinfo == dwarf::DW_MACINFO_invalid)
4002  return TokError(
4003  "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
4004  assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4005 
4006  Result.assign(Macinfo);
4007  Lex.Lex();
4008  return false;
4009 }
4010 
4011 template <>
4012 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4013  DwarfVirtualityField &Result) {
4014  if (Lex.getKind() == lltok::APSInt)
4015  return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4016 
4017  if (Lex.getKind() != lltok::DwarfVirtuality)
4018  return TokError("expected DWARF virtuality code");
4019 
4020  unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4021  if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4022  return TokError("invalid DWARF virtuality code" + Twine(" '") +
4023  Lex.getStrVal() + "'");
4024  assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4025  Result.assign(Virtuality);
4026  Lex.Lex();
4027  return false;
4028 }
4029 
4030 template <>
4031 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4032  if (Lex.getKind() == lltok::APSInt)
4033  return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4034 
4035  if (Lex.getKind() != lltok::DwarfLang)
4036  return TokError("expected DWARF language");
4037 
4038  unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4039  if (!Lang)
4040  return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4041  "'");
4042  assert(Lang <= Result.Max && "Expected valid DWARF language");
4043  Result.assign(Lang);
4044  Lex.Lex();
4045  return false;
4046 }
4047 
4048 template <>
4049 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4050  if (Lex.getKind() == lltok::APSInt)
4051  return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4052 
4053  if (Lex.getKind() != lltok::DwarfCC)
4054  return TokError("expected DWARF calling convention");
4055 
4056  unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4057  if (!CC)
4058  return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
4059  "'");
4060  assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4061  Result.assign(CC);
4062  Lex.Lex();
4063  return false;
4064 }
4065 
4066 template <>
4067 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
4068  if (Lex.getKind() == lltok::APSInt)
4069  return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4070 
4071  if (Lex.getKind() != lltok::EmissionKind)
4072  return TokError("expected emission kind");
4073 
4074  auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4075  if (!Kind)
4076  return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4077  "'");
4078  assert(*Kind <= Result.Max && "Expected valid emission kind");
4079  Result.assign(*Kind);
4080  Lex.Lex();
4081  return false;
4082 }
4083 
4084 template <>
4085 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4086  NameTableKindField &Result) {
4087  if (Lex.getKind() == lltok::APSInt)
4088  return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4089 
4090  if (Lex.getKind() != lltok::NameTableKind)
4091  return TokError("expected nameTable kind");
4092 
4093  auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4094  if (!Kind)
4095  return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4096  "'");
4097  assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4098  Result.assign((unsigned)*Kind);
4099  Lex.Lex();
4100  return false;
4101 }
4102 
4103 template <>
4104 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4105  DwarfAttEncodingField &Result) {
4106  if (Lex.getKind() == lltok::APSInt)
4107  return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4108 
4109  if (Lex.getKind() != lltok::DwarfAttEncoding)
4110  return TokError("expected DWARF type attribute encoding");
4111 
4112  unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4113  if (!Encoding)
4114  return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4115  Lex.getStrVal() + "'");
4116  assert(Encoding <= Result.Max && "Expected valid DWARF language");
4117  Result.assign(Encoding);
4118  Lex.Lex();
4119  return false;
4120 }
4121 
4122 /// DIFlagField
4123 /// ::= uint32
4124 /// ::= DIFlagVector
4125 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4126 template <>
4127 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4128 
4129  // Parser for a single flag.
4130  auto parseFlag = [&](DINode::DIFlags &Val) {
4131  if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4132  uint32_t TempVal = static_cast<uint32_t>(Val);
4133  bool Res = ParseUInt32(TempVal);
4134  Val = static_cast<DINode::DIFlags>(TempVal);
4135  return Res;
4136  }
4137 
4138  if (Lex.getKind() != lltok::DIFlag)
4139  return TokError("expected debug info flag");
4140 
4141  Val = DINode::getFlag(Lex.getStrVal());
4142  if (!Val)
4143  return TokError(Twine("invalid debug info flag flag '") +
4144  Lex.getStrVal() + "'");
4145  Lex.Lex();
4146  return false;
4147  };
4148 
4149  // Parse the flags and combine them together.
4150  DINode::DIFlags Combined = DINode::FlagZero;
4151  do {
4152  DINode::DIFlags Val;
4153  if (parseFlag(Val))
4154  return true;
4155  Combined |= Val;
4156  } while (EatIfPresent(lltok::bar));
4157 
4158  Result.assign(Combined);
4159  return false;
4160 }
4161 
4162 /// DISPFlagField
4163 /// ::= uint32
4164 /// ::= DISPFlagVector
4165 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4166 template <>
4167 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4168 
4169  // Parser for a single flag.
4170  auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4171  if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4172  uint32_t TempVal = static_cast<uint32_t>(Val);
4173  bool Res = ParseUInt32(TempVal);
4174  Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4175  return Res;
4176  }
4177 
4178  if (Lex.getKind() != lltok::DISPFlag)
4179  return TokError("expected debug info flag");
4180 
4181  Val = DISubprogram::getFlag(Lex.getStrVal());
4182  if (!Val)
4183  return TokError(Twine("invalid subprogram debug info flag '") +
4184  Lex.getStrVal() + "'");
4185  Lex.Lex();
4186  return false;
4187  };
4188 
4189  // Parse the flags and combine them together.
4190  DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4191  do {
4193  if (parseFlag(Val))
4194  return true;
4195  Combined |= Val;
4196  } while (EatIfPresent(lltok::bar));
4197 
4198  Result.assign(Combined);
4199  return false;
4200 }
4201 
4202 template <>
4203 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4204  MDSignedField &Result) {
4205  if (Lex.getKind() != lltok::APSInt)
4206  return TokError("expected signed integer");
4207 
4208  auto &S = Lex.getAPSIntVal();
4209  if (S < Result.Min)
4210  return TokError("value for '" + Name + "' too small, limit is " +
4211  Twine(Result.Min));
4212  if (S > Result.Max)
4213  return TokError("value for '" + Name + "' too large, limit is " +
4214  Twine(Result.Max));
4215  Result.assign(S.getExtValue());
4216  assert(Result.Val >= Result.Min && "Expected value in range");
4217  assert(Result.Val <= Result.Max && "Expected value in range");
4218  Lex.Lex();
4219  return false;
4220 }
4221 
4222 template <>
4223 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4224  switch (Lex.getKind()) {
4225  default:
4226  return TokError("expected 'true' or 'false'");
4227  case lltok::kw_true:
4228  Result.assign(true);
4229  break;
4230  case lltok::kw_false:
4231  Result.assign(false);
4232  break;
4233  }
4234  Lex.Lex();
4235  return false;
4236 }
4237 
4238 template <>
4239 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4240  if (Lex.getKind() == lltok::kw_null) {
4241  if (!Result.AllowNull)
4242  return TokError("'" + Name + "' cannot be null");
4243  Lex.Lex();
4244  Result.assign(nullptr);
4245  return false;
4246  }
4247 
4248  Metadata *MD;
4249  if (ParseMetadata(MD, nullptr))
4250  return true;
4251 
4252  Result.assign(MD);
4253  return false;
4254 }
4255 
4256 template <>
4257 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4258  MDSignedOrMDField &Result) {
4259  // Try to parse a signed int.
4260  if (Lex.getKind() == lltok::APSInt) {
4261  MDSignedField Res = Result.A;
4262  if (!ParseMDField(Loc, Name, Res)) {
4263  Result.assign(Res);
4264  return false;
4265  }
4266  return true;
4267  }
4268 
4269  // Otherwise, try to parse as an MDField.
4270  MDField Res = Result.B;
4271  if (!ParseMDField(Loc, Name, Res)) {
4272  Result.assign(Res);
4273  return false;
4274  }
4275 
4276  return true;
4277 }
4278 
4279 template <>
4280 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4281  MDSignedOrUnsignedField &Result) {
4282  if (Lex.getKind() != lltok::APSInt)
4283  return false;
4284 
4285  if (Lex.getAPSIntVal().isSigned()) {
4286  MDSignedField Res = Result.A;
4287  if (ParseMDField(Loc, Name, Res))
4288  return true;
4289  Result.assign(Res);
4290  return false;
4291  }
4292 
4293  MDUnsignedField Res = Result.B;
4294  if (ParseMDField(Loc, Name, Res))
4295  return true;
4296  Result.assign(Res);
4297  return false;
4298 }
4299 
4300 template <>
4301 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4302  LocTy ValueLoc = Lex.getLoc();
4303  std::string S;
4304  if (ParseStringConstant(S))
4305  return true;
4306 
4307  if (!Result.AllowEmpty && S.empty())
4308  return Error(ValueLoc, "'" + Name + "' cannot be empty");
4309 
4310  Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4311  return false;
4312 }
4313 
4314 template <>
4315 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4317  if (ParseMDNodeVector(MDs))
4318  return true;
4319 
4320  Result.assign(std::move(MDs));
4321  return false;
4322 }
4323 
4324 template <>
4325 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4326  ChecksumKindField &Result) {
4328  DIFile::getChecksumKind(Lex.getStrVal());
4329 
4330  if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4331  return TokError(
4332  "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4333 
4334  Result.assign(*CSKind);
4335  Lex.Lex();
4336  return false;
4337 }
4338 
4339 } // end namespace llvm
4340 
4341 template <class ParserTy>
4342 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
4343  do {
4344  if (Lex.getKind() != lltok::LabelStr)
4345  return TokError("expected field label here");
4346 
4347  if (parseField())
4348  return true;
4349  } while (EatIfPresent(lltok::comma));
4350 
4351  return false;
4352 }
4353 
4354 template <class ParserTy>
4355 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4356  assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4357  Lex.Lex();
4358 
4359  if (ParseToken(lltok::lparen, "expected '(' here"))
4360  return true;
4361  if (Lex.getKind() != lltok::rparen)
4362  if (ParseMDFieldsImplBody(parseField))
4363  return true;
4364 
4365  ClosingLoc = Lex.getLoc();
4366  return ParseToken(lltok::rparen, "expected ')' here");
4367 }
4368 
4369 template <class FieldTy>
4370 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4371  if (Result.Seen)
4372  return TokError("field '" + Name + "' cannot be specified more than once");
4373 
4374  LocTy Loc = Lex.getLoc();
4375  Lex.Lex();
4376  return ParseMDField(Loc, Name, Result);
4377 }
4378 
4379 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4380  assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4381 
4382 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4383  if (Lex.getStrVal() == #CLASS) \
4384  return Parse##CLASS(N, IsDistinct);
4385 #include "llvm/IR/Metadata.def"
4386 
4387  return TokError("expected metadata type");
4388 }
4389 
4390 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4391 #define NOP_FIELD(NAME, TYPE, INIT)
4392 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4393  if (!NAME.Seen) \
4394  return Error(ClosingLoc, "missing required field '" #NAME "'");
4395 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4396  if (Lex.getStrVal() == #NAME) \
4397  return ParseMDField(#NAME, NAME);
4398 #define PARSE_MD_FIELDS() \
4399  VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4400  do { \
4401  LocTy ClosingLoc; \
4402  if (ParseMDFieldsImpl([&]() -> bool { \
4403  VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4404  return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4405  }, ClosingLoc)) \
4406  return true; \
4407  VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4408  } while (false)
4409 #define GET_OR_DISTINCT(CLASS, ARGS) \
4410  (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4411 
4412 /// ParseDILocationFields:
4413 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4414 /// isImplicitCode: true)
4415 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
4416 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4417  OPTIONAL(line, LineField, ); \
4418  OPTIONAL(column, ColumnField, ); \
4419  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4420  OPTIONAL(inlinedAt, MDField, ); \
4421  OPTIONAL(isImplicitCode, MDBoolField, (false));
4422  PARSE_MD_FIELDS();
4423 #undef VISIT_MD_FIELDS
4424 
4425  Result =
4426  GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4427  inlinedAt.Val, isImplicitCode.Val));
4428  return false;
4429 }
4430 
4431 /// ParseGenericDINode:
4432 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4433 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
4434 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4435  REQUIRED(tag, DwarfTagField, ); \
4436  OPTIONAL(header, MDStringField, ); \
4437  OPTIONAL(operands, MDFieldList, );
4438  PARSE_MD_FIELDS();
4439 #undef VISIT_MD_FIELDS
4440 
4441  Result = GET_OR_DISTINCT(GenericDINode,
4442  (Context, tag.Val, header.Val, operands.Val));
4443  return false;
4444 }
4445 
4446 /// ParseDISubrange:
4447 /// ::= !DISubrange(count: 30, lowerBound: 2)
4448 /// ::= !DISubrange(count: !node, lowerBound: 2)
4449 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
4450 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4451  REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4452  OPTIONAL(lowerBound, MDSignedField, );
4453  PARSE_MD_FIELDS();
4454 #undef VISIT_MD_FIELDS
4455 
4456  if (count.isMDSignedField())
4457  Result = GET_OR_DISTINCT(
4458  DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4459  else if (count.isMDField())
4460  Result = GET_OR_DISTINCT(
4461  DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4462  else
4463  return true;
4464 
4465  return false;
4466 }
4467 
4468 /// ParseDIEnumerator:
4469 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4470 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4471 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4472  REQUIRED(name, MDStringField, ); \
4473  REQUIRED(value, MDSignedOrUnsignedField, ); \
4474  OPTIONAL(isUnsigned, MDBoolField, (false));
4475  PARSE_MD_FIELDS();
4476 #undef VISIT_MD_FIELDS
4477 
4478  if (isUnsigned.Val && value.isMDSignedField())
4479  return TokError("unsigned enumerator with negative value");
4480 
4481  int64_t Value = value.isMDSignedField()
4482  ? value.getMDSignedValue()
4483  : static_cast<int64_t>(value.getMDUnsignedValue());
4484  Result =
4485  GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4486 
4487  return false;
4488 }
4489 
4490 /// ParseDIBasicType:
4491 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4492 /// encoding: DW_ATE_encoding, flags: 0)
4493 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
4494 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4495  OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4496  OPTIONAL(name, MDStringField, ); \
4497  OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4498  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4499  OPTIONAL(encoding, DwarfAttEncodingField, ); \
4500  OPTIONAL(flags, DIFlagField, );
4501  PARSE_MD_FIELDS();
4502 #undef VISIT_MD_FIELDS
4503 
4504  Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4505  align.Val, encoding.Val, flags.Val));
4506  return false;
4507 }
4508 
4509 /// ParseDIDerivedType:
4510 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4511 /// line: 7, scope: !1, baseType: !2, size: 32,
4512 /// align: 32, offset: 0, flags: 0, extraData: !3,
4513 /// dwarfAddressSpace: 3)
4514 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4515 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4516  REQUIRED(tag, DwarfTagField, ); \
4517  OPTIONAL(name, MDStringField, ); \
4518  OPTIONAL(file, MDField, ); \
4519  OPTIONAL(line, LineField, ); \
4520  OPTIONAL(scope, MDField, ); \
4521  REQUIRED(baseType, MDField, ); \
4522  OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4523  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4524  OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4525  OPTIONAL(flags, DIFlagField, ); \
4526  OPTIONAL(extraData, MDField, ); \
4527  OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4528  PARSE_MD_FIELDS();
4529 #undef VISIT_MD_FIELDS
4530 
4531  Optional<unsigned> DWARFAddressSpace;
4532  if (dwarfAddressSpace.Val != UINT32_MAX)
4533  DWARFAddressSpace = dwarfAddressSpace.Val;
4534 
4535  Result = GET_OR_DISTINCT(DIDerivedType,
4536  (Context, tag.Val, name.Val, file.Val, line.Val,
4537  scope.Val, baseType.Val, size.Val, align.Val,
4538  offset.Val, DWARFAddressSpace, flags.Val,
4539  extraData.Val));
4540  return false;
4541 }
4542 
4543 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
4544 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4545  REQUIRED(tag, DwarfTagField, ); \
4546  OPTIONAL(name, MDStringField, ); \
4547  OPTIONAL(file, MDField, ); \
4548  OPTIONAL(line, LineField, ); \
4549  OPTIONAL(scope, MDField, ); \
4550  OPTIONAL(baseType, MDField, ); \
4551  OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4552  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4553  OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4554  OPTIONAL(flags, DIFlagField, ); \
4555  OPTIONAL(elements, MDField, ); \
4556  OPTIONAL(runtimeLang, DwarfLangField, ); \
4557  OPTIONAL(vtableHolder, MDField, ); \
4558  OPTIONAL(templateParams, MDField, ); \
4559  OPTIONAL(identifier, MDStringField, ); \
4560  OPTIONAL(discriminator, MDField, );
4561  PARSE_MD_FIELDS();
4562 #undef VISIT_MD_FIELDS
4563 
4564  // If this has an identifier try to build an ODR type.
4565  if (identifier.Val)
4566  if (auto *CT = DICompositeType::buildODRType(
4567  Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4568  scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4569  elements.Val, runtimeLang.Val, vtableHolder.Val,
4570  templateParams.Val, discriminator.Val)) {
4571  Result = CT;
4572  return false;
4573  }
4574 
4575  // Create a new node, and save it in the context if it belongs in the type
4576  // map.
4577  Result = GET_OR_DISTINCT(
4579  (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4580  size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4581  runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4582  discriminator.Val));
4583  return false;
4584 }
4585 
4586 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4587 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4588  OPTIONAL(flags, DIFlagField, ); \
4589  OPTIONAL(cc, DwarfCCField, ); \
4590  REQUIRED(types, MDField, );
4591  PARSE_MD_FIELDS();
4592 #undef VISIT_MD_FIELDS
4593 
4595  (Context, flags.Val, cc.Val, types.Val));
4596  return false;
4597 }
4598 
4599 /// ParseDIFileType:
4600 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4601 /// checksumkind: CSK_MD5,
4602 /// checksum: "000102030405060708090a0b0c0d0e0f",
4603 /// source: "source file contents")
4604 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
4605  // The default constructed value for checksumkind is required, but will never
4606  // be used, as the parser checks if the field was actually Seen before using
4607  // the Val.
4608 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4609  REQUIRED(filename, MDStringField, ); \
4610  REQUIRED(directory, MDStringField, ); \
4611  OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4612  OPTIONAL(checksum, MDStringField, ); \
4613  OPTIONAL(source, MDStringField, );
4614  PARSE_MD_FIELDS();
4615 #undef VISIT_MD_FIELDS
4616 
4618  if (checksumkind.Seen && checksum.Seen)
4619  OptChecksum.emplace(checksumkind.Val, checksum.Val);
4620  else if (checksumkind.Seen || checksum.Seen)
4621  return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4622 
4623  Optional<MDString *> OptSource;
4624  if (source.Seen)
4625  OptSource = source.Val;
4626  Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4627  OptChecksum, OptSource));
4628  return false;
4629 }
4630 
4631 /// ParseDICompileUnit:
4632 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4633 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4634 /// splitDebugFilename: "abc.debug",
4635 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4636 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4637 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4638  if (!IsDistinct)
4639  return Lex.Error("missing 'distinct', required for !DICompileUnit");
4640 
4641 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4642  REQUIRED(language, DwarfLangField, ); \
4643  REQUIRED(file, MDField, (/* AllowNull */ false)); \
4644  OPTIONAL(producer, MDStringField, ); \
4645  OPTIONAL(isOptimized, MDBoolField, ); \
4646  OPTIONAL(flags, MDStringField, ); \
4647  OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4648  OPTIONAL(splitDebugFilename, MDStringField, ); \
4649  OPTIONAL(emissionKind, EmissionKindField, ); \
4650  OPTIONAL(enums, MDField, ); \
4651  OPTIONAL(retainedTypes, MDField, ); \
4652  OPTIONAL(globals, MDField, ); \
4653  OPTIONAL(imports, MDField, ); \
4654  OPTIONAL(macros, MDField, ); \
4655  OPTIONAL(dwoId, MDUnsignedField, ); \
4656  OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4657  OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4658  OPTIONAL(nameTableKind, NameTableKindField, ); \
4659  OPTIONAL(debugBaseAddress, MDBoolField, = false);
4660  PARSE_MD_FIELDS();
4661 #undef VISIT_MD_FIELDS
4662 
4663  Result = DICompileUnit::getDistinct(
4664  Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4665  runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4666  retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4667  splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4668  debugBaseAddress.Val);
4669  return false;
4670 }
4671 
4672 /// ParseDISubprogram:
4673 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4674 /// file: !1, line: 7, type: !2, isLocal: false,
4675 /// isDefinition: true, scopeLine: 8, containingType: !3,
4676 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4677 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4678 /// spFlags: 10, isOptimized: false, templateParams: !4,
4679 /// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4680 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4681  auto Loc = Lex.getLoc();
4682 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4683  OPTIONAL(scope, MDField, ); \
4684  OPTIONAL(name, MDStringField, ); \
4685  OPTIONAL(linkageName, MDStringField, ); \
4686  OPTIONAL(file, MDField, ); \
4687  OPTIONAL(line, LineField, ); \
4688  OPTIONAL(type, MDField, ); \
4689  OPTIONAL(isLocal, MDBoolField, ); \
4690  OPTIONAL(isDefinition, MDBoolField, (true)); \
4691  OPTIONAL(scopeLine, LineField, ); \
4692  OPTIONAL(containingType, MDField, ); \
4693  OPTIONAL(virtuality, DwarfVirtualityField, ); \
4694  OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4695  OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4696  OPTIONAL(flags, DIFlagField, ); \
4697  OPTIONAL(spFlags, DISPFlagField, ); \
4698  OPTIONAL(isOptimized, MDBoolField, ); \
4699  OPTIONAL(unit, MDField, ); \
4700  OPTIONAL(templateParams, MDField, ); \
4701  OPTIONAL(declaration, MDField, ); \
4702  OPTIONAL(retainedNodes, MDField, ); \
4703  OPTIONAL(thrownTypes, MDField, );
4704  PARSE_MD_FIELDS();
4705 #undef VISIT_MD_FIELDS
4706 
4707  // An explicit spFlags field takes precedence over individual fields in
4708  // older IR versions.
4709  DISubprogram::DISPFlags SPFlags =
4710  spFlags.Seen ? spFlags.Val
4711  : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4712  isOptimized.Val, virtuality.Val);
4713  if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4714  return Lex.Error(
4715  Loc,
4716  "missing 'distinct', required for !DISubprogram that is a Definition");
4717  Result = GET_OR_DISTINCT(
4718  DISubprogram,
4719  (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4720  type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4721  thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
4722  declaration.Val, retainedNodes.Val, thrownTypes.Val));
4723  return false;
4724 }
4725 
4726 /// ParseDILexicalBlock:
4727 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4728 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4729 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4730  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4731  OPTIONAL(file, MDField, ); \
4732  OPTIONAL(line, LineField, ); \
4733  OPTIONAL(column, ColumnField, );
4734  PARSE_MD_FIELDS();
4735 #undef VISIT_MD_FIELDS
4736 
4737  Result = GET_OR_DISTINCT(
4738  DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4739  return false;
4740 }
4741 
4742 /// ParseDILexicalBlockFile:
4743 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4744 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4745 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4746  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4747  OPTIONAL(file, MDField, ); \
4748  REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4749  PARSE_MD_FIELDS();
4750 #undef VISIT_MD_FIELDS
4751 
4753  (Context, scope.Val, file.Val, discriminator.Val));
4754  return false;
4755 }
4756 
4757 /// ParseDICommonBlock:
4758 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4759 bool LLParser::ParseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4760 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4761  REQUIRED(scope, MDField, ); \
4762  OPTIONAL(declaration, MDField, ); \
4763  OPTIONAL(name, MDStringField, ); \
4764  OPTIONAL(file, MDField, ); \
4765  OPTIONAL(line, LineField, );
4766  PARSE_MD_FIELDS();
4767 #undef VISIT_MD_FIELDS
4768 
4769  Result = GET_OR_DISTINCT(DICommonBlock,
4770  (Context, scope.Val, declaration.Val, name.Val,
4771  file.Val, line.Val));
4772  return false;
4773 }
4774 
4775 /// ParseDINamespace:
4776 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4777 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4778 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4779  REQUIRED(scope, MDField, ); \
4780  OPTIONAL(name, MDStringField, ); \
4781  OPTIONAL(exportSymbols, MDBoolField, );
4782  PARSE_MD_FIELDS();
4783 #undef VISIT_MD_FIELDS
4784 
4785  Result = GET_OR_DISTINCT(DINamespace,
4786  (Context, scope.Val, name.Val, exportSymbols.Val));
4787  return false;
4788 }
4789 
4790 /// ParseDIMacro:
4791 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4792 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4793 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4794  REQUIRED(type, DwarfMacinfoTypeField, ); \
4795  OPTIONAL(line, LineField, ); \
4796  REQUIRED(name, MDStringField, ); \
4797  OPTIONAL(value, MDStringField, );
4798  PARSE_MD_FIELDS();
4799 #undef VISIT_MD_FIELDS
4800 
4801  Result = GET_OR_DISTINCT(DIMacro,
4802  (Context, type.Val, line.Val, name.Val, value.Val));
4803  return false;
4804 }
4805 
4806 /// ParseDIMacroFile:
4807 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4808 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4809 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4810  OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4811  OPTIONAL(line, LineField, ); \
4812  REQUIRED(file, MDField, ); \
4813  OPTIONAL(nodes, MDField, );
4814  PARSE_MD_FIELDS();
4815 #undef VISIT_MD_FIELDS
4816 
4817  Result = GET_OR_DISTINCT(DIMacroFile,
4818  (Context, type.Val, line.Val, file.Val, nodes.Val));
4819  return false;
4820 }
4821 
4822 /// ParseDIModule:
4823 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4824 /// includePath: "/usr/include", sysroot: "/")
4825 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4826 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4827  REQUIRED(scope, MDField, ); \
4828  REQUIRED(name, MDStringField, ); \
4829  OPTIONAL(configMacros, MDStringField, ); \
4830  OPTIONAL(includePath, MDStringField, ); \
4831  OPTIONAL(sysroot, MDStringField, );
4832  PARSE_MD_FIELDS();
4833 #undef VISIT_MD_FIELDS
4834 
4835  Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4836  configMacros.Val, includePath.Val, sysroot.Val));
4837  return false;
4838 }
4839 
4840 /// ParseDITemplateTypeParameter:
4841 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4842 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4843 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4844  OPTIONAL(name, MDStringField, ); \
4845  REQUIRED(type, MDField, );
4846  PARSE_MD_FIELDS();
4847 #undef VISIT_MD_FIELDS
4848 
4849  Result =
4851  return false;
4852 }
4853 
4854 /// ParseDITemplateValueParameter:
4855 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4856 /// name: "V", type: !1, value: i32 7)
4857 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4858 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4859  OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4860  OPTIONAL(name, MDStringField, ); \
4861  OPTIONAL(type, MDField, ); \
4862  REQUIRED(value, MDField, );
4863  PARSE_MD_FIELDS();
4864 #undef VISIT_MD_FIELDS
4865 
4867  (Context, tag.Val, name.Val, type.Val, value.Val));
4868  return false;
4869 }
4870 
4871 /// ParseDIGlobalVariable:
4872 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4873 /// file: !1, line: 7, type: !2, isLocal: false,
4874 /// isDefinition: true, templateParams: !3,
4875 /// declaration: !4, align: 8)
4876 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4877 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4878  REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4879  OPTIONAL(scope, MDField, ); \
4880  OPTIONAL(linkageName, MDStringField, ); \
4881  OPTIONAL(file, MDField, ); \
4882  OPTIONAL(line, LineField, ); \
4883  OPTIONAL(type, MDField, ); \
4884  OPTIONAL(isLocal, MDBoolField, ); \
4885  OPTIONAL(isDefinition, MDBoolField, (true)); \
4886  OPTIONAL(templateParams, MDField, ); \
4887  OPTIONAL(declaration, MDField, ); \
4888  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4889  PARSE_MD_FIELDS();
4890 #undef VISIT_MD_FIELDS
4891 
4892  Result =
4894  (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4895  line.Val, type.Val, isLocal.Val, isDefinition.Val,
4896  declaration.Val, templateParams.Val, align.Val));
4897  return false;
4898 }
4899 
4900 /// ParseDILocalVariable:
4901 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4902 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4903 /// align: 8)
4904 /// ::= !DILocalVariable(scope: !0, name: "foo",
4905 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4906 /// align: 8)
4907 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4908 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4909  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4910  OPTIONAL(name, MDStringField, ); \
4911  OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4912  OPTIONAL(file, MDField, ); \
4913  OPTIONAL(line, LineField, ); \
4914  OPTIONAL(type, MDField, ); \
4915  OPTIONAL(flags, DIFlagField, ); \
4916  OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4917  PARSE_MD_FIELDS();
4918 #undef VISIT_MD_FIELDS
4919 
4921  (Context, scope.Val, name.Val, file.Val, line.Val,
4922  type.Val, arg.Val, flags.Val, align.Val));
4923  return false;
4924 }
4925 
4926 /// ParseDILabel:
4927 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4928 bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4929 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4930  REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4931  REQUIRED(name, MDStringField, ); \
4932  REQUIRED(file, MDField, ); \
4933  REQUIRED(line, LineField, );
4934  PARSE_MD_FIELDS();
4935 #undef VISIT_MD_FIELDS
4936 
4937  Result = GET_OR_DISTINCT(DILabel,
4938  (Context, scope.Val, name.Val, file.Val, line.Val));
4939  return false;
4940 }
4941 
4942 /// ParseDIExpression:
4943 /// ::= !DIExpression(0, 7, -1)
4944 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4945  assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4946  Lex.Lex();
4947 
4948  if (ParseToken(lltok::lparen, "expected '(' here"))
4949  return true;
4950 
4951  SmallVector<uint64_t, 8> Elements;
4952  if (Lex.getKind() != lltok::rparen)
4953  do {
4954  if (Lex.getKind() == lltok::DwarfOp) {
4955  if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4956  Lex.Lex();
4957  Elements.push_back(Op);
4958  continue;
4959  }
4960  return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4961  }
4962 
4963  if (Lex.getKind() == lltok::DwarfAttEncoding) {
4964  if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
4965  Lex.Lex();
4966  Elements.push_back(Op);
4967  continue;
4968  }
4969  return TokError(Twine("invalid DWARF attribute encoding '") + Lex.getStrVal() + "'");
4970  }
4971 
4972  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4973  return TokError("expected unsigned integer");
4974 
4975  auto &U = Lex.getAPSIntVal();
4976  if (U.ugt(UINT64_MAX))
4977  return TokError("element too large, limit is " + Twine(UINT64_MAX));
4978  Elements.push_back(U.getZExtValue());
4979  Lex.Lex();
4980  } while (EatIfPresent(lltok::comma));
4981 
4982  if (ParseToken(lltok::rparen, "expected ')' here"))
4983  return true;
4984 
4985  Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4986  return false;
4987 }
4988 
4989 /// ParseDIGlobalVariableExpression:
4990 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4991 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4992  bool IsDistinct) {
4993 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4994  REQUIRED(var, MDField, ); \
4995  REQUIRED(expr, MDField, );
4996  PARSE_MD_FIELDS();
4997 #undef VISIT_MD_FIELDS
4998 
4999  Result =
5000  GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5001  return false;
5002 }
5003 
5004 /// ParseDIObjCProperty:
5005 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5006 /// getter: "getFoo", attributes: 7, type: !2)
5007 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5008 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5009  OPTIONAL(name, MDStringField, ); \
5010  OPTIONAL(file, MDField, ); \
5011  OPTIONAL(line, LineField, ); \
5012  OPTIONAL(setter, MDStringField, ); \
5013  OPTIONAL(getter, MDStringField, ); \
5014  OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5015  OPTIONAL(type, MDField, );
5016  PARSE_MD_FIELDS();
5017 #undef VISIT_MD_FIELDS
5018 
5020  (Context, name.Val, file.Val, line.Val, setter.Val,
5021  getter.Val, attributes.Val, type.Val));
5022  return false;
5023 }
5024 
5025 /// ParseDIImportedEntity:
5026 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5027 /// line: 7, name: "foo")
5028 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5029 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5030  REQUIRED(tag, DwarfTagField, ); \
5031  REQUIRED(scope, MDField, ); \
5032  OPTIONAL(entity, MDField, ); \
5033  OPTIONAL(file, MDField, ); \
5034  OPTIONAL(line, LineField, ); \
5035  OPTIONAL(name, MDStringField, );
5036  PARSE_MD_FIELDS();
5037 #undef VISIT_MD_FIELDS
5038 
5039  Result = GET_OR_DISTINCT(
5041  (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
5042  return false;
5043 }
5044 
5045 #undef PARSE_MD_FIELD
5046 #undef NOP_FIELD
5047 #undef REQUIRE_FIELD
5048 #undef DECLARE_FIELD
5049 
5050 /// ParseMetadataAsValue
5051 /// ::= metadata i32 %local
5052 /// ::= metadata i32 @global
5053 /// ::= metadata i32 7
5054 /// ::= metadata !0
5055 /// ::= metadata !{...}
5056 /// ::= metadata !"string"
5057 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5058  // Note: the type 'metadata' has already been parsed.
5059  Metadata *MD;
5060  if (ParseMetadata(MD, &PFS))
5061  return true;
5062 
5063  V = MetadataAsValue::get(Context, MD);
5064  return false;
5065 }
5066 
5067 /// ParseValueAsMetadata
5068 /// ::= i32 %local
5069 /// ::= i32 @global
5070 /// ::= i32 7
5071 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5072  PerFunctionState *PFS) {
5073  Type *Ty;
5074  LocTy Loc;
5075  if (ParseType(Ty, TypeMsg, Loc))
5076  return true;
5077  if (Ty->isMetadataTy())
5078  return Error(Loc, "invalid metadata-value-metadata roundtrip");
5079 
5080  Value *V;
5081  if (ParseValue(Ty, V, PFS))
5082  return true;
5083 
5084  MD = ValueAsMetadata::get(V);
5085  return false;
5086 }
5087 
5088 /// ParseMetadata
5089 /// ::= i32 %local
5090 /// ::= i32 @global
5091 /// ::= i32 7
5092 /// ::= !42
5093 /// ::= !{...}
5094 /// ::= !"string"
5095 /// ::= !DILocation(...)
5096 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5097  if (Lex.getKind() == lltok::MetadataVar) {
5098  MDNode *N;
5099  if (ParseSpecializedMDNode(N))
5100  return true;
5101  MD = N;
5102  return false;
5103  }
5104 
5105  // ValueAsMetadata:
5106  // <type> <value>
5107  if (Lex.getKind() != lltok::exclaim)
5108  return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
5109 
5110  // '!'.
5111  assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5112  Lex.Lex();
5113 
5114  // MDString:
5115  // ::= '!' STRINGCONSTANT
5116  if (Lex.getKind() == lltok::StringConstant) {
5117  MDString *S;
5118  if (ParseMDString(S))
5119  return true;
5120  MD = S;
5121  return false;
5122  }
5123 
5124  // MDNode:
5125  // !{ ... }
5126  // !7
5127  MDNode *N;
5128  if (ParseMDNodeTail(N))
5129  return true;
5130  MD = N;
5131  return false;
5132 }
5133 
5134 //===----------------------------------------------------------------------===//
5135 // Function Parsing.
5136 //===----------------------------------------------------------------------===//
5137 
5138 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5139  PerFunctionState *PFS, bool IsCall) {
5140  if (Ty->isFunctionTy())
5141  return Error(ID.Loc, "functions are not values, refer to them as pointers");
5142 
5143  switch (ID.Kind) {
5144  case ValID::t_LocalID:
5145  if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5146  V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5147  return V == nullptr;
5148  case ValID::t_LocalName:
5149  if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5150  V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
5151  return V == nullptr;
5152  case ValID::t_InlineAsm: {
5153  if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5154  return Error(ID.Loc, "invalid type for inline asm constraint string");
5155  V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
5156  (ID.UIntVal >> 1) & 1,
5157  (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
5158  return false;
5159  }
5160  case ValID::t_GlobalName:
5161  V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
5162  return V == nullptr;
5163  case ValID::t_GlobalID:
5164  V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5165  return V == nullptr;
5166  case ValID::t_APSInt:
5167  if (!Ty->isIntegerTy())
5168  return Error(ID.Loc, "integer constant must have integer type");
5171  return false;
5172  case ValID::t_APFloat:
5173  if (!Ty->isFloatingPointTy() ||
5175  return Error(ID.Loc, "floating point constant invalid for type");
5176 
5177  // The lexer has no type info, so builds all half, float, and double FP
5178  // constants as double. Fix this here. Long double does not need this.
5179  if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5180  bool Ignored;
5181  if (Ty->isHalfTy())
5183  &Ignored);
5184  else if (Ty->isFloatTy())
5186  &Ignored);
5187  }
5189 
5190  if (V->getType() != Ty)
5191  return Error(ID.Loc, "floating point constant does not have type '" +
5192  getTypeString(Ty) + "'");
5193 
5194  return false;
5195  case ValID::t_Null:
5196  if (!Ty->isPointerTy())
5197  return Error(ID.Loc, "null must be a pointer type");
5198  V = ConstantPointerNull::get(cast<PointerType>(Ty));
5199  return false;
5200  case ValID::t_Undef:
5201  // FIXME: LabelTy should not be a first-class type.
5202  if (!Ty->isFirstClassType() || Ty->isLabelTy())
5203  return Error(ID.Loc, "invalid type for undef constant");
5204  V = UndefValue::get(Ty);
5205  return false;
5206  case ValID::t_EmptyArray:
5207  if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5208  return Error(ID.Loc, "invalid empty array initializer");
5209  V = UndefValue::get(Ty);
5210  return false;
5211  case ValID::t_Zero:
5212  // FIXME: LabelTy should not be a first-class type.
5213  if (!Ty->isFirstClassType() || Ty->isLabelTy())
5214  return Error(ID.Loc, "invalid type for null constant");
5215  V = Constant::getNullValue(Ty);
5216  return false;
5217  case ValID::t_None:
5218  if (!Ty->isTokenTy())
5219  return Error(ID.Loc, "invalid type for none constant");
5220  V = Constant::getNullValue(Ty);
5221  return false;
5222  case ValID::t_Constant:
5223  if (ID.ConstantVal->getType() != Ty)
5224  return Error(ID.Loc, "constant expression type mismatch");
5225 
5226  V = ID.ConstantVal;
5227  return false;
5230  if (StructType *ST = dyn_cast<StructType>(Ty)) {
5231  if (ST->getNumElements() != ID.UIntVal)
5232  return Error(ID.Loc,
5233  "initializer with struct type has wrong # elements");
5234  if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5235  return Error(ID.Loc, "packed'ness of initializer and type don't match");
5236 
5237  // Verify that the elements are compatible with the structtype.
5238  for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5239  if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5240  return Error(ID.Loc, "element " + Twine(i) +
5241  " of struct initializer doesn't match struct element type");
5242 
5243  V = ConstantStruct::get(
5244  ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5245  } else
5246  return Error(ID.Loc, "constant expression type mismatch");
5247  return false;
5248  }
5249  llvm_unreachable("Invalid ValID");
5250 }
5251 
5252 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5253  C = nullptr;
5254  ValID ID;
5255  auto Loc = Lex.getLoc();
5256  if (ParseValID(ID, /*PFS=*/nullptr))
5257  return true;
5258  switch (ID.Kind) {
5259  case ValID::t_APSInt:
5260  case ValID::t_APFloat:
5261  case ValID::t_Undef:
5262  case ValID::t_Constant:
5265  Value *V;
5266  if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
5267  return true;
5268  assert(isa<Constant>(V) && "Expected a constant value");
5269  C = cast<Constant>(V);
5270  return false;
5271  }
5272  case ValID::t_Null:
5273  C = Constant::getNullValue(Ty);
5274  return false;
5275  default:
5276  return Error(Loc, "expected a constant value");
5277  }
5278 }
5279 
5280 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5281  V = nullptr;
5282  ValID ID;
5283  return ParseValID(ID, PFS) ||
5284  ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
5285 }
5286 
5287 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5288  Type *Ty = nullptr;
5289  return ParseType(Ty) ||
5290  ParseValue(Ty, V, PFS);
5291 }
5292 
5293 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5294  PerFunctionState &PFS) {
5295  Value *V;
5296  Loc = Lex.getLoc();
5297  if (ParseTypeAndValue(V, PFS)) return true;
5298  if (!isa<BasicBlock>(V))
5299  return Error(Loc, "expected a basic block");
5300  BB = cast<BasicBlock>(V);
5301  return false;
5302 }
5303 
5304 /// FunctionHeader
5305 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5306 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5307 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5308 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5309 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5310  // Parse the linkage.
5311  LocTy LinkageLoc = Lex.getLoc();
5312  unsigned Linkage;
5313  unsigned Visibility;
5314  unsigned DLLStorageClass;
5315  bool DSOLocal;
5316  AttrBuilder RetAttrs;
5317  unsigned CC;
5318  bool HasLinkage;
5319  Type *RetType = nullptr;
5320  LocTy RetTypeLoc = Lex.getLoc();
5321  if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5322  DSOLocal) ||
5323  ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5324  ParseType(RetType, RetTypeLoc, true /*void allowed*/))
5325  return true;
5326 
5327  // Verify that the linkage is ok.
5328  switch ((GlobalValue::LinkageTypes)Linkage) {
5330  break; // always ok.
5332  if (isDefine)
5333  return Error(LinkageLoc, "invalid linkage for function definition");
5334  break;
5342  if (!isDefine)
5343  return Error(LinkageLoc, "invalid linkage for function declaration");
5344  break;
5347  return Error(LinkageLoc, "invalid function linkage type");
5348  }
5349 
5350  if (!isValidVisibilityForLinkage(Visibility, Linkage))
5351  return Error(LinkageLoc,
5352  "symbol with local linkage must have default visibility");
5353 
5354  if (!FunctionType::isValidReturnType(RetType))
5355  return Error(RetTypeLoc, "invalid function return type");
5356 
5357  LocTy NameLoc = Lex.getLoc();
5358 
5359  std::string FunctionName;
5360  if (Lex.getKind() == lltok::GlobalVar) {
5361  FunctionName = Lex.getStrVal();
5362  } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5363  unsigned NameID = Lex.getUIntVal();
5364 
5365  if (NameID != NumberedVals.size())
5366  return TokError("function expected to be numbered '%" +
5367  Twine(NumberedVals.size()) + "'");
5368  } else {
5369  return TokError("expected function name");
5370  }
5371 
5372  Lex.Lex();
5373 
5374  if (Lex.getKind() != lltok::lparen)
5375  return TokError("expected '(' in function argument list");
5376 
5377  SmallVector<ArgInfo, 8> ArgList;
5378  bool isVarArg;
5379  AttrBuilder FuncAttrs;
5380  std::vector<unsigned> FwdRefAttrGrps;
5381  LocTy BuiltinLoc;
5382  std::string Section;
5383  std::string Partition;
5384  MaybeAlign Alignment;
5385  std::string GC;
5387  unsigned AddrSpace = 0;
5388  Constant *Prefix = nullptr;
5389  Constant *Prologue = nullptr;
5390  Constant *PersonalityFn = nullptr;
5391  Comdat *C;
5392 
5393  if (ParseArgumentList(ArgList, isVarArg) ||
5394  ParseOptionalUnnamedAddr(UnnamedAddr) ||
5395  ParseOptionalProgramAddrSpace(AddrSpace) ||
5396  ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5397  BuiltinLoc) ||
5398  (EatIfPresent(lltok::kw_section) &&
5399  ParseStringConstant(Section)) ||
5400  (EatIfPresent(lltok::kw_partition) &&
5401  ParseStringConstant(Partition)) ||
5402  parseOptionalComdat(FunctionName, C) ||
5403  ParseOptionalAlignment(Alignment) ||
5404  (EatIfPresent(lltok::kw_gc) &&
5405  ParseStringConstant(GC)) ||
5406  (EatIfPresent(lltok::kw_prefix) &&
5407  ParseGlobalTypeAndValue(Prefix)) ||
5408  (EatIfPresent(lltok::kw_prologue) &&
5409  ParseGlobalTypeAndValue(Prologue)) ||
5410  (EatIfPresent(lltok::kw_personality) &&
5411  ParseGlobalTypeAndValue(PersonalityFn)))
5412  return true;
5413 
5414  if (FuncAttrs.contains(Attribute::Builtin))
5415  return Error(BuiltinLoc, "'builtin' attribute not valid on function");
5416 
5417  // If the alignment was parsed as an attribute, move to the alignment field.
5418  if (FuncAttrs.hasAlignmentAttr()) {
5419  Alignment = FuncAttrs.getAlignment();
5420  FuncAttrs.removeAttribute(Attribute::Alignment);
5421  }
5422 
5423  // Okay, if we got here, the function is syntactically valid. Convert types
5424  // and do semantic checks.
5425  std::vector<Type*> ParamTypeList;
5427 
5428  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5429  ParamTypeList.push_back(ArgList[i].Ty);
5430  Attrs.push_back(ArgList[i].Attrs);
5431  }
5432 
5433  AttributeList PAL =
5435  AttributeSet::get(Context, RetAttrs), Attrs);
5436 
5437  if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
5438  return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5439 
5440  FunctionType *FT =
5441  FunctionType::get(RetType, ParamTypeList, isVarArg);
5442  PointerType *PFT = PointerType::get(FT, AddrSpace);
5443 
5444  Fn = nullptr;
5445  if (!FunctionName.empty()) {
5446  // If this was a definition of a forward reference, remove the definition
5447  // from the forward reference table and fill in the forward ref.
5448  auto FRVI = ForwardRefVals.find(FunctionName);
5449  if (FRVI != ForwardRefVals.end()) {
5450  Fn = M->getFunction(FunctionName);
5451  if (!Fn)
5452  return Error(FRVI->second.second, "invalid forward reference to "
5453  "function as global value!");
5454  if (Fn->getType() != PFT)
5455  return Error(FRVI->second.second, "invalid forward reference to "
5456  "function '" + FunctionName + "' with wrong type: "
5457  "expected '" + getTypeString(PFT) + "' but was '" +
5458  getTypeString(Fn->getType()) + "'");
5459  ForwardRefVals.erase(FRVI);
5460  } else if ((Fn = M->getFunction(FunctionName))) {
5461  // Reject redefinitions.
5462  return Error(NameLoc, "invalid redefinition of function '" +
5463  FunctionName + "'");
5464  } else if (M->getNamedValue(FunctionName)) {
5465  return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5466  }
5467 
5468  } else {
5469  // If this is a definition of a forward referenced function, make sure the
5470  // types agree.
5471  auto I = ForwardRefValIDs.find(NumberedVals.size());
5472  if (I != ForwardRefValIDs.end()) {
5473  Fn = cast<Function>(I->second.first);
5474  if (Fn->getType() != PFT)
5475  return Error(NameLoc, "type of definition and forward reference of '@" +
5476  Twine(NumberedVals.size()) + "' disagree: "
5477  "expected '" + getTypeString(PFT) + "' but was '" +
5478  getTypeString(Fn->getType()) + "'");
5479  ForwardRefValIDs.erase(I);
5480  }
5481  }
5482 
5483  if (!Fn)
5484  Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5485  FunctionName, M);
5486  else // Move the forward-reference to the correct spot in the module.
5487  M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5488 
5489  assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5490 
5491  if (FunctionName.empty())
5492  NumberedVals.push_back(Fn);
5493 
5494  Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5495  maybeSetDSOLocal(DSOLocal, *Fn);
5498  Fn->setCallingConv(CC);
5499  Fn->setAttributes(PAL);
5500  Fn->setUnnamedAddr(UnnamedAddr);
5501  Fn->setAlignment(MaybeAlign(Alignment));
5502  Fn->setSection(Section);
5503  Fn->setPartition(Partition);
5504  Fn->setComdat(C);
5505  Fn->setPersonalityFn(PersonalityFn);
5506  if (!GC.empty()) Fn->setGC(GC);
5507  Fn->setPrefixData(Prefix);
5508  Fn->setPrologueData(Prologue);
5509  ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5510 
5511  // Add all of the arguments we parsed to the function.
5512  Function::arg_iterator ArgIt = Fn->arg_begin();
5513  for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5514  // If the argument has a name, insert it into the argument symbol table.
5515  if (ArgList[i].Name.empty()) continue;
5516 
5517  // Set the name, if it conflicted, it will be auto-renamed.
5518  ArgIt->setName(ArgList[i].Name);
5519 
5520  if (ArgIt->getName() != ArgList[i].Name)
5521  return Error(ArgList[i].Loc, "redefinition of argument '%" +
5522  ArgList[i].Name + "'");
5523  }
5524 
5525  if (isDefine)
5526  return false;
5527 
5528  // Check the declaration has no block address forward references.
5529  ValID ID;
5530  if (FunctionName.empty()) {
5531  ID.Kind = ValID::t_GlobalID;
5532  ID.UIntVal = NumberedVals.size() - 1;
5533  } else {
5535  ID.StrVal = FunctionName;
5536  }
5537  auto Blocks = ForwardRefBlockAddresses.find(ID);
5538  if (Blocks != ForwardRefBlockAddresses.end())
5539  return Error(Blocks->first.Loc,
5540  "cannot take blockaddress inside a declaration");
5541  return false;
5542 }
5543 
5544 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5545  ValID ID;
5546  if (FunctionNumber == -1) {
5548  ID.StrVal = F.getName();
5549  } else {
5550  ID.Kind = ValID::t_GlobalID;
5551  ID.UIntVal = FunctionNumber;
5552  }
5553 
5554  auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5555  if (Blocks == P.ForwardRefBlockAddresses.end())
5556  return false;
5557 
5558  for (const auto &I : Blocks->second) {
5559  const ValID &BBID = I.first;
5560  GlobalValue *GV = I.second;
5561 
5562  assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5563  "Expected local id or name");
5564  BasicBlock *BB;
5565  if (BBID.Kind == ValID::t_LocalName)
5566  BB = GetBB(BBID.StrVal, BBID.Loc);
5567  else
5568  BB = GetBB(BBID.UIntVal, BBID.Loc);
5569  if (!BB)
5570  return P.Error(BBID.Loc, "referenced value is not a basic block");
5571 
5573  GV->eraseFromParent();
5574  }
5575 
5576  P.ForwardRefBlockAddresses.erase(Blocks);
5577  return false;
5578 }
5579 
5580 /// ParseFunctionBody
5581 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5582 bool LLParser::ParseFunctionBody(Function &Fn) {
5583  if (Lex.getKind() != lltok::lbrace)
5584  return TokError("expected '{' in function body");
5585  Lex.Lex(); // eat the {.
5586 
5587  int FunctionNumber = -1;
5588  if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5589 
5590  PerFunctionState PFS(*this, Fn, FunctionNumber);
5591 
5592  // Resolve block addresses and allow basic blocks to be forward-declared
5593  // within this function.
5594  if (PFS.resolveForwardRefBlockAddresses())
5595  return true;
5596  SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5597 
5598  // We need at least one basic block.
5599  if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5600  return TokError("function body requires at least one basic block");
5601 
5602  while (Lex.getKind() != lltok::rbrace &&
5603  Lex.getKind() != lltok::kw_uselistorder)
5604  if (ParseBasicBlock(PFS)) return true;
5605 
5606  while (Lex.getKind() != lltok::rbrace)
5607  if (ParseUseListOrder(&PFS))
5608  return true;
5609 
5610  // Eat the }.
5611  Lex.Lex();
5612 
5613  // Verify function is ok.
5614  return PFS.FinishFunction();
5615 }
5616 
5617 /// ParseBasicBlock
5618 /// ::= (LabelStr|LabelID)? Instruction*
5619 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5620  // If this basic block starts out with a name, remember it.
5621  std::string Name;
5622  int NameID = -1;
5623  LocTy NameLoc = Lex.getLoc();
5624  if (Lex.getKind() == lltok::LabelStr) {
5625  Name = Lex.getStrVal();
5626  Lex.Lex();
5627  } else if (Lex.getKind() == lltok::LabelID) {
5628  NameID = Lex.getUIntVal();
5629  Lex.Lex();
5630  }
5631 
5632  BasicBlock *BB = PFS.DefineBB(Name, NameID, NameLoc);
5633  if (!BB)
5634  return true;
5635 
5636  std::string NameStr;
5637 
5638  // Parse the instructions in this block until we get a terminator.
5639  Instruction *Inst;
5640  do {
5641  // This instruction may have three possibilities for a name: a) none
5642  // specified, b) name specified "%foo =", c) number specified: "%4 =".
5643  LocTy NameLoc = Lex.getLoc();
5644  int NameID = -1;
5645  NameStr = "";
5646 
5647  if (Lex.getKind() == lltok::LocalVarID) {
5648  NameID = Lex.getUIntVal();
5649  Lex.Lex();
5650  if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5651  return true;
5652  } else if (Lex.getKind() == lltok::LocalVar) {
5653  NameStr = Lex.getStrVal();
5654  Lex.Lex();
5655  if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5656  return true;
5657  }
5658 
5659  switch (ParseInstruction(Inst, BB, PFS)) {
5660  default: llvm_unreachable("Unknown ParseInstruction result!");
5661  case InstError: return true;
5662  case InstNormal:
5663  BB->getInstList().push_back(Inst);
5664 
5665  // With a normal result, we check to see if the instruction is followed by
5666  // a comma and metadata.
5667  if (EatIfPresent(lltok::comma))
5668  if (ParseInstructionMetadata(*Inst))
5669  return true;
5670  break;
5671  case InstExtraComma:
5672  BB->getInstList().push_back(Inst);
5673 
5674  // If the instruction parser ate an extra comma at the end of it, it
5675  // *must* be followed by metadata.
5676  if (ParseInstructionMetadata(*Inst))
5677  return true;
5678  break;
5679  }
5680 
5681  // Set the name on the instruction.
5682  if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5683  } while (!Inst->isTerminator());
5684 
5685  return false;
5686 }
5687 
5688 //===----------------------------------------------------------------------===//
5689 // Instruction Parsing.
5690 //===----------------------------------------------------------------------===//
5691 
5692 /// ParseInstruction - Parse one of the many different instructions.
5693 ///
5694 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5695  PerFunctionState &PFS) {
5696  lltok::Kind Token = Lex.getKind();
5697  if (Token == lltok::Eof)
5698  return TokError("found end of file when expecting more instructions");
5699  LocTy Loc = Lex.getLoc();
5700  unsigned KeywordVal = Lex.getUIntVal();
5701  Lex.Lex(); // Eat the keyword.
5702 
5703  switch (Token) {
5704  default: return Error(Loc, "expected instruction opcode");
5705  // Terminator Instructions.
5706  case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5707  case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5708  case lltok::kw_br: return ParseBr(Inst, PFS);
5709  case lltok::kw_switch: return ParseSwitch(Inst, PFS);
5710  case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
5711  case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
5712  case lltok::kw_resume: return ParseResume(Inst, PFS);
5713  case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5714  case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
5715  case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5716  case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
5717  case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
5718  case lltok::kw_callbr: return ParseCallBr(Inst, PFS);
5719  // Unary Operators.
5720  case lltok::kw_fneg: {
5721  FastMathFlags FMF = EatFastMathFlagsIfPresent();
5722  int Res = ParseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/true);
5723  if (Res != 0)
5724  return Res;
5725  if (FMF.any())
5726  Inst->setFastMathFlags(FMF);
5727  return false;
5728  }
5729  // Binary Operators.
5730  case lltok::kw_add:
5731  case lltok::kw_sub:
5732  case lltok::kw_mul:
5733  case lltok::kw_shl: {
5734  bool NUW = EatIfPresent(lltok::kw_nuw);
5735  bool NSW = EatIfPresent(lltok::kw_nsw);
5736  if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5737 
5738  if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true;
5739 
5740  if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5741  if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5742  return false;
5743  }
5744  case lltok::kw_fadd:
5745  case lltok::kw_fsub:
5746  case lltok::kw_fmul:
5747  case lltok::kw_fdiv:
5748  case lltok::kw_frem: {
5749  FastMathFlags FMF = EatFastMathFlagsIfPresent();
5750  int Res = ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/true);
5751  if (Res != 0)
5752  return Res;
5753  if (FMF.any())
5754  Inst->setFastMathFlags(FMF);
5755  return 0;
5756  }
5757 
5758  case lltok::kw_sdiv:
5759  case lltok::kw_udiv:
5760  case lltok::kw_lshr:
5761  case lltok::kw_ashr: {
5762  bool Exact = EatIfPresent(lltok::kw_exact);
5763 
5764  if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true;
5765  if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5766  return false;
5767  }
5768 
5769  case lltok::kw_urem:
5770  case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal,
5771  /*IsFP*/false);
5772  case lltok::kw_and:
5773  case lltok::kw_or:
5774  case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
5775  case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5776  case lltok::kw_fcmp: {
5777  FastMathFlags FMF = EatFastMathFlagsIfPresent();
5778  int Res = ParseCompare(Inst, PFS, KeywordVal);
5779  if (Res != 0)
5780  return Res;
5781  if (FMF.any())
5782  Inst->setFastMathFlags(FMF);
5783  return 0;
5784  }
5785 
5786  // Casts.
5787  case lltok::kw_trunc:
5788  case lltok::kw_zext:
5789  case lltok::kw_sext:
5790  case lltok::kw_fptrunc:
5791  case lltok::kw_fpext:
5792  case lltok::kw_bitcast:
5794  case lltok::kw_uitofp:
5795  case lltok::kw_sitofp:
5796  case lltok::kw_fptoui:
5797  case lltok::kw_fptosi:
5798  case lltok::kw_inttoptr:
5799  case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5800  // Other.
5801  case lltok::kw_select: {
5802  FastMathFlags FMF = EatFastMathFlagsIfPresent();
5803  int Res = ParseSelect(Inst, PFS);
5804  if (Res != 0)
5805  return Res;
5806  if (FMF.any()) {
5807  if (!isa<FPMathOperator>(Inst))
5808  return Error(Loc, "fast-math-flags specified for select without "
5809  "floating-point scalar or vector return type");
5810  Inst->setFastMathFlags(FMF);
5811  }
5812  return 0;
5813  }
5814  case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5815  case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5816  case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5817  case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5818  case lltok::kw_phi: {
5819  FastMathFlags FMF = EatFastMathFlagsIfPresent();
5820  int Res = ParsePHI(Inst, PFS);
5821  if (Res != 0)
5822  return Res;
5823  if (FMF.any()) {
5824  if (!isa<FPMathOperator>(Inst))
5825  return Error(Loc, "fast-math-flags specified for phi without "
5826  "floating-point scalar or vector return type");
5827  Inst->setFastMathFlags(FMF);
5828  }
5829  return 0;
5830  }
5831  case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5832  case lltok::kw_freeze: return ParseFreeze(Inst, PFS);
5833  // Call.
5834  case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5835  case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5836  case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5837  case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5838  // Memory.
5839  case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5840  case lltok::kw_load: return ParseLoad(Inst, PFS);
5841  case lltok::kw_store: return ParseStore(Inst, PFS);
5842  case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5843  case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5844  case lltok::kw_fence: return ParseFence(Inst, PFS);
5845  case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5846  case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5847  case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5848  }
5849 }
5850 
5851 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5852 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5853  if (Opc == Instruction::FCmp) {
5854  switch (Lex.getKind()) {
5855  default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5856  case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5857  case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5858  case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5859  case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5860  case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5861  case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5862  case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5863  case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5864  case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5865  case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5866  case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5867  case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5868  case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5869  case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5870  case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5871  case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5872  }
5873  } else {
5874  switch (Lex.getKind()) {
5875  default: return TokError("expected icmp predicate (e.g. 'eq')");
5876  case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5877  case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5878  case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5879  case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5880  case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5881  case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5882  case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5883  case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5884  case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5885  case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5886  }
5887  }
5888  Lex.Lex();
5889  return false;
5890 }
5891 
5892 //===----------------------------------------------------------------------===//
5893 // Terminator Instructions.
5894 //===----------------------------------------------------------------------===//
5895 
5896 /// ParseRet - Parse a return instruction.
5897 /// ::= 'ret' void (',' !dbg, !1)*
5898 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5899 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5900  PerFunctionState &PFS) {
5901  SMLoc TypeLoc = Lex.getLoc();
5902  Type *Ty = nullptr;
5903  if (ParseType(Ty, true /*void allowed*/)) return true;
5904 
5905  Type *ResType = PFS.getFunction().getReturnType();
5906 
5907  if (Ty->isVoidTy()) {
5908  if (!ResType->isVoidTy())
5909  return Error(TypeLoc, "value doesn't match function result type '" +
5910  getTypeString(ResType) + "'");
5911 
5912  Inst = ReturnInst::Create(Context);
5913  return false;
5914  }
5915 
5916  Value *RV;
5917  if (ParseValue(Ty, RV, PFS)) return true;
5918 
5919  if (ResType != RV->getType())
5920  return Error(TypeLoc, "value doesn't match function result type '" +
5921  getTypeString(ResType) + "'");
5922 
5923  Inst = ReturnInst::Create(Context, RV);
5924  return false;
5925 }
5926 
5927 /// ParseBr
5928 /// ::= 'br' TypeAndValue
5929 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5930 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5931  LocTy Loc, Loc2;
5932  Value *Op0;
5933  BasicBlock *Op1, *Op2;
5934  if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5935 
5936  if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5937  Inst = BranchInst::Create(BB);
5938  return false;
5939  }
5940 
5941  if (Op0->getType() != Type::getInt1Ty(Context))
5942  return Error(Loc, "branch condition must have 'i1' type");
5943 
5944  if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5945  ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5946  ParseToken(lltok::comma, "expected ',' after true destination") ||
5947  ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5948  return true;
5949 
5950  Inst = BranchInst::Create(Op1, Op2, Op0);
5951  return false;
5952 }
5953 
5954 /// ParseSwitch
5955 /// Instruction
5956 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5957 /// JumpTable
5958 /// ::= (TypeAndValue ',' TypeAndValue)*
5959 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5960  LocTy CondLoc, BBLoc;
5961  Value *Cond;
5962  BasicBlock *DefaultBB;
5963  if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5964  ParseToken(lltok::comma, "expected ',' after switch condition") ||
5965  ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5966  ParseToken(lltok::lsquare, "expected '[' with switch table"))
5967  return true;
5968 
5969  if (!Cond->getType()->isIntegerTy())
5970  return Error(CondLoc, "switch condition must have integer type");
5971 
5972  // Parse the jump table pairs.
5973  SmallPtrSet<Value*, 32> SeenCases;
5975  while (Lex.getKind() != lltok::rsquare) {
5976  Value *Constant;
5977  BasicBlock *DestBB;
5978 
5979  if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5980  ParseToken(lltok::comma, "expected ',' after case value") ||
5981  ParseTypeAndBasicBlock(DestBB, PFS))
5982  return true;
5983 
5984  if (!SeenCases.insert(Constant).second)
5985  return Error(CondLoc, "duplicate case value in switch");
5986  if (!isa<ConstantInt>(Constant))
5987  return Error(CondLoc, "case value is not a constant integer");
5988 
5989  Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5990  }
5991 
5992  Lex.Lex(); // Eat the ']'.
5993 
5994  SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5995  for (unsigned i = 0, e = Table.size(); i != e; ++i)
5996  SI->addCase(Table[i].first, Table[i].second);
5997  Inst = SI;
5998  return false;
5999 }
6000 
6001 /// ParseIndirectBr
6002 /// Instruction
6003 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
6004 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
6005  LocTy AddrLoc;
6006  Value *Address;
6007  if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
6008  ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
6009  ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
6010  return true;
6011 
6012  if (!Address->getType()->isPointerTy())
6013  return Error(AddrLoc, "indirectbr address must have pointer type");
6014 
6015  // Parse the destination list.
6017 
6018  if (Lex.getKind() != lltok::rsquare) {
6019  BasicBlock *DestBB;
6020  if (ParseTypeAndBasicBlock(DestBB, PFS))
6021  return true;
6022  DestList.push_back(DestBB);
6023 
6024  while (EatIfPresent(lltok::comma)) {
6025  if (ParseTypeAndBasicBlock(DestBB, PFS))
6026  return true;
6027  DestList.push_back(DestBB);
6028  }
6029  }
6030 
6031  if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
6032  return true;
6033 
6034  IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
6035  for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6036  IBI->addDestination(DestList[i]);
6037  Inst = IBI;
6038  return false;
6039 }
6040 
6041 /// ParseInvoke
6042 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6043 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6044 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6045  LocTy CallLoc = Lex.getLoc();
6046  AttrBuilder RetAttrs, FnAttrs;
6047  std::vector<unsigned> FwdRefAttrGrps;
6048  LocTy NoBuiltinLoc;
6049  unsigned CC;
6050  unsigned InvokeAddrSpace;
6051  Type *RetType = nullptr;
6052  LocTy RetTypeLoc;
6053  ValID CalleeID;
6056 
6057  BasicBlock *NormalBB, *UnwindBB;
6058  if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6059  ParseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6060  ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6061  ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
6062  ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6063  NoBuiltinLoc) ||
6064  ParseOptionalOperandBundles(BundleList, PFS) ||
6065  ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
6066  ParseTypeAndBasicBlock(NormalBB, PFS) ||
6067  ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6068  ParseTypeAndBasicBlock(UnwindBB, PFS))
6069  return true;
6070 
6071  // If RetType is a non-function pointer type, then this is the short syntax
6072  // for the call, which means that RetType is just the return type. Infer the
6073  // rest of the function argument types from the arguments that are present.
6074  FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6075  if (!Ty) {
6076  // Pull out the types of all of the arguments...
6077  std::vector<Type*> ParamTypes;
6078  for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6079  ParamTypes.push_back(ArgList[i].V->getType());
6080 
6081  if (!FunctionType::isValidReturnType(RetType))
6082  return Error(RetTypeLoc, "Invalid result type for LLVM function");
6083 
6084  Ty = FunctionType::get(RetType, ParamTypes, false);
6085  }
6086 
6087  CalleeID.FTy = Ty;
6088 
6089  // Look up the callee.
6090  Value *Callee;
6091  if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6092  Callee, &PFS, /*IsCall=*/true))
6093  return true;
6094 
6095  // Set up the Attribute for the function.
6098 
6099  // Loop through FunctionType's arguments and ensure they are specified
6100  // correctly. Also, gather any parameter attributes.
6103  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6104  Type *ExpectedTy = nullptr;
6105  if (I != E) {
6106  ExpectedTy = *I++;
6107  } else if (!Ty->isVarArg()) {
6108  return Error(ArgList[i].Loc, "too many arguments specified");
6109  }
6110 
6111  if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6112  return Error(ArgList[i].Loc, "argument is not of expected type '" +
6113  getTypeString(ExpectedTy) + "'");
6114  Args.push_back(ArgList[i].V);
6115  ArgAttrs.push_back(ArgList[i].Attrs);
6116  }
6117 
6118  if (I != E)
6119  return Error(CallLoc, "not enough parameters specified for call");
6120 
6121  if (FnAttrs.hasAlignmentAttr())
6122  return Error(CallLoc, "invoke instructions may not have an alignment");
6123 
6124  // Finish off the Attribute and check them
6125  AttributeList PAL =
6127  AttributeSet::get(Context, RetAttrs), ArgAttrs);
6128 
6129  InvokeInst *II =
6130  InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6131  II->setCallingConv(CC);
6132  II->setAttributes(PAL);
6133  ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6134  Inst = II;
6135  return false;
6136 }
6137 
6138 /// ParseResume
6139 /// ::= 'resume' TypeAndValue
6140 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
6141  Value *Exn; LocTy ExnLoc;
6142  if (ParseTypeAndValue(Exn, ExnLoc, PFS))
6143  return true;
6144 
6145  ResumeInst *RI = ResumeInst::Create(Exn);
6146  Inst = RI;
6147  return false;
6148 }
6149 
6150 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
6151  PerFunctionState &PFS) {
6152  if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6153  return true;
6154 
6155  while (Lex.getKind() != lltok::rsquare) {
6156  // If this isn't the first argument, we need a comma.
6157  if (!Args.empty() &&
6158  ParseToken(lltok::comma, "expected ',' in argument list"))
6159  return true;
6160 
6161  // Parse the argument.
6162  LocTy ArgLoc;
6163  Type *ArgTy = nullptr;
6164  if (ParseType(ArgTy, ArgLoc))
6165  return true;
6166 
6167  Value *V;
6168  if (ArgTy->isMetadataTy()) {
6169  if (ParseMetadataAsValue(V, PFS))
6170  return true;
6171  } else {
6172  if (ParseValue(ArgTy, V, PFS))
6173  return true;
6174  }
6175  Args.push_back(V);
6176  }
6177 
6178  Lex.Lex(); // Lex the ']'.
6179  return false;
6180 }
6181 
6182 /// ParseCleanupRet
6183 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6184 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6185  Value *CleanupPad = nullptr;
6186 
6187  if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6188  return true;
6189 
6190  if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6191  return true;
6192 
6193  if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6194  return true;
6195 
6196  BasicBlock *UnwindBB = nullptr;
6197  if (Lex.getKind() == lltok::kw_to) {
6198  Lex.Lex();
6199  if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6200  return true;
6201  } else {
6202  if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
6203  return true;
6204  }
6205  }
6206 
6207  Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6208  return false;
6209 }
6210 
6211 /// ParseCatchRet
6212 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6213 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6214  Value *CatchPad = nullptr;
6215 
6216  if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
6217  return true;
6218 
6219  if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
6220  return true;
6221 
6222  BasicBlock *BB;
6223  if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
6224  ParseTypeAndBasicBlock(BB, PFS))
6225  return true;
6226 
6227  Inst = CatchReturnInst::Create(CatchPad, BB);
6228  return false;
6229 }
6230 
6231 /// ParseCatchSwitch
6232 /// ::= 'catchswitch' within Parent
6233 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6234  Value *ParentPad;
6235 
6236  if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6237  return true;
6238 
6239  if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6240  Lex.getKind() != lltok::LocalVarID)
6241  return TokError("expected scope value for catchswitch");
6242 
6243  if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6244  return true;
6245 
6246  if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6247  return true;
6248 
6250  do {
6251  BasicBlock *DestBB;
6252  if (ParseTypeAndBasicBlock(DestBB, PFS))
6253  return true;
6254  Table.push_back(DestBB);
6255  } while (EatIfPresent(lltok::comma));
6256 
6257  if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6258  return true;
6259 
6260  if (ParseToken(lltok::kw_unwind,
6261  "expected 'unwind' after catchswitch scope"))
6262  return true;
6263 
6264  BasicBlock *UnwindBB = nullptr;
6265  if (EatIfPresent(lltok::kw_to)) {
6266  if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6267  return true;
6268  } else {
6269  if (ParseTypeAndBasicBlock(UnwindBB, PFS))
6270  return true;
6271  }
6272 
6273  auto *CatchSwitch =
6274  CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6275  for (BasicBlock *DestBB : Table)
6276  CatchSwitch->addHandler(DestBB);
6277  Inst = CatchSwitch;
6278  return false;
6279 }
6280 
6281 /// ParseCatchPad
6282 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6283 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6284  Value *CatchSwitch = nullptr;
6285 
6286  if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
6287  return true;
6288 
6289  if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6290  return TokError("expected scope value for catchpad");
6291 
6292  if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6293  return true;
6294 
6296  if (ParseExceptionArgs(Args, PFS))
6297  return true;
6298 
6299  Inst = CatchPadInst::Create(CatchSwitch, Args);
6300  return false;
6301 }
6302 
6303 /// ParseCleanupPad
6304 /// ::= 'cleanuppad' within Parent ParamList
6305 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6306  Value *ParentPad = nullptr;
6307 
6308  if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6309  return true;
6310 
6311  if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6312  Lex.getKind() != lltok::LocalVarID)
6313  return TokError("expected scope value for cleanuppad");
6314 
6315  if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6316  return true;
6317 
6319  if (ParseExceptionArgs(Args, PFS))
6320  return true;
6321 
6322  Inst = CleanupPadInst::Create(ParentPad, Args);
6323  return false;
6324 }
6325 
6326 //===----------------------------------------------------------------------===//
6327 // Unary Operators.
6328 //===----------------------------------------------------------------------===//
6329 
6330 /// ParseUnaryOp
6331 /// ::= UnaryOp TypeAndValue ',' Value
6332 ///
6333 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6334 /// operand is allowed.
6335 bool LLParser::ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6336  unsigned Opc, bool IsFP) {
6337  LocTy Loc; Value *LHS;
6338  if (ParseTypeAndValue(LHS, Loc, PFS))
6339  return true;
6340 
6341  bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6342  : LHS->getType()->isIntOrIntVectorTy();
6343 
6344  if (!Valid)
6345  return Error(Loc, "invalid operand type for instruction");
6346 
6347  Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6348  return false;
6349 }
6350 
6351 /// ParseCallBr
6352 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6353 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6354 /// '[' LabelList ']'
6355 bool LLParser::ParseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6356  LocTy CallLoc = Lex.getLoc();
6357  AttrBuilder RetAttrs, FnAttrs;
6358  std::vector<unsigned> FwdRefAttrGrps;
6359  LocTy NoBuiltinLoc;
6360  unsigned CC;
6361  Type *RetType = nullptr;
6362  LocTy RetTypeLoc;
6363  ValID CalleeID;
6366 
6367  BasicBlock *DefaultDest;
6368  if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6369  ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6370  ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
6371  ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6372  NoBuiltinLoc) ||
6373  ParseOptionalOperandBundles(BundleList, PFS) ||
6374  ParseToken(lltok::kw_to, "expected 'to' in callbr") ||
6375  ParseTypeAndBasicBlock(DefaultDest, PFS) ||
6376  ParseToken(lltok::lsquare, "expected '[' in callbr"))
6377  return true;
6378 
6379  // Parse the destination list.
6380  SmallVector<BasicBlock *, 16> IndirectDests;
6381 
6382  if (Lex.getKind() != lltok::rsquare) {
6383  BasicBlock *DestBB;
6384  if (ParseTypeAndBasicBlock(DestBB, PFS))
6385  return true;
6386  IndirectDests.push_back(DestBB);
6387 
6388  while (EatIfPresent(lltok::comma)) {
6389  if (ParseTypeAndBasicBlock(DestBB, PFS))
6390  return true;
6391  IndirectDests.push_back(DestBB);
6392  }
6393  }
6394 
6395  if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
6396  return true;
6397 
6398  // If RetType is a non-function pointer type, then this is the short syntax
6399  // for the call, which means that RetType is just the return type. Infer the
6400  // rest of the function argument types from the arguments that are present.
6401  FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6402  if (!Ty) {
6403  // Pull out the types of all of the arguments...
6404  std::vector<Type *> ParamTypes;
6405  for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6406  ParamTypes.push_back(ArgList[i].V->getType());
6407 
6408  if (!FunctionType::isValidReturnType(RetType))
6409  return Error(RetTypeLoc, "Invalid result type for LLVM function");
6410 
6411  Ty = FunctionType::get(RetType, ParamTypes, false);
6412  }
6413 
6414  CalleeID.FTy = Ty;
6415 
6416  // Look up the callee.
6417  Value *Callee;
6418  if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6419  /*IsCall=*/true))
6420  return true;
6421 
6422  if (isa<InlineAsm>(Callee) && !Ty->getReturnType()->isVoidTy())
6423  return Error(RetTypeLoc, "asm-goto outputs not supported");
6424 
6425  // Set up the Attribute for the function.
6428 
6429  // Loop through FunctionType's arguments and ensure they are specified
6430  // correctly. Also, gather any parameter attributes.
6433  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6434  Type *ExpectedTy = nullptr;
6435  if (I != E) {
6436  ExpectedTy = *I++;
6437  } else if (!Ty->isVarArg()) {
6438  return Error(ArgList[i].Loc, "too many arguments specified");
6439  }
6440 
6441  if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6442  return Error(ArgList[i].Loc, "argument is not of expected type '" +
6443  getTypeString(ExpectedTy) + "'");
6444  Args.push_back(ArgList[i].V);
6445  ArgAttrs.push_back(ArgList[i].Attrs);
6446  }
6447 
6448  if (I != E)
6449  return Error(CallLoc, "not enough parameters specified for call");
6450 
6451  if (FnAttrs.hasAlignmentAttr())
6452  return Error(CallLoc, "callbr instructions may not have an alignment");
6453 
6454  // Finish off the Attribute and check them
6455  AttributeList PAL =
6457  AttributeSet::get(Context, RetAttrs), ArgAttrs);
6458 
6459  CallBrInst *CBI =
6460  CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6461  BundleList);
6462  CBI->setCallingConv(CC);
6463  CBI->setAttributes(PAL);
6464  ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6465  Inst = CBI;
6466  return false;
6467 }
6468 
6469 //===----------------------------------------------------------------------===//
6470 // Binary Operators.
6471 //===----------------------------------------------------------------------===//
6472 
6473 /// ParseArithmetic
6474 /// ::= ArithmeticOps TypeAndValue ',' Value
6475 ///
6476 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6477 /// operand is allowed.
6478 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6479  unsigned Opc, bool IsFP) {
6480  LocTy Loc; Value *LHS, *RHS;
6481  if (ParseTypeAndValue(LHS, Loc, PFS) ||
6482  ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6483  ParseValue(LHS->getType(), RHS, PFS))
6484  return true;
6485 
6486  bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6487  : LHS->getType()->isIntOrIntVectorTy();
6488 
6489  if (!Valid)
6490  return Error(Loc, "invalid operand type for instruction");
6491 
6492  Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6493  return false;
6494 }
6495 
6496 /// ParseLogical
6497 /// ::= ArithmeticOps TypeAndValue ',' Value {
6498 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
6499  unsigned Opc) {
6500  LocTy Loc; Value *LHS, *RHS;
6501  if (ParseTypeAndValue(LHS, Loc, PFS) ||
6502  ParseToken(lltok::comma, "expected ',' in logical operation") ||
6503  ParseValue(LHS->getType(), RHS, PFS))
6504  return true;
6505 
6506  if (!LHS->getType()->isIntOrIntVectorTy())
6507  return Error(Loc,"instruction requires integer or integer vector operands");
6508 
6509  Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6510  return false;
6511 }
6512 
6513 /// ParseCompare
6514 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
6515 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
6516 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6517  unsigned Opc) {
6518  // Parse the integer/fp comparison predicate.
6519  LocTy Loc;
6520  unsigned Pred;
6521  Value *LHS, *RHS;
6522  if (ParseCmpPredicate(Pred, Opc) ||
6523  ParseTypeAndValue(LHS, Loc, PFS) ||
6524  ParseToken(lltok::comma, "expected ',' after compare value") ||
6525  ParseValue(LHS->getType(), RHS, PFS))
6526  return true;
6527 
6528  if (Opc == Instruction::FCmp) {
6529  if (!LHS->getType()->isFPOrFPVectorTy())
6530  return Error(Loc, "fcmp requires floating point operands");
6531  Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6532  } else {
6533  assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
6534  if (!LHS->getType()->isIntOrIntVectorTy() &&
6535  !LHS->getType()->isPtrOrPtrVectorTy())
6536  return Error(Loc, "icmp requires integer operands");
6537  Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6538  }
6539  return false;
6540 }
6541 
6542 //===----------------------------------------------------------------------===//
6543 // Other Instructions.
6544 //===----------------------------------------------------------------------===//
6545 
6546 
6547 /// ParseCast
6548 /// ::= CastOpc TypeAndValue 'to' Type
6549 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6550  unsigned Opc) {
6551  LocTy Loc;
6552  Value *Op;
6553  Type *DestTy = nullptr;
6554  if (ParseTypeAndValue(Op, Loc, PFS) ||
6555  ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6556  ParseType(DestTy))
6557  return true;
6558 
6559  if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6560  CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
6561  return Error(Loc, "invalid cast opcode for cast from '" +
6562  getTypeString(Op->getType()) + "' to '" +
6563  getTypeString(DestTy) + "'");
6564  }
6565  Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6566  return false;
6567 }
6568 
6569 /// ParseSelect
6570 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6571 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6572  LocTy Loc;
6573  Value *Op0, *Op1, *Op2;
6574  if (ParseTypeAndValue(Op0, Loc, PFS) ||
6575  ParseToken(lltok::comma, "expected ',' after select condition") ||
6576  ParseTypeAndValue(Op1, PFS) ||
6577  ParseToken(lltok::comma, "expected ',' after select value") ||
6578  ParseTypeAndValue(Op2, PFS))
6579  return true;
6580 
6581  if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6582  return Error(Loc, Reason);
6583 
6584  Inst = SelectInst::Create(Op0, Op1, Op2);
6585  return false;
6586 }
6587 
6588 /// ParseVA_Arg
6589 /// ::= 'va_arg' TypeAndValue ',' Type
6590 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
6591  Value *Op;
6592  Type *EltTy = nullptr;
6593  LocTy TypeLoc;
6594  if (ParseTypeAndValue(Op, PFS) ||
6595  ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
6596  ParseType(EltTy, TypeLoc))
6597  return true;
6598 
6599  if (!EltTy->isFirstClassType())
6600  return Error(TypeLoc, "va_arg requires operand with first class type");
6601 
6602  Inst = new VAArgInst(Op, EltTy);
6603  return false;
6604 }
6605 
6606 /// ParseExtractElement
6607 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6608 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6609  LocTy Loc;
6610  Value *Op0, *Op1;
6611  if (ParseTypeAndValue(Op0, Loc, PFS) ||
6612  ParseToken(lltok::comma, "expected ',' after extract value") ||
6613  ParseTypeAndValue(Op1, PFS))
6614  return true;
6615 
6616  if (!ExtractElementInst::isValidOperands(Op0, Op1))
6617  return Error(Loc, "invalid extractelement operands");
6618 
6619  Inst = ExtractElementInst::Create(Op0, Op1);
6620  return false;
6621 }
6622 
6623 /// ParseInsertElement
6624 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6625 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6626  LocTy Loc;
6627  Value *Op0, *Op1, *Op2;
6628  if (ParseTypeAndValue(Op0, Loc, PFS) ||
6629  ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6630  ParseTypeAndValue(Op1, PFS) ||
6631  ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6632  ParseTypeAndValue(Op2, PFS))
6633  return true;
6634 
6635  if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
6636  return Error(Loc, "invalid insertelement operands");
6637 
6638  Inst = InsertElementInst::Create(Op0, Op1, Op2);
6639  return false;
6640 }
6641 
6642 /// ParseShuffleVector
6643 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6644 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6645  LocTy Loc;
6646  Value *Op0, *Op1, *Op2;
6647  if (ParseTypeAndValue(Op0, Loc, PFS) ||
6648  ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6649  ParseTypeAndValue(Op1, PFS) ||
6650  ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6651  ParseTypeAndValue(Op2, PFS))
6652  return true;
6653 
6654  if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
6655  return Error(Loc, "invalid shufflevector operands");
6656 
6657  Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6658  return false;
6659 }
6660 
6661 /// ParsePHI
6662 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6663 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
6664  Type *Ty = nullptr; LocTy TypeLoc;
6665  Value *Op0, *Op1;
6666 
6667  if (ParseType(Ty, TypeLoc) ||
6668  ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6669  ParseValue(Ty, Op0, PFS) ||
6670  ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6671  ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
6672  ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6673  return true;
6674 
6675  bool AteExtraComma = false;
6677 
6678  while (true) {
6679  PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
6680 
6681  if (!EatIfPresent(lltok::comma))
6682  break;
6683 
6684  if (Lex.getKind() == lltok::MetadataVar) {
6685  AteExtraComma = true;
6686  break;
6687  }
6688 
6689  if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6690  ParseValue(Ty, Op0, PFS) ||
6691  ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6692  ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
6693  ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6694  return true;
6695  }
6696 
6697  if (!Ty->isFirstClassType())
6698  return Error(TypeLoc, "phi node must have first class type");
6699 
6700  PHINode *PN = PHINode::Create(Ty, PHIVals.size());
6701  for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6702  PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6703  Inst = PN;
6704  return AteExtraComma ? InstExtraComma : InstNormal;
6705 }
6706 
6707 /// ParseLandingPad
6708 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6709 /// Clause
6710 /// ::= 'catch' TypeAndValue
6711 /// ::= 'filter'
6712 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6713 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
6714  Type *Ty = nullptr; LocTy TyLoc;
6715 
6716  if (ParseType(Ty, TyLoc))
6717  return true;
6718 
6719  std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
6720  LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6721 
6722  while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6724  if (EatIfPresent(lltok::kw_catch))
6725  CT = LandingPadInst::Catch;
6726  else if (EatIfPresent(lltok::kw_filter))
6728  else
6729  return TokError("expected 'catch' or 'filter' clause type");
6730 
6731  Value *V;
6732  LocTy VLoc;
6733  if (ParseTypeAndValue(V, VLoc, PFS))
6734  return true;
6735 
6736  // A 'catch' type expects a non-array constant. A filter clause expects an
6737  // array constant.
6738  if (CT == LandingPadInst::Catch) {
6739  if (isa<ArrayType>(V->getType()))
6740  Error(VLoc, "'catch' clause has an invalid type");
6741  } else {
6742  if (!isa<ArrayType>(V->getType()))
6743  Error(VLoc, "'filter' clause has an invalid type");
6744  }
6745 
6746  Constant *CV = dyn_cast<Constant>(V);
6747  if (!CV)
6748  return Error(VLoc, "clause argument must be a constant");
6749  LP->addClause(CV);
6750  }
6751 
6752  Inst = LP.release();
6753  return false;
6754 }
6755 
6756 /// ParseFreeze
6757 /// ::= 'freeze' Type Value
6758 bool LLParser::ParseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
6759  LocTy Loc;
6760  Value *Op;
6761  if (ParseTypeAndValue(Op, Loc, PFS))
6762  return true;
6763 
6764  Inst = new FreezeInst(Op);
6765  return false;
6766 }
6767 
6768 /// ParseCall
6769 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6770 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6771 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6772 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6773 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6774 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6775 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6776 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6777 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
6778  CallInst::TailCallKind TCK) {
6779  AttrBuilder RetAttrs, FnAttrs;
6780  std::vector<unsigned> FwdRefAttrGrps;
6781  LocTy BuiltinLoc;
6782  unsigned CallAddrSpace;
6783  unsigned CC;
6784  Type *RetType = nullptr;
6785  LocTy RetTypeLoc;
6786  ValID CalleeID;
6789  LocTy CallLoc = Lex.getLoc();
6790 
6791  if (TCK != CallInst::TCK_None &&
6792  ParseToken(lltok::kw_call,
6793  "expected 'tail call', 'musttail call', or 'notail call'"))
6794  return true;
6795 
6796  FastMathFlags FMF = EatFastMathFlagsIfPresent();
6797 
6798  if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6799  ParseOptionalProgramAddrSpace(CallAddrSpace) ||
6800  ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6801  ParseValID(CalleeID) ||
6802  ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6803  PFS.getFunction().isVarArg()) ||
6804  ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6805  ParseOptionalOperandBundles(BundleList, PFS))
6806  return true;
6807 
6808  // If RetType is a non-function pointer type, then this is the short syntax
6809  // for the call, which means that RetType is just the return type. Infer the
6810  // rest of the function argument types from the arguments that are present.
6811  FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6812  if (!Ty) {
6813  // Pull out the types of all of the arguments...
6814  std::vector<Type*> ParamTypes;
6815  for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6816  ParamTypes.push_back(ArgList[i].V->getType());
6817 
6818  if (!FunctionType::isValidReturnType(RetType))
6819  return Error(RetTypeLoc, "Invalid result type for LLVM function");
6820 
6821  Ty = FunctionType::get(RetType, ParamTypes, false);
6822  }
6823 
6824  CalleeID.FTy = Ty;
6825 
6826  // Look up the callee.
6827  Value *Callee;
6828  if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
6829  &PFS, /*IsCall=*/true))
6830  return true;
6831 
6832  // Set up the Attribute for the function.
6834 
6836 
6837  // Loop through FunctionType's arguments and ensure they are specified
6838  // correctly. Also, gather any parameter attributes.
6841  for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6842  Type *ExpectedTy = nullptr;
6843  if (I != E) {
6844  ExpectedTy = *I++;
6845  } else if (!Ty->isVarArg()) {
6846  return Error(ArgList[i].Loc, "too many arguments specified");
6847  }
6848 
6849  if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6850  return Error(ArgList[i].Loc, "argument is not of expected type '" +
6851  getTypeString(ExpectedTy) + "'");
6852  Args.push_back(ArgList[i].V);
6853  Attrs.push_back(ArgList[i].Attrs);
6854  }
6855 
6856  if (I != E)
6857  return Error(CallLoc, "not enough parameters specified for call");
6858 
6859  if (FnAttrs.hasAlignmentAttr())
6860  return Error(CallLoc, "call instructions may not have an alignment");
6861 
6862  // Finish off the Attribute and check them
6863  AttributeList PAL =
6865  AttributeSet::get(Context, RetAttrs), Attrs);
6866 
6867  CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
6868  CI->setTailCallKind(TCK);
6869  CI->setCallingConv(CC);
6870  if (FMF.any()) {
6871  if (!isa<FPMathOperator>(CI))
6872  return Error(CallLoc, "fast-math-flags specified for call without "
6873  "floating-point scalar or vector return type");
6874  CI->setFastMathFlags(FMF);
6875  }
6876  CI->setAttributes(PAL);
6877  ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6878  Inst = CI;
6879  return false;
6880 }
6881 
6882 //===----------------------------------------------------------------------===//
6883 // Memory Instructions.
6884 //===----------------------------------------------------------------------===//
6885 
6886 /// ParseAlloc
6887 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6888 /// (',' 'align' i32)? (',', 'addrspace(n))?
6889 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
6890  Value *Size = nullptr;
6891  LocTy SizeLoc, TyLoc, ASLoc;
6892  MaybeAlign Alignment;
6893  unsigned AddrSpace = 0;
6894  Type *Ty = nullptr;
6895 
6896  bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
6897  bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
6898 
6899  if (ParseType(Ty, TyLoc)) return true;
6900 
6902  return Error(TyLoc, "invalid type for alloca");
6903 
6904  bool AteExtraComma = false;
6905  if (EatIfPresent(lltok::comma)) {
6906  if (Lex.getKind() == lltok::kw_align) {
6907  if (ParseOptionalAlignment(Alignment))
6908  return true;
6909  if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6910  return true;
6911  } else if (Lex.getKind() == lltok::kw_addrspace) {
6912  ASLoc = Lex.getLoc();
6913  if (ParseOptionalAddrSpace(AddrSpace))
6914  return true;
6915  } else if (Lex.getKind() == lltok::MetadataVar) {
6916  AteExtraComma = true;
6917  } else {
6918  if (ParseTypeAndValue(Size, SizeLoc, PFS))
6919  return true;
6920  if (EatIfPresent(lltok::comma)) {
6921  if (Lex.getKind() == lltok::kw_align) {
6922  if (ParseOptionalAlignment(Alignment))
6923  return true;
6924  if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6925  return true;
6926  } else if (Lex.getKind() == lltok::kw_addrspace) {
6927  ASLoc = Lex.getLoc();
6928  if (ParseOptionalAddrSpace(AddrSpace))
6929  return true;
6930  } else if (Lex.getKind() == lltok::MetadataVar) {
6931  AteExtraComma = true;
6932  }
6933  }
6934  }
6935  }
6936 
6937  if (Size && !Size->getType()->isIntegerTy())
6938  return Error(SizeLoc, "element count must have integer type");
6939 
6940  AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
6941  AI->setUsedWithInAlloca(IsInAlloca);
6942  AI->setSwiftError(IsSwiftError);
6943  Inst = AI;
6944  return AteExtraComma ? InstExtraComma : InstNormal;
6945 }
6946 
6947 /// ParseLoad
6948 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6949 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6950 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6951 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6952  Value *Val; LocTy Loc;
6953  MaybeAlign Alignment;
6954  bool AteExtraComma = false;
6955  bool isAtomic = false;
6958 
6959  if (Lex.getKind() == lltok::kw_atomic) {
6960  isAtomic = true;
6961  Lex.Lex();
6962  }
6963 
6964  bool isVolatile = false;
6965  if (Lex.getKind() == lltok::kw_volatile) {
6966  isVolatile = true;
6967  Lex.Lex();
6968  }
6969 
6970  Type *Ty;
6971  LocTy ExplicitTypeLoc = Lex.getLoc();
6972  if (ParseType(Ty) ||
6973  ParseToken(lltok::comma, "expected comma after load's type") ||
6974  ParseTypeAndValue(Val, Loc, PFS) ||
6975  ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6976  ParseOptionalCommaAlign(Alignment, AteExtraComma))
6977  return true;
6978 
6979  if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6980  return Error(Loc, "load operand must be a pointer to a first class type");
6981  if (isAtomic && !Alignment)
6982  return Error(Loc, "atomic load must have explicit non-zero alignment");
6983  if (Ordering == AtomicOrdering::Release ||
6984  Ordering == AtomicOrdering::AcquireRelease)
6985  return Error(Loc, "atomic load cannot use Release ordering");
6986 
6987  if (Ty != cast<PointerType>(Val->getType())->getElementType())
6988  return Error(ExplicitTypeLoc,
6989  "explicit pointee type doesn't match operand's pointee type");
6990 
6991  Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
6992  return AteExtraComma ? InstExtraComma : InstNormal;
6993 }
6994 
6995 /// ParseStore
6996 
6997 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6998 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6999 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7000 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
7001  Value *Val, *Ptr; LocTy Loc, PtrLoc;
7002  MaybeAlign Alignment;
7003  bool AteExtraComma = false;
7004  bool isAtomic = false;
7007 
7008  if (Lex.getKind() == lltok::kw_atomic) {
7009  isAtomic = true;
7010  Lex.Lex();
7011  }
7012 
7013  bool isVolatile = false;
7014  if (Lex.getKind() == lltok::kw_volatile) {
7015  isVolatile = true;
7016  Lex.Lex();
7017  }
7018 
7019  if (ParseTypeAndValue(Val, Loc, PFS) ||
7020  ParseToken(lltok::comma, "expected ',' after store operand") ||
7021  ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
7022  ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7023  ParseOptionalCommaAlign(Alignment, AteExtraComma))
7024  return true;
7025 
7026  if (!Ptr->getType()->isPointerTy())
7027  return Error(PtrLoc, "store operand must be a pointer");
7028  if (!Val->getType()->isFirstClassType())
7029  return Error(Loc, "store operand must be a first class value");
7030  if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
7031  return Error(Loc, "stored value and pointer type do not match");
7032  if (isAtomic && !Alignment)
7033  return Error(Loc, "atomic store must have explicit non-zero alignment");
7034  if (Ordering == AtomicOrdering::Acquire ||
7035  Ordering == AtomicOrdering::AcquireRelease)
7036  return Error(Loc, "atomic store cannot use Acquire ordering");
7037 
7038  Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
7039  return AteExtraComma ? InstExtraComma : InstNormal;
7040 }
7041 
7042 /// ParseCmpXchg
7043 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7044 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
7045 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
7046  Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7047  bool AteExtraComma = false;
7048  AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7049  AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
7051  bool isVolatile = false;
7052  bool isWeak = false;
7053 
7054  if (EatIfPresent(lltok::kw_weak))
7055  isWeak = true;
7056 
7057  if (EatIfPresent(lltok::kw_volatile))
7058  isVolatile = true;
7059 
7060  if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
7061  ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7062  ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
7063  ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7064  ParseTypeAndValue(New, NewLoc, PFS) ||
7065  ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7066  ParseOrdering(FailureOrdering))
7067  return true;
7068 
7069  if (SuccessOrdering == AtomicOrdering::Unordered ||
7070  FailureOrdering == AtomicOrdering::Unordered)
7071  return TokError("cmpxchg cannot be unordered");
7072  if (isStrongerThan(FailureOrdering, SuccessOrdering))
7073  return TokError("cmpxchg failure argument shall be no stronger than the "
7074  "success argument");
7075  if (FailureOrdering == AtomicOrdering::Release ||
7076  FailureOrdering == AtomicOrdering::AcquireRelease)
7077  return TokError(
7078  "cmpxchg failure ordering cannot include release semantics");
7079  if (!Ptr->getType()->isPointerTy())
7080  return Error(PtrLoc, "cmpxchg operand must be a pointer");
7081  if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
7082  return Error(CmpLoc, "compare value and pointer type do not match");
7083  if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
7084  return Error(NewLoc, "new value and pointer type do not match");
7085  if (!New->getType()->isFirstClassType())
7086  return Error(NewLoc, "cmpxchg operand must be a first class value");
7088  Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
7089  CXI->setVolatile(isVolatile);
7090  CXI->setWeak(isWeak);
7091  Inst = CXI;
7092  return AteExtraComma ? InstExtraComma : InstNormal;
7093 }
7094 
7095 /// ParseAtomicRMW
7096 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7097 /// 'singlethread'? AtomicOrdering
7098 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7099  Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7100  bool AteExtraComma = false;
7103  bool isVolatile = false;
7104  bool IsFP = false;
7106 
7107  if (EatIfPresent(lltok::kw_volatile))
7108  isVolatile = true;
7109 
7110  switch (Lex.getKind()) {
7111  default: return TokError("expected binary operation in atomicrmw");
7112  case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7113  case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7114  case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7115  case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7116  case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7117  case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7118  case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7119  case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7120  case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7121  case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7122  case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7123  case lltok::kw_fadd:
7124  Operation = AtomicRMWInst::FAdd;
7125  IsFP = true;
7126  break;
7127  case lltok::kw_fsub:
7128  Operation = AtomicRMWInst::FSub;
7129  IsFP = true;
7130  break;
7131  }
7132  Lex.Lex(); // Eat the operation.
7133 
7134  if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
7135  ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7136  ParseTypeAndValue(Val, ValLoc, PFS) ||
7137  ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7138  return true;
7139 
7140  if (Ordering == AtomicOrdering::Unordered)
7141  return TokError("atomicrmw cannot be unordered");
7142  if (!Ptr->getType()->isPointerTy())
7143  return Error(PtrLoc, "atomicrmw operand must be a pointer");
7144  if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
7145  return Error(ValLoc, "atomicrmw value and pointer type do not match");
7146 
7147  if (Operation == AtomicRMWInst::Xchg) {
7148  if (!Val->getType()->isIntegerTy() &&
7149  !Val->getType()->isFloatingPointTy()) {
7150  return Error(ValLoc, "atomicrmw " +
7151  AtomicRMWInst::getOperationName(Operation) +
7152  " operand must be an integer or floating point type");
7153  }
7154  } else if (IsFP) {
7155  if (!Val->getType()->isFloatingPointTy()) {
7156  return Error(ValLoc, "atomicrmw " +
7157  AtomicRMWInst::getOperationName(Operation) +
7158  " operand must be a floating point type");
7159  }
7160  } else {
7161  if (!Val->getType()->isIntegerTy()) {
7162  return Error(ValLoc, "atomicrmw " +
7163  AtomicRMWInst::getOperationName(Operation) +
7164  " operand must be an integer");
7165  }
7166  }
7167 
7168  unsigned Size = Val->getType()->getPrimitiveSizeInBits();
7169  if (Size < 8 || (Size & (Size - 1)))
7170  return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7171  " integer");
7172 
7173  AtomicRMWInst *RMWI =
7174  new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
7175  RMWI->setVolatile(isVolatile);
7176  Inst = RMWI;
7177  return AteExtraComma ? InstExtraComma : InstNormal;
7178 }
7179 
7180 /// ParseFence
7181 /// ::= 'fence' 'singlethread'? AtomicOrdering
7182 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
7185  if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7186  return true;
7187 
7188  if (Ordering == AtomicOrdering::Unordered)
7189  return TokError("fence cannot be unordered");
7190  if (Ordering == AtomicOrdering::Monotonic)
7191  return TokError("fence cannot be monotonic");
7192 
7193  Inst = new FenceInst(Context, Ordering, SSID);
7194  return InstNormal;
7195 }
7196 
7197 /// ParseGetElementPtr
7198 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7199 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7200  Value *Ptr = nullptr;
7201  Value *Val = nullptr;
7202  LocTy Loc, EltLoc;
7203 
7204  bool InBounds = EatIfPresent(lltok::kw_inbounds);
7205 
7206  Type *Ty = nullptr;
7207  LocTy ExplicitTypeLoc = Lex.getLoc();
7208  if (ParseType(Ty) ||
7209  ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
7210  ParseTypeAndValue(Ptr, Loc, PFS))
7211  return true;
7212 
7213  Type *BaseType = Ptr->getType();
7214  PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7215  if (!BasePointerType)
7216  return Error(Loc, "base of getelementptr must be a pointer");
7217 
7218  if (Ty != BasePointerType->getElementType())
7219  return Error(ExplicitTypeLoc,
7220  "explicit pointee type doesn't match operand's pointee type");
7221 
7222  SmallVector<Value*, 16> Indices;
7223  bool AteExtraComma = false;
7224  // GEP returns a vector of pointers if at least one of parameters is a vector.
7225  // All vector parameters should have the same vector width.
7226  unsigned GEPWidth = BaseType->isVectorTy() ?
7227  BaseType->getVectorNumElements() : 0;
7228 
7229  while (EatIfPresent(lltok::comma)) {
7230  if (Lex.getKind() == lltok::MetadataVar) {
7231  AteExtraComma = true;
7232  break;
7233  }
7234  if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
7235  if (!Val->getType()->isIntOrIntVectorTy())
7236  return Error(EltLoc, "getelementptr index must be an integer");
7237 
7238  if (Val->getType()->isVectorTy()) {
7239  unsigned ValNumEl = Val->getType()->getVectorNumElements();
7240  if (GEPWidth && GEPWidth != ValNumEl)
7241  return Error(EltLoc,
7242  "getelementptr vector index has a wrong number of elements");
7243  GEPWidth = ValNumEl;
7244  }
7245  Indices.push_back(Val);
7246  }
7247 
7248  SmallPtrSet<Type*, 4> Visited;
7249  if (!Indices.empty() && !Ty->isSized(&Visited))
7250  return Error(Loc, "base element of getelementptr must be sized");
7251 
7252  if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7253  return Error(Loc, "invalid getelementptr indices");
7254  Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7255  if (InBounds)
7256  cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7257  return AteExtraComma ? InstExtraComma : InstNormal;
7258 }
7259 
7260 /// ParseExtractValue
7261 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
7262 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7263  Value *Val; LocTy Loc;
7264  SmallVector<unsigned, 4> Indices;
7265  bool AteExtraComma;
7266  if (ParseTypeAndValue(Val, Loc, PFS) ||
7267  ParseIndexList(Indices, AteExtraComma))
7268  return true;
7269 
7270  if (!Val->getType()->isAggregateType())
7271  return Error(Loc, "extractvalue operand must be aggregate type");
7272 
7273  if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7274  return Error(Loc, "invalid indices for extractvalue");
7275  Inst = ExtractValueInst::Create(Val, Indices);
7276  return AteExtraComma ? InstExtraComma : InstNormal;
7277 }
7278 
7279 /// ParseInsertValue
7280 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7281 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7282  Value *Val0, *Val1; LocTy Loc0, Loc1;
7283  SmallVector<unsigned, 4> Indices;
7284  bool AteExtraComma;
7285  if (ParseTypeAndValue(Val0, Loc0, PFS) ||
7286  ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
7287  ParseTypeAndValue(Val1, Loc1, PFS) ||
7288  ParseIndexList(Indices, AteExtraComma))
7289  return true;
7290 
7291  if (!Val0->getType()->isAggregateType())
7292  return Error(Loc0, "insertvalue operand must be aggregate type");
7293 
7294  Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7295  if (!IndexedType)
7296  return Error(Loc0, "invalid indices for insertvalue");
7297  if (IndexedType != Val1->getType())
7298  return Error(Loc1, "insertvalue operand and field disagree in type: '" +
7299  getTypeString(Val1->getType()) + "' instead of '" +
7300  getTypeString(IndexedType) + "'");
7301  Inst = InsertValueInst::Create(Val0, Val1, Indices);
7302  return AteExtraComma ? InstExtraComma : InstNormal;
7303 }
7304 
7305 //===----------------------------------------------------------------------===//
7306 // Embedded metadata.
7307 //===----------------------------------------------------------------------===//
7308 
7309 /// ParseMDNodeVector
7310 /// ::= { Element (',' Element)* }
7311 /// Element
7312 /// ::= 'null' | TypeAndValue
7313 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7314  if (ParseToken(lltok::lbrace, "expected '{' here"))
7315  return true;
7316 
7317  // Check for an empty list.
7318  if (EatIfPresent(lltok::rbrace))
7319  return false;
7320 
7321  do {
7322  // Null is a special case since it is typeless.
7323  if (EatIfPresent(lltok::kw_null)) {
7324  Elts.push_back(nullptr);
7325  continue;
7326  }
7327 
7328  Metadata *MD;
7329  if (ParseMetadata(MD, nullptr))
7330  return true;
7331  Elts.push_back(MD);
7332  } while (EatIfPresent(lltok::comma));
7333 
7334  return ParseToken(lltok::rbrace, "expected end of metadata node");
7335 }
7336 
7337 //===----------------------------------------------------------------------===//
7338 // Use-list order directives.
7339 //===----------------------------------------------------------------------===//
7340 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7341  SMLoc Loc) {
7342  if (V->use_empty())
7343  return Error(Loc, "value has no uses");
7344 
7345  unsigned NumUses = 0;
7347  for (const Use &U : V->uses()) {
7348  if (++NumUses > Indexes.size())
7349  break;
7350  Order[&U] = Indexes[NumUses - 1];
7351  }
7352  if (NumUses < 2)
7353  return Error(Loc, "value only has one use");
7354  if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7355  return Error(Loc,
7356  "wrong number of indexes, expected " + Twine(V->getNumUses()));
7357 
7358  V->sortUseList([&](const Use &L, const Use &R) {
7359  return Order.lookup(&L) < Order.lookup(&R);
7360  });
7361  return false;
7362 }
7363 
7364 /// ParseUseListOrderIndexes
7365 /// ::= '{' uint32 (',' uint32)+ '}'
7366 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7367  SMLoc Loc = Lex.getLoc();
7368  if (ParseToken(lltok::lbrace, "expected '{' here"))
7369  return true;
7370  if (Lex.getKind() == lltok::rbrace)
7371  return Lex.Error("expected non-empty list of uselistorder indexes");
7372 
7373  // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7374  // indexes should be distinct numbers in the range [0, size-1], and should
7375  // not be in order.
7376  unsigned Offset = 0;
7377  unsigned Max = 0;
7378  bool IsOrdered = true;
7379  assert(Indexes.empty() && "Expected empty order vector");
7380  do {
7381  unsigned Index;
7382  if (ParseUInt32(Index))
7383  return true;
7384 
7385  // Update consistency checks.
7386  Offset += Index - Indexes.size();
7387  Max = std::max(Max, Index);
7388  IsOrdered &= Index == Indexes.size();
7389 
7390  Indexes.push_back(Index);
7391  } while (EatIfPresent(lltok::comma));
7392 
7393  if (ParseToken(lltok::rbrace, "expected '}' here"))
7394  return true;
7395 
7396  if (Indexes.size() < 2)
7397  return Error(Loc, "expected >= 2 uselistorder indexes");
7398  if (Offset != 0 || Max >= Indexes.size())
7399  return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
7400  if (IsOrdered)
7401  return Error(Loc, "expected uselistorder indexes to change the order");
7402 
7403  return false;
7404 }
7405 
7406 /// ParseUseListOrder
7407 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7408 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
7409  SMLoc Loc = Lex.getLoc();
7410  if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7411  return true;
7412 
7413  Value *V;
7414  SmallVector<unsigned, 16> Indexes;
7415  if (ParseTypeAndValue(V, PFS) ||
7416  ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
7417  ParseUseListOrderIndexes(Indexes))
7418  return true;
7419 
7420  return sortUseListOrder(V, Indexes, Loc);
7421 }
7422 
7423 /// ParseUseListOrderBB
7424 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7425 bool LLParser::ParseUseListOrderBB() {
7426  assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7427  SMLoc Loc = Lex.getLoc();
7428  Lex.Lex();
7429 
7430  ValID Fn, Label;
7431  SmallVector<unsigned, 16> Indexes;
7432  if (ParseValID(Fn) ||
7433  ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7434  ParseValID(Label) ||
7435  ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7436  ParseUseListOrderIndexes(Indexes))
7437  return true;
7438 
7439  // Check the function.
7440  GlobalValue *GV;
7441  if (Fn.Kind == ValID::t_GlobalName)
7442  GV = M->getNamedValue(Fn.StrVal);
7443  else if (Fn.Kind == ValID::t_GlobalID)
7444  GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7445  else
7446  return Error(Fn.Loc, "expected function name in uselistorder_bb");
7447  if (!GV)
7448  return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
7449  auto *F = dyn_cast<Function>(GV);
7450  if (!F)
7451  return Error(Fn.Loc, "expected function name in uselistorder_bb");
7452  if (F->isDeclaration())
7453  return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
7454 
7455  // Check the basic block.
7456  if (Label.Kind == ValID::t_LocalID)
7457  return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
7458  if (Label.Kind != ValID::t_LocalName)
7459  return Error(Label.Loc, "expected basic block name in uselistorder_bb");
7460  Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7461  if (!V)
7462  return Error(Label.Loc, "invalid basic block in uselistorder_bb");
7463  if (!isa<BasicBlock>(V))
7464  return Error(Label.Loc, "expected basic block in uselistorder_bb");
7465 
7466  return sortUseListOrder(V, Indexes, Loc);
7467 }
7468 
7469 /// ModuleEntry
7470 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7471 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7472 bool LLParser::ParseModuleEntry(unsigned ID) {
7473  assert(Lex.getKind() == lltok::kw_module);
7474  Lex.Lex();
7475 
7476  std::string Path;
7477  if (ParseToken(lltok::colon, "expected ':' here") ||
7478  ParseToken(lltok::lparen, "expected '(' here") ||
7479  ParseToken(lltok::kw_path, "expected 'path' here") ||
7480  ParseToken(lltok::colon, "expected ':' here") ||
7481  ParseStringConstant(Path) ||
7482  ParseToken(lltok::comma, "expected ',' here") ||
7483  ParseToken(lltok::kw_hash, "expected 'hash' here") ||
7484  ParseToken(lltok::colon, "expected ':' here") ||
7485  ParseToken(lltok::lparen, "expected '(' here"))
7486  return true;
7487 
7488  ModuleHash Hash;
7489  if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
7490  ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
7491  ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
7492  ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
7493  ParseUInt32(Hash[4]))
7494  return true;
7495 
7496  if (ParseToken(lltok::rparen, "expected ')' here") ||
7497  ParseToken(lltok::rparen, "expected ')' here"))
7498  return true;
7499 
7500  auto ModuleEntry = Index->addModule(Path, ID, Hash);
7501  ModuleIdMap[ID] = ModuleEntry->first();
7502 
7503  return false;
7504 }
7505 
7506 /// TypeIdEntry
7507 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7508 bool LLParser::ParseTypeIdEntry(unsigned ID) {
7509  assert(Lex.getKind() == lltok::kw_typeid);
7510  Lex.Lex();
7511 
7512  std::string Name;
7513  if (ParseToken(lltok::colon, "expected ':' here") ||
7514  ParseToken(lltok::lparen, "expected '(' here") ||
7515  ParseToken(lltok::kw_name, "expected 'name' here") ||
7516  ParseToken(lltok::colon, "expected ':' here") ||
7517  ParseStringConstant(Name))
7518  return true;
7519 
7520  TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7521  if (ParseToken(lltok::comma, "expected ',' here") ||
7522  ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
7523  return true;
7524 
7525  // Check if this ID was forward referenced, and if so, update the
7526  // corresponding GUIDs.
7527  auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7528  if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7529  for (auto TIDRef : FwdRefTIDs->second) {
7530  assert(!*TIDRef.first &&
7531  "Forward referenced type id GUID expected to be 0");
7532  *TIDRef.first = GlobalValue::getGUID(Name);
7533  }
7534  ForwardRefTypeIds.erase(FwdRefTIDs);
7535  }
7536 
7537  return false;
7538 }
7539 
7540 /// TypeIdSummary
7541 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7542 bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
7543  if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7544  ParseToken(lltok::colon, "expected ':' here") ||
7545  ParseToken(lltok::lparen, "expected '(' here") ||
7546  ParseTypeTestResolution(TIS.TTRes))
7547  return true;
7548 
7549  if (EatIfPresent(lltok::comma)) {
7550  // Expect optional wpdResolutions field
7551  if (ParseOptionalWpdResolutions(TIS.WPDRes))
7552  return true;
7553  }
7554 
7555  if (ParseToken(lltok::rparen, "expected ')' here"))
7556  return true;
7557 
7558  return false;
7559 }
7560 
7561 static ValueInfo EmptyVI =
7562  ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7563 
7564 /// TypeIdCompatibleVtableEntry
7565 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
7566 /// TypeIdCompatibleVtableInfo
7567 /// ')'
7568 bool LLParser::ParseTypeIdCompatibleVtableEntry(unsigned ID) {
7569  assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
7570  Lex.Lex();
7571 
7572  std::string Name;
7573  if (ParseToken(lltok::colon, "expected ':' here") ||
7574  ParseToken(lltok::lparen, "expected '(' here") ||
7575  ParseToken(lltok::kw_name, "expected 'name' here") ||
7576  ParseToken(lltok::colon, "expected ':' here") ||
7577  ParseStringConstant(Name))
7578  return true;
7579 
7581  Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
7582  if (ParseToken(lltok::comma, "expected ',' here") ||
7583  ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7584  ParseToken(lltok::colon, "expected ':' here") ||
7585  ParseToken(lltok::lparen, "expected '(' here"))
7586  return true;
7587 
7588  IdToIndexMapType IdToIndexMap;
7589  // Parse each call edge
7590  do {
7591  uint64_t Offset;
7592  if (ParseToken(lltok::lparen, "expected '(' here") ||
7593  ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7594  ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7595  ParseToken(lltok::comma, "expected ',' here"))
7596  return true;
7597 
7598  LocTy Loc = Lex.getLoc();
7599  unsigned GVId;
7600  ValueInfo VI;
7601  if (ParseGVReference(VI, GVId))
7602  return true;
7603 
7604  // Keep track of the TypeIdCompatibleVtableInfo array index needing a
7605  // forward reference. We will save the location of the ValueInfo needing an
7606  // update, but can only do so once the std::vector is finalized.
7607  if (VI == EmptyVI)
7608  IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
7609  TI.push_back({Offset, VI});
7610 
7611  if (ParseToken(lltok::rparen, "expected ')' in call"))
7612  return true;
7613  } while (EatIfPresent(lltok::comma));
7614 
7615  // Now that the TI vector is finalized, it is safe to save the locations
7616  // of any forward GV references that need updating later.
7617  for (auto I : IdToIndexMap) {
7618  for (auto P : I.second) {
7619  assert(TI[P.first].VTableVI == EmptyVI &&
7620  "Forward referenced ValueInfo expected to be empty");
7621  auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7622  I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7623  FwdRef.first->second.push_back(
7624  std::make_pair(&TI[P.first].VTableVI, P.second));
7625  }
7626  }
7627 
7628  if (ParseToken(lltok::rparen, "expected ')' here") ||
7629  ParseToken(lltok::rparen, "expected ')' here"))
7630  return true;
7631 
7632  // Check if this ID was forward referenced, and if so, update the
7633  // corresponding GUIDs.
7634  auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7635  if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7636  for (auto TIDRef : FwdRefTIDs->second) {
7637  assert(!*TIDRef.first &&
7638  "Forward referenced type id GUID expected to be 0");
7639  *TIDRef.first = GlobalValue::getGUID(Name);
7640  }
7641  ForwardRefTypeIds.erase(FwdRefTIDs);
7642  }
7643 
7644  return false;
7645 }
7646 
7647 /// TypeTestResolution
7648 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
7649 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7650 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7651 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7652 /// [',' 'inlinesBits' ':' UInt64]? ')'
7653 bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
7654  if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7655  ParseToken(lltok::colon, "expected ':' here") ||
7656  ParseToken(lltok::lparen, "expected '(' here") ||
7657  ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7658  ParseToken(lltok::colon, "expected ':' here"))
7659  return true;
7660 
7661  switch (Lex.getKind()) {
7662  case lltok::kw_unsat:
7664  break;
7665  case lltok::kw_byteArray:
7667  break;
7668  case lltok::kw_inline:
7670  break;
7671  case lltok::kw_single:
7673  break;
7674  case lltok::kw_allOnes:
7676  break;
7677  default:
7678  return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7679  }
7680  Lex.Lex();
7681 
7682  if (ParseToken(lltok::comma, "expected ',' here") ||
7683  ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7684  ParseToken(lltok::colon, "expected ':' here") ||
7685  ParseUInt32(TTRes.SizeM1BitWidth))
7686  return true;
7687 
7688  // Parse optional fields
7689  while (EatIfPresent(lltok::comma)) {
7690  switch (Lex.getKind()) {
7691  case lltok::kw_alignLog2:
7692  Lex.Lex();
7693  if (ParseToken(lltok::colon, "expected ':'") ||
7694  ParseUInt64(TTRes.AlignLog2))
7695  return true;
7696  break;
7697  case lltok::kw_sizeM1:
7698  Lex.Lex();
7699  if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
7700  return true;
7701  break;
7702  case lltok::kw_bitMask: {
7703  unsigned Val;
7704  Lex.Lex();
7705  if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
7706  return true;
7707  assert(Val <= 0xff);
7708  TTRes.BitMask = (uint8_t)Val;
7709  break;
7710  }
7711  case lltok::kw_inlineBits:
7712  Lex.Lex();
7713  if (ParseToken(lltok::colon, "expected ':'") ||
7714  ParseUInt64(TTRes.InlineBits))
7715  return true;
7716  break;
7717  default:
7718  return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
7719  }
7720  }
7721 
7722  if (ParseToken(lltok::rparen, "expected ')' here"))
7723  return true;
7724 
7725  return false;
7726 }
7727 
7728 /// OptionalWpdResolutions
7729 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7730 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7731 bool LLParser::ParseOptionalWpdResolutions(
7732  std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7733  if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7734  ParseToken(lltok::colon, "expected ':' here") ||
7735  ParseToken(lltok::lparen, "expected '(' here"))
7736  return true;
7737 
7738  do {
7739  uint64_t Offset;
7741  if (ParseToken(lltok::lparen, "expected '(' here") ||
7742  ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7743  ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7744  ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
7745  ParseToken(lltok::rparen, "expected ')' here"))
7746  return true;
7747  WPDResMap[Offset] = WPDRes;
7748  } while (EatIfPresent(lltok::comma));
7749 
7750  if (ParseToken(lltok::rparen, "expected ')' here"))
7751  return true;
7752 
7753  return false;
7754 }
7755 
7756 /// WpdRes
7757 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7758 /// [',' OptionalResByArg]? ')'
7759 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7760 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
7761 /// [',' OptionalResByArg]? ')'
7762 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7763 /// [',' OptionalResByArg]? ')'
7764 bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7765  if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7766  ParseToken(lltok::colon, "expected ':' here") ||
7767  ParseToken(lltok::lparen, "expected '(' here") ||
7768  ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7769  ParseToken(lltok::colon, "expected ':' here"))
7770  return true;
7771 
7772  switch (Lex.getKind()) {
7773  case lltok::kw_indir:
7775  break;
7776  case lltok::kw_singleImpl:
7778  break;
7781  break;
7782  default:
7783  return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7784  }
7785  Lex.Lex();
7786 
7787  // Parse optional fields
7788  while (EatIfPresent(lltok::comma)) {
7789  switch (Lex.getKind()) {
7791  Lex.Lex();
7792  if (ParseToken(lltok::colon, "expected ':' here") ||
7793  ParseStringConstant(WPDRes.SingleImplName))
7794  return true;
7795  break;
7796  case lltok::kw_resByArg:
7797  if (ParseOptionalResByArg(WPDRes.ResByArg))
7798  return true;
7799  break;
7800  default:
7801  return Error(Lex.getLoc(),
7802  "expected optional WholeProgramDevirtResolution field");
7803  }
7804  }
7805 
7806  if (ParseToken(lltok::rparen, "expected ')' here"))
7807  return true;
7808 
7809  return false;
7810 }
7811 
7812 /// OptionalResByArg
7813 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7814 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7815 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7816 /// 'virtualConstProp' )
7817 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7818 /// [',' 'bit' ':' UInt32]? ')'
7819 bool LLParser::ParseOptionalResByArg(
7820  std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
7821  &ResByArg) {
7822  if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
7823  ParseToken(lltok::colon, "expected ':' here") ||
7824  ParseToken(lltok::lparen, "expected '(' here"))
7825  return true;
7826 
7827  do {
7828  std::vector<uint64_t> Args;
7829  if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
7830  ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
7831  ParseToken(lltok::colon, "expected ':' here") ||
7832  ParseToken(lltok::lparen, "expected '(' here") ||
7833  ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7834  ParseToken(lltok::colon, "expected ':' here"))
7835  return true;
7836 
7838  switch (Lex.getKind()) {
7839  case lltok::kw_indir:
7841  break;
7844  break;
7847  break;
7850  break;
7851  default:
7852  return Error(Lex.getLoc(),
7853  "unexpected WholeProgramDevirtResolution::ByArg kind");
7854  }
7855  Lex.Lex();
7856 
7857  // Parse optional fields
7858  while (EatIfPresent(lltok::comma)) {
7859  switch (Lex.getKind()) {
7860  case lltok::kw_info:
7861  Lex.Lex();
7862  if (ParseToken(lltok::colon, "expected ':' here") ||
7863  ParseUInt64(ByArg.Info))
7864  return true;
7865  break;
7866  case lltok::kw_byte:
7867  Lex.Lex();
7868  if (ParseToken(lltok::colon, "expected ':' here") ||
7869  ParseUInt32(ByArg.Byte))
7870  return true;
7871  break;
7872  case lltok::kw_bit:
7873  Lex.Lex();
7874  if (ParseToken(lltok::colon, "expected ':' here") ||
7875  ParseUInt32(ByArg.Bit))
7876  return true;
7877  break;
7878  default:
7879  return Error(Lex.getLoc(),
7880  "expected optional whole program devirt field");
7881  }
7882  }
7883 
7884  if (ParseToken(lltok::rparen, "expected ')' here"))
7885  return true;
7886 
7887  ResByArg[Args] = ByArg;
7888  } while (EatIfPresent(lltok::comma));
7889 
7890  if (ParseToken(lltok::rparen, "expected ')' here"))
7891  return true;
7892 
7893  return false;
7894 }
7895 
7896 /// OptionalResByArg
7897 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7898 bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7899  if (ParseToken(lltok::kw_args, "expected 'args' here") ||
7900  ParseToken(lltok::colon, "expected ':' here") ||
7901  ParseToken(lltok::lparen, "expected '(' here"))
7902  return true;
7903 
7904  do {
7905  uint64_t Val;
7906  if (ParseUInt64(Val))
7907  return true;
7908  Args.push_back(Val);
7909  } while (EatIfPresent(lltok::comma));
7910 
7911  if (ParseToken(lltok::rparen, "expected ')' here"))
7912  return true;
7913 
7914  return false;
7915 }
7916 
7917 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
7918 
7919 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
7920  bool ReadOnly = Fwd->isReadOnly();
7921  bool WriteOnly = Fwd->isWriteOnly();
7922  assert(!(ReadOnly && WriteOnly));
7923  *Fwd = Resolved;
7924  if (ReadOnly)
7925  Fwd->setReadOnly();
7926  if (WriteOnly)
7927  Fwd->setWriteOnly();
7928 }
7929 
7930 /// Stores the given Name/GUID and associated summary into the Index.
7931 /// Also updates any forward references to the associated entry ID.
7932 void LLParser::AddGlobalValueToIndex(
7933  std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
7934  unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7935  // First create the ValueInfo utilizing the Name or GUID.
7936  ValueInfo VI;
7937  if (GUID != 0) {
7938  assert(Name.empty());
7939  VI = Index->getOrInsertValueInfo(GUID);
7940  } else {
7941  assert(!Name.empty());
7942  if (M) {
7943  auto *GV = M->getNamedValue(Name);
7944  assert(GV);
7945  VI = Index->getOrInsertValueInfo(GV);
7946  } else {
7947  assert(
7948  (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
7949  "Need a source_filename to compute GUID for local");
7950  GUID = GlobalValue::getGUID(
7951  GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
7952  VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7953  }
7954  }
7955 
7956  // Resolve forward references from calls/refs
7957  auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7958  if (FwdRefVIs != ForwardRefValueInfos.end()) {
7959  for (auto VIRef : FwdRefVIs->second) {
7960  assert(VIRef.first->getRef() == FwdVIRef &&
7961  "Forward referenced ValueInfo expected to be empty");
7962  resolveFwdRef(VIRef.first, VI);
7963  }
7964  ForwardRefValueInfos.erase(FwdRefVIs);
7965  }
7966 
7967  // Resolve forward references from aliases
7968  auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7969  if (FwdRefAliasees != ForwardRefAliasees.end()) {
7970  for (auto AliaseeRef : FwdRefAliasees->second) {
7971  assert(!AliaseeRef.first->hasAliasee() &&
7972  "Forward referencing alias already has aliasee");
7973  assert(Summary && "Aliasee must be a definition");
7974  AliaseeRef.first->setAliasee(VI, Summary.get());
7975  }
7976  ForwardRefAliasees.erase(FwdRefAliasees);
7977  }
7978 
7979  // Add the summary if one was provided.
7980  if (Summary)
7981  Index->addGlobalValueSummary(VI, std::move(Summary));
7982 
7983  // Save the associated ValueInfo for use in later references by ID.
7984  if (ID == NumberedValueInfos.size())
7985  NumberedValueInfos.push_back(VI);
7986  else {
7987  // Handle non-continuous numbers (to make test simplification easier).
7988  if (ID > NumberedValueInfos.size())
7989  NumberedValueInfos.resize(ID + 1);
7990  NumberedValueInfos[ID] = VI;
7991  }
7992 }
7993 
7994 /// ParseGVEntry
7995 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7996 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7997 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7998 bool LLParser::ParseGVEntry(unsigned ID) {
7999  assert(Lex.getKind() == lltok::kw_gv);
8000  Lex.Lex();
8001 
8002  if (ParseToken(lltok::colon, "expected ':' here") ||
8003  ParseToken(lltok::lparen, "expected '(' here"))
8004  return true;
8005 
8006  std::string Name;
8007  GlobalValue::GUID GUID = 0;
8008  switch (Lex.getKind()) {
8009  case lltok::kw_name:
8010  Lex.Lex();
8011  if (ParseToken(lltok::colon, "expected ':' here") ||
8012  ParseStringConstant(Name))
8013  return true;
8014  // Can't create GUID/ValueInfo until we have the linkage.
8015  break;
8016  case lltok::kw_guid:
8017  Lex.Lex();
8018  if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
8019  return true;
8020  break;
8021  default:
8022  return Error(Lex.getLoc(), "expected name or guid tag");
8023  }
8024 
8025  if (!EatIfPresent(lltok::comma)) {
8026  // No summaries. Wrap up.
8027  if (ParseToken(lltok::rparen, "expected ')' here"))
8028  return true;
8029  // This was created for a call to an external or indirect target.
8030  // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8031  // created for indirect calls with VP. A Name with no GUID came from
8032  // an external definition. We pass ExternalLinkage since that is only
8033  // used when the GUID must be computed from Name, and in that case
8034  // the symbol must have external linkage.
8035  AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8036  nullptr);
8037  return false;
8038  }
8039 
8040  // Have a list of summaries
8041  if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8042  ParseToken(lltok::colon, "expected ':' here"))
8043  return true;
8044 
8045  do {
8046  if (ParseToken(lltok::lparen, "expected '(' here"))
8047  return true;
8048  switch (Lex.getKind()) {
8049  case lltok::kw_function:
8050  if (ParseFunctionSummary(Name, GUID, ID))
8051  return true;
8052  break;
8053  case lltok::kw_variable:
8054  if (ParseVariableSummary(Name, GUID, ID))
8055  return true;
8056  break;
8057  case lltok::kw_alias:
8058  if (ParseAliasSummary(Name, GUID, ID))
8059  return true;
8060  break;
8061  default:
8062  return Error(Lex.getLoc(), "expected summary type");
8063  }
8064  if (ParseToken(lltok::rparen, "expected ')' here"))
8065  return true;
8066  } while (EatIfPresent(lltok::comma));
8067 
8068  if (ParseToken(lltok::rparen, "expected ')' here"))
8069  return true;
8070 
8071  return false;
8072 }
8073 
8074 /// FunctionSummary
8075 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8076 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8077 /// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
8078 bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8079  unsigned ID) {
8080  assert(Lex.getKind() == lltok::kw_function);
8081  Lex.Lex();
8082 
8083  StringRef ModulePath;
8085  /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
8086  /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8087  unsigned InstCount;
8088  std::vector<FunctionSummary::EdgeTy> Calls;
8089  FunctionSummary::TypeIdInfo TypeIdInfo;
8090  std::vector<ValueInfo> Refs;
8091  // Default is all-zeros (conservative values).
8092  FunctionSummary::FFlags FFlags = {};
8093  if (ParseToken(lltok::colon, "expected ':' here") ||
8094  ParseToken(lltok::lparen, "expected '(' here") ||
8095  ParseModuleReference(ModulePath) ||
8096  ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
8097  ParseToken(lltok::comma, "expected ',' here") ||
8098  ParseToken(lltok::kw_insts, "expected 'insts' here") ||
8099  ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
8100  return true;
8101 
8102  // Parse optional fields
8103  while (EatIfPresent(lltok::comma)) {
8104  switch (Lex.getKind()) {
8105  case lltok::kw_funcFlags:
8106  if (ParseOptionalFFlags(FFlags))
8107  return true;
8108  break;
8109  case lltok::kw_calls:
8110  if (ParseOptionalCalls(Calls))
8111  return true;
8112  break;
8113  case lltok::kw_typeIdInfo:
8114  if (ParseOptionalTypeIdInfo(TypeIdInfo))
8115  return true;
8116  break;
8117  case lltok::kw_refs:
8118  if (ParseOptionalRefs(Refs))
8119  return true;
8120  break;
8121  default:
8122  return Error(Lex.getLoc(), "expected optional function summary field");
8123  }
8124  }
8125 
8126  if (ParseToken(lltok::rparen, "expected ')' here"))
8127  return true;
8128 
8129  auto FS = std::make_unique<FunctionSummary>(
8130  GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8131  std::move(Calls), std::move(TypeIdInfo.TypeTests),
8132  std::move(TypeIdInfo.TypeTestAssumeVCalls),
8133  std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8134  std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8135  std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
8136 
8137  FS->setModulePath(ModulePath);
8138 
8139  AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8140  ID, std::move(FS));
8141 
8142  return false;
8143 }
8144 
8145 /// VariableSummary
8146 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8147 /// [',' OptionalRefs]? ')'
8148 bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8149  unsigned ID) {
8150  assert(Lex.getKind() == lltok::kw_variable);
8151  Lex.Lex();
8152 
8153  StringRef ModulePath;
8155  /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
8156  /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8157  GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8158  /* WriteOnly */ false);
8159  std::vector<ValueInfo> Refs;
8160  VTableFuncList VTableFuncs;
8161  if (ParseToken(lltok::colon, "expected ':' here") ||
8162  ParseToken(lltok::lparen, "expected '(' here") ||
8163  ParseModuleReference(ModulePath) ||
8164  ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
8165  ParseToken(lltok::comma, "expected ',' here") ||
8166  ParseGVarFlags(GVarFlags))
8167  return true;
8168 
8169  // Parse optional fields
8170  while (EatIfPresent(lltok::comma)) {
8171  switch (Lex.getKind()) {
8172  case lltok::kw_vTableFuncs:
8173  if (ParseOptionalVTableFuncs(VTableFuncs))
8174  return true;
8175  break;
8176  case lltok::kw_refs:
8177  if (ParseOptionalRefs(Refs))
8178  return true;
8179  break;
8180  default:
8181  return Error(Lex.getLoc(), "expected optional variable summary field");
8182  }
8183  }
8184 
8185  if (ParseToken(lltok::rparen, "expected ')' here"))
8186  return true;
8187 
8188  auto GS =
8189  std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8190 
8191  GS->setModulePath(ModulePath);
8192  GS->setVTableFuncs(std::move(VTableFuncs));
8193 
8194  AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8195  ID, std::move(GS));
8196 
8197  return false;
8198 }
8199 
8200 /// AliasSummary
8201 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8202 /// 'aliasee' ':' GVReference ')'
8203 bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8204  unsigned ID) {
8205  assert(Lex.getKind() == lltok::kw_alias);
8206  LocTy Loc = Lex.getLoc();
8207  Lex.Lex();
8208 
8209  StringRef ModulePath;
8211  /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
8212  /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8213  if (ParseToken(lltok::colon, "expected ':' here") ||
8214  ParseToken(lltok::lparen, "expected '(' here") ||
8215  ParseModuleReference(ModulePath) ||
8216  ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
8217  ParseToken(lltok::comma, "expected ',' here") ||
8218  ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8219  ParseToken(lltok::colon, "expected ':' here"))
8220  return true;
8221 
8222  ValueInfo AliaseeVI;
8223  unsigned GVId;
8224  if (ParseGVReference(AliaseeVI, GVId))
8225  return true;
8226 
8227  if (ParseToken(lltok::rparen, "expected ')' here"))
8228  return true;
8229 
8230  auto AS = std::make_unique<AliasSummary>(GVFlags);
8231 
8232  AS->setModulePath(ModulePath);
8233 
8234  // Record forward reference if the aliasee is not parsed yet.
8235  if (AliaseeVI.getRef() == FwdVIRef) {
8236  auto FwdRef = ForwardRefAliasees.insert(
8237  std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
8238  FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
8239  } else {
8240  auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8241  assert(Summary && "Aliasee must be a definition");
8242  AS->setAliasee(AliaseeVI, Summary);
8243  }
8244 
8245  AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8246  ID, std::move(AS));
8247 
8248  return false;
8249 }
8250 
8251 /// Flag
8252 /// ::= [0|1]
8253 bool LLParser::ParseFlag(unsigned &Val) {
8254  if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8255  return TokError("expected integer");
8256  Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8257  Lex.Lex();
8258  return false;
8259 }
8260 
8261 /// OptionalFFlags
8262 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8263 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8264 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
8265 /// [',' 'noInline' ':' Flag]? ')'
8266 /// [',' 'alwaysInline' ':' Flag]? ')'
8267 
8268 bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8269  assert(Lex.getKind() == lltok::kw_funcFlags);
8270  Lex.Lex();
8271 
8272  if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
8273  ParseToken(lltok::lparen, "expected '(' in funcFlags"))
8274  return true;
8275 
8276  do {
8277  unsigned Val = 0;
8278  switch (Lex.getKind()) {
8279  case lltok::kw_readNone:
8280  Lex.Lex();
8281  if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8282  return true;
8283  FFlags.ReadNone = Val;
8284  break;
8285  case lltok::kw_readOnly:
8286  Lex.Lex();
8287  if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8288  return true;
8289  FFlags.ReadOnly = Val;
8290  break;
8291  case lltok::kw_noRecurse:
8292  Lex.Lex();
8293  if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8294  return true;
8295  FFlags.NoRecurse = Val;
8296  break;
8298  Lex.Lex();
8299  if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8300  return true;
8301  FFlags.ReturnDoesNotAlias = Val;
8302  break;
8303  case lltok::kw_noInline:
8304  Lex.Lex();
8305  if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8306  return true;
8307  FFlags.NoInline = Val;
8308  break;
8310  Lex.Lex();
8311  if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8312  return true;
8313  FFlags.AlwaysInline = Val;
8314  break;
8315  default:
8316  return Error(Lex.getLoc(), "expected function flag type");
8317  }
8318  } while (EatIfPresent(lltok::comma));
8319 
8320  if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
8321  return true;
8322 
8323  return false;
8324 }
8325 
8326 /// OptionalCalls
8327 /// := 'calls' ':' '(' Call [',' Call]* ')'
8328 /// Call ::= '(' 'callee' ':' GVReference
8329 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8330 bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8331  assert(Lex.getKind() == lltok::kw_calls);
8332  Lex.Lex();
8333 
8334  if (ParseToken(lltok::colon, "expected ':' in calls") |
8335  ParseToken(lltok::lparen, "expected '(' in calls"))
8336  return true;
8337 
8338  IdToIndexMapType IdToIndexMap;
8339  // Parse each call edge
8340  do {
8341  ValueInfo VI;
8342  if (ParseToken(lltok::lparen, "expected '(' in call") ||
8343  ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
8344  ParseToken(lltok::colon, "expected ':'"))
8345  return true;
8346 
8347  LocTy Loc = Lex.getLoc();
8348  unsigned GVId;
8349  if (ParseGVReference(VI, GVId))
8350  return true;
8351 
8353  unsigned RelBF = 0;
8354  if (EatIfPresent(lltok::comma)) {
8355  // Expect either hotness or relbf
8356  if (EatIfPresent(lltok::kw_hotness)) {
8357  if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
8358  return true;
8359  } else {
8360  if (ParseToken(lltok::kw_relbf, "expected relbf") ||
8361  ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
8362  return true;
8363  }
8364  }
8365  // Keep track of the Call array index needing a forward reference.
8366  // We will save the location of the ValueInfo needing an update, but
8367  // can only do so once the std::vector is finalized.
8368  if (VI.getRef() == FwdVIRef)
8369  IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8370  Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8371 
8372  if (ParseToken(lltok::rparen, "expected ')' in call"))
8373  return true;
8374  } while (EatIfPresent(lltok::comma));
8375 
8376  // Now that the Calls vector is finalized, it is safe to save the locations
8377  // of any forward GV references that need updating later.
8378  for (auto I : IdToIndexMap) {
8379  for (auto P : I.second) {
8380  assert(Calls[P.first].first.getRef() == FwdVIRef &&
8381  "Forward referenced ValueInfo expected to be empty");
8382  auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8383  I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8384  FwdRef.first->second.push_back(
8385  std::make_pair(&Calls[P.first].first, P.second));
8386  }
8387  }
8388 
8389  if (ParseToken(lltok::rparen, "expected ')' in calls"))
8390  return true;
8391 
8392  return false;
8393 }
8394 
8395 /// Hotness
8396 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
8397 bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
8398  switch (Lex.getKind()) {
8399  case lltok::kw_unknown:
8401  break;
8402  case lltok::kw_cold:
8404  break;
8405  case lltok::kw_none:
8407  break;
8408  case lltok::kw_hot:
8409  Hotness = CalleeInfo::HotnessType::Hot;
8410  break;
8411  case lltok::kw_critical:
8413  break;
8414  default:
8415  return Error(Lex.getLoc(), "invalid call edge hotness");
8416  }
8417  Lex.Lex();
8418  return false;
8419 }
8420 
8421 /// OptionalVTableFuncs
8422 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8423 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8424 bool LLParser::ParseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
8425  assert(Lex.getKind() == lltok::kw_vTableFuncs);
8426  Lex.Lex();
8427 
8428  if (ParseToken(lltok::colon, "expected ':' in vTableFuncs") |
8429  ParseToken(lltok::lparen, "expected '(' in vTableFuncs"))
8430  return true;
8431 
8432  IdToIndexMapType IdToIndexMap;
8433  // Parse each virtual function pair
8434  do {
8435  ValueInfo VI;
8436  if (ParseToken(lltok::lparen, "expected '(' in vTableFunc") ||
8437  ParseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
8438  ParseToken(lltok::colon, "expected ':'"))
8439  return true;
8440 
8441  LocTy Loc = Lex.getLoc();
8442  unsigned GVId;
8443  if (ParseGVReference(VI, GVId))
8444  return true;
8445 
8446  uint64_t Offset;
8447  if (ParseToken(lltok::comma, "expected comma") ||
8448  ParseToken(lltok::kw_offset, "expected offset") ||
8449  ParseToken(lltok::colon, "expected ':'") || ParseUInt64(Offset))
8450  return true;
8451 
8452  // Keep track of the VTableFuncs array index needing a forward reference.
8453  // We will save the location of the ValueInfo needing an update, but
8454  // can only do so once the std::vector is finalized.
8455  if (VI == EmptyVI)
8456  IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
8457  VTableFuncs.push_back({VI, Offset});
8458 
8459  if (ParseToken(lltok::rparen, "expected ')' in vTableFunc"))
8460  return true;
8461  } while (EatIfPresent(lltok::comma));
8462 
8463  // Now that the VTableFuncs vector is finalized, it is safe to save the
8464  // locations of any forward GV references that need updating later.
8465  for (auto I : IdToIndexMap) {
8466  for (auto P : I.second) {
8467  assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
8468  "Forward referenced ValueInfo expected to be empty");
8469  auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8470  I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8471  FwdRef.first->second.push_back(
8472  std::make_pair(&VTableFuncs[P.first].FuncVI, P.second));
8473  }
8474  }
8475 
8476  if (ParseToken(lltok::rparen, "expected ')' in vTableFuncs"))
8477  return true;
8478 
8479  return false;
8480 }
8481 
8482 /// OptionalRefs
8483 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8484 bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
8485  assert(Lex.getKind() == lltok::kw_refs);
8486  Lex.Lex();
8487 
8488  if (ParseToken(lltok::colon, "expected ':' in refs") |
8489  ParseToken(lltok::lparen, "expected '(' in refs"))
8490  return true;
8491 
8492  struct ValueContext {
8493  ValueInfo VI;
8494  unsigned GVId;
8495  LocTy Loc;
8496  };
8497  std::vector<ValueContext> VContexts;
8498  // Parse each ref edge
8499  do {
8500  ValueContext VC;
8501  VC.Loc = Lex.getLoc();
8502  if (ParseGVReference(VC.VI, VC.GVId))
8503  return true;
8504  VContexts.push_back(VC);
8505  } while (EatIfPresent(lltok::comma));
8506 
8507  // Sort value contexts so that ones with writeonly
8508  // and readonly ValueInfo are at the end of VContexts vector.
8509  // See FunctionSummary::specialRefCounts()
8510  llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
8511  return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
8512  });
8513 
8514  IdToIndexMapType IdToIndexMap;
8515  for (auto &VC : VContexts) {
8516  // Keep track of the Refs array index needing a forward reference.
8517  // We will save the location of the ValueInfo needing an update, but
8518  // can only do so once the std::vector is finalized.
8519  if (VC.VI.getRef() == FwdVIRef)
8520  IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
8521  Refs.push_back(VC.VI);
8522  }
8523 
8524  // Now that the Refs vector is finalized, it is safe to save the locations
8525  // of any forward GV references that need updating later.
8526  for (auto I : IdToIndexMap) {
8527  for (auto P : I.second) {
8528  assert(Refs[P.first].getRef() == FwdVIRef &&
8529  "Forward referenced ValueInfo expected to be empty");
8530  auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8531  I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8532  FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
8533  }
8534  }
8535 
8536  if (ParseToken(lltok::rparen, "expected ')' in refs"))
8537  return true;
8538 
8539  return false;
8540 }
8541 
8542 /// OptionalTypeIdInfo
8543 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8544 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8545 /// [',' TypeCheckedLoadConstVCalls]? ')'
8546 bool LLParser::ParseOptionalTypeIdInfo(
8547  FunctionSummary::TypeIdInfo &TypeIdInfo) {
8548  assert(Lex.getKind() == lltok::kw_typeIdInfo);
8549  Lex.Lex();
8550 
8551  if (ParseToken(lltok::colon, "expected ':' here") ||
8552  ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8553  return true;
8554 
8555  do {
8556  switch (Lex.getKind()) {
8557  case lltok::kw_typeTests:
8558  if (ParseTypeTests(TypeIdInfo.TypeTests))
8559  return true;
8560  break;
8562  if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
8563  TypeIdInfo.TypeTestAssumeVCalls))
8564  return true;
8565  break;
8567  if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
8568  TypeIdInfo.TypeCheckedLoadVCalls))
8569  return true;
8570  break;
8572  if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
8573  TypeIdInfo.TypeTestAssumeConstVCalls))
8574  return true;
8575  break;
8577  if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
8578  TypeIdInfo.TypeCheckedLoadConstVCalls))
8579  return true;
8580  break;
8581  default:
8582  return Error(Lex.getLoc(), "invalid typeIdInfo list type");
8583  }
8584  } while (EatIfPresent(lltok::comma));
8585 
8586  if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8587  return true;
8588 
8589  return false;
8590 }
8591 
8592 /// TypeTests
8593 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8594 /// [',' (SummaryID | UInt64)]* ')'
8595 bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
8596  assert(Lex.getKind() == lltok::kw_typeTests);
8597  Lex.Lex();
8598 
8599  if (ParseToken(lltok::colon, "expected ':' here") ||
8600  ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8601  return true;
8602 
8603  IdToIndexMapType IdToIndexMap;
8604  do {
8605  GlobalValue::GUID GUID = 0;
8606  if (Lex.getKind() == lltok::SummaryID) {
8607  unsigned ID = Lex.getUIntVal();
8608  LocTy Loc = Lex.getLoc();
8609  // Keep track of the TypeTests array index needing a forward reference.
8610  // We will save the location of the GUID needing an update, but
8611  // can only do so once the std::vector is finalized.
8612  IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
8613  Lex.Lex();
8614  } else if (ParseUInt64(GUID))
8615  return true;
8616  TypeTests.push_back(GUID);
8617  } while (EatIfPresent(lltok::comma));
8618 
8619  // Now that the TypeTests vector is finalized, it is safe to save the
8620  // locations of any forward GV references that need updating later.
8621  for (auto I : IdToIndexMap) {
8622  for (auto P : I.second) {
8623  assert(TypeTests[P.first] == 0 &&
8624  "Forward referenced type id GUID expected to be 0");
8625  auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8626  I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8627  FwdRef.first->second.push_back(
8628  std::make_pair(&TypeTests[P.first], P.second));
8629  }
8630  }
8631 
8632  if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8633  return true;
8634 
8635  return false;
8636 }
8637 
8638 /// VFuncIdList
8639 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
8640 bool LLParser::ParseVFuncIdList(
8641  lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
8642  assert(Lex.getKind() == Kind);
8643  Lex.Lex();
8644 
8645  if (ParseToken(lltok::colon, "expected ':' here") ||
8646  ParseToken(lltok::lparen, "expected '(' here"))
8647  return true;
8648 
8649  IdToIndexMapType IdToIndexMap;
8650  do {
8651  FunctionSummary::VFuncId VFuncId;
8652  if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
8653  return true;
8654  VFuncIdList.push_back(VFuncId);
8655  } while (EatIfPresent(lltok::comma));
8656 
8657  if (ParseToken(lltok::rparen, "expected ')' here"))
8658  return true;
8659 
8660  // Now that the VFuncIdList vector is finalized, it is safe to save the
8661  // locations of any forward GV references that need updating later.
8662  for (auto I : IdToIndexMap) {
8663  for (auto P : I.second) {
8664  assert(VFuncIdList[P.first].GUID == 0 &&
8665  "Forward referenced type id GUID expected to be 0");
8666  auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8667  I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8668  FwdRef.first->second.push_back(
8669  std::make_pair(&VFuncIdList[P.first].GUID, P.second));
8670  }
8671  }
8672 
8673  return false;
8674 }
8675 
8676 /// ConstVCallList
8677 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8678 bool LLParser::ParseConstVCallList(
8679  lltok::Kind Kind,
8680  std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8681  assert(Lex.getKind() == Kind);
8682  Lex.Lex();
8683 
8684  if (ParseToken(lltok::colon, "expected ':' here") ||
8685  ParseToken(lltok::lparen, "expected '(' here"))
8686  return true;
8687 
8688  IdToIndexMapType IdToIndexMap;
8689  do {
8690  FunctionSummary::ConstVCall ConstVCall;
8691  if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8692  return true;
8693  ConstVCallList.push_back(ConstVCall);
8694  } while (EatIfPresent(lltok::comma));
8695 
8696  if (ParseToken(lltok::rparen, "expected ')' here"))
8697  return true;
8698 
8699  // Now that the ConstVCallList vector is finalized, it is safe to save the
8700  // locations of any forward GV references that need updating later.
8701  for (auto I : IdToIndexMap) {
8702  for (auto P : I.second) {
8703  assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8704  "Forward referenced type id GUID expected to be 0");
8705  auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8706  I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8707  FwdRef.first->second.push_back(
8708  std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8709  }
8710  }
8711 
8712  return false;
8713 }
8714 
8715 /// ConstVCall
8716 /// ::= '(' VFuncId ',' Args ')'
8717 bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
8718  IdToIndexMapType &IdToIndexMap, unsigned Index) {
8719  if (ParseToken(lltok::lparen, "expected '(' here") ||
8720  ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
8721  return true;
8722 
8723  if (EatIfPresent(lltok::comma))
8724  if (ParseArgs(ConstVCall.Args))
8725  return true;
8726 
8727  if (ParseToken(lltok::rparen, "expected ')' here"))
8728  return true;
8729 
8730  return false;
8731 }
8732 
8733 /// VFuncId
8734 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8735 /// 'offset' ':' UInt64 ')'
8736 bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
8737  IdToIndexMapType &IdToIndexMap, unsigned Index) {
8738  assert(Lex.getKind() == lltok::kw_vFuncId);
8739  Lex.Lex();
8740 
8741  if (ParseToken(lltok::colon, "expected ':' here") ||
8742  ParseToken(lltok::lparen, "expected '(' here"))
8743  return true;
8744 
8745  if (Lex.getKind() == lltok::SummaryID) {
8746  VFuncId.GUID = 0;
8747  unsigned ID = Lex.getUIntVal();
8748  LocTy Loc = Lex.getLoc();
8749  // Keep track of the array index needing a forward reference.
8750  // We will save the location of the GUID needing an update, but
8751  // can only do so once the caller's std::vector is finalized.
8752  IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
8753  Lex.Lex();
8754  } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
8755  ParseToken(lltok::colon, "expected ':' here") ||
8756  ParseUInt64(VFuncId.GUID))
8757  return true;
8758 
8759  if (ParseToken(lltok::comma, "expected ',' here") ||
8760  ParseToken(lltok::kw_offset, "expected 'offset' here") ||
8761  ParseToken(lltok::colon, "expected ':' here") ||
8762  ParseUInt64(VFuncId.Offset) ||
8763  ParseToken(lltok::rparen, "expected ')' here"))
8764  return true;
8765 
8766  return false;
8767 }
8768 
8769 /// GVFlags
8770 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8771 /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8772 /// 'dsoLocal' ':' Flag ',' 'canAutoHide' ':' Flag ')'
8773 bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
8774  assert(Lex.getKind() == lltok::kw_flags);
8775  Lex.Lex();
8776 
8777  if (ParseToken(lltok::colon, "expected ':' here") ||
8778  ParseToken(lltok::lparen, "expected '(' here"))
8779  return true;
8780 
8781  do {
8782  unsigned Flag = 0;
8783  switch (Lex.getKind()) {
8784  case lltok::kw_linkage:
8785  Lex.Lex();
8786  if (ParseToken(lltok::colon, "expected ':'"))
8787  return true;
8788  bool HasLinkage;
8789  GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
8790  assert(HasLinkage && "Linkage not optional in summary entry");
8791  Lex.Lex();
8792  break;
8794  Lex.Lex();
8795  if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8796  return true;
8797  GVFlags.NotEligibleToImport = Flag;
8798  break;
8799  case lltok::kw_live:
8800  Lex.Lex();
8801  if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8802  return true;
8803  GVFlags.Live = Flag;
8804  break;
8805  case lltok::kw_dsoLocal:
8806  Lex.Lex();
8807  if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8808  return true;
8809  GVFlags.DSOLocal = Flag;
8810  break;
8811  case lltok::kw_canAutoHide:
8812  Lex.Lex();
8813  if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8814  return true;
8815  GVFlags.CanAutoHide = Flag;
8816  break;
8817  default:
8818  return Error(Lex.getLoc(), "expected gv flag type");
8819  }
8820  } while (EatIfPresent(lltok::comma));
8821 
8822  if (ParseToken(lltok::rparen, "expected ')' here"))
8823  return true;
8824 
8825  return false;
8826 }
8827 
8828 /// GVarFlags
8829 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
8830 /// ',' 'writeonly' ':' Flag ')'
8831 bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
8832  assert(Lex.getKind() == lltok::kw_varFlags);
8833  Lex.Lex();
8834 
8835  if (ParseToken(lltok::colon, "expected ':' here") ||
8836  ParseToken(lltok::lparen, "expected '(' here"))
8837  return true;
8838 
8839  auto ParseRest = [this](unsigned int &Val) {
8840  Lex.Lex();
8841  if (ParseToken(lltok::colon, "expected ':'"))
8842  return true;
8843  return ParseFlag(Val);
8844  };
8845 
8846  do {
8847  unsigned Flag = 0;
8848  switch (Lex.getKind()) {
8849  case lltok::kw_readonly:
8850  if (ParseRest(Flag))
8851  return true;
8852  GVarFlags.MaybeReadOnly = Flag;
8853  break;
8854  case lltok::kw_writeonly:
8855  if (ParseRest(Flag))
8856  return true;
8857  GVarFlags.MaybeWriteOnly = Flag;
8858  break;
8859  default:
8860  return Error(Lex.getLoc(), "expected gvar flag type");
8861  }
8862  } while (EatIfPresent(lltok::comma));
8863  return ParseToken(lltok::rparen, "expected ')' here");
8864 }
8865 
8866 /// ModuleReference
8867 /// ::= 'module' ':' UInt
8868 bool LLParser::ParseModuleReference(StringRef &ModulePath) {
8869  // Parse module id.
8870  if (ParseToken(lltok::kw_module, "expected 'module' here") ||
8871  ParseToken(lltok::colon, "expected ':' here") ||
8872  ParseToken(lltok::SummaryID, "expected module ID"))
8873  return true;
8874 
8875  unsigned ModuleID = Lex.getUIntVal();
8876  auto I = ModuleIdMap.find(ModuleID);
8877  // We should have already parsed all module IDs
8878  assert(I != ModuleIdMap.end());
8879  ModulePath = I->second;
8880  return false;
8881 }
8882 
8883 /// GVReference
8884 /// ::= SummaryID
8885 bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
8886  bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
8887  if (!ReadOnly)
8888  WriteOnly = EatIfPresent(lltok::kw_writeonly);
8889  if (ParseToken(lltok::SummaryID, "expected GV ID"))
8890  return true;
8891 
8892  GVId = Lex.getUIntVal();
8893  // Check if we already have a VI for this GV
8894  if (GVId < NumberedValueInfos.size()) {
8895  assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
8896  VI = NumberedValueInfos[GVId];
8897  } else
8898  // We will create a forward reference to the stored location.
8899  VI = ValueInfo(false, FwdVIRef);
8900 
8901  if (ReadOnly)
8902  VI.setReadOnly();
8903  if (WriteOnly)
8904  VI.setWriteOnly();
8905  return false;
8906 }
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:242
LLLexer::LocTy Loc
Definition: LLParser.h:60
uint64_t CallInst * C
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
Definition: CallingConv.h:168
void sortUseList(Compare Cmp)
Sort the use-list.
Definition: Value.h:746
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition: LLParser.cpp:77
static const char * name
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:667
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:641
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
MacinfoRecordType
Definition: Dwarf.h:295
*ViewGraph Emit a dot run run gv on the postscript file
Definition: GraphWriter.h:362
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
Calling convention used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
Definition: CallingConv.h:218
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1141
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2647
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
iterator_range< use_iterator > uses()
Definition: Value.h:375
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:177
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:54
MaybeAlign getAlignment() const
Retrieve the alignment attribute, if it exists.
Definition: Attributes.h:777
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1620
*p = old <signed v ? old : v
Definition: Instructions.h:740
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
LLVMContext & Context
void UpgradeSectionAttributes(Module &M)
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
Definition: CallingConv.h:154
bool isMetadataTy() const
Return true if this is &#39;metadata&#39;.
Definition: Type.h:191
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:502
This class represents lattice values for constants.
Definition: AllocatorList.h:23
unsigned Linkage
The linkage type of the associated global value.
static bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
Calling convention used by HipHop Virtual Machine (HHVM) to perform calls to and from translation cac...
Definition: CallingConv.h:174
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1154
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:265
static ResumeInst * Create(Value *Exn, Instruction *InsertBefore=nullptr)
An instruction for ordering other memory operations.
Definition: Instructions.h:471
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:53
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
An instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:547
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:453
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Unsatisfiable type (i.e. no global has this type metadata)
Available for inspection, not emission.
Definition: GlobalValue.h:49
void push_back(const T &Elt)
Definition: SmallVector.h:211
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
const ValueSymbolTable & getValueSymbolTable() const
Get the symbol table of global variable and function identifiers.
Definition: Module.h:569
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Definition: Instructions.h:918
void addOperand(MDNode *M)
Definition: Metadata.cpp:1088
This class represents a function call, abstracting a target machine&#39;s calling convention.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID...
void setGC(std::string Str)
Definition: Function.cpp:501
This file contains the declarations for metadata subclasses.
void emplace(ArgTypes &&... Args)
Create a new object by constructing it in place with the given arguments.
Definition: Optional.h:237
static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:637
unsigned less or equal
Definition: InstrTypes.h:758
The two locations do not alias at all.
Definition: AliasAnalysis.h:84
unsigned less than
Definition: InstrTypes.h:757
*p = old <unsigned v ? old : v
Definition: Instructions.h:744
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2183
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
Definition: Instructions.h:582
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:738
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
uint64_t Info
Additional information for the resolution:
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
iterator find(StringRef Key)
Definition: StringMap.h:355
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition: LLParser.cpp:90
*p = old >unsigned v ? old : v
Definition: Instructions.h:742
This instruction constructs a fixed permutation of two input vectors.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
Externally visible function.
Definition: GlobalValue.h:48
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition: Module.cpp:259
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:744
bool isTerminator() const
Definition: Instruction.h:128
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics that do not have all constant integer arguments.
void setDataLayout(StringRef Desc)
Set the data layout.
Definition: Module.cpp:363
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:748
void deleteValue()
Delete a pointer to a generic Value.
Definition: Value.cpp:99
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:38
C - The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
AttrBuilder & addDereferenceableAttr(uint64_t Bytes)
This turns the number of dereferenceable bytes into the form used internally in Attribute.
Metadata node.
Definition: Metadata.h:872
F(f)
static bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition: Type.cpp:331
unsigned UIntVal
Definition: LLParser.h:61
const fltSemantics & getSemantics() const
Definition: APFloat.h:1175
param_iterator param_end() const
Definition: DerivedTypes.h:134
An instruction for reading from memory.
Definition: Instructions.h:169
void setIgnoreColonInIdentifiers(bool val)
Definition: LLLexer.h:65
const GlobalListType & getGlobalList() const
Get the Module&#39;s list of global variables (constant).
Definition: Module.h:525
AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:710
Calling convention used for AMDPAL vertex shader if tessellation is in use.
Definition: CallingConv.h:226
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:230
const APFloat & getAPFloatVal() const
Definition: LLLexer.h:63
Calling convention between AArch64 SVE functions.
Definition: CallingConv.h:237
static bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Definition: Type.cpp:336
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e...
Definition: Globals.cpp:160
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy, const std::string &Name)
Definition: LLParser.cpp:1364
Type * getTyVal() const
Definition: LLLexer.h:60
unsigned getVirtuality(StringRef VirtualityString)
Definition: Dwarf.cpp:313
*p = old >signed v ? old : v
Definition: Instructions.h:738
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock *> IndirectDests, ArrayRef< Value *> Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair...
Tentative definitions.
Definition: GlobalValue.h:58
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return true if the attribute exists at the given index.
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:1065
LegalityPredicate isVector(unsigned TypeIdx)
True iff the specified type index is a vector.
static Optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
static LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
Calling convention used for Mesa/AMDPAL geometry shaders.
Definition: CallingConv.h:202
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1566
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:330
TypeTestResolution TTRes
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2205
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:130
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
Definition: Instructions.h:799
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:318
const AliasListType & getAliasList() const
Get the Module&#39;s list of aliases (constant).
Definition: Module.h:542
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
bool Run()
Run: module ::= toplevelentity*.
Definition: LLParser.cpp:64
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:743
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition: InstrTypes.h:742
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition: SlotMapping.h:34
A tuple of MDNodes.
Definition: Metadata.h:1334
static bool castIsValid(Instruction::CastOps op, Value *S, Type *DstTy)
This method can be used to determine if a cast from S to DstTy using Opcode op is valid or not...
SPIR_KERNEL - Calling convention for SPIR kernel functions.
Definition: CallingConv.h:147
static Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static Type * getTokenTy(LLVMContext &C)
Definition: Type.cpp:171
bool hasAttributes() const
Return true if the builder has IR-level attributes.
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:369
bool hasAlignmentAttr() const
Return true if the builder has an alignment attribute.
AttrBuilder & addDereferenceableOrNullAttr(uint64_t Bytes)
This turns the number of dereferenceable_or_null bytes into the form used internally in Attribute...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:460
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
Definition: Type.h:162
#define INT64_MIN
Definition: DataTypes.h:80
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:388
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module...
bool isStrongerThan(AtomicOrdering ao, AtomicOrdering other)
Returns true if ao is stronger than other as defined by the AtomicOrdering lattice, which is based on C++&#39;s definition.
const ComdatSymTabType & getComdatSymbolTable() const
Get the Module&#39;s symbol table for COMDATs (constant).
Definition: Module.h:574
Class to represent struct types.
Definition: DerivedTypes.h:238
Array subrange.
APSInt extOrTrunc(uint32_t width) const
Definition: APSInt.h:109
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:659
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
#define INT64_MAX
Definition: DataTypes.h:77
void setThreadLocalMode(ThreadLocalMode Val)
Definition: GlobalValue.h:254
static GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:541
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
AttrBuilder & addAllocSizeAttr(unsigned ElemSizeArg, const Optional< unsigned > &NumElemsArg)
This turns one (or two) ints into the form used internally in Attribute.
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:739
TypeID
Definitions of all of the base types for the Type system.
Definition: Type.h:55
Just do a regular virtual call.
The linker may choose any COMDAT.
Definition: Comdat.h:34
lltok::Kind Lex()
Definition: LLLexer.h:52
AttrBuilder & addByValAttr(Type *Ty)
This turns a byval type into the form used internally in Attribute.
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:286
static const unsigned MaximumAlignment
Definition: Value.h:655
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
void setDLLStorageClass(DLLStorageClassTypes C)
Definition: GlobalValue.h:271
static StructType * get(LLVMContext &Context, ArrayRef< Type *> Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:346
AtomicOrdering
Atomic ordering for LLVM&#39;s memory model.
enum llvm::WholeProgramDevirtResolution::Kind TheKind
static bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
void addHandler(BasicBlock *Dest)
Add an entry to the switch instruction...
static StringRef getOperationName(BinOp Op)
void setPartition(StringRef Part)
Definition: Globals.cpp:194
Subprogram description.
llvm::Optional< Function * > remangleIntrinsicFunction(Function *F)
Definition: Function.cpp:1408
Class to represent function types.
Definition: DerivedTypes.h:108
#define UINT64_MAX
Definition: DataTypes.h:83
static Type * getLabelTy(LLVMContext &C)
Definition: Type.cpp:166
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:246
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value. ...
Definition: Type.h:244
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4525
LLVM_NODISCARD AttributeList removeAttributes(LLVMContext &C, unsigned Index, const AttrBuilder &AttrsToRemove) const
Remove the specified attributes at the specified index from this attribute list.
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Definition: Instructions.h:722
Class to represent array types.
Definition: DerivedTypes.h:408
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:62
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:628
Enumeration value.
This instruction compares its operands according to the predicate given to the constructor.
static Constant * getSelect(Constant *C, Constant *V1, Constant *V2, Type *OnlyIfReducedTy=nullptr)
Select constant expr.
Definition: Constants.cpp:2058
void setComdat(Comdat *C)
Definition: GlobalObject.h:122
bool isVarArg() const
Definition: DerivedTypes.h:128
unsigned getUIntVal() const
Definition: LLLexer.h:61
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type. ...
Definition: Module.cpp:113
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
std::string StrVal
Definition: LLParser.h:63
static bool Verify(FunctionType *Ty, StringRef Constraints)
Verify - This static method can be used by the parser to check to see if the specified constraint str...
Definition: InlineAsm.cpp:253
An instruction for storing to memory.
Definition: Instructions.h:331
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:203
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:430
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:158
Debug location.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
PTX_Kernel - Call to a PTX kernel.
Definition: CallingConv.h:125
void setBody(ArrayRef< Type *> Elements, bool isPacked=false)
Specify a body for an opaque identified type.
Definition: Type.cpp:373
Calling convention used for AVR signal routines.
Definition: CallingConv.h:190
Class to represent pointers.
Definition: DerivedTypes.h:579
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1248
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:139
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
Calling convention used for Mesa/AMDPAL compute shaders.
Definition: CallingConv.h:208
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return &#39;this&#39;.
Definition: Type.h:307
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
The C convention as implemented on Windows/x86-64 and AArch64.
Definition: CallingConv.h:164
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:105
X86_INTR - x86 hardware interrupt context.
Definition: CallingConv.h:184
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:141
bool isFloatTy() const
Return true if this is &#39;float&#39;, a 32-bit IEEE fp type.
Definition: Type.h:147
ExternalWeak linkage description.
Definition: GlobalValue.h:57
static Constant * getInsertValue(Constant *Agg, Constant *Val, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2251
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Return a temporary node.
Definition: Metadata.h:1161
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1174
void setCallingConv(CallingConv::ID CC)
Definition: Function.h:216
#define P(N)
const char * getPointer() const
Definition: SMLoc.h:34
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:51
Intel_OCL_BI - Calling conventions for Intel OpenCL built-ins.
Definition: CallingConv.h:150
No other Module may specify this COMDAT.
Definition: Comdat.h:37
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:135
bool isLabelTy() const
Return true if this is &#39;label&#39;.
Definition: Type.h:188
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Definition: Attributes.cpp:589
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1500
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:465
bool hasName() const
Definition: Value.h:252
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:115
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
Definition: LLParser.cpp:1797
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
PowerPC Reduce CR logical Operation
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1533
bool any() const
Definition: Operator.h:197
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:158
This function has undefined behavior.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
Resume the propagation of an exception.
const APSInt & getAPSIntVal() const
Definition: LLLexer.h:62
unsigned getCallingConvention(StringRef LanguageString)
Definition: Dwarf.cpp:398
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1182
bool isSigned() const
Definition: APSInt.h:76
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
Definition: Instructions.h:131
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:224
Indirect Branch Instruction.
ARM_AAPCS - ARM Architecture Procedure Calling Standard calling convention (aka EABI).
Definition: CallingConv.h:110
void setExternallyInitialized(bool Val)
unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition: Dwarf.cpp:157
StringMap< Type * > NamedTypes
Definition: SlotMapping.h:35
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
Class to accumulate and hold information about a callee.
Constant * ConstantVal
Definition: LLParser.h:66
static bool isValidLinkage(LinkageTypes L)
Definition: GlobalAlias.h:80
static Constant * getShuffleVector(Constant *V1, Constant *V2, Constant *Mask, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2228
param_iterator param_begin() const
Definition: DerivedTypes.h:133
A pair of DIGlobalVariable and DIExpression.
void splice(iterator where, iplist_impl &L2)
Definition: ilist.h:327
Single element (last example in "Short Inline Bit Vectors")
Type::TypeID TypeID
bool isHalfTy() const
Return true if this is &#39;half&#39;, a 16-bit IEEE fp type.
Definition: Type.h:144
AttrBuilder & addAlignmentAttr(MaybeAlign Align)
This turns an alignment into the form used internally in Attribute.
This instruction compares its operands according to the predicate given to the constructor.
unsigned getAddressSpace() const
Definition: Globals.cpp:111
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:732
constexpr double e
Definition: MathExtras.h:57
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1366
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition: GlobalValue.h:69
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:301
static Constant * get(StructType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:1126
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:741
static bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
Definition: Constants.cpp:1363
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:607
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:99
arg_iterator arg_begin()
Definition: Function.h:706
MSP430_INTR - Calling convention used for MSP430 interrupt routines.
Definition: CallingConv.h:116
static Constant * getICmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
get* - Return some common constants without having to specify the full Instruction::OPCODE identifier...
Definition: Constants.cpp:2133
APFloat APFloatVal
Definition: LLParser.h:65
ChecksumKind
Which algorithm (e.g.
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:35
All type identifier related information.
void setTailCallKind(TailCallKind TCK)
std::vector< GlobalValue * > GlobalValues
Definition: SlotMapping.h:33
void setConstant(bool Val)
lltok::Kind getKind() const
Definition: LLLexer.h:58
unsigned getLanguage(StringRef LanguageString)
Definition: Dwarf.cpp:332
1 1 1 1 Always true (always folded)
Definition: InstrTypes.h:749
DebugNameTableKind getNameTableKind() const
std::map< unsigned, Type * > Types
Definition: SlotMapping.h:36
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:511
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1514
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:498
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
static UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
size_t size() const
Definition: SmallVector.h:52
static bool isAtomic(Instruction *I)
enum llvm::ValID::@356 Kind
static wasm::ValType getType(const TargetRegisterClass *RC)
PTX_Device - Call to a PTX device function.
Definition: CallingConv.h:129
static bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h:747
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:532
name anon globals
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1224
static IndirectBrInst * Create(Value *Address, unsigned NumDests, Instruction *InsertBefore=nullptr)
const IFuncListType & getIFuncList() const
Get the Module&#39;s list of ifuncs (constant).
Definition: Module.h:551
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
signed greater than
Definition: InstrTypes.h:759
An imported module (C++ using directive or similar).
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:53
unsigned getTag(StringRef TagString)
Definition: Dwarf.cpp:32
An "identifier" for a virtual function.
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1114
Struct that holds a reference to a particular GUID in a global value summary.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Return a distinct node.
Definition: Metadata.h:1152
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
unsigned DefaultAS
Definition: LLParser.cpp:1568
global_iterator global_end()
Definition: Module.h:584
Register calling convention used for parameters transfer optimization.
Definition: CallingConv.h:214
static Constant * getFCmp(unsigned short pred, Constant *LHS, Constant *RHS, bool OnlyIfReduced=false)
Definition: Constants.cpp:2158
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:736
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:227
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:338
std::vector< VFuncId > TypeCheckedLoadVCalls
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition: APFloat.cpp:155
LocTy getLoc() const
Definition: LLLexer.h:57
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
APSInt APSIntVal
Definition: LLParser.h:64
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
Definition: DerivedTypes.h:594
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:663
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
Definition: LLParser.cpp:846
void setSelectionKind(SelectionKind Val)
Definition: Comdat.h:45
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1163
static DISPFlags getFlag(StringRef Flag)
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:152
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:390
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value *> Args=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
ARM_AAPCS_VFP - Same as ARM_AAPCS, but uses hard floating point ABI.
Definition: CallingConv.h:113
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
Definition: Attributes.h:757
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, Instruction *InsertBefore=nullptr)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
Definition: Alignment.h:117
AttrBuilder & removeAttribute(Attribute::AttrKind Val)
Remove an attribute from the builder.
ARM_APCS - ARM Procedure Calling Standard calling convention (obsolete, but still used on some target...
Definition: CallingConv.h:106
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:348
Calling convention used for Mesa/AMDPAL pixel shaders.
Definition: CallingConv.h:205
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:746
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:50
Module.h This file contains the declarations for the Module class.
Type::subtype_iterator param_iterator
Definition: DerivedTypes.h:131
X86_StdCall - stdcall is the calling conventions mostly used by the Win32 API.
Definition: CallingConv.h:97
Single implementation devirtualization.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1393
This class represents a freeze function that returns random concrete value if an operand is either a ...
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition: Type.h:258
signed less than
Definition: InstrTypes.h:761
Type * getReturnType() const
Definition: DerivedTypes.h:129
unsigned getProgramAddressSpace() const
Definition: DataLayout.h:286
#define GET_OR_DISTINCT(CLASS, ARGS)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:704
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
The linker will choose the largest COMDAT.
Definition: Comdat.h:36
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
Definition: Constants.cpp:767
AttrBuilder & addStackAlignmentAttr(MaybeAlign Align)
This turns a stack alignment into the form used internally in Attribute.
bool isReadOnly() const
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:660
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition: Function.h:226
DWARF expression.
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:454
enum llvm::TypeTestResolution::Kind TheKind
ValueSymbolTable * getValueSymbolTable()
getSymbolTable() - Return the symbol table if any, otherwise nullptr.
Definition: Function.h:683
DebugEmissionKind getEmissionKind() const
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:566
MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
signed less or equal
Definition: InstrTypes.h:762
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:242
This file contains constants used for implementing Dwarf debug support.
static DIFlags getFlag(StringRef Flag)
void push_back(pointer val)
Definition: ilist.h:311
A specification for a virtual function call with all constant integer arguments.
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:47
X86_FastCall - &#39;fast&#39; analog of X86_StdCall.
Definition: CallingConv.h:102
amdgpu Simplify well known AMD library false FunctionCallee Callee
A (clang) module that has been imported by the compile unit.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
void setWeak(bool IsWeak)
Definition: Instructions.h:592
SPIR_FUNC - Calling convention for SPIR non-kernel device functions.
Definition: CallingConv.h:139
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:510
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1629
void setAttributes(AttributeSet A)
Set attribute list for this global.
Generic tagged DWARF-like metadata node.
This struct contains the mappings from the slot numbers to unnamed metadata nodes, global values and types.
Definition: SlotMapping.h:32
A utility class that uses RAII to save and restore the value of a variable.
FunctionNumber(functionNumber)
Definition: LLParser.cpp:2836
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value *> Args, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
Definition: Instructions.h:142
const std::string & getStrVal() const
Definition: LLLexer.h:59
Type array for a subprogram.
Test a byte array (first example)
static std::string getTypeString(Type *T)
Definition: LLParser.cpp:56
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass&#39;s ...
Function to be accessible from DLL.
Definition: GlobalValue.h:72
void eraseFromParent()
This method unlinks &#39;this&#39; from the containing module and deletes it.
Definition: Globals.cpp:85
DIFlags
Debug info flags.
unsigned getNumUses() const
This method computes the number of uses of this Value.
Definition: Value.cpp:161
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument, "this"), where the key is the argument vector.
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:215
ValID - Represents a reference of a definition of some sort with no type.
Definition: LLParser.h:47
void setAlignment(MaybeAlign Align)
Definition: Globals.cpp:116
iterator end()
Definition: Module.h:601
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:144
iterator_range< typename GraphTraits< GraphType >::nodes_iterator > nodes(const GraphType &G)
Definition: GraphTraits.h:108
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:219
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:588
static Type * getIndexedType(Type *Ty, ArrayRef< Value *> IdxList)
Returns the type of the element that would be loaded with a load instruction with the specified param...
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
unsigned greater or equal
Definition: InstrTypes.h:756
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
Definition: APInt.h:486
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value *> Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors") ...
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit...
bool isTokenTy() const
Return true if this is &#39;token&#39;.
Definition: Type.h:194
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:599
void setSourceFileName(StringRef Name)
Set the module&#39;s original source file name.
Definition: Module.h:277
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:614
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
ParseRet
Utilities for the Vector Function ABI name parser.
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
bool isWriteOnly() const
LLVM_NODISCARD AttributeList removeAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const
Remove the specified attribute at the specified index from this attribute list.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
Calling convention used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (ve...
Definition: CallingConv.h:199
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
void setPrologueData(Constant *PrologueData)
Definition: Function.cpp:1509
iterator begin()
Definition: Module.h:599
void appendModuleInlineAsm(StringRef Asm)
Append to the module-scope inline assembly blocks.
Definition: Module.h:296
std::unique_ptr< Constant *[]> ConstantStructElts
Definition: LLParser.h:67
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:740
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:587
void setAttributes(AttributeList A)
Set the parameter attributes for this call.
Definition: InstrTypes.h:1388
void setTargetTriple(StringRef T)
Set the target triple.
Definition: Module.h:284
static const auto FwdVIRef
Definition: LLParser.cpp:7917
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
Definition: LLParser.cpp:7919
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Type * getValueType() const
Definition: GlobalValue.h:279
uint32_t Size
Definition: Profile.cpp:46
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:52
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
void eraseFromParent()
eraseFromParent - This method unlinks &#39;this&#39; from the containing module and deletes it...
Definition: Function.cpp:244
Flags specific to function summaries.
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:42
Tail - This calling convention attemps to make calls as fast as possible while guaranteeing that tail...
Definition: CallingConv.h:81
Inlined bit vector ("Short Inline Bit Vectors")
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:744
Value * lookup(StringRef Name) const
This method finds the value with the given Name in the the symbol table.
FunctionType * FTy
Definition: LLParser.h:62
DISPFlags
Debug info subprogram flags.
Function to be imported from DLL.
Definition: GlobalValue.h:71
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:185
unsigned getMacinfo(StringRef MacinfoString)
Definition: Dwarf.cpp:470
LLVM_NODISCARD AttributeList addAttributes(LLVMContext &C, unsigned Index, const AttrBuilder &B) const
Add attributes to the attribute set at the given index.
void addDestination(BasicBlock *Dest)
Add a destination.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:231
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:185
AttrBuilder & merge(const AttrBuilder &B)
Add the attributes from the builder.
Multiway switch.
static DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator)
Build a DICompositeType with the given ODR identifier.
Deduce and propagate attributes
unsigned getMDKindID(StringRef Name) const
Return a unique non-zero ID for the specified metadata kind.
Definition: Module.cpp:119
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition: CallingConv.h:87
std::string StrVal2
Definition: LLParser.h:63
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:516
LLLexer::LocTy LocTy
Definition: LLParser.h:89
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, Instruction *InsertBefore=nullptr)
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:735
LLVM Value Representation.
Definition: Value.h:74
Fast - This calling convention attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:42
1 0 1 1 True if unordered, greater than, or equal
Definition: InstrTypes.h:745
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:441
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, Instruction *InsertBefore=nullptr)
AttributeSet getFnAttributes() const
The function attributes are returned.
unsigned getAttributeEncoding(StringRef EncodingString)
Definition: Dwarf.cpp:202
This file provides utility classes that use RAII to save and restore values.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
Invoke instruction.
#define PARSE_MD_FIELDS()
static Constant * getExtractValue(Constant *Agg, ArrayRef< unsigned > Idxs, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2275
Convenience struct for specifying and reasoning about fast-math flags.
Definition: Operator.h:160
unsigned greater than
Definition: InstrTypes.h:755
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
A single uniqued string.
Definition: Metadata.h:604
void setPersonalityFn(Constant *Fn)
Definition: Function.cpp:1489
const GlobalValueSummaryMapTy::value_type * getRef() const
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
Definition: LLParser.cpp:853
static bool isVolatile(Instruction *Inst)
Represents a location in source code.
Definition: SMLoc.h:23
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:339
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:737
Calling convention for AMDGPU code object kernels.
Definition: CallingConv.h:211
Used for AVR interrupt routines.
Definition: CallingConv.h:187
Root of the metadata hierarchy.
Definition: Metadata.h:58
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:178
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:215
HHVM calling convention for invoking C/C++ helpers.
Definition: CallingConv.h:177
bool use_empty() const
Definition: Value.h:343
iterator end()
Definition: StringMap.h:340
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:485
static Constant * get(ArrayRef< Constant *> V)
Definition: Constants.cpp:1161
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
Type * getElementType() const
Definition: DerivedTypes.h:598
TLM
Definition: LLParser.cpp:1556
void setDSOLocal(bool Local)
Definition: GlobalValue.h:281
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:277
X86_ThisCall - Similar to X86_StdCall.
Definition: CallingConv.h:121
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
Definition: Attributes.cpp:972
iterator_range< arg_iterator > args()
Definition: Function.h:730
0 0 0 0 Always false (always folded)
Definition: InstrTypes.h:734
signed greater or equal
Definition: InstrTypes.h:760
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:221
Calling convention used for AMDPAL shader stage before geometry shader if geometry is in use...
Definition: CallingConv.h:231
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
an instruction to allocate memory on the stack
Definition: Instructions.h:59
Basic type, like &#39;int&#39; or &#39;float&#39;.
static bool parseField(amd_kernel_code_t &C, MCAsmParser &MCParser, raw_ostream &Err)
void setPrefixData(Constant *PrefixData)
Definition: Function.cpp:1499
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm.type.test) or llvm.type.checked.load intrinsics with all constant integer arguments.
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.
Definition: Constants.cpp:1905
static const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null...