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