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