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