1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/AsmParser/LLParser.h"
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/AsmParser/LLToken.h"
20#include "llvm/AsmParser/SlotMapping.h"
21#include "llvm/BinaryFormat/Dwarf.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/Attributes.h"
24#include "llvm/IR/AutoUpgrade.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/Comdat.h"
28#include "llvm/IR/ConstantRange.h"
29#include "llvm/IR/ConstantRangeList.h"
30#include "llvm/IR/Constants.h"
31#include "llvm/IR/DebugInfoMetadata.h"
32#include "llvm/IR/DerivedTypes.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/GlobalIFunc.h"
35#include "llvm/IR/GlobalObject.h"
36#include "llvm/IR/InlineAsm.h"
37#include "llvm/IR/InstIterator.h"
38#include "llvm/IR/Instructions.h"
39#include "llvm/IR/IntrinsicInst.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Operator.h"
45#include "llvm/IR/Value.h"
46#include "llvm/IR/ValueSymbolTable.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/Compiler.h"
49#include "llvm/Support/ErrorHandling.h"
50#include "llvm/Support/MathExtras.h"
51#include "llvm/Support/ModRef.h"
52#include "llvm/Support/SaveAndRestore.h"
53#include "llvm/Support/raw_ostream.h"
54#include <algorithm>
55#include <cassert>
56#include <cstring>
57#include <optional>
58#include <vector>
59
60using namespace llvm;
61
62static cl::opt<bool> AllowIncompleteIR(
63 "allow-incomplete-ir", cl::init(Val: false), cl::Hidden,
64 cl::desc(
65 "Allow incomplete IR on a best effort basis (references to unknown "
66 "metadata will be dropped)"));
67
68static std::string getTypeString(Type *T) {
69 std::string Result;
70 raw_string_ostream Tmp(Result);
71 Tmp << *T;
72 return Tmp.str();
73}
74
75/// Run: module ::= toplevelentity*
76bool LLParser::Run(bool UpgradeDebugInfo,
77 DataLayoutCallbackTy DataLayoutCallback) {
78 // Prime the lexer.
79 Lex.Lex();
80
81 if (Context.shouldDiscardValueNames())
82 return error(
83 L: Lex.getLoc(),
84 Msg: "Can't read textual IR with a Context that discards named Values");
85
86 if (M) {
87 if (parseTargetDefinitions(DataLayoutCallback))
88 return true;
89 }
90
91 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
92 validateEndOfIndex();
93}
94
95bool LLParser::parseStandaloneConstantValue(Constant *&C,
96 const SlotMapping *Slots) {
97 restoreParsingState(Slots);
98 Lex.Lex();
99
100 Type *Ty = nullptr;
101 if (parseType(Result&: Ty) || parseConstantValue(Ty, C))
102 return true;
103 if (Lex.getKind() != lltok::Eof)
104 return error(L: Lex.getLoc(), Msg: "expected end of string");
105 return false;
106}
107
108bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
109 const SlotMapping *Slots) {
110 restoreParsingState(Slots);
111 Lex.Lex();
112
113 Read = 0;
114 SMLoc Start = Lex.getLoc();
115 Ty = nullptr;
116 if (parseType(Result&: Ty))
117 return true;
118 SMLoc End = Lex.getLoc();
119 Read = End.getPointer() - Start.getPointer();
120
121 return false;
122}
123
124bool LLParser::parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read,
125 const SlotMapping *Slots) {
126 restoreParsingState(Slots);
127 Lex.Lex();
128
129 Read = 0;
130 SMLoc Start = Lex.getLoc();
131 Result = nullptr;
132 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
133 SMLoc End = Lex.getLoc();
134 Read = End.getPointer() - Start.getPointer();
135
136 return Status;
137}
138
139void LLParser::restoreParsingState(const SlotMapping *Slots) {
140 if (!Slots)
141 return;
142 NumberedVals = Slots->GlobalValues;
143 NumberedMetadata = Slots->MetadataNodes;
144 for (const auto &I : Slots->NamedTypes)
145 NamedTypes.insert(
146 KV: std::make_pair(x: I.getKey(), y: std::make_pair(x: I.second, y: LocTy())));
147 for (const auto &I : Slots->Types)
148 NumberedTypes.insert(
149 x: std::make_pair(x: I.first, y: std::make_pair(x: I.second, y: LocTy())));
150}
151
152static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II) {
153 // White-list intrinsics that are safe to drop.
154 if (!isa<DbgInfoIntrinsic>(Val: II) &&
155 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
156 return;
157
158 SmallVector<MetadataAsValue *> MVs;
159 for (Value *V : II->args())
160 if (auto *MV = dyn_cast<MetadataAsValue>(Val: V))
161 if (auto *MD = dyn_cast<MDNode>(Val: MV->getMetadata()))
162 if (MD->isTemporary())
163 MVs.push_back(Elt: MV);
164
165 if (!MVs.empty()) {
166 assert(II->use_empty() && "Cannot have uses");
167 II->eraseFromParent();
168
169 // Also remove no longer used MetadataAsValue wrappers.
170 for (MetadataAsValue *MV : MVs)
171 if (MV->use_empty())
172 delete MV;
173 }
174}
175
176void LLParser::dropUnknownMetadataReferences() {
177 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
178 for (Function &F : *M) {
179 F.eraseMetadataIf(Pred);
180 for (Instruction &I : make_early_inc_range(Range: instructions(F))) {
181 I.eraseMetadataIf(Pred);
182
183 if (auto *II = dyn_cast<IntrinsicInst>(Val: &I))
184 dropIntrinsicWithUnknownMetadataArgument(II);
185 }
186 }
187
188 for (GlobalVariable &GV : M->globals())
189 GV.eraseMetadataIf(Pred);
190
191 for (const auto &[ID, Info] : make_early_inc_range(Range&: ForwardRefMDNodes)) {
192 // Check whether there is only a single use left, which would be in our
193 // own NumberedMetadata.
194 if (Info.first->getNumTemporaryUses() == 1) {
195 NumberedMetadata.erase(x: ID);
196 ForwardRefMDNodes.erase(x: ID);
197 }
198 }
199}
200
201/// validateEndOfModule - Do final validity and basic correctness checks at the
202/// end of the module.
203bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
204 if (!M)
205 return false;
206
207 // We should have already returned an error if we observed both intrinsics and
208 // records in this IR.
209 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
210 "Mixed debug intrinsics/records seen without a parsing error?");
211
212 // Handle any function attribute group forward references.
213 for (const auto &RAG : ForwardRefAttrGroups) {
214 Value *V = RAG.first;
215 const std::vector<unsigned> &Attrs = RAG.second;
216 AttrBuilder B(Context);
217
218 for (const auto &Attr : Attrs) {
219 auto R = NumberedAttrBuilders.find(x: Attr);
220 if (R != NumberedAttrBuilders.end())
221 B.merge(B: R->second);
222 }
223
224 if (Function *Fn = dyn_cast<Function>(Val: V)) {
225 AttributeList AS = Fn->getAttributes();
226 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
227 AS = AS.removeFnAttributes(C&: Context);
228
229 FnAttrs.merge(B);
230
231 // If the alignment was parsed as an attribute, move to the alignment
232 // field.
233 if (MaybeAlign A = FnAttrs.getAlignment()) {
234 Fn->setAlignment(*A);
235 FnAttrs.removeAttribute(Val: Attribute::Alignment);
236 }
237
238 AS = AS.addFnAttributes(C&: Context, B: FnAttrs);
239 Fn->setAttributes(AS);
240 } else if (CallInst *CI = dyn_cast<CallInst>(Val: V)) {
241 AttributeList AS = CI->getAttributes();
242 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
243 AS = AS.removeFnAttributes(C&: Context);
244 FnAttrs.merge(B);
245 AS = AS.addFnAttributes(C&: Context, B: FnAttrs);
246 CI->setAttributes(AS);
247 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Val: V)) {
248 AttributeList AS = II->getAttributes();
249 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
250 AS = AS.removeFnAttributes(C&: Context);
251 FnAttrs.merge(B);
252 AS = AS.addFnAttributes(C&: Context, B: FnAttrs);
253 II->setAttributes(AS);
254 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(Val: V)) {
255 AttributeList AS = CBI->getAttributes();
256 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
257 AS = AS.removeFnAttributes(C&: Context);
258 FnAttrs.merge(B);
259 AS = AS.addFnAttributes(C&: Context, B: FnAttrs);
260 CBI->setAttributes(AS);
261 } else if (auto *GV = dyn_cast<GlobalVariable>(Val: V)) {
262 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
263 Attrs.merge(B);
264 GV->setAttributes(AttributeSet::get(C&: Context,B: Attrs));
265 } else {
266 llvm_unreachable("invalid object with forward attribute group reference");
267 }
268 }
269
270 // If there are entries in ForwardRefBlockAddresses at this point, the
271 // function was never defined.
272 if (!ForwardRefBlockAddresses.empty())
273 return error(L: ForwardRefBlockAddresses.begin()->first.Loc,
274 Msg: "expected function name in blockaddress");
275
276 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
277 GlobalValue *FwdRef) {
278 GlobalValue *GV = nullptr;
279 if (GVRef.Kind == ValID::t_GlobalName) {
280 GV = M->getNamedValue(Name: GVRef.StrVal);
281 } else {
282 GV = NumberedVals.get(ID: GVRef.UIntVal);
283 }
284
285 if (!GV)
286 return error(L: GVRef.Loc, Msg: "unknown function '" + GVRef.StrVal +
287 "' referenced by dso_local_equivalent");
288
289 if (!GV->getValueType()->isFunctionTy())
290 return error(L: GVRef.Loc,
291 Msg: "expected a function, alias to function, or ifunc "
292 "in dso_local_equivalent");
293
294 auto *Equiv = DSOLocalEquivalent::get(GV);
295 FwdRef->replaceAllUsesWith(V: Equiv);
296 FwdRef->eraseFromParent();
297 return false;
298 };
299
300 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
301 // point, they are references after the function was defined. Resolve those
302 // now.
303 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
304 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
305 return true;
306 }
307 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
308 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
309 return true;
310 }
311 ForwardRefDSOLocalEquivalentIDs.clear();
312 ForwardRefDSOLocalEquivalentNames.clear();
313
314 for (const auto &NT : NumberedTypes)
315 if (NT.second.second.isValid())
316 return error(L: NT.second.second,
317 Msg: "use of undefined type '%" + Twine(NT.first) + "'");
318
319 for (const auto &[Name, TypeInfo] : NamedTypes)
320 if (TypeInfo.second.isValid())
321 return error(L: TypeInfo.second,
322 Msg: "use of undefined type named '" + Name + "'");
323
324 if (!ForwardRefComdats.empty())
325 return error(L: ForwardRefComdats.begin()->second,
326 Msg: "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first + "'");
328
329 for (const auto &[Name, Info] : make_early_inc_range(Range&: ForwardRefVals)) {
330 if (StringRef(Name).starts_with(Prefix: "llvm.")) {
331 Intrinsic::ID IID = Intrinsic::lookupIntrinsicID(Name);
332 // Automatically create declarations for intrinsics. Intrinsics can only
333 // be called directly, so the call function type directly determines the
334 // declaration function type.
335 //
336 // Additionally, automatically add the required mangling suffix to the
337 // intrinsic name. This means that we may replace a single forward
338 // declaration with multiple functions here.
339 for (Use &U : make_early_inc_range(Range: Info.first->uses())) {
340 auto *CB = dyn_cast<CallBase>(Val: U.getUser());
341 if (!CB || !CB->isCallee(U: &U))
342 return error(L: Info.second, Msg: "intrinsic can only be used as callee");
343
344 SmallVector<Type *> OverloadTys;
345 if (IID != Intrinsic::not_intrinsic &&
346 Intrinsic::getIntrinsicSignature(IID, FT: CB->getFunctionType(),
347 ArgTys&: OverloadTys)) {
348 U.set(Intrinsic::getOrInsertDeclaration(M, id: IID, Tys: OverloadTys));
349 } else {
350 // Try to upgrade the intrinsic.
351 Function *TmpF = Function::Create(Ty: CB->getFunctionType(),
352 Linkage: Function::ExternalLinkage, N: Name, M);
353 Function *NewF = nullptr;
354 if (!UpgradeIntrinsicFunction(F: TmpF, NewFn&: NewF)) {
355 if (IID == Intrinsic::not_intrinsic)
356 return error(L: Info.second, Msg: "unknown intrinsic '" + Name + "'");
357 return error(L: Info.second, Msg: "invalid intrinsic signature");
358 }
359
360 U.set(TmpF);
361 UpgradeIntrinsicCall(CB, NewFn: NewF);
362 if (TmpF->use_empty())
363 TmpF->eraseFromParent();
364 }
365 }
366
367 Info.first->eraseFromParent();
368 ForwardRefVals.erase(x: Name);
369 continue;
370 }
371
372 // If incomplete IR is allowed, also add declarations for
373 // non-intrinsics.
374 if (!AllowIncompleteIR)
375 continue;
376
377 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
378 FunctionType *FTy = nullptr;
379 for (Use &U : V->uses()) {
380 auto *CB = dyn_cast<CallBase>(Val: U.getUser());
381 if (!CB || !CB->isCallee(U: &U) || (FTy && FTy != CB->getFunctionType()))
382 return nullptr;
383 FTy = CB->getFunctionType();
384 }
385 return FTy;
386 };
387
388 // First check whether this global is only used in calls with the same
389 // type, in which case we'll insert a function. Otherwise, fall back to
390 // using a dummy i8 type.
391 Type *Ty = GetCommonFunctionType(Info.first);
392 if (!Ty)
393 Ty = Type::getInt8Ty(C&: Context);
394
395 GlobalValue *GV;
396 if (auto *FTy = dyn_cast<FunctionType>(Val: Ty))
397 GV = Function::Create(Ty: FTy, Linkage: GlobalValue::ExternalLinkage, N: Name, M);
398 else
399 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
400 GlobalValue::ExternalLinkage,
401 /*Initializer*/ nullptr, Name);
402 Info.first->replaceAllUsesWith(V: GV);
403 Info.first->eraseFromParent();
404 ForwardRefVals.erase(x: Name);
405 }
406
407 if (!ForwardRefVals.empty())
408 return error(L: ForwardRefVals.begin()->second.second,
409 Msg: "use of undefined value '@" + ForwardRefVals.begin()->first +
410 "'");
411
412 if (!ForwardRefValIDs.empty())
413 return error(L: ForwardRefValIDs.begin()->second.second,
414 Msg: "use of undefined value '@" +
415 Twine(ForwardRefValIDs.begin()->first) + "'");
416
417 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
418 dropUnknownMetadataReferences();
419
420 if (!ForwardRefMDNodes.empty())
421 return error(L: ForwardRefMDNodes.begin()->second.second,
422 Msg: "use of undefined metadata '!" +
423 Twine(ForwardRefMDNodes.begin()->first) + "'");
424
425 // Resolve metadata cycles.
426 for (auto &N : NumberedMetadata) {
427 if (N.second && !N.second->isResolved())
428 N.second->resolveCycles();
429 }
430
431 DISubprogram::cleanupRetainedNodes(NewDistinctSPs);
432 NewDistinctSPs.clear();
433
434 for (auto *Inst : InstsWithTBAATag) {
435 MDNode *MD = Inst->getMetadata(KindID: LLVMContext::MD_tbaa);
436 // With incomplete IR, the tbaa metadata may have been dropped.
437 if (!AllowIncompleteIR)
438 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
439 if (MD) {
440 auto *UpgradedMD = UpgradeTBAANode(TBAANode&: *MD);
441 if (MD != UpgradedMD)
442 Inst->setMetadata(KindID: LLVMContext::MD_tbaa, Node: UpgradedMD);
443 }
444 }
445
446 // Look for intrinsic functions and CallInst that need to be upgraded. We use
447 // make_early_inc_range here because we may remove some functions.
448 for (Function &F : llvm::make_early_inc_range(Range&: *M))
449 UpgradeCallsToIntrinsic(F: &F);
450
451 if (UpgradeDebugInfo)
452 llvm::UpgradeDebugInfo(M&: *M);
453
454 UpgradeModuleFlags(M&: *M);
455 UpgradeNVVMAnnotations(M&: *M);
456 UpgradeSectionAttributes(M&: *M);
457 copyModuleAttrToFunctions(M&: *M);
458
459 if (!Slots)
460 return false;
461 // Initialize the slot mapping.
462 // Because by this point we've parsed and validated everything, we can "steal"
463 // the mapping from LLParser as it doesn't need it anymore.
464 Slots->GlobalValues = std::move(NumberedVals);
465 Slots->MetadataNodes = std::move(NumberedMetadata);
466 for (const auto &I : NamedTypes)
467 Slots->NamedTypes.insert(KV: std::make_pair(x: I.getKey(), y: I.second.first));
468 for (const auto &I : NumberedTypes)
469 Slots->Types.insert(x: std::make_pair(x: I.first, y: I.second.first));
470
471 return false;
472}
473
474/// Do final validity and basic correctness checks at the end of the index.
475bool LLParser::validateEndOfIndex() {
476 if (!Index)
477 return false;
478
479 if (!ForwardRefValueInfos.empty())
480 return error(L: ForwardRefValueInfos.begin()->second.front().second,
481 Msg: "use of undefined summary '^" +
482 Twine(ForwardRefValueInfos.begin()->first) + "'");
483
484 if (!ForwardRefAliasees.empty())
485 return error(L: ForwardRefAliasees.begin()->second.front().second,
486 Msg: "use of undefined summary '^" +
487 Twine(ForwardRefAliasees.begin()->first) + "'");
488
489 if (!ForwardRefTypeIds.empty())
490 return error(L: ForwardRefTypeIds.begin()->second.front().second,
491 Msg: "use of undefined type id summary '^" +
492 Twine(ForwardRefTypeIds.begin()->first) + "'");
493
494 return false;
495}
496
497//===----------------------------------------------------------------------===//
498// Top-Level Entities
499//===----------------------------------------------------------------------===//
500
501bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
502 // Delay parsing of the data layout string until the target triple is known.
503 // Then, pass both the the target triple and the tentative data layout string
504 // to DataLayoutCallback, allowing to override the DL string.
505 // This enables importing modules with invalid DL strings.
506 std::string TentativeDLStr = M->getDataLayoutStr();
507 LocTy DLStrLoc;
508
509 bool Done = false;
510 while (!Done) {
511 switch (Lex.getKind()) {
512 case lltok::kw_target:
513 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
514 return true;
515 break;
516 case lltok::kw_source_filename:
517 if (parseSourceFileName())
518 return true;
519 break;
520 default:
521 Done = true;
522 }
523 }
524 // Run the override callback to potentially change the data layout string, and
525 // parse the data layout string.
526 if (auto LayoutOverride =
527 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
528 TentativeDLStr = *LayoutOverride;
529 DLStrLoc = {};
530 }
531 Expected<DataLayout> MaybeDL = DataLayout::parse(LayoutString: TentativeDLStr);
532 if (!MaybeDL)
533 return error(L: DLStrLoc, Msg: toString(E: MaybeDL.takeError()));
534 M->setDataLayout(MaybeDL.get());
535 return false;
536}
537
538bool LLParser::parseTopLevelEntities() {
539 // If there is no Module, then parse just the summary index entries.
540 if (!M) {
541 while (true) {
542 switch (Lex.getKind()) {
543 case lltok::Eof:
544 return false;
545 case lltok::SummaryID:
546 if (parseSummaryEntry())
547 return true;
548 break;
549 case lltok::kw_source_filename:
550 if (parseSourceFileName())
551 return true;
552 break;
553 default:
554 // Skip everything else
555 Lex.Lex();
556 }
557 }
558 }
559 while (true) {
560 switch (Lex.getKind()) {
561 default:
562 return tokError(Msg: "expected top-level entity");
563 case lltok::Eof: return false;
564 case lltok::kw_declare:
565 if (parseDeclare())
566 return true;
567 break;
568 case lltok::kw_define:
569 if (parseDefine())
570 return true;
571 break;
572 case lltok::kw_module:
573 if (parseModuleAsm())
574 return true;
575 break;
576 case lltok::LocalVarID:
577 if (parseUnnamedType())
578 return true;
579 break;
580 case lltok::LocalVar:
581 if (parseNamedType())
582 return true;
583 break;
584 case lltok::GlobalID:
585 if (parseUnnamedGlobal())
586 return true;
587 break;
588 case lltok::GlobalVar:
589 if (parseNamedGlobal())
590 return true;
591 break;
592 case lltok::ComdatVar: if (parseComdat()) return true; break;
593 case lltok::exclaim:
594 if (parseStandaloneMetadata())
595 return true;
596 break;
597 case lltok::SummaryID:
598 if (parseSummaryEntry())
599 return true;
600 break;
601 case lltok::MetadataVar:
602 if (parseNamedMetadata())
603 return true;
604 break;
605 case lltok::kw_attributes:
606 if (parseUnnamedAttrGrp())
607 return true;
608 break;
609 case lltok::kw_uselistorder:
610 if (parseUseListOrder())
611 return true;
612 break;
613 case lltok::kw_uselistorder_bb:
614 if (parseUseListOrderBB())
615 return true;
616 break;
617 }
618 }
619}
620
621/// toplevelentity
622/// ::= 'module' 'asm' STRINGCONSTANT
623bool LLParser::parseModuleAsm() {
624 assert(Lex.getKind() == lltok::kw_module);
625 Lex.Lex();
626
627 std::string AsmStr;
628 if (parseToken(T: lltok::kw_asm, ErrMsg: "expected 'module asm'") ||
629 parseStringConstant(Result&: AsmStr))
630 return true;
631
632 M->appendModuleInlineAsm(Asm: AsmStr);
633 return false;
634}
635
636/// toplevelentity
637/// ::= 'target' 'triple' '=' STRINGCONSTANT
638/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
639bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
640 LocTy &DLStrLoc) {
641 assert(Lex.getKind() == lltok::kw_target);
642 std::string Str;
643 switch (Lex.Lex()) {
644 default:
645 return tokError(Msg: "unknown target property");
646 case lltok::kw_triple:
647 Lex.Lex();
648 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after target triple") ||
649 parseStringConstant(Result&: Str))
650 return true;
651 M->setTargetTriple(Triple(std::move(Str)));
652 return false;
653 case lltok::kw_datalayout:
654 Lex.Lex();
655 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after target datalayout"))
656 return true;
657 DLStrLoc = Lex.getLoc();
658 if (parseStringConstant(Result&: TentativeDLStr))
659 return true;
660 return false;
661 }
662}
663
664/// toplevelentity
665/// ::= 'source_filename' '=' STRINGCONSTANT
666bool LLParser::parseSourceFileName() {
667 assert(Lex.getKind() == lltok::kw_source_filename);
668 Lex.Lex();
669 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after source_filename") ||
670 parseStringConstant(Result&: SourceFileName))
671 return true;
672 if (M)
673 M->setSourceFileName(SourceFileName);
674 return false;
675}
676
677/// parseUnnamedType:
678/// ::= LocalVarID '=' 'type' type
679bool LLParser::parseUnnamedType() {
680 LocTy TypeLoc = Lex.getLoc();
681 unsigned TypeID = Lex.getUIntVal();
682 Lex.Lex(); // eat LocalVarID;
683
684 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after name") ||
685 parseToken(T: lltok::kw_type, ErrMsg: "expected 'type' after '='"))
686 return true;
687
688 Type *Result = nullptr;
689 if (parseStructDefinition(TypeLoc, Name: "", Entry&: NumberedTypes[TypeID], ResultTy&: Result))
690 return true;
691
692 if (!isa<StructType>(Val: Result)) {
693 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
694 if (Entry.first)
695 return error(L: TypeLoc, Msg: "non-struct types may not be recursive");
696 Entry.first = Result;
697 Entry.second = SMLoc();
698 }
699
700 return false;
701}
702
703/// toplevelentity
704/// ::= LocalVar '=' 'type' type
705bool LLParser::parseNamedType() {
706 std::string Name = Lex.getStrVal();
707 LocTy NameLoc = Lex.getLoc();
708 Lex.Lex(); // eat LocalVar.
709
710 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after name") ||
711 parseToken(T: lltok::kw_type, ErrMsg: "expected 'type' after name"))
712 return true;
713
714 Type *Result = nullptr;
715 if (parseStructDefinition(TypeLoc: NameLoc, Name, Entry&: NamedTypes[Name], ResultTy&: Result))
716 return true;
717
718 if (!isa<StructType>(Val: Result)) {
719 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
720 if (Entry.first)
721 return error(L: NameLoc, Msg: "non-struct types may not be recursive");
722 Entry.first = Result;
723 Entry.second = SMLoc();
724 }
725
726 return false;
727}
728
729/// toplevelentity
730/// ::= 'declare' FunctionHeader
731bool LLParser::parseDeclare() {
732 assert(Lex.getKind() == lltok::kw_declare);
733 Lex.Lex();
734
735 std::vector<std::pair<unsigned, MDNode *>> MDs;
736 while (Lex.getKind() == lltok::MetadataVar) {
737 unsigned MDK;
738 MDNode *N;
739 if (parseMetadataAttachment(Kind&: MDK, MD&: N))
740 return true;
741 MDs.push_back(x: {MDK, N});
742 }
743
744 Function *F;
745 unsigned FunctionNumber = -1;
746 SmallVector<unsigned> UnnamedArgNums;
747 if (parseFunctionHeader(Fn&: F, IsDefine: false, FunctionNumber, UnnamedArgNums))
748 return true;
749 for (auto &MD : MDs)
750 F->addMetadata(KindID: MD.first, MD&: *MD.second);
751 return false;
752}
753
754/// toplevelentity
755/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
756bool LLParser::parseDefine() {
757 assert(Lex.getKind() == lltok::kw_define);
758
759 FileLoc FunctionStart = getTokLineColumnPos();
760 Lex.Lex();
761
762 Function *F;
763 unsigned FunctionNumber = -1;
764 SmallVector<unsigned> UnnamedArgNums;
765 bool RetValue =
766 parseFunctionHeader(Fn&: F, IsDefine: true, FunctionNumber, UnnamedArgNums) ||
767 parseOptionalFunctionMetadata(F&: *F) ||
768 parseFunctionBody(Fn&: *F, FunctionNumber, UnnamedArgNums);
769 if (ParserContext)
770 ParserContext->addFunctionLocation(
771 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
772
773 return RetValue;
774}
775
776/// parseGlobalType
777/// ::= 'constant'
778/// ::= 'global'
779bool LLParser::parseGlobalType(bool &IsConstant) {
780 if (Lex.getKind() == lltok::kw_constant)
781 IsConstant = true;
782 else if (Lex.getKind() == lltok::kw_global)
783 IsConstant = false;
784 else {
785 IsConstant = false;
786 return tokError(Msg: "expected 'global' or 'constant'");
787 }
788 Lex.Lex();
789 return false;
790}
791
792bool LLParser::parseOptionalUnnamedAddr(
793 GlobalVariable::UnnamedAddr &UnnamedAddr) {
794 if (EatIfPresent(T: lltok::kw_unnamed_addr))
795 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
796 else if (EatIfPresent(T: lltok::kw_local_unnamed_addr))
797 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
798 else
799 UnnamedAddr = GlobalValue::UnnamedAddr::None;
800 return false;
801}
802
803/// parseUnnamedGlobal:
804/// OptionalVisibility (ALIAS | IFUNC) ...
805/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
806/// OptionalDLLStorageClass
807/// ... -> global variable
808/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
809/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
810/// OptionalVisibility
811/// OptionalDLLStorageClass
812/// ... -> global variable
813bool LLParser::parseUnnamedGlobal() {
814 unsigned VarID;
815 std::string Name;
816 LocTy NameLoc = Lex.getLoc();
817
818 // Handle the GlobalID form.
819 if (Lex.getKind() == lltok::GlobalID) {
820 VarID = Lex.getUIntVal();
821 if (checkValueID(L: NameLoc, Kind: "global", Prefix: "@", NextID: NumberedVals.getNext(), ID: VarID))
822 return true;
823
824 Lex.Lex(); // eat GlobalID;
825 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after name"))
826 return true;
827 } else {
828 VarID = NumberedVals.getNext();
829 }
830
831 bool HasLinkage;
832 unsigned Linkage, Visibility, DLLStorageClass;
833 bool DSOLocal;
834 GlobalVariable::ThreadLocalMode TLM;
835 GlobalVariable::UnnamedAddr UnnamedAddr;
836 if (parseOptionalLinkage(Res&: Linkage, HasLinkage, Visibility, DLLStorageClass,
837 DSOLocal) ||
838 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
839 return true;
840
841 switch (Lex.getKind()) {
842 default:
843 return parseGlobal(Name, NameID: VarID, NameLoc, Linkage, HasLinkage, Visibility,
844 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
845 case lltok::kw_alias:
846 case lltok::kw_ifunc:
847 return parseAliasOrIFunc(Name, NameID: VarID, NameLoc, L: Linkage, Visibility,
848 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
849 }
850}
851
852/// parseNamedGlobal:
853/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
854/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
855/// OptionalVisibility OptionalDLLStorageClass
856/// ... -> global variable
857bool LLParser::parseNamedGlobal() {
858 assert(Lex.getKind() == lltok::GlobalVar);
859 LocTy NameLoc = Lex.getLoc();
860 std::string Name = Lex.getStrVal();
861 Lex.Lex();
862
863 bool HasLinkage;
864 unsigned Linkage, Visibility, DLLStorageClass;
865 bool DSOLocal;
866 GlobalVariable::ThreadLocalMode TLM;
867 GlobalVariable::UnnamedAddr UnnamedAddr;
868 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' in global variable") ||
869 parseOptionalLinkage(Res&: Linkage, HasLinkage, Visibility, DLLStorageClass,
870 DSOLocal) ||
871 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
872 return true;
873
874 switch (Lex.getKind()) {
875 default:
876 return parseGlobal(Name, NameID: -1, NameLoc, Linkage, HasLinkage, Visibility,
877 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
878 case lltok::kw_alias:
879 case lltok::kw_ifunc:
880 return parseAliasOrIFunc(Name, NameID: -1, NameLoc, L: Linkage, Visibility,
881 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
882 }
883}
884
885bool LLParser::parseComdat() {
886 assert(Lex.getKind() == lltok::ComdatVar);
887 std::string Name = Lex.getStrVal();
888 LocTy NameLoc = Lex.getLoc();
889 Lex.Lex();
890
891 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' here"))
892 return true;
893
894 if (parseToken(T: lltok::kw_comdat, ErrMsg: "expected comdat keyword"))
895 return tokError(Msg: "expected comdat type");
896
897 Comdat::SelectionKind SK;
898 switch (Lex.getKind()) {
899 default:
900 return tokError(Msg: "unknown selection kind");
901 case lltok::kw_any:
902 SK = Comdat::Any;
903 break;
904 case lltok::kw_exactmatch:
905 SK = Comdat::ExactMatch;
906 break;
907 case lltok::kw_largest:
908 SK = Comdat::Largest;
909 break;
910 case lltok::kw_nodeduplicate:
911 SK = Comdat::NoDeduplicate;
912 break;
913 case lltok::kw_samesize:
914 SK = Comdat::SameSize;
915 break;
916 }
917 Lex.Lex();
918
919 // See if the comdat was forward referenced, if so, use the comdat.
920 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
921 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Key: Name);
922 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(x: Name))
923 return error(L: NameLoc, Msg: "redefinition of comdat '$" + Name + "'");
924
925 Comdat *C;
926 if (I != ComdatSymTab.end())
927 C = &I->second;
928 else
929 C = M->getOrInsertComdat(Name);
930 C->setSelectionKind(SK);
931
932 return false;
933}
934
935// MDString:
936// ::= '!' STRINGCONSTANT
937bool LLParser::parseMDString(MDString *&Result) {
938 std::string Str;
939 if (parseStringConstant(Result&: Str))
940 return true;
941 Result = MDString::get(Context, Str);
942 return false;
943}
944
945// MDNode:
946// ::= '!' MDNodeNumber
947bool LLParser::parseMDNodeID(MDNode *&Result) {
948 // !{ ..., !42, ... }
949 LocTy IDLoc = Lex.getLoc();
950 unsigned MID = 0;
951 if (parseUInt32(Val&: MID))
952 return true;
953
954 // If not a forward reference, just return it now.
955 auto [It, Inserted] = NumberedMetadata.try_emplace(k: MID);
956 if (!Inserted) {
957 Result = It->second;
958 return false;
959 }
960
961 // Otherwise, create MDNode forward reference.
962 auto &FwdRef = ForwardRefMDNodes[MID];
963 FwdRef = std::make_pair(x: MDTuple::getTemporary(Context, MDs: {}), y&: IDLoc);
964
965 Result = FwdRef.first.get();
966 It->second.reset(MD: Result);
967 return false;
968}
969
970/// parseNamedMetadata:
971/// !foo = !{ !1, !2 }
972bool LLParser::parseNamedMetadata() {
973 assert(Lex.getKind() == lltok::MetadataVar);
974 std::string Name = Lex.getStrVal();
975 Lex.Lex();
976
977 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' here") ||
978 parseToken(T: lltok::exclaim, ErrMsg: "Expected '!' here") ||
979 parseToken(T: lltok::lbrace, ErrMsg: "Expected '{' here"))
980 return true;
981
982 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
983 if (Lex.getKind() != lltok::rbrace)
984 do {
985 MDNode *N = nullptr;
986 // parse DIExpressions inline as a special case. They are still MDNodes,
987 // so they can still appear in named metadata. Remove this logic if they
988 // become plain Metadata.
989 if (Lex.getKind() == lltok::MetadataVar &&
990 Lex.getStrVal() == "DIExpression") {
991 if (parseDIExpression(Result&: N, /*IsDistinct=*/false))
992 return true;
993 // DIArgLists should only appear inline in a function, as they may
994 // contain LocalAsMetadata arguments which require a function context.
995 } else if (Lex.getKind() == lltok::MetadataVar &&
996 Lex.getStrVal() == "DIArgList") {
997 return tokError(Msg: "found DIArgList outside of function");
998 } else if (parseToken(T: lltok::exclaim, ErrMsg: "Expected '!' here") ||
999 parseMDNodeID(Result&: N)) {
1000 return true;
1001 }
1002 NMD->addOperand(M: N);
1003 } while (EatIfPresent(T: lltok::comma));
1004
1005 return parseToken(T: lltok::rbrace, ErrMsg: "expected end of metadata node");
1006}
1007
1008/// parseStandaloneMetadata:
1009/// !42 = !{...}
1010bool LLParser::parseStandaloneMetadata() {
1011 assert(Lex.getKind() == lltok::exclaim);
1012 Lex.Lex();
1013 unsigned MetadataID = 0;
1014
1015 MDNode *Init;
1016 if (parseUInt32(Val&: MetadataID) || parseToken(T: lltok::equal, ErrMsg: "expected '=' here"))
1017 return true;
1018
1019 // Detect common error, from old metadata syntax.
1020 if (Lex.getKind() == lltok::Type)
1021 return tokError(Msg: "unexpected type in metadata definition");
1022
1023 bool IsDistinct = EatIfPresent(T: lltok::kw_distinct);
1024 if (Lex.getKind() == lltok::MetadataVar) {
1025 if (parseSpecializedMDNode(N&: Init, IsDistinct))
1026 return true;
1027 } else if (parseToken(T: lltok::exclaim, ErrMsg: "Expected '!' here") ||
1028 parseMDTuple(MD&: Init, IsDistinct))
1029 return true;
1030
1031 // See if this was forward referenced, if so, handle it.
1032 auto FI = ForwardRefMDNodes.find(x: MetadataID);
1033 if (FI != ForwardRefMDNodes.end()) {
1034 auto *ToReplace = FI->second.first.get();
1035 // DIAssignID has its own special forward-reference "replacement" for
1036 // attachments (the temporary attachments are never actually attached).
1037 if (isa<DIAssignID>(Val: Init)) {
1038 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1039 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1040 "Inst unexpectedly already has DIAssignID attachment");
1041 Inst->setMetadata(KindID: LLVMContext::MD_DIAssignID, Node: Init);
1042 }
1043 }
1044
1045 ToReplace->replaceAllUsesWith(MD: Init);
1046 ForwardRefMDNodes.erase(position: FI);
1047
1048 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1049 } else {
1050 auto [It, Inserted] = NumberedMetadata.try_emplace(k: MetadataID);
1051 if (!Inserted)
1052 return tokError(Msg: "Metadata id is already used");
1053 It->second.reset(MD: Init);
1054 }
1055
1056 return false;
1057}
1058
1059// Skips a single module summary entry.
1060bool LLParser::skipModuleSummaryEntry() {
1061 // Each module summary entry consists of a tag for the entry
1062 // type, followed by a colon, then the fields which may be surrounded by
1063 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1064 // support is in place we will look for the tokens corresponding to the
1065 // expected tags.
1066 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1067 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
1068 Lex.getKind() != lltok::kw_blockcount)
1069 return tokError(
1070 Msg: "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1071 "start of summary entry");
1072 if (Lex.getKind() == lltok::kw_flags)
1073 return parseSummaryIndexFlags();
1074 if (Lex.getKind() == lltok::kw_blockcount)
1075 return parseBlockCount();
1076 Lex.Lex();
1077 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' at start of summary entry") ||
1078 parseToken(T: lltok::lparen, ErrMsg: "expected '(' at start of summary entry"))
1079 return true;
1080 // Now walk through the parenthesized entry, until the number of open
1081 // parentheses goes back down to 0 (the first '(' was parsed above).
1082 unsigned NumOpenParen = 1;
1083 do {
1084 switch (Lex.getKind()) {
1085 case lltok::lparen:
1086 NumOpenParen++;
1087 break;
1088 case lltok::rparen:
1089 NumOpenParen--;
1090 break;
1091 case lltok::Eof:
1092 return tokError(Msg: "found end of file while parsing summary entry");
1093 default:
1094 // Skip everything in between parentheses.
1095 break;
1096 }
1097 Lex.Lex();
1098 } while (NumOpenParen > 0);
1099 return false;
1100}
1101
1102/// SummaryEntry
1103/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1104bool LLParser::parseSummaryEntry() {
1105 assert(Lex.getKind() == lltok::SummaryID);
1106 unsigned SummaryID = Lex.getUIntVal();
1107
1108 // For summary entries, colons should be treated as distinct tokens,
1109 // not an indication of the end of a label token.
1110 Lex.setIgnoreColonInIdentifiers(true);
1111
1112 Lex.Lex();
1113 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' here"))
1114 return true;
1115
1116 // If we don't have an index object, skip the summary entry.
1117 if (!Index)
1118 return skipModuleSummaryEntry();
1119
1120 bool result = false;
1121 switch (Lex.getKind()) {
1122 case lltok::kw_gv:
1123 result = parseGVEntry(ID: SummaryID);
1124 break;
1125 case lltok::kw_module:
1126 result = parseModuleEntry(ID: SummaryID);
1127 break;
1128 case lltok::kw_typeid:
1129 result = parseTypeIdEntry(ID: SummaryID);
1130 break;
1131 case lltok::kw_typeidCompatibleVTable:
1132 result = parseTypeIdCompatibleVtableEntry(ID: SummaryID);
1133 break;
1134 case lltok::kw_flags:
1135 result = parseSummaryIndexFlags();
1136 break;
1137 case lltok::kw_blockcount:
1138 result = parseBlockCount();
1139 break;
1140 default:
1141 result = error(L: Lex.getLoc(), Msg: "unexpected summary kind");
1142 break;
1143 }
1144 Lex.setIgnoreColonInIdentifiers(false);
1145 return result;
1146}
1147
1148static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
1149 return !GlobalValue::isLocalLinkage(Linkage: (GlobalValue::LinkageTypes)L) ||
1150 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
1151}
1152static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L) {
1153 return !GlobalValue::isLocalLinkage(Linkage: (GlobalValue::LinkageTypes)L) ||
1154 (GlobalValue::DLLStorageClassTypes)S == GlobalValue::DefaultStorageClass;
1155}
1156
1157// If there was an explicit dso_local, update GV. In the absence of an explicit
1158// dso_local we keep the default value.
1159static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1160 if (DSOLocal)
1161 GV.setDSOLocal(true);
1162}
1163
1164/// parseAliasOrIFunc:
1165/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1166/// OptionalVisibility OptionalDLLStorageClass
1167/// OptionalThreadLocal OptionalUnnamedAddr
1168/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1169///
1170/// AliaseeOrResolver
1171/// ::= TypeAndValue
1172///
1173/// SymbolAttrs
1174/// ::= ',' 'partition' StringConstant
1175///
1176/// Everything through OptionalUnnamedAddr has already been parsed.
1177///
1178bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1179 LocTy NameLoc, unsigned L, unsigned Visibility,
1180 unsigned DLLStorageClass, bool DSOLocal,
1181 GlobalVariable::ThreadLocalMode TLM,
1182 GlobalVariable::UnnamedAddr UnnamedAddr) {
1183 bool IsAlias;
1184 if (Lex.getKind() == lltok::kw_alias)
1185 IsAlias = true;
1186 else if (Lex.getKind() == lltok::kw_ifunc)
1187 IsAlias = false;
1188 else
1189 llvm_unreachable("Not an alias or ifunc!");
1190 Lex.Lex();
1191
1192 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
1193
1194 if(IsAlias && !GlobalAlias::isValidLinkage(L: Linkage))
1195 return error(L: NameLoc, Msg: "invalid linkage type for alias");
1196
1197 if (!isValidVisibilityForLinkage(V: Visibility, L))
1198 return error(L: NameLoc,
1199 Msg: "symbol with local linkage must have default visibility");
1200
1201 if (!isValidDLLStorageClassForLinkage(S: DLLStorageClass, L))
1202 return error(L: NameLoc,
1203 Msg: "symbol with local linkage cannot have a DLL storage class");
1204
1205 Type *Ty;
1206 LocTy ExplicitTypeLoc = Lex.getLoc();
1207 if (parseType(Result&: Ty) ||
1208 parseToken(T: lltok::comma, ErrMsg: "expected comma after alias or ifunc's type"))
1209 return true;
1210
1211 Constant *Aliasee;
1212 LocTy AliaseeLoc = Lex.getLoc();
1213 if (Lex.getKind() != lltok::kw_bitcast &&
1214 Lex.getKind() != lltok::kw_getelementptr &&
1215 Lex.getKind() != lltok::kw_addrspacecast &&
1216 Lex.getKind() != lltok::kw_inttoptr) {
1217 if (parseGlobalTypeAndValue(V&: Aliasee))
1218 return true;
1219 } else {
1220 // The bitcast dest type is not present, it is implied by the dest type.
1221 ValID ID;
1222 if (parseValID(ID, /*PFS=*/nullptr))
1223 return true;
1224 if (ID.Kind != ValID::t_Constant)
1225 return error(L: AliaseeLoc, Msg: "invalid aliasee");
1226 Aliasee = ID.ConstantVal;
1227 }
1228
1229 Type *AliaseeType = Aliasee->getType();
1230 auto *PTy = dyn_cast<PointerType>(Val: AliaseeType);
1231 if (!PTy)
1232 return error(L: AliaseeLoc, Msg: "An alias or ifunc must have pointer type");
1233 unsigned AddrSpace = PTy->getAddressSpace();
1234
1235 GlobalValue *GVal = nullptr;
1236
1237 // See if the alias was forward referenced, if so, prepare to replace the
1238 // forward reference.
1239 if (!Name.empty()) {
1240 auto I = ForwardRefVals.find(x: Name);
1241 if (I != ForwardRefVals.end()) {
1242 GVal = I->second.first;
1243 ForwardRefVals.erase(x: Name);
1244 } else if (M->getNamedValue(Name)) {
1245 return error(L: NameLoc, Msg: "redefinition of global '@" + Name + "'");
1246 }
1247 } else {
1248 auto I = ForwardRefValIDs.find(x: NameID);
1249 if (I != ForwardRefValIDs.end()) {
1250 GVal = I->second.first;
1251 ForwardRefValIDs.erase(position: I);
1252 }
1253 }
1254
1255 // Okay, create the alias/ifunc but do not insert it into the module yet.
1256 std::unique_ptr<GlobalAlias> GA;
1257 std::unique_ptr<GlobalIFunc> GI;
1258 GlobalValue *GV;
1259 if (IsAlias) {
1260 GA.reset(p: GlobalAlias::create(Ty, AddressSpace: AddrSpace, Linkage, Name, Aliasee,
1261 /*Parent=*/nullptr));
1262 GV = GA.get();
1263 } else {
1264 GI.reset(p: GlobalIFunc::create(Ty, AddressSpace: AddrSpace, Linkage, Name, Resolver: Aliasee,
1265 /*Parent=*/nullptr));
1266 GV = GI.get();
1267 }
1268 GV->setThreadLocalMode(TLM);
1269 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1270 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1271 GV->setUnnamedAddr(UnnamedAddr);
1272 maybeSetDSOLocal(DSOLocal, GV&: *GV);
1273
1274 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1275 // Now parse them if there are any.
1276 while (Lex.getKind() == lltok::comma) {
1277 Lex.Lex();
1278
1279 if (Lex.getKind() == lltok::kw_partition) {
1280 Lex.Lex();
1281 GV->setPartition(Lex.getStrVal());
1282 if (parseToken(T: lltok::StringConstant, ErrMsg: "expected partition string"))
1283 return true;
1284 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1285 if (parseGlobalObjectMetadataAttachment(GO&: *GI))
1286 return true;
1287 } else {
1288 return tokError(Msg: "unknown alias or ifunc property!");
1289 }
1290 }
1291
1292 if (Name.empty())
1293 NumberedVals.add(ID: NameID, V: GV);
1294
1295 if (GVal) {
1296 // Verify that types agree.
1297 if (GVal->getType() != GV->getType())
1298 return error(
1299 L: ExplicitTypeLoc,
1300 Msg: "forward reference and definition of alias have different types");
1301
1302 // If they agree, just RAUW the old value with the alias and remove the
1303 // forward ref info.
1304 GVal->replaceAllUsesWith(V: GV);
1305 GVal->eraseFromParent();
1306 }
1307
1308 // Insert into the module, we know its name won't collide now.
1309 if (IsAlias)
1310 M->insertAlias(Alias: GA.release());
1311 else
1312 M->insertIFunc(IFunc: GI.release());
1313 assert(GV->getName() == Name && "Should not be a name conflict!");
1314
1315 return false;
1316}
1317
1318static bool isSanitizer(lltok::Kind Kind) {
1319 switch (Kind) {
1320 case lltok::kw_no_sanitize_address:
1321 case lltok::kw_no_sanitize_hwaddress:
1322 case lltok::kw_sanitize_memtag:
1323 case lltok::kw_sanitize_address_dyninit:
1324 return true;
1325 default:
1326 return false;
1327 }
1328}
1329
1330bool LLParser::parseSanitizer(GlobalVariable *GV) {
1331 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1332 SanitizerMetadata Meta;
1333 if (GV->hasSanitizerMetadata())
1334 Meta = GV->getSanitizerMetadata();
1335
1336 switch (Lex.getKind()) {
1337 case lltok::kw_no_sanitize_address:
1338 Meta.NoAddress = true;
1339 break;
1340 case lltok::kw_no_sanitize_hwaddress:
1341 Meta.NoHWAddress = true;
1342 break;
1343 case lltok::kw_sanitize_memtag:
1344 Meta.Memtag = true;
1345 break;
1346 case lltok::kw_sanitize_address_dyninit:
1347 Meta.IsDynInit = true;
1348 break;
1349 default:
1350 return tokError(Msg: "non-sanitizer token passed to LLParser::parseSanitizer()");
1351 }
1352 GV->setSanitizerMetadata(Meta);
1353 Lex.Lex();
1354 return false;
1355}
1356
1357/// parseGlobal
1358/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1359/// OptionalVisibility OptionalDLLStorageClass
1360/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1361/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1362/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1363/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1364/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1365/// Const OptionalAttrs
1366///
1367/// Everything up to and including OptionalUnnamedAddr has been parsed
1368/// already.
1369///
1370bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1371 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1372 unsigned Visibility, unsigned DLLStorageClass,
1373 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1374 GlobalVariable::UnnamedAddr UnnamedAddr) {
1375 if (!isValidVisibilityForLinkage(V: Visibility, L: Linkage))
1376 return error(L: NameLoc,
1377 Msg: "symbol with local linkage must have default visibility");
1378
1379 if (!isValidDLLStorageClassForLinkage(S: DLLStorageClass, L: Linkage))
1380 return error(L: NameLoc,
1381 Msg: "symbol with local linkage cannot have a DLL storage class");
1382
1383 unsigned AddrSpace;
1384 bool IsConstant, IsExternallyInitialized;
1385 LocTy IsExternallyInitializedLoc;
1386 LocTy TyLoc;
1387
1388 Type *Ty = nullptr;
1389 if (parseOptionalAddrSpace(AddrSpace) ||
1390 parseOptionalToken(T: lltok::kw_externally_initialized,
1391 Present&: IsExternallyInitialized,
1392 Loc: &IsExternallyInitializedLoc) ||
1393 parseGlobalType(IsConstant) || parseType(Result&: Ty, Loc&: TyLoc))
1394 return true;
1395
1396 // If the linkage is specified and is external, then no initializer is
1397 // present.
1398 Constant *Init = nullptr;
1399 if (!HasLinkage ||
1400 !GlobalValue::isValidDeclarationLinkage(
1401 Linkage: (GlobalValue::LinkageTypes)Linkage)) {
1402 if (parseGlobalValue(Ty, C&: Init))
1403 return true;
1404 }
1405
1406 if (Ty->isFunctionTy() || !PointerType::isValidElementType(ElemTy: Ty))
1407 return error(L: TyLoc, Msg: "invalid type for global variable");
1408
1409 GlobalValue *GVal = nullptr;
1410
1411 // See if the global was forward referenced, if so, use the global.
1412 if (!Name.empty()) {
1413 auto I = ForwardRefVals.find(x: Name);
1414 if (I != ForwardRefVals.end()) {
1415 GVal = I->second.first;
1416 ForwardRefVals.erase(position: I);
1417 } else if (M->getNamedValue(Name)) {
1418 return error(L: NameLoc, Msg: "redefinition of global '@" + Name + "'");
1419 }
1420 } else {
1421 // Handle @"", where a name is syntactically specified, but semantically
1422 // missing.
1423 if (NameID == (unsigned)-1)
1424 NameID = NumberedVals.getNext();
1425
1426 auto I = ForwardRefValIDs.find(x: NameID);
1427 if (I != ForwardRefValIDs.end()) {
1428 GVal = I->second.first;
1429 ForwardRefValIDs.erase(position: I);
1430 }
1431 }
1432
1433 GlobalVariable *GV = new GlobalVariable(
1434 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1435 GlobalVariable::NotThreadLocal, AddrSpace);
1436
1437 if (Name.empty())
1438 NumberedVals.add(ID: NameID, V: GV);
1439
1440 // Set the parsed properties on the global.
1441 if (Init)
1442 GV->setInitializer(Init);
1443 GV->setConstant(IsConstant);
1444 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1445 maybeSetDSOLocal(DSOLocal, GV&: *GV);
1446 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1447 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1448 GV->setExternallyInitialized(IsExternallyInitialized);
1449 GV->setThreadLocalMode(TLM);
1450 GV->setUnnamedAddr(UnnamedAddr);
1451
1452 if (GVal) {
1453 if (GVal->getAddressSpace() != AddrSpace)
1454 return error(
1455 L: TyLoc,
1456 Msg: "forward reference and definition of global have different types");
1457
1458 GVal->replaceAllUsesWith(V: GV);
1459 GVal->eraseFromParent();
1460 }
1461
1462 // parse attributes on the global.
1463 while (Lex.getKind() == lltok::comma) {
1464 Lex.Lex();
1465
1466 if (Lex.getKind() == lltok::kw_section) {
1467 Lex.Lex();
1468 GV->setSection(Lex.getStrVal());
1469 if (parseToken(T: lltok::StringConstant, ErrMsg: "expected global section string"))
1470 return true;
1471 } else if (Lex.getKind() == lltok::kw_partition) {
1472 Lex.Lex();
1473 GV->setPartition(Lex.getStrVal());
1474 if (parseToken(T: lltok::StringConstant, ErrMsg: "expected partition string"))
1475 return true;
1476 } else if (Lex.getKind() == lltok::kw_align) {
1477 MaybeAlign Alignment;
1478 if (parseOptionalAlignment(Alignment))
1479 return true;
1480 if (Alignment)
1481 GV->setAlignment(*Alignment);
1482 } else if (Lex.getKind() == lltok::kw_code_model) {
1483 CodeModel::Model CodeModel;
1484 if (parseOptionalCodeModel(model&: CodeModel))
1485 return true;
1486 GV->setCodeModel(CodeModel);
1487 } else if (Lex.getKind() == lltok::MetadataVar) {
1488 if (parseGlobalObjectMetadataAttachment(GO&: *GV))
1489 return true;
1490 } else if (isSanitizer(Kind: Lex.getKind())) {
1491 if (parseSanitizer(GV))
1492 return true;
1493 } else {
1494 Comdat *C;
1495 if (parseOptionalComdat(GlobalName: Name, C))
1496 return true;
1497 if (C)
1498 GV->setComdat(C);
1499 else
1500 return tokError(Msg: "unknown global variable property!");
1501 }
1502 }
1503
1504 AttrBuilder Attrs(M->getContext());
1505 LocTy BuiltinLoc;
1506 std::vector<unsigned> FwdRefAttrGrps;
1507 if (parseFnAttributeValuePairs(B&: Attrs, FwdRefAttrGrps, inAttrGrp: false, BuiltinLoc))
1508 return true;
1509 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1510 GV->setAttributes(AttributeSet::get(C&: Context, B: Attrs));
1511 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1512 }
1513
1514 return false;
1515}
1516
1517/// parseUnnamedAttrGrp
1518/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1519bool LLParser::parseUnnamedAttrGrp() {
1520 assert(Lex.getKind() == lltok::kw_attributes);
1521 LocTy AttrGrpLoc = Lex.getLoc();
1522 Lex.Lex();
1523
1524 if (Lex.getKind() != lltok::AttrGrpID)
1525 return tokError(Msg: "expected attribute group id");
1526
1527 unsigned VarID = Lex.getUIntVal();
1528 std::vector<unsigned> unused;
1529 LocTy BuiltinLoc;
1530 Lex.Lex();
1531
1532 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' here") ||
1533 parseToken(T: lltok::lbrace, ErrMsg: "expected '{' here"))
1534 return true;
1535
1536 auto R = NumberedAttrBuilders.find(x: VarID);
1537 if (R == NumberedAttrBuilders.end())
1538 R = NumberedAttrBuilders.emplace(args&: VarID, args: AttrBuilder(M->getContext())).first;
1539
1540 if (parseFnAttributeValuePairs(B&: R->second, FwdRefAttrGrps&: unused, inAttrGrp: true, BuiltinLoc) ||
1541 parseToken(T: lltok::rbrace, ErrMsg: "expected end of attribute group"))
1542 return true;
1543
1544 if (!R->second.hasAttributes())
1545 return error(L: AttrGrpLoc, Msg: "attribute group has no attributes");
1546
1547 return false;
1548}
1549
1550static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) {
1551 switch (Kind) {
1552#define GET_ATTR_NAMES
1553#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1554 case lltok::kw_##DISPLAY_NAME: \
1555 return Attribute::ENUM_NAME;
1556#include "llvm/IR/Attributes.inc"
1557 default:
1558 return Attribute::None;
1559 }
1560}
1561
1562bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1563 bool InAttrGroup) {
1564 if (Attribute::isTypeAttrKind(Kind: Attr))
1565 return parseRequiredTypeAttr(B, AttrToken: Lex.getKind(), AttrKind: Attr);
1566
1567 switch (Attr) {
1568 case Attribute::Alignment: {
1569 MaybeAlign Alignment;
1570 if (InAttrGroup) {
1571 uint32_t Value = 0;
1572 Lex.Lex();
1573 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' here") || parseUInt32(Val&: Value))
1574 return true;
1575 Alignment = Align(Value);
1576 } else {
1577 if (parseOptionalAlignment(Alignment, AllowParens: true))
1578 return true;
1579 }
1580 B.addAlignmentAttr(Align: Alignment);
1581 return false;
1582 }
1583 case Attribute::StackAlignment: {
1584 unsigned Alignment;
1585 if (InAttrGroup) {
1586 Lex.Lex();
1587 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' here") ||
1588 parseUInt32(Val&: Alignment))
1589 return true;
1590 } else {
1591 if (parseOptionalStackAlignment(Alignment))
1592 return true;
1593 }
1594 B.addStackAlignmentAttr(Align: Alignment);
1595 return false;
1596 }
1597 case Attribute::AllocSize: {
1598 unsigned ElemSizeArg;
1599 std::optional<unsigned> NumElemsArg;
1600 if (parseAllocSizeArguments(BaseSizeArg&: ElemSizeArg, HowManyArg&: NumElemsArg))
1601 return true;
1602 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1603 return false;
1604 }
1605 case Attribute::VScaleRange: {
1606 unsigned MinValue, MaxValue;
1607 if (parseVScaleRangeArguments(MinValue, MaxValue))
1608 return true;
1609 B.addVScaleRangeAttr(MinValue,
1610 MaxValue: MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1611 return false;
1612 }
1613 case Attribute::Dereferenceable: {
1614 std::optional<uint64_t> Bytes;
1615 if (parseOptionalAttrBytes(AttrKind: lltok::kw_dereferenceable, Bytes))
1616 return true;
1617 assert(Bytes.has_value());
1618 B.addDereferenceableAttr(Bytes: Bytes.value());
1619 return false;
1620 }
1621 case Attribute::DeadOnReturn: {
1622 std::optional<uint64_t> Bytes;
1623 if (parseOptionalAttrBytes(AttrKind: lltok::kw_dead_on_return, Bytes,
1624 /*ErrorNoBytes=*/false))
1625 return true;
1626 if (Bytes.has_value()) {
1627 B.addDeadOnReturnAttr(Info: DeadOnReturnInfo(Bytes.value()));
1628 } else {
1629 B.addDeadOnReturnAttr(Info: DeadOnReturnInfo());
1630 }
1631 return false;
1632 }
1633 case Attribute::DereferenceableOrNull: {
1634 std::optional<uint64_t> Bytes;
1635 if (parseOptionalAttrBytes(AttrKind: lltok::kw_dereferenceable_or_null, Bytes))
1636 return true;
1637 assert(Bytes.has_value());
1638 B.addDereferenceableOrNullAttr(Bytes: Bytes.value());
1639 return false;
1640 }
1641 case Attribute::UWTable: {
1642 UWTableKind Kind;
1643 if (parseOptionalUWTableKind(Kind))
1644 return true;
1645 B.addUWTableAttr(Kind);
1646 return false;
1647 }
1648 case Attribute::AllocKind: {
1649 AllocFnKind Kind = AllocFnKind::Unknown;
1650 if (parseAllocKind(Kind))
1651 return true;
1652 B.addAllocKindAttr(Kind);
1653 return false;
1654 }
1655 case Attribute::Memory: {
1656 std::optional<MemoryEffects> ME = parseMemoryAttr();
1657 if (!ME)
1658 return true;
1659 B.addMemoryAttr(ME: *ME);
1660 return false;
1661 }
1662 case Attribute::DenormalFPEnv: {
1663 std::optional<DenormalFPEnv> Mode = parseDenormalFPEnvAttr();
1664 if (!Mode)
1665 return true;
1666
1667 B.addDenormalFPEnvAttr(Mode: *Mode);
1668 return false;
1669 }
1670 case Attribute::NoFPClass: {
1671 if (FPClassTest NoFPClass =
1672 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1673 B.addNoFPClassAttr(NoFPClassMask: NoFPClass);
1674 return false;
1675 }
1676
1677 return true;
1678 }
1679 case Attribute::Range:
1680 return parseRangeAttr(B);
1681 case Attribute::Initializes:
1682 return parseInitializesAttr(B);
1683 case Attribute::Captures:
1684 return parseCapturesAttr(B);
1685 default:
1686 B.addAttribute(Val: Attr);
1687 Lex.Lex();
1688 return false;
1689 }
1690}
1691
1692static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind) {
1693 switch (Kind) {
1694 case lltok::kw_readnone:
1695 ME &= MemoryEffects::none();
1696 return true;
1697 case lltok::kw_readonly:
1698 ME &= MemoryEffects::readOnly();
1699 return true;
1700 case lltok::kw_writeonly:
1701 ME &= MemoryEffects::writeOnly();
1702 return true;
1703 case lltok::kw_argmemonly:
1704 ME &= MemoryEffects::argMemOnly();
1705 return true;
1706 case lltok::kw_inaccessiblememonly:
1707 ME &= MemoryEffects::inaccessibleMemOnly();
1708 return true;
1709 case lltok::kw_inaccessiblemem_or_argmemonly:
1710 ME &= MemoryEffects::inaccessibleOrArgMemOnly();
1711 return true;
1712 default:
1713 return false;
1714 }
1715}
1716
1717/// parseFnAttributeValuePairs
1718/// ::= <attr> | <attr> '=' <value>
1719bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1720 std::vector<unsigned> &FwdRefAttrGrps,
1721 bool InAttrGrp, LocTy &BuiltinLoc) {
1722 bool HaveError = false;
1723
1724 B.clear();
1725
1726 MemoryEffects ME = MemoryEffects::unknown();
1727 while (true) {
1728 lltok::Kind Token = Lex.getKind();
1729 if (Token == lltok::rbrace)
1730 break; // Finished.
1731
1732 if (Token == lltok::StringConstant) {
1733 if (parseStringAttribute(B))
1734 return true;
1735 continue;
1736 }
1737
1738 if (Token == lltok::AttrGrpID) {
1739 // Allow a function to reference an attribute group:
1740 //
1741 // define void @foo() #1 { ... }
1742 if (InAttrGrp) {
1743 HaveError |= error(
1744 L: Lex.getLoc(),
1745 Msg: "cannot have an attribute group reference in an attribute group");
1746 } else {
1747 // Save the reference to the attribute group. We'll fill it in later.
1748 FwdRefAttrGrps.push_back(x: Lex.getUIntVal());
1749 }
1750 Lex.Lex();
1751 continue;
1752 }
1753
1754 SMLoc Loc = Lex.getLoc();
1755 if (Token == lltok::kw_builtin)
1756 BuiltinLoc = Loc;
1757
1758 if (upgradeMemoryAttr(ME, Kind: Token)) {
1759 Lex.Lex();
1760 continue;
1761 }
1762
1763 Attribute::AttrKind Attr = tokenToAttribute(Kind: Token);
1764 if (Attr == Attribute::None) {
1765 if (!InAttrGrp)
1766 break;
1767 return error(L: Lex.getLoc(), Msg: "unterminated attribute group");
1768 }
1769
1770 if (parseEnumAttribute(Attr, B, InAttrGroup: InAttrGrp))
1771 return true;
1772
1773 // As a hack, we allow function alignment to be initially parsed as an
1774 // attribute on a function declaration/definition or added to an attribute
1775 // group and later moved to the alignment field.
1776 if (!Attribute::canUseAsFnAttr(Kind: Attr) && Attr != Attribute::Alignment)
1777 HaveError |= error(L: Loc, Msg: "this attribute does not apply to functions");
1778 }
1779
1780 if (ME != MemoryEffects::unknown())
1781 B.addMemoryAttr(ME);
1782 return HaveError;
1783}
1784
1785//===----------------------------------------------------------------------===//
1786// GlobalValue Reference/Resolution Routines.
1787//===----------------------------------------------------------------------===//
1788
1789static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) {
1790 // The used global type does not matter. We will later RAUW it with a
1791 // global/function of the correct type.
1792 return new GlobalVariable(*M, Type::getInt8Ty(C&: M->getContext()), false,
1793 GlobalValue::ExternalWeakLinkage, nullptr, "",
1794 nullptr, GlobalVariable::NotThreadLocal,
1795 PTy->getAddressSpace());
1796}
1797
1798Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1799 Value *Val) {
1800 Type *ValTy = Val->getType();
1801 if (ValTy == Ty)
1802 return Val;
1803 if (Ty->isLabelTy())
1804 error(L: Loc, Msg: "'" + Name + "' is not a basic block");
1805 else
1806 error(L: Loc, Msg: "'" + Name + "' defined with type '" +
1807 getTypeString(T: Val->getType()) + "' but expected '" +
1808 getTypeString(T: Ty) + "'");
1809 return nullptr;
1810}
1811
1812/// getGlobalVal - Get a value with the specified name or ID, creating a
1813/// forward reference record if needed. This can return null if the value
1814/// exists but does not have the right type.
1815GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1816 LocTy Loc) {
1817 PointerType *PTy = dyn_cast<PointerType>(Val: Ty);
1818 if (!PTy) {
1819 error(L: Loc, Msg: "global variable reference must have pointer type");
1820 return nullptr;
1821 }
1822
1823 // Look this name up in the normal function symbol table.
1824 GlobalValue *Val =
1825 cast_or_null<GlobalValue>(Val: M->getValueSymbolTable().lookup(Name));
1826
1827 // If this is a forward reference for the value, see if we already created a
1828 // forward ref record.
1829 if (!Val) {
1830 auto I = ForwardRefVals.find(x: Name);
1831 if (I != ForwardRefVals.end())
1832 Val = I->second.first;
1833 }
1834
1835 // If we have the value in the symbol table or fwd-ref table, return it.
1836 if (Val)
1837 return cast_or_null<GlobalValue>(
1838 Val: checkValidVariableType(Loc, Name: "@" + Name, Ty, Val));
1839
1840 // Otherwise, create a new forward reference for this value and remember it.
1841 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1842 ForwardRefVals[Name] = std::make_pair(x&: FwdVal, y&: Loc);
1843 return FwdVal;
1844}
1845
1846GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1847 PointerType *PTy = dyn_cast<PointerType>(Val: Ty);
1848 if (!PTy) {
1849 error(L: Loc, Msg: "global variable reference must have pointer type");
1850 return nullptr;
1851 }
1852
1853 GlobalValue *Val = NumberedVals.get(ID);
1854
1855 // If this is a forward reference for the value, see if we already created a
1856 // forward ref record.
1857 if (!Val) {
1858 auto I = ForwardRefValIDs.find(x: ID);
1859 if (I != ForwardRefValIDs.end())
1860 Val = I->second.first;
1861 }
1862
1863 // If we have the value in the symbol table or fwd-ref table, return it.
1864 if (Val)
1865 return cast_or_null<GlobalValue>(
1866 Val: checkValidVariableType(Loc, Name: "@" + Twine(ID), Ty, Val));
1867
1868 // Otherwise, create a new forward reference for this value and remember it.
1869 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1870 ForwardRefValIDs[ID] = std::make_pair(x&: FwdVal, y&: Loc);
1871 return FwdVal;
1872}
1873
1874//===----------------------------------------------------------------------===//
1875// Comdat Reference/Resolution Routines.
1876//===----------------------------------------------------------------------===//
1877
1878Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1879 // Look this name up in the comdat symbol table.
1880 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1881 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Key: Name);
1882 if (I != ComdatSymTab.end())
1883 return &I->second;
1884
1885 // Otherwise, create a new forward reference for this value and remember it.
1886 Comdat *C = M->getOrInsertComdat(Name);
1887 ForwardRefComdats[Name] = Loc;
1888 return C;
1889}
1890
1891//===----------------------------------------------------------------------===//
1892// Helper Routines.
1893//===----------------------------------------------------------------------===//
1894
1895/// parseToken - If the current token has the specified kind, eat it and return
1896/// success. Otherwise, emit the specified error and return failure.
1897bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1898 if (Lex.getKind() != T)
1899 return tokError(Msg: ErrMsg);
1900 Lex.Lex();
1901 return false;
1902}
1903
1904/// parseStringConstant
1905/// ::= StringConstant
1906bool LLParser::parseStringConstant(std::string &Result) {
1907 if (Lex.getKind() != lltok::StringConstant)
1908 return tokError(Msg: "expected string constant");
1909 Result = Lex.getStrVal();
1910 Lex.Lex();
1911 return false;
1912}
1913
1914/// parseUInt32
1915/// ::= uint32
1916bool LLParser::parseUInt32(uint32_t &Val) {
1917 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1918 return tokError(Msg: "expected integer");
1919 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(Limit: 0xFFFFFFFFULL+1);
1920 if (Val64 != unsigned(Val64))
1921 return tokError(Msg: "expected 32-bit integer (too large)");
1922 Val = Val64;
1923 Lex.Lex();
1924 return false;
1925}
1926
1927/// parseUInt64
1928/// ::= uint64
1929bool LLParser::parseUInt64(uint64_t &Val) {
1930 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1931 return tokError(Msg: "expected integer");
1932 Val = Lex.getAPSIntVal().getLimitedValue();
1933 Lex.Lex();
1934 return false;
1935}
1936
1937/// parseTLSModel
1938/// := 'localdynamic'
1939/// := 'initialexec'
1940/// := 'localexec'
1941bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1942 switch (Lex.getKind()) {
1943 default:
1944 return tokError(Msg: "expected localdynamic, initialexec or localexec");
1945 case lltok::kw_localdynamic:
1946 TLM = GlobalVariable::LocalDynamicTLSModel;
1947 break;
1948 case lltok::kw_initialexec:
1949 TLM = GlobalVariable::InitialExecTLSModel;
1950 break;
1951 case lltok::kw_localexec:
1952 TLM = GlobalVariable::LocalExecTLSModel;
1953 break;
1954 }
1955
1956 Lex.Lex();
1957 return false;
1958}
1959
1960/// parseOptionalThreadLocal
1961/// := /*empty*/
1962/// := 'thread_local'
1963/// := 'thread_local' '(' tlsmodel ')'
1964bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1965 TLM = GlobalVariable::NotThreadLocal;
1966 if (!EatIfPresent(T: lltok::kw_thread_local))
1967 return false;
1968
1969 TLM = GlobalVariable::GeneralDynamicTLSModel;
1970 if (Lex.getKind() == lltok::lparen) {
1971 Lex.Lex();
1972 return parseTLSModel(TLM) ||
1973 parseToken(T: lltok::rparen, ErrMsg: "expected ')' after thread local model");
1974 }
1975 return false;
1976}
1977
1978/// parseOptionalAddrSpace
1979/// := /*empty*/
1980/// := 'addrspace' '(' uint32 ')'
1981bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1982 AddrSpace = DefaultAS;
1983 if (!EatIfPresent(T: lltok::kw_addrspace))
1984 return false;
1985
1986 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1987 if (Lex.getKind() == lltok::StringConstant) {
1988 const std::string &AddrSpaceStr = Lex.getStrVal();
1989 if (AddrSpaceStr == "A") {
1990 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1991 } else if (AddrSpaceStr == "G") {
1992 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1993 } else if (AddrSpaceStr == "P") {
1994 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1995 } else if (std::optional<unsigned> AS =
1996 M->getDataLayout().getNamedAddressSpace(Name: AddrSpaceStr)) {
1997 AddrSpace = *AS;
1998 } else {
1999 return tokError(Msg: "invalid symbolic addrspace '" + AddrSpaceStr + "'");
2000 }
2001 Lex.Lex();
2002 return false;
2003 }
2004 if (Lex.getKind() != lltok::APSInt)
2005 return tokError(Msg: "expected integer or string constant");
2006 SMLoc Loc = Lex.getLoc();
2007 if (parseUInt32(Val&: AddrSpace))
2008 return true;
2009 if (!isUInt<24>(x: AddrSpace))
2010 return error(L: Loc, Msg: "invalid address space, must be a 24-bit integer");
2011 return false;
2012 };
2013
2014 return parseToken(T: lltok::lparen, ErrMsg: "expected '(' in address space") ||
2015 ParseAddrspaceValue(AddrSpace) ||
2016 parseToken(T: lltok::rparen, ErrMsg: "expected ')' in address space");
2017}
2018
2019/// parseStringAttribute
2020/// := StringConstant
2021/// := StringConstant '=' StringConstant
2022bool LLParser::parseStringAttribute(AttrBuilder &B) {
2023 std::string Attr = Lex.getStrVal();
2024 Lex.Lex();
2025 std::string Val;
2026 if (EatIfPresent(T: lltok::equal) && parseStringConstant(Result&: Val))
2027 return true;
2028 B.addAttribute(A: Attr, V: Val);
2029 return false;
2030}
2031
2032/// Parse a potentially empty list of parameter or return attributes.
2033bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2034 bool HaveError = false;
2035
2036 B.clear();
2037
2038 while (true) {
2039 lltok::Kind Token = Lex.getKind();
2040 if (Token == lltok::StringConstant) {
2041 if (parseStringAttribute(B))
2042 return true;
2043 continue;
2044 }
2045
2046 if (Token == lltok::kw_nocapture) {
2047 Lex.Lex();
2048 B.addCapturesAttr(CI: CaptureInfo::none());
2049 continue;
2050 }
2051
2052 SMLoc Loc = Lex.getLoc();
2053 Attribute::AttrKind Attr = tokenToAttribute(Kind: Token);
2054 if (Attr == Attribute::None)
2055 return HaveError;
2056
2057 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2058 return true;
2059
2060 if (IsParam && !Attribute::canUseAsParamAttr(Kind: Attr))
2061 HaveError |= error(L: Loc, Msg: "this attribute does not apply to parameters");
2062 if (!IsParam && !Attribute::canUseAsRetAttr(Kind: Attr))
2063 HaveError |= error(L: Loc, Msg: "this attribute does not apply to return values");
2064 }
2065}
2066
2067static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2068 HasLinkage = true;
2069 switch (Kind) {
2070 default:
2071 HasLinkage = false;
2072 return GlobalValue::ExternalLinkage;
2073 case lltok::kw_private:
2074 return GlobalValue::PrivateLinkage;
2075 case lltok::kw_internal:
2076 return GlobalValue::InternalLinkage;
2077 case lltok::kw_weak:
2078 return GlobalValue::WeakAnyLinkage;
2079 case lltok::kw_weak_odr:
2080 return GlobalValue::WeakODRLinkage;
2081 case lltok::kw_linkonce:
2082 return GlobalValue::LinkOnceAnyLinkage;
2083 case lltok::kw_linkonce_odr:
2084 return GlobalValue::LinkOnceODRLinkage;
2085 case lltok::kw_available_externally:
2086 return GlobalValue::AvailableExternallyLinkage;
2087 case lltok::kw_appending:
2088 return GlobalValue::AppendingLinkage;
2089 case lltok::kw_common:
2090 return GlobalValue::CommonLinkage;
2091 case lltok::kw_extern_weak:
2092 return GlobalValue::ExternalWeakLinkage;
2093 case lltok::kw_external:
2094 return GlobalValue::ExternalLinkage;
2095 }
2096}
2097
2098/// parseOptionalLinkage
2099/// ::= /*empty*/
2100/// ::= 'private'
2101/// ::= 'internal'
2102/// ::= 'weak'
2103/// ::= 'weak_odr'
2104/// ::= 'linkonce'
2105/// ::= 'linkonce_odr'
2106/// ::= 'available_externally'
2107/// ::= 'appending'
2108/// ::= 'common'
2109/// ::= 'extern_weak'
2110/// ::= 'external'
2111bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2112 unsigned &Visibility,
2113 unsigned &DLLStorageClass, bool &DSOLocal) {
2114 Res = parseOptionalLinkageAux(Kind: Lex.getKind(), HasLinkage);
2115 if (HasLinkage)
2116 Lex.Lex();
2117 parseOptionalDSOLocal(DSOLocal);
2118 parseOptionalVisibility(Res&: Visibility);
2119 parseOptionalDLLStorageClass(Res&: DLLStorageClass);
2120
2121 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2122 return error(L: Lex.getLoc(), Msg: "dso_location and DLL-StorageClass mismatch");
2123 }
2124
2125 return false;
2126}
2127
2128void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2129 switch (Lex.getKind()) {
2130 default:
2131 DSOLocal = false;
2132 break;
2133 case lltok::kw_dso_local:
2134 DSOLocal = true;
2135 Lex.Lex();
2136 break;
2137 case lltok::kw_dso_preemptable:
2138 DSOLocal = false;
2139 Lex.Lex();
2140 break;
2141 }
2142}
2143
2144/// parseOptionalVisibility
2145/// ::= /*empty*/
2146/// ::= 'default'
2147/// ::= 'hidden'
2148/// ::= 'protected'
2149///
2150void LLParser::parseOptionalVisibility(unsigned &Res) {
2151 switch (Lex.getKind()) {
2152 default:
2153 Res = GlobalValue::DefaultVisibility;
2154 return;
2155 case lltok::kw_default:
2156 Res = GlobalValue::DefaultVisibility;
2157 break;
2158 case lltok::kw_hidden:
2159 Res = GlobalValue::HiddenVisibility;
2160 break;
2161 case lltok::kw_protected:
2162 Res = GlobalValue::ProtectedVisibility;
2163 break;
2164 }
2165 Lex.Lex();
2166}
2167
2168bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2169 GlobalValueSummary::ImportKind &Res) {
2170 switch (Kind) {
2171 default:
2172 return tokError(Msg: "unknown import kind. Expect definition or declaration.");
2173 case lltok::kw_definition:
2174 Res = GlobalValueSummary::Definition;
2175 return false;
2176 case lltok::kw_declaration:
2177 Res = GlobalValueSummary::Declaration;
2178 return false;
2179 }
2180}
2181
2182/// parseOptionalDLLStorageClass
2183/// ::= /*empty*/
2184/// ::= 'dllimport'
2185/// ::= 'dllexport'
2186///
2187void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2188 switch (Lex.getKind()) {
2189 default:
2190 Res = GlobalValue::DefaultStorageClass;
2191 return;
2192 case lltok::kw_dllimport:
2193 Res = GlobalValue::DLLImportStorageClass;
2194 break;
2195 case lltok::kw_dllexport:
2196 Res = GlobalValue::DLLExportStorageClass;
2197 break;
2198 }
2199 Lex.Lex();
2200}
2201
2202/// parseOptionalCallingConv
2203/// ::= /*empty*/
2204/// ::= 'ccc'
2205/// ::= 'fastcc'
2206/// ::= 'intel_ocl_bicc'
2207/// ::= 'coldcc'
2208/// ::= 'cfguard_checkcc'
2209/// ::= 'x86_stdcallcc'
2210/// ::= 'x86_fastcallcc'
2211/// ::= 'x86_thiscallcc'
2212/// ::= 'x86_vectorcallcc'
2213/// ::= 'arm_apcscc'
2214/// ::= 'arm_aapcscc'
2215/// ::= 'arm_aapcs_vfpcc'
2216/// ::= 'aarch64_vector_pcs'
2217/// ::= 'aarch64_sve_vector_pcs'
2218/// ::= 'aarch64_sme_preservemost_from_x0'
2219/// ::= 'aarch64_sme_preservemost_from_x1'
2220/// ::= 'aarch64_sme_preservemost_from_x2'
2221/// ::= 'msp430_intrcc'
2222/// ::= 'avr_intrcc'
2223/// ::= 'avr_signalcc'
2224/// ::= 'ptx_kernel'
2225/// ::= 'ptx_device'
2226/// ::= 'spir_func'
2227/// ::= 'spir_kernel'
2228/// ::= 'x86_64_sysvcc'
2229/// ::= 'win64cc'
2230/// ::= 'anyregcc'
2231/// ::= 'preserve_mostcc'
2232/// ::= 'preserve_allcc'
2233/// ::= 'preserve_nonecc'
2234/// ::= 'ghccc'
2235/// ::= 'swiftcc'
2236/// ::= 'swifttailcc'
2237/// ::= 'x86_intrcc'
2238/// ::= 'hhvmcc'
2239/// ::= 'hhvm_ccc'
2240/// ::= 'cxx_fast_tlscc'
2241/// ::= 'amdgpu_vs'
2242/// ::= 'amdgpu_ls'
2243/// ::= 'amdgpu_hs'
2244/// ::= 'amdgpu_es'
2245/// ::= 'amdgpu_gs'
2246/// ::= 'amdgpu_ps'
2247/// ::= 'amdgpu_cs'
2248/// ::= 'amdgpu_cs_chain'
2249/// ::= 'amdgpu_cs_chain_preserve'
2250/// ::= 'amdgpu_kernel'
2251/// ::= 'tailcc'
2252/// ::= 'm68k_rtdcc'
2253/// ::= 'graalcc'
2254/// ::= 'riscv_vector_cc'
2255/// ::= 'riscv_vls_cc'
2256/// ::= 'cc' UINT
2257///
2258bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2259 switch (Lex.getKind()) {
2260 default: CC = CallingConv::C; return false;
2261 case lltok::kw_ccc: CC = CallingConv::C; break;
2262 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2263 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2264 case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
2265 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
2266 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
2267 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
2268 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
2269 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
2270 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
2271 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
2272 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
2273 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
2274 case lltok::kw_aarch64_sve_vector_pcs:
2275 CC = CallingConv::AArch64_SVE_VectorCall;
2276 break;
2277 case lltok::kw_aarch64_sme_preservemost_from_x0:
2278 CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0;
2279 break;
2280 case lltok::kw_aarch64_sme_preservemost_from_x1:
2281 CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1;
2282 break;
2283 case lltok::kw_aarch64_sme_preservemost_from_x2:
2284 CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2;
2285 break;
2286 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
2287 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
2288 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
2289 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
2290 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
2291 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
2292 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
2293 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
2294 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
2295 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2296 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2297 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
2298 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
2299 case lltok::kw_preserve_nonecc:CC = CallingConv::PreserveNone; break;
2300 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2301 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2302 case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; break;
2303 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
2304 case lltok::kw_hhvmcc:
2305 CC = CallingConv::DUMMY_HHVM;
2306 break;
2307 case lltok::kw_hhvm_ccc:
2308 CC = CallingConv::DUMMY_HHVM_C;
2309 break;
2310 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
2311 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
2312 case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break;
2313 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
2314 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
2315 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
2316 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
2317 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
2318 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
2319 case lltok::kw_amdgpu_cs_chain:
2320 CC = CallingConv::AMDGPU_CS_Chain;
2321 break;
2322 case lltok::kw_amdgpu_cs_chain_preserve:
2323 CC = CallingConv::AMDGPU_CS_ChainPreserve;
2324 break;
2325 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
2326 case lltok::kw_amdgpu_gfx_whole_wave:
2327 CC = CallingConv::AMDGPU_Gfx_WholeWave;
2328 break;
2329 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2330 case lltok::kw_m68k_rtdcc: CC = CallingConv::M68k_RTD; break;
2331 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2332 case lltok::kw_riscv_vector_cc:
2333 CC = CallingConv::RISCV_VectorCall;
2334 break;
2335 case lltok::kw_riscv_vls_cc:
2336 // Default ABI_VLEN
2337 CC = CallingConv::RISCV_VLSCall_128;
2338 Lex.Lex();
2339 if (!EatIfPresent(T: lltok::lparen))
2340 break;
2341 uint32_t ABIVlen;
2342 if (parseUInt32(Val&: ABIVlen) || !EatIfPresent(T: lltok::rparen))
2343 return true;
2344 switch (ABIVlen) {
2345 default:
2346 return tokError(Msg: "unknown RISC-V ABI VLEN");
2347#define CC_VLS_CASE(ABIVlen) \
2348 case ABIVlen: \
2349 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2350 break;
2351 CC_VLS_CASE(32)
2352 CC_VLS_CASE(64)
2353 CC_VLS_CASE(128)
2354 CC_VLS_CASE(256)
2355 CC_VLS_CASE(512)
2356 CC_VLS_CASE(1024)
2357 CC_VLS_CASE(2048)
2358 CC_VLS_CASE(4096)
2359 CC_VLS_CASE(8192)
2360 CC_VLS_CASE(16384)
2361 CC_VLS_CASE(32768)
2362 CC_VLS_CASE(65536)
2363#undef CC_VLS_CASE
2364 }
2365 return false;
2366 case lltok::kw_cheriot_compartmentcallcc:
2367 CC = CallingConv::CHERIoT_CompartmentCall;
2368 break;
2369 case lltok::kw_cheriot_compartmentcalleecc:
2370 CC = CallingConv::CHERIoT_CompartmentCallee;
2371 break;
2372 case lltok::kw_cheriot_librarycallcc:
2373 CC = CallingConv::CHERIoT_LibraryCall;
2374 break;
2375 case lltok::kw_cc: {
2376 Lex.Lex();
2377 return parseUInt32(Val&: CC);
2378 }
2379 }
2380
2381 Lex.Lex();
2382 return false;
2383}
2384
2385/// parseMetadataAttachment
2386/// ::= !dbg !42
2387bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2388 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2389
2390 std::string Name = Lex.getStrVal();
2391 Kind = M->getMDKindID(Name);
2392 Lex.Lex();
2393
2394 return parseMDNode(N&: MD);
2395}
2396
2397/// parseInstructionMetadata
2398/// ::= !dbg !42 (',' !dbg !57)*
2399bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2400 do {
2401 if (Lex.getKind() != lltok::MetadataVar)
2402 return tokError(Msg: "expected metadata after comma");
2403
2404 unsigned MDK;
2405 MDNode *N;
2406 if (parseMetadataAttachment(Kind&: MDK, MD&: N))
2407 return true;
2408
2409 if (MDK == LLVMContext::MD_DIAssignID)
2410 TempDIAssignIDAttachments[N].push_back(Elt: &Inst);
2411 else
2412 Inst.setMetadata(KindID: MDK, Node: N);
2413
2414 if (MDK == LLVMContext::MD_tbaa)
2415 InstsWithTBAATag.push_back(Elt: &Inst);
2416
2417 // If this is the end of the list, we're done.
2418 } while (EatIfPresent(T: lltok::comma));
2419 return false;
2420}
2421
2422/// parseGlobalObjectMetadataAttachment
2423/// ::= !dbg !57
2424bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2425 unsigned MDK;
2426 MDNode *N;
2427 if (parseMetadataAttachment(Kind&: MDK, MD&: N))
2428 return true;
2429
2430 GO.addMetadata(KindID: MDK, MD&: *N);
2431 return false;
2432}
2433
2434/// parseOptionalFunctionMetadata
2435/// ::= (!dbg !57)*
2436bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2437 while (Lex.getKind() == lltok::MetadataVar)
2438 if (parseGlobalObjectMetadataAttachment(GO&: F))
2439 return true;
2440 return false;
2441}
2442
2443/// parseOptionalAlignment
2444/// ::= /* empty */
2445/// ::= 'align' 4
2446bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2447 Alignment = std::nullopt;
2448 if (!EatIfPresent(T: lltok::kw_align))
2449 return false;
2450 LocTy AlignLoc = Lex.getLoc();
2451 uint64_t Value = 0;
2452
2453 LocTy ParenLoc = Lex.getLoc();
2454 bool HaveParens = false;
2455 if (AllowParens) {
2456 if (EatIfPresent(T: lltok::lparen))
2457 HaveParens = true;
2458 }
2459
2460 if (parseUInt64(Val&: Value))
2461 return true;
2462
2463 if (HaveParens && !EatIfPresent(T: lltok::rparen))
2464 return error(L: ParenLoc, Msg: "expected ')'");
2465
2466 if (!isPowerOf2_64(Value))
2467 return error(L: AlignLoc, Msg: "alignment is not a power of two");
2468 if (Value > Value::MaximumAlignment)
2469 return error(L: AlignLoc, Msg: "huge alignments are not supported yet");
2470 Alignment = Align(Value);
2471 return false;
2472}
2473
2474/// parseOptionalPrefAlignment
2475/// ::= /* empty */
2476/// ::= 'prefalign' '(' 4 ')'
2477bool LLParser::parseOptionalPrefAlignment(MaybeAlign &Alignment) {
2478 Alignment = std::nullopt;
2479 if (!EatIfPresent(T: lltok::kw_prefalign))
2480 return false;
2481 LocTy AlignLoc = Lex.getLoc();
2482 uint64_t Value = 0;
2483
2484 LocTy ParenLoc = Lex.getLoc();
2485 if (!EatIfPresent(T: lltok::lparen))
2486 return error(L: ParenLoc, Msg: "expected '('");
2487
2488 if (parseUInt64(Val&: Value))
2489 return true;
2490
2491 ParenLoc = Lex.getLoc();
2492 if (!EatIfPresent(T: lltok::rparen))
2493 return error(L: ParenLoc, Msg: "expected ')'");
2494
2495 if (!isPowerOf2_64(Value))
2496 return error(L: AlignLoc, Msg: "alignment is not a power of two");
2497 if (Value > Value::MaximumAlignment)
2498 return error(L: AlignLoc, Msg: "huge alignments are not supported yet");
2499 Alignment = Align(Value);
2500 return false;
2501}
2502
2503/// parseOptionalCodeModel
2504/// ::= /* empty */
2505/// ::= 'code_model' "large"
2506bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2507 Lex.Lex();
2508 auto StrVal = Lex.getStrVal();
2509 auto ErrMsg = "expected global code model string";
2510 if (StrVal == "tiny")
2511 model = CodeModel::Tiny;
2512 else if (StrVal == "small")
2513 model = CodeModel::Small;
2514 else if (StrVal == "kernel")
2515 model = CodeModel::Kernel;
2516 else if (StrVal == "medium")
2517 model = CodeModel::Medium;
2518 else if (StrVal == "large")
2519 model = CodeModel::Large;
2520 else
2521 return tokError(Msg: ErrMsg);
2522 if (parseToken(T: lltok::StringConstant, ErrMsg))
2523 return true;
2524 return false;
2525}
2526
2527/// parseOptionalAttrBytes
2528/// ::= /* empty */
2529/// ::= AttrKind '(' 4 ')'
2530///
2531/// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or
2532/// 'dead_on_return'
2533bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind,
2534 std::optional<uint64_t> &Bytes,
2535 bool ErrorNoBytes) {
2536 assert((AttrKind == lltok::kw_dereferenceable ||
2537 AttrKind == lltok::kw_dereferenceable_or_null ||
2538 AttrKind == lltok::kw_dead_on_return) &&
2539 "contract!");
2540
2541 Bytes = 0;
2542 if (!EatIfPresent(T: AttrKind))
2543 return false;
2544 LocTy ParenLoc = Lex.getLoc();
2545 if (!EatIfPresent(T: lltok::lparen)) {
2546 if (ErrorNoBytes)
2547 return error(L: ParenLoc, Msg: "expected '('");
2548 Bytes = std::nullopt;
2549 return false;
2550 }
2551 LocTy DerefLoc = Lex.getLoc();
2552 if (parseUInt64(Val&: Bytes.value()))
2553 return true;
2554 ParenLoc = Lex.getLoc();
2555 if (!EatIfPresent(T: lltok::rparen))
2556 return error(L: ParenLoc, Msg: "expected ')'");
2557 if (!Bytes.value())
2558 return error(L: DerefLoc, Msg: "byte count specified must be non-zero");
2559 return false;
2560}
2561
2562bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2563 Lex.Lex();
2564 Kind = UWTableKind::Default;
2565 if (!EatIfPresent(T: lltok::lparen))
2566 return false;
2567 LocTy KindLoc = Lex.getLoc();
2568 if (Lex.getKind() == lltok::kw_sync)
2569 Kind = UWTableKind::Sync;
2570 else if (Lex.getKind() == lltok::kw_async)
2571 Kind = UWTableKind::Async;
2572 else
2573 return error(L: KindLoc, Msg: "expected unwind table kind");
2574 Lex.Lex();
2575 return parseToken(T: lltok::rparen, ErrMsg: "expected ')'");
2576}
2577
2578bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2579 Lex.Lex();
2580 LocTy ParenLoc = Lex.getLoc();
2581 if (!EatIfPresent(T: lltok::lparen))
2582 return error(L: ParenLoc, Msg: "expected '('");
2583 LocTy KindLoc = Lex.getLoc();
2584 std::string Arg;
2585 if (parseStringConstant(Result&: Arg))
2586 return error(L: KindLoc, Msg: "expected allockind value");
2587 for (StringRef A : llvm::split(Str: Arg, Separator: ",")) {
2588 if (A == "alloc") {
2589 Kind |= AllocFnKind::Alloc;
2590 } else if (A == "realloc") {
2591 Kind |= AllocFnKind::Realloc;
2592 } else if (A == "free") {
2593 Kind |= AllocFnKind::Free;
2594 } else if (A == "uninitialized") {
2595 Kind |= AllocFnKind::Uninitialized;
2596 } else if (A == "zeroed") {
2597 Kind |= AllocFnKind::Zeroed;
2598 } else if (A == "aligned") {
2599 Kind |= AllocFnKind::Aligned;
2600 } else {
2601 return error(L: KindLoc, Msg: Twine("unknown allockind ") + A);
2602 }
2603 }
2604 ParenLoc = Lex.getLoc();
2605 if (!EatIfPresent(T: lltok::rparen))
2606 return error(L: ParenLoc, Msg: "expected ')'");
2607 if (Kind == AllocFnKind::Unknown)
2608 return error(L: KindLoc, Msg: "expected allockind value");
2609 return false;
2610}
2611
2612static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2613 switch (Tok) {
2614 case lltok::kw_argmem:
2615 return IRMemLocation::ArgMem;
2616 case lltok::kw_inaccessiblemem:
2617 return IRMemLocation::InaccessibleMem;
2618 case lltok::kw_errnomem:
2619 return IRMemLocation::ErrnoMem;
2620 case lltok::kw_target_mem0:
2621 return IRMemLocation::TargetMem0;
2622 case lltok::kw_target_mem1:
2623 return IRMemLocation::TargetMem1;
2624 default:
2625 return std::nullopt;
2626 }
2627}
2628
2629static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2630 switch (Tok) {
2631 case lltok::kw_none:
2632 return ModRefInfo::NoModRef;
2633 case lltok::kw_read:
2634 return ModRefInfo::Ref;
2635 case lltok::kw_write:
2636 return ModRefInfo::Mod;
2637 case lltok::kw_readwrite:
2638 return ModRefInfo::ModRef;
2639 default:
2640 return std::nullopt;
2641 }
2642}
2643
2644static std::optional<DenormalMode::DenormalModeKind>
2645keywordToDenormalModeKind(lltok::Kind Tok) {
2646 switch (Tok) {
2647 case lltok::kw_ieee:
2648 return DenormalMode::IEEE;
2649 case lltok::kw_preservesign:
2650 return DenormalMode::PreserveSign;
2651 case lltok::kw_positivezero:
2652 return DenormalMode::PositiveZero;
2653 case lltok::kw_dynamic:
2654 return DenormalMode::Dynamic;
2655 default:
2656 return std::nullopt;
2657 }
2658}
2659
2660std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2661 MemoryEffects ME = MemoryEffects::none();
2662
2663 // We use syntax like memory(argmem: read), so the colon should not be
2664 // interpreted as a label terminator.
2665 Lex.setIgnoreColonInIdentifiers(true);
2666 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2667
2668 Lex.Lex();
2669 if (!EatIfPresent(T: lltok::lparen)) {
2670 tokError(Msg: "expected '('");
2671 return std::nullopt;
2672 }
2673
2674 bool SeenLoc = false;
2675 do {
2676 std::optional<IRMemLocation> Loc = keywordToLoc(Tok: Lex.getKind());
2677 if (Loc) {
2678 Lex.Lex();
2679 if (!EatIfPresent(T: lltok::colon)) {
2680 tokError(Msg: "expected ':' after location");
2681 return std::nullopt;
2682 }
2683 }
2684
2685 std::optional<ModRefInfo> MR = keywordToModRef(Tok: Lex.getKind());
2686 if (!MR) {
2687 if (!Loc)
2688 tokError(Msg: "expected memory location (argmem, inaccessiblemem, errnomem) "
2689 "or access kind (none, read, write, readwrite)");
2690 else
2691 tokError(Msg: "expected access kind (none, read, write, readwrite)");
2692 return std::nullopt;
2693 }
2694
2695 Lex.Lex();
2696 if (Loc) {
2697 SeenLoc = true;
2698 ME = ME.getWithModRef(Loc: *Loc, MR: *MR);
2699 } else {
2700 if (SeenLoc) {
2701 tokError(Msg: "default access kind must be specified first");
2702 return std::nullopt;
2703 }
2704 ME = MemoryEffects(*MR);
2705 }
2706
2707 if (EatIfPresent(T: lltok::rparen))
2708 return ME;
2709 } while (EatIfPresent(T: lltok::comma));
2710
2711 tokError(Msg: "unterminated memory attribute");
2712 return std::nullopt;
2713}
2714
2715std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2716 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2717 keywordToDenormalModeKind(Tok: Lex.getKind());
2718 if (!OutputMode) {
2719 tokError(Msg: "expected denormal behavior kind (ieee, preservesign, "
2720 "positivezero, dynamic)");
2721 return {};
2722 }
2723
2724 Lex.Lex();
2725
2726 std::optional<DenormalMode::DenormalModeKind> InputMode;
2727 if (EatIfPresent(T: lltok::bar)) {
2728 InputMode = keywordToDenormalModeKind(Tok: Lex.getKind());
2729 if (!InputMode) {
2730 tokError(Msg: "expected denormal behavior kind (ieee, preservesign, "
2731 "positivezero, dynamic)");
2732 return {};
2733 }
2734
2735 Lex.Lex();
2736 } else {
2737 // Single item, input == output mode
2738 InputMode = OutputMode;
2739 }
2740
2741 return DenormalMode(*OutputMode, *InputMode);
2742}
2743
2744std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2745 // We use syntax like denormal_fpenv(float: preservesign), so the colon should
2746 // not be interpreted as a label terminator.
2747 Lex.setIgnoreColonInIdentifiers(true);
2748 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2749
2750 Lex.Lex();
2751
2752 if (parseToken(T: lltok::lparen, ErrMsg: "expected '('"))
2753 return {};
2754
2755 DenormalMode DefaultMode = DenormalMode::getIEEE();
2756 DenormalMode F32Mode = DenormalMode::getInvalid();
2757
2758 bool HasDefaultSection = false;
2759 if (Lex.getKind() != lltok::Type) {
2760 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2761 if (!ParsedDefaultMode)
2762 return {};
2763 DefaultMode = *ParsedDefaultMode;
2764 HasDefaultSection = true;
2765 }
2766
2767 bool HasComma = EatIfPresent(T: lltok::comma);
2768 if (Lex.getKind() == lltok::Type) {
2769 if (HasDefaultSection && !HasComma) {
2770 tokError(Msg: "expected ',' before float:");
2771 return {};
2772 }
2773
2774 Type *Ty = nullptr;
2775 if (parseType(Result&: Ty) || !Ty->isFloatTy()) {
2776 tokError(Msg: "expected float:");
2777 return {};
2778 }
2779
2780 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' before float denormal_fpenv"))
2781 return {};
2782
2783 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2784 if (!ParsedF32Mode)
2785 return {};
2786
2787 F32Mode = *ParsedF32Mode;
2788 }
2789
2790 if (parseToken(T: lltok::rparen, ErrMsg: "unterminated denormal_fpenv"))
2791 return {};
2792
2793 return DenormalFPEnv(DefaultMode, F32Mode);
2794}
2795
2796static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2797 switch (Tok) {
2798 case lltok::kw_all:
2799 return fcAllFlags;
2800 case lltok::kw_nan:
2801 return fcNan;
2802 case lltok::kw_snan:
2803 return fcSNan;
2804 case lltok::kw_qnan:
2805 return fcQNan;
2806 case lltok::kw_inf:
2807 return fcInf;
2808 case lltok::kw_ninf:
2809 return fcNegInf;
2810 case lltok::kw_pinf:
2811 return fcPosInf;
2812 case lltok::kw_norm:
2813 return fcNormal;
2814 case lltok::kw_nnorm:
2815 return fcNegNormal;
2816 case lltok::kw_pnorm:
2817 return fcPosNormal;
2818 case lltok::kw_sub:
2819 return fcSubnormal;
2820 case lltok::kw_nsub:
2821 return fcNegSubnormal;
2822 case lltok::kw_psub:
2823 return fcPosSubnormal;
2824 case lltok::kw_zero:
2825 return fcZero;
2826 case lltok::kw_nzero:
2827 return fcNegZero;
2828 case lltok::kw_pzero:
2829 return fcPosZero;
2830 default:
2831 return 0;
2832 }
2833}
2834
2835unsigned LLParser::parseNoFPClassAttr() {
2836 unsigned Mask = fcNone;
2837
2838 Lex.Lex();
2839 if (!EatIfPresent(T: lltok::lparen)) {
2840 tokError(Msg: "expected '('");
2841 return 0;
2842 }
2843
2844 do {
2845 uint64_t Value = 0;
2846 unsigned TestMask = keywordToFPClassTest(Tok: Lex.getKind());
2847 if (TestMask != 0) {
2848 Mask |= TestMask;
2849 // TODO: Disallow overlapping masks to avoid copy paste errors
2850 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2851 !parseUInt64(Val&: Value)) {
2852 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2853 error(L: Lex.getLoc(), Msg: "invalid mask value for 'nofpclass'");
2854 return 0;
2855 }
2856
2857 if (!EatIfPresent(T: lltok::rparen)) {
2858 error(L: Lex.getLoc(), Msg: "expected ')'");
2859 return 0;
2860 }
2861
2862 return Value;
2863 } else {
2864 error(L: Lex.getLoc(), Msg: "expected nofpclass test mask");
2865 return 0;
2866 }
2867
2868 Lex.Lex();
2869 if (EatIfPresent(T: lltok::rparen))
2870 return Mask;
2871 } while (1);
2872
2873 llvm_unreachable("unterminated nofpclass attribute");
2874}
2875
2876/// parseOptionalCommaAlign
2877/// ::=
2878/// ::= ',' align 4
2879///
2880/// This returns with AteExtraComma set to true if it ate an excess comma at the
2881/// end.
2882bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2883 bool &AteExtraComma) {
2884 AteExtraComma = false;
2885 while (EatIfPresent(T: lltok::comma)) {
2886 // Metadata at the end is an early exit.
2887 if (Lex.getKind() == lltok::MetadataVar) {
2888 AteExtraComma = true;
2889 return false;
2890 }
2891
2892 if (Lex.getKind() != lltok::kw_align)
2893 return error(L: Lex.getLoc(), Msg: "expected metadata or 'align'");
2894
2895 if (parseOptionalAlignment(Alignment))
2896 return true;
2897 }
2898
2899 return false;
2900}
2901
2902/// parseOptionalCommaAddrSpace
2903/// ::=
2904/// ::= ',' addrspace(1)
2905///
2906/// This returns with AteExtraComma set to true if it ate an excess comma at the
2907/// end.
2908bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2909 bool &AteExtraComma) {
2910 AteExtraComma = false;
2911 while (EatIfPresent(T: lltok::comma)) {
2912 // Metadata at the end is an early exit.
2913 if (Lex.getKind() == lltok::MetadataVar) {
2914 AteExtraComma = true;
2915 return false;
2916 }
2917
2918 Loc = Lex.getLoc();
2919 if (Lex.getKind() != lltok::kw_addrspace)
2920 return error(L: Lex.getLoc(), Msg: "expected metadata or 'addrspace'");
2921
2922 if (parseOptionalAddrSpace(AddrSpace))
2923 return true;
2924 }
2925
2926 return false;
2927}
2928
2929bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2930 std::optional<unsigned> &HowManyArg) {
2931 Lex.Lex();
2932
2933 auto StartParen = Lex.getLoc();
2934 if (!EatIfPresent(T: lltok::lparen))
2935 return error(L: StartParen, Msg: "expected '('");
2936
2937 if (parseUInt32(Val&: BaseSizeArg))
2938 return true;
2939
2940 if (EatIfPresent(T: lltok::comma)) {
2941 auto HowManyAt = Lex.getLoc();
2942 unsigned HowMany;
2943 if (parseUInt32(Val&: HowMany))
2944 return true;
2945 if (HowMany == BaseSizeArg)
2946 return error(L: HowManyAt,
2947 Msg: "'allocsize' indices can't refer to the same parameter");
2948 HowManyArg = HowMany;
2949 } else
2950 HowManyArg = std::nullopt;
2951
2952 auto EndParen = Lex.getLoc();
2953 if (!EatIfPresent(T: lltok::rparen))
2954 return error(L: EndParen, Msg: "expected ')'");
2955 return false;
2956}
2957
2958bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2959 unsigned &MaxValue) {
2960 Lex.Lex();
2961
2962 auto StartParen = Lex.getLoc();
2963 if (!EatIfPresent(T: lltok::lparen))
2964 return error(L: StartParen, Msg: "expected '('");
2965
2966 if (parseUInt32(Val&: MinValue))
2967 return true;
2968
2969 if (EatIfPresent(T: lltok::comma)) {
2970 if (parseUInt32(Val&: MaxValue))
2971 return true;
2972 } else
2973 MaxValue = MinValue;
2974
2975 auto EndParen = Lex.getLoc();
2976 if (!EatIfPresent(T: lltok::rparen))
2977 return error(L: EndParen, Msg: "expected ')'");
2978 return false;
2979}
2980
2981/// parseScopeAndOrdering
2982/// if isAtomic: ::= SyncScope? AtomicOrdering
2983/// else: ::=
2984///
2985/// This sets Scope and Ordering to the parsed values.
2986bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2987 AtomicOrdering &Ordering) {
2988 if (!IsAtomic)
2989 return false;
2990
2991 return parseScope(SSID) || parseOrdering(Ordering);
2992}
2993
2994/// parseScope
2995/// ::= syncscope("singlethread" | "<target scope>")?
2996///
2997/// This sets synchronization scope ID to the ID of the parsed value.
2998bool LLParser::parseScope(SyncScope::ID &SSID) {
2999 SSID = SyncScope::System;
3000 if (EatIfPresent(T: lltok::kw_syncscope)) {
3001 auto StartParenAt = Lex.getLoc();
3002 if (!EatIfPresent(T: lltok::lparen))
3003 return error(L: StartParenAt, Msg: "Expected '(' in syncscope");
3004
3005 std::string SSN;
3006 auto SSNAt = Lex.getLoc();
3007 if (parseStringConstant(Result&: SSN))
3008 return error(L: SSNAt, Msg: "Expected synchronization scope name");
3009
3010 auto EndParenAt = Lex.getLoc();
3011 if (!EatIfPresent(T: lltok::rparen))
3012 return error(L: EndParenAt, Msg: "Expected ')' in syncscope");
3013
3014 SSID = Context.getOrInsertSyncScopeID(SSN);
3015 }
3016
3017 return false;
3018}
3019
3020/// parseOrdering
3021/// ::= AtomicOrdering
3022///
3023/// This sets Ordering to the parsed value.
3024bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
3025 switch (Lex.getKind()) {
3026 default:
3027 return tokError(Msg: "Expected ordering on atomic instruction");
3028 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
3029 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
3030 // Not specified yet:
3031 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
3032 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
3033 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
3034 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
3035 case lltok::kw_seq_cst:
3036 Ordering = AtomicOrdering::SequentiallyConsistent;
3037 break;
3038 }
3039 Lex.Lex();
3040 return false;
3041}
3042
3043/// parseOptionalStackAlignment
3044/// ::= /* empty */
3045/// ::= 'alignstack' '(' 4 ')'
3046bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
3047 Alignment = 0;
3048 if (!EatIfPresent(T: lltok::kw_alignstack))
3049 return false;
3050 LocTy ParenLoc = Lex.getLoc();
3051 if (!EatIfPresent(T: lltok::lparen))
3052 return error(L: ParenLoc, Msg: "expected '('");
3053 LocTy AlignLoc = Lex.getLoc();
3054 if (parseUInt32(Val&: Alignment))
3055 return true;
3056 ParenLoc = Lex.getLoc();
3057 if (!EatIfPresent(T: lltok::rparen))
3058 return error(L: ParenLoc, Msg: "expected ')'");
3059 if (!isPowerOf2_32(Value: Alignment))
3060 return error(L: AlignLoc, Msg: "stack alignment is not a power of two");
3061 return false;
3062}
3063
3064/// parseIndexList - This parses the index list for an insert/extractvalue
3065/// instruction. This sets AteExtraComma in the case where we eat an extra
3066/// comma at the end of the line and find that it is followed by metadata.
3067/// Clients that don't allow metadata can call the version of this function that
3068/// only takes one argument.
3069///
3070/// parseIndexList
3071/// ::= (',' uint32)+
3072///
3073bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
3074 bool &AteExtraComma) {
3075 AteExtraComma = false;
3076
3077 if (Lex.getKind() != lltok::comma)
3078 return tokError(Msg: "expected ',' as start of index list");
3079
3080 while (EatIfPresent(T: lltok::comma)) {
3081 if (Lex.getKind() == lltok::MetadataVar) {
3082 if (Indices.empty())
3083 return tokError(Msg: "expected index");
3084 AteExtraComma = true;
3085 return false;
3086 }
3087 unsigned Idx = 0;
3088 if (parseUInt32(Val&: Idx))
3089 return true;
3090 Indices.push_back(Elt: Idx);
3091 }
3092
3093 return false;
3094}
3095
3096//===----------------------------------------------------------------------===//
3097// Type Parsing.
3098//===----------------------------------------------------------------------===//
3099
3100/// parseType - parse a type.
3101bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
3102 SMLoc TypeLoc = Lex.getLoc();
3103 switch (Lex.getKind()) {
3104 default:
3105 return tokError(Msg);
3106 case lltok::Type:
3107 // Type ::= 'float' | 'void' (etc)
3108 Result = Lex.getTyVal();
3109 Lex.Lex();
3110
3111 // Handle "ptr" opaque pointer type.
3112 //
3113 // Type ::= ptr ('addrspace' '(' uint32 ')')?
3114 if (Result->isPointerTy()) {
3115 unsigned AddrSpace;
3116 if (parseOptionalAddrSpace(AddrSpace))
3117 return true;
3118 Result = PointerType::get(C&: getContext(), AddressSpace: AddrSpace);
3119
3120 // Give a nice error for 'ptr*'.
3121 if (Lex.getKind() == lltok::star)
3122 return tokError(Msg: "ptr* is invalid - use ptr instead");
3123
3124 // Fall through to parsing the type suffixes only if this 'ptr' is a
3125 // function return. Otherwise, return success, implicitly rejecting other
3126 // suffixes.
3127 if (Lex.getKind() != lltok::lparen)
3128 return false;
3129 }
3130 break;
3131 case lltok::kw_target: {
3132 // Type ::= TargetExtType
3133 if (parseTargetExtType(Result))
3134 return true;
3135 break;
3136 }
3137 case lltok::lbrace:
3138 // Type ::= StructType
3139 if (parseAnonStructType(Result, Packed: false))
3140 return true;
3141 break;
3142 case lltok::lsquare:
3143 // Type ::= '[' ... ']'
3144 Lex.Lex(); // eat the lsquare.
3145 if (parseArrayVectorType(Result, IsVector: false))
3146 return true;
3147 break;
3148 case lltok::less: // Either vector or packed struct.
3149 // Type ::= '<' ... '>'
3150 Lex.Lex();
3151 if (Lex.getKind() == lltok::lbrace) {
3152 if (parseAnonStructType(Result, Packed: true) ||
3153 parseToken(T: lltok::greater, ErrMsg: "expected '>' at end of packed struct"))
3154 return true;
3155 } else if (parseArrayVectorType(Result, IsVector: true))
3156 return true;
3157 break;
3158 case lltok::LocalVar: {
3159 // Type ::= %foo
3160 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3161
3162 // If the type hasn't been defined yet, create a forward definition and
3163 // remember where that forward def'n was seen (in case it never is defined).
3164 if (!Entry.first) {
3165 Entry.first = StructType::create(Context, Name: Lex.getStrVal());
3166 Entry.second = Lex.getLoc();
3167 }
3168 Result = Entry.first;
3169 Lex.Lex();
3170 break;
3171 }
3172
3173 case lltok::LocalVarID: {
3174 // Type ::= %4
3175 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3176
3177 // If the type hasn't been defined yet, create a forward definition and
3178 // remember where that forward def'n was seen (in case it never is defined).
3179 if (!Entry.first) {
3180 Entry.first = StructType::create(Context);
3181 Entry.second = Lex.getLoc();
3182 }
3183 Result = Entry.first;
3184 Lex.Lex();
3185 break;
3186 }
3187 }
3188
3189 // parse the type suffixes.
3190 while (true) {
3191 switch (Lex.getKind()) {
3192 // End of type.
3193 default:
3194 if (!AllowVoid && Result->isVoidTy())
3195 return error(L: TypeLoc, Msg: "void type only allowed for function results");
3196 return false;
3197
3198 // Type ::= Type '*'
3199 case lltok::star:
3200 if (Result->isLabelTy())
3201 return tokError(Msg: "basic block pointers are invalid");
3202 if (Result->isVoidTy())
3203 return tokError(Msg: "pointers to void are invalid - use i8* instead");
3204 if (!PointerType::isValidElementType(ElemTy: Result))
3205 return tokError(Msg: "pointer to this type is invalid");
3206 Result = PointerType::getUnqual(C&: Context);
3207 Lex.Lex();
3208 break;
3209
3210 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3211 case lltok::kw_addrspace: {
3212 if (Result->isLabelTy())
3213 return tokError(Msg: "basic block pointers are invalid");
3214 if (Result->isVoidTy())
3215 return tokError(Msg: "pointers to void are invalid; use i8* instead");
3216 if (!PointerType::isValidElementType(ElemTy: Result))
3217 return tokError(Msg: "pointer to this type is invalid");
3218 unsigned AddrSpace;
3219 if (parseOptionalAddrSpace(AddrSpace) ||
3220 parseToken(T: lltok::star, ErrMsg: "expected '*' in address space"))
3221 return true;
3222
3223 Result = PointerType::get(C&: Context, AddressSpace: AddrSpace);
3224 break;
3225 }
3226
3227 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3228 case lltok::lparen:
3229 if (parseFunctionType(Result))
3230 return true;
3231 break;
3232 }
3233 }
3234}
3235
3236/// parseParameterList
3237/// ::= '(' ')'
3238/// ::= '(' Arg (',' Arg)* ')'
3239/// Arg
3240/// ::= Type OptionalAttributes Value OptionalAttributes
3241bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3242 PerFunctionState &PFS, bool IsMustTailCall,
3243 bool InVarArgsFunc) {
3244 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in call"))
3245 return true;
3246
3247 while (Lex.getKind() != lltok::rparen) {
3248 // If this isn't the first argument, we need a comma.
3249 if (!ArgList.empty() &&
3250 parseToken(T: lltok::comma, ErrMsg: "expected ',' in argument list"))
3251 return true;
3252
3253 // parse an ellipsis if this is a musttail call in a variadic function.
3254 if (Lex.getKind() == lltok::dotdotdot) {
3255 const char *Msg = "unexpected ellipsis in argument list for ";
3256 if (!IsMustTailCall)
3257 return tokError(Msg: Twine(Msg) + "non-musttail call");
3258 if (!InVarArgsFunc)
3259 return tokError(Msg: Twine(Msg) + "musttail call in non-varargs function");
3260 Lex.Lex(); // Lex the '...', it is purely for readability.
3261 return parseToken(T: lltok::rparen, ErrMsg: "expected ')' at end of argument list");
3262 }
3263
3264 // parse the argument.
3265 LocTy ArgLoc;
3266 Type *ArgTy = nullptr;
3267 Value *V;
3268 if (parseType(Result&: ArgTy, Loc&: ArgLoc))
3269 return true;
3270 if (!FunctionType::isValidArgumentType(ArgTy))
3271 return error(L: ArgLoc, Msg: "invalid type for function argument");
3272
3273 AttrBuilder ArgAttrs(M->getContext());
3274
3275 if (ArgTy->isMetadataTy()) {
3276 if (parseMetadataAsValue(V, PFS))
3277 return true;
3278 } else {
3279 // Otherwise, handle normal operands.
3280 if (parseOptionalParamAttrs(B&: ArgAttrs) || parseValue(Ty: ArgTy, V, PFS))
3281 return true;
3282 }
3283 ArgList.push_back(Elt: ParamInfo(
3284 ArgLoc, V, AttributeSet::get(C&: V->getContext(), B: ArgAttrs)));
3285 }
3286
3287 if (IsMustTailCall && InVarArgsFunc)
3288 return tokError(Msg: "expected '...' at end of argument list for musttail call "
3289 "in varargs function");
3290
3291 Lex.Lex(); // Lex the ')'.
3292 return false;
3293}
3294
3295/// parseRequiredTypeAttr
3296/// ::= attrname(<ty>)
3297bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3298 Attribute::AttrKind AttrKind) {
3299 Type *Ty = nullptr;
3300 if (!EatIfPresent(T: AttrToken))
3301 return true;
3302 if (!EatIfPresent(T: lltok::lparen))
3303 return error(L: Lex.getLoc(), Msg: "expected '('");
3304 if (parseType(Result&: Ty))
3305 return true;
3306 if (!EatIfPresent(T: lltok::rparen))
3307 return error(L: Lex.getLoc(), Msg: "expected ')'");
3308
3309 B.addTypeAttr(Kind: AttrKind, Ty);
3310 return false;
3311}
3312
3313/// parseRangeAttr
3314/// ::= range(<ty> <n>,<n>)
3315bool LLParser::parseRangeAttr(AttrBuilder &B) {
3316 Lex.Lex();
3317
3318 APInt Lower;
3319 APInt Upper;
3320 Type *Ty = nullptr;
3321 LocTy TyLoc;
3322
3323 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3324 if (Lex.getKind() != lltok::APSInt)
3325 return tokError(Msg: "expected integer");
3326 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3327 return tokError(
3328 Msg: "integer is too large for the bit width of specified type");
3329 Val = Lex.getAPSIntVal().extend(width: BitWidth);
3330 Lex.Lex();
3331 return false;
3332 };
3333
3334 if (parseToken(T: lltok::lparen, ErrMsg: "expected '('") || parseType(Result&: Ty, Loc&: TyLoc))
3335 return true;
3336 if (!Ty->isIntegerTy())
3337 return error(L: TyLoc, Msg: "the range must have integer type!");
3338
3339 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3340
3341 if (ParseAPSInt(BitWidth, Lower) ||
3342 parseToken(T: lltok::comma, ErrMsg: "expected ','") || ParseAPSInt(BitWidth, Upper))
3343 return true;
3344 if (Lower == Upper && !Lower.isZero())
3345 return tokError(Msg: "the range represent the empty set but limits aren't 0!");
3346
3347 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')'"))
3348 return true;
3349
3350 B.addRangeAttr(CR: ConstantRange(Lower, Upper));
3351 return false;
3352}
3353
3354/// parseInitializesAttr
3355/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3356bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3357 Lex.Lex();
3358
3359 auto ParseAPSInt = [&](APInt &Val) {
3360 if (Lex.getKind() != lltok::APSInt)
3361 return tokError(Msg: "expected integer");
3362 Val = Lex.getAPSIntVal().extend(width: 64);
3363 Lex.Lex();
3364 return false;
3365 };
3366
3367 if (parseToken(T: lltok::lparen, ErrMsg: "expected '('"))
3368 return true;
3369
3370 SmallVector<ConstantRange, 2> RangeList;
3371 // Parse each constant range.
3372 do {
3373 APInt Lower, Upper;
3374 if (parseToken(T: lltok::lparen, ErrMsg: "expected '('"))
3375 return true;
3376
3377 if (ParseAPSInt(Lower) || parseToken(T: lltok::comma, ErrMsg: "expected ','") ||
3378 ParseAPSInt(Upper))
3379 return true;
3380
3381 if (Lower == Upper)
3382 return tokError(Msg: "the range should not represent the full or empty set!");
3383
3384 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')'"))
3385 return true;
3386
3387 RangeList.push_back(Elt: ConstantRange(Lower, Upper));
3388 } while (EatIfPresent(T: lltok::comma));
3389
3390 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')'"))
3391 return true;
3392
3393 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangesRef: RangeList);
3394 if (!CRLOrNull.has_value())
3395 return tokError(Msg: "Invalid (unordered or overlapping) range list");
3396 B.addInitializesAttr(CRL: *CRLOrNull);
3397 return false;
3398}
3399
3400bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3401 CaptureComponents Other = CaptureComponents::None;
3402 std::optional<CaptureComponents> Ret;
3403
3404 // We use syntax like captures(ret: address, provenance), so the colon
3405 // should not be interpreted as a label terminator.
3406 Lex.setIgnoreColonInIdentifiers(true);
3407 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
3408
3409 Lex.Lex();
3410 if (parseToken(T: lltok::lparen, ErrMsg: "expected '('"))
3411 return true;
3412
3413 CaptureComponents *Current = &Other;
3414 bool SeenComponent = false;
3415 while (true) {
3416 if (EatIfPresent(T: lltok::kw_ret)) {
3417 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'"))
3418 return true;
3419 if (Ret)
3420 return tokError(Msg: "duplicate 'ret' location");
3421 Ret = CaptureComponents::None;
3422 Current = &*Ret;
3423 SeenComponent = false;
3424 }
3425
3426 if (EatIfPresent(T: lltok::kw_none)) {
3427 if (SeenComponent)
3428 return tokError(Msg: "cannot use 'none' with other component");
3429 *Current = CaptureComponents::None;
3430 } else {
3431 if (SeenComponent && capturesNothing(CC: *Current))
3432 return tokError(Msg: "cannot use 'none' with other component");
3433
3434 if (EatIfPresent(T: lltok::kw_address_is_null))
3435 *Current |= CaptureComponents::AddressIsNull;
3436 else if (EatIfPresent(T: lltok::kw_address))
3437 *Current |= CaptureComponents::Address;
3438 else if (EatIfPresent(T: lltok::kw_provenance))
3439 *Current |= CaptureComponents::Provenance;
3440 else if (EatIfPresent(T: lltok::kw_read_provenance))
3441 *Current |= CaptureComponents::ReadProvenance;
3442 else
3443 return tokError(Msg: "expected one of 'none', 'address', 'address_is_null', "
3444 "'provenance' or 'read_provenance'");
3445 }
3446
3447 SeenComponent = true;
3448 if (EatIfPresent(T: lltok::rparen))
3449 break;
3450
3451 if (parseToken(T: lltok::comma, ErrMsg: "expected ',' or ')'"))
3452 return true;
3453 }
3454
3455 B.addCapturesAttr(CI: CaptureInfo(Other, Ret.value_or(u&: Other)));
3456 return false;
3457}
3458
3459/// parseOptionalOperandBundles
3460/// ::= /*empty*/
3461/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3462///
3463/// OperandBundle
3464/// ::= bundle-tag '(' ')'
3465/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3466///
3467/// bundle-tag ::= String Constant
3468bool LLParser::parseOptionalOperandBundles(
3469 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3470 LocTy BeginLoc = Lex.getLoc();
3471 if (!EatIfPresent(T: lltok::lsquare))
3472 return false;
3473
3474 while (Lex.getKind() != lltok::rsquare) {
3475 // If this isn't the first operand bundle, we need a comma.
3476 if (!BundleList.empty() &&
3477 parseToken(T: lltok::comma, ErrMsg: "expected ',' in input list"))
3478 return true;
3479
3480 std::string Tag;
3481 if (parseStringConstant(Result&: Tag))
3482 return true;
3483
3484 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in operand bundle"))
3485 return true;
3486
3487 std::vector<Value *> Inputs;
3488 while (Lex.getKind() != lltok::rparen) {
3489 // If this isn't the first input, we need a comma.
3490 if (!Inputs.empty() &&
3491 parseToken(T: lltok::comma, ErrMsg: "expected ',' in input list"))
3492 return true;
3493
3494 Type *Ty = nullptr;
3495 Value *Input = nullptr;
3496 if (parseType(Result&: Ty))
3497 return true;
3498 if (Ty->isMetadataTy()) {
3499 if (parseMetadataAsValue(V&: Input, PFS))
3500 return true;
3501 } else if (parseValue(Ty, V&: Input, PFS)) {
3502 return true;
3503 }
3504 Inputs.push_back(x: Input);
3505 }
3506
3507 BundleList.emplace_back(Args: std::move(Tag), Args: std::move(Inputs));
3508
3509 Lex.Lex(); // Lex the ')'.
3510 }
3511
3512 if (BundleList.empty())
3513 return error(L: BeginLoc, Msg: "operand bundle set must not be empty");
3514
3515 Lex.Lex(); // Lex the ']'.
3516 return false;
3517}
3518
3519bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3520 unsigned NextID, unsigned ID) {
3521 if (ID < NextID)
3522 return error(L: Loc, Msg: Kind + " expected to be numbered '" + Prefix +
3523 Twine(NextID) + "' or greater");
3524
3525 return false;
3526}
3527
3528/// parseArgumentList - parse the argument list for a function type or function
3529/// prototype.
3530/// ::= '(' ArgTypeListI ')'
3531/// ArgTypeListI
3532/// ::= /*empty*/
3533/// ::= '...'
3534/// ::= ArgTypeList ',' '...'
3535/// ::= ArgType (',' ArgType)*
3536///
3537bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3538 SmallVectorImpl<unsigned> &UnnamedArgNums,
3539 bool &IsVarArg) {
3540 unsigned CurValID = 0;
3541 IsVarArg = false;
3542 assert(Lex.getKind() == lltok::lparen);
3543 Lex.Lex(); // eat the (.
3544
3545 if (Lex.getKind() != lltok::rparen) {
3546 do {
3547 // Handle ... at end of arg list.
3548 if (EatIfPresent(T: lltok::dotdotdot)) {
3549 IsVarArg = true;
3550 break;
3551 }
3552
3553 // Otherwise must be an argument type.
3554 LocTy TypeLoc = Lex.getLoc();
3555 Type *ArgTy = nullptr;
3556 AttrBuilder Attrs(M->getContext());
3557 if (parseType(Result&: ArgTy) || parseOptionalParamAttrs(B&: Attrs))
3558 return true;
3559
3560 if (ArgTy->isVoidTy())
3561 return error(L: TypeLoc, Msg: "argument can not have void type");
3562
3563 std::string Name;
3564 FileLoc IdentStart;
3565 FileLoc IdentEnd;
3566 bool Unnamed = false;
3567 if (Lex.getKind() == lltok::LocalVar) {
3568 Name = Lex.getStrVal();
3569 IdentStart = getTokLineColumnPos();
3570 Lex.Lex();
3571 IdentEnd = getPrevTokEndLineColumnPos();
3572 } else {
3573 unsigned ArgID;
3574 if (Lex.getKind() == lltok::LocalVarID) {
3575 ArgID = Lex.getUIntVal();
3576 IdentStart = getTokLineColumnPos();
3577 if (checkValueID(Loc: TypeLoc, Kind: "argument", Prefix: "%", NextID: CurValID, ID: ArgID))
3578 return true;
3579 Lex.Lex();
3580 IdentEnd = getPrevTokEndLineColumnPos();
3581 } else {
3582 ArgID = CurValID;
3583 Unnamed = true;
3584 }
3585 UnnamedArgNums.push_back(Elt: ArgID);
3586 CurValID = ArgID + 1;
3587 }
3588
3589 if (!FunctionType::isValidArgumentType(ArgTy))
3590 return error(L: TypeLoc, Msg: "invalid type for function argument");
3591
3592 ArgList.emplace_back(
3593 Args&: TypeLoc, Args&: ArgTy,
3594 Args: Unnamed ? std::nullopt
3595 : std::make_optional(t: FileLocRange(IdentStart, IdentEnd)),
3596 Args: AttributeSet::get(C&: ArgTy->getContext(), B: Attrs), Args: std::move(Name));
3597 } while (EatIfPresent(T: lltok::comma));
3598 }
3599
3600 return parseToken(T: lltok::rparen, ErrMsg: "expected ')' at end of argument list");
3601}
3602
3603/// parseFunctionType
3604/// ::= Type ArgumentList OptionalAttrs
3605bool LLParser::parseFunctionType(Type *&Result) {
3606 assert(Lex.getKind() == lltok::lparen);
3607
3608 if (!FunctionType::isValidReturnType(RetTy: Result))
3609 return tokError(Msg: "invalid function return type");
3610
3611 SmallVector<ArgInfo, 8> ArgList;
3612 bool IsVarArg;
3613 SmallVector<unsigned> UnnamedArgNums;
3614 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3615 return true;
3616
3617 // Reject names on the arguments lists.
3618 for (const ArgInfo &Arg : ArgList) {
3619 if (!Arg.Name.empty())
3620 return error(L: Arg.Loc, Msg: "argument name invalid in function type");
3621 if (Arg.Attrs.hasAttributes())
3622 return error(L: Arg.Loc, Msg: "argument attributes invalid in function type");
3623 }
3624
3625 SmallVector<Type*, 16> ArgListTy;
3626 for (const ArgInfo &Arg : ArgList)
3627 ArgListTy.push_back(Elt: Arg.Ty);
3628
3629 Result = FunctionType::get(Result, Params: ArgListTy, isVarArg: IsVarArg);
3630 return false;
3631}
3632
3633/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3634/// other structs.
3635bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3636 SmallVector<Type*, 8> Elts;
3637 if (parseStructBody(Body&: Elts))
3638 return true;
3639
3640 Result = StructType::get(Context, Elements: Elts, isPacked: Packed);
3641 return false;
3642}
3643
3644/// parseStructDefinition - parse a struct in a 'type' definition.
3645bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3646 std::pair<Type *, LocTy> &Entry,
3647 Type *&ResultTy) {
3648 // If the type was already defined, diagnose the redefinition.
3649 if (Entry.first && !Entry.second.isValid())
3650 return error(L: TypeLoc, Msg: "redefinition of type");
3651
3652 // If we have opaque, just return without filling in the definition for the
3653 // struct. This counts as a definition as far as the .ll file goes.
3654 if (EatIfPresent(T: lltok::kw_opaque)) {
3655 // This type is being defined, so clear the location to indicate this.
3656 Entry.second = SMLoc();
3657
3658 // If this type number has never been uttered, create it.
3659 if (!Entry.first)
3660 Entry.first = StructType::create(Context, Name);
3661 ResultTy = Entry.first;
3662 return false;
3663 }
3664
3665 // If the type starts with '<', then it is either a packed struct or a vector.
3666 bool isPacked = EatIfPresent(T: lltok::less);
3667
3668 // If we don't have a struct, then we have a random type alias, which we
3669 // accept for compatibility with old files. These types are not allowed to be
3670 // forward referenced and not allowed to be recursive.
3671 if (Lex.getKind() != lltok::lbrace) {
3672 if (Entry.first)
3673 return error(L: TypeLoc, Msg: "forward references to non-struct type");
3674
3675 ResultTy = nullptr;
3676 if (isPacked)
3677 return parseArrayVectorType(Result&: ResultTy, IsVector: true);
3678 return parseType(Result&: ResultTy);
3679 }
3680
3681 // This type is being defined, so clear the location to indicate this.
3682 Entry.second = SMLoc();
3683
3684 // If this type number has never been uttered, create it.
3685 if (!Entry.first)
3686 Entry.first = StructType::create(Context, Name);
3687
3688 StructType *STy = cast<StructType>(Val: Entry.first);
3689
3690 SmallVector<Type*, 8> Body;
3691 if (parseStructBody(Body) ||
3692 (isPacked && parseToken(T: lltok::greater, ErrMsg: "expected '>' in packed struct")))
3693 return true;
3694
3695 if (auto E = STy->setBodyOrError(Elements: Body, isPacked))
3696 return tokError(Msg: toString(E: std::move(E)));
3697
3698 ResultTy = STy;
3699 return false;
3700}
3701
3702/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3703/// StructType
3704/// ::= '{' '}'
3705/// ::= '{' Type (',' Type)* '}'
3706/// ::= '<' '{' '}' '>'
3707/// ::= '<' '{' Type (',' Type)* '}' '>'
3708bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3709 assert(Lex.getKind() == lltok::lbrace);
3710 Lex.Lex(); // Consume the '{'
3711
3712 // Handle the empty struct.
3713 if (EatIfPresent(T: lltok::rbrace))
3714 return false;
3715
3716 LocTy EltTyLoc = Lex.getLoc();
3717 Type *Ty = nullptr;
3718 if (parseType(Result&: Ty))
3719 return true;
3720 Body.push_back(Elt: Ty);
3721
3722 if (!StructType::isValidElementType(ElemTy: Ty))
3723 return error(L: EltTyLoc, Msg: "invalid element type for struct");
3724
3725 while (EatIfPresent(T: lltok::comma)) {
3726 EltTyLoc = Lex.getLoc();
3727 if (parseType(Result&: Ty))
3728 return true;
3729
3730 if (!StructType::isValidElementType(ElemTy: Ty))
3731 return error(L: EltTyLoc, Msg: "invalid element type for struct");
3732
3733 Body.push_back(Elt: Ty);
3734 }
3735
3736 return parseToken(T: lltok::rbrace, ErrMsg: "expected '}' at end of struct");
3737}
3738
3739/// parseArrayVectorType - parse an array or vector type, assuming the first
3740/// token has already been consumed.
3741/// Type
3742/// ::= '[' APSINTVAL 'x' Types ']'
3743/// ::= '<' APSINTVAL 'x' Types '>'
3744/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3745bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3746 bool Scalable = false;
3747
3748 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3749 Lex.Lex(); // consume the 'vscale'
3750 if (parseToken(T: lltok::kw_x, ErrMsg: "expected 'x' after vscale"))
3751 return true;
3752
3753 Scalable = true;
3754 }
3755
3756 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3757 Lex.getAPSIntVal().getBitWidth() > 64)
3758 return tokError(Msg: "expected number in address space");
3759
3760 LocTy SizeLoc = Lex.getLoc();
3761 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3762 Lex.Lex();
3763
3764 if (parseToken(T: lltok::kw_x, ErrMsg: "expected 'x' after element count"))
3765 return true;
3766
3767 LocTy TypeLoc = Lex.getLoc();
3768 Type *EltTy = nullptr;
3769 if (parseType(Result&: EltTy))
3770 return true;
3771
3772 if (parseToken(T: IsVector ? lltok::greater : lltok::rsquare,
3773 ErrMsg: "expected end of sequential type"))
3774 return true;
3775
3776 if (IsVector) {
3777 if (Size == 0)
3778 return error(L: SizeLoc, Msg: "zero element vector is illegal");
3779 if ((unsigned)Size != Size)
3780 return error(L: SizeLoc, Msg: "size too large for vector");
3781 if (!VectorType::isValidElementType(ElemTy: EltTy))
3782 return error(L: TypeLoc, Msg: "invalid vector element type");
3783 Result = VectorType::get(ElementType: EltTy, NumElements: unsigned(Size), Scalable);
3784 } else {
3785 if (!ArrayType::isValidElementType(ElemTy: EltTy))
3786 return error(L: TypeLoc, Msg: "invalid array element type");
3787 Result = ArrayType::get(ElementType: EltTy, NumElements: Size);
3788 }
3789 return false;
3790}
3791
3792/// parseTargetExtType - handle target extension type syntax
3793/// TargetExtType
3794/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3795///
3796/// TargetExtTypeParams
3797/// ::= /*empty*/
3798/// ::= ',' Type TargetExtTypeParams
3799///
3800/// TargetExtIntParams
3801/// ::= /*empty*/
3802/// ::= ',' uint32 TargetExtIntParams
3803bool LLParser::parseTargetExtType(Type *&Result) {
3804 Lex.Lex(); // Eat the 'target' keyword.
3805
3806 // Get the mandatory type name.
3807 std::string TypeName;
3808 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in target extension type") ||
3809 parseStringConstant(Result&: TypeName))
3810 return true;
3811
3812 // Parse all of the integer and type parameters at the same time; the use of
3813 // SeenInt will allow us to catch cases where type parameters follow integer
3814 // parameters.
3815 SmallVector<Type *> TypeParams;
3816 SmallVector<unsigned> IntParams;
3817 bool SeenInt = false;
3818 while (Lex.getKind() == lltok::comma) {
3819 Lex.Lex(); // Eat the comma.
3820
3821 if (Lex.getKind() == lltok::APSInt) {
3822 SeenInt = true;
3823 unsigned IntVal;
3824 if (parseUInt32(Val&: IntVal))
3825 return true;
3826 IntParams.push_back(Elt: IntVal);
3827 } else if (SeenInt) {
3828 // The only other kind of parameter we support is type parameters, which
3829 // must precede the integer parameters. This is therefore an error.
3830 return tokError(Msg: "expected uint32 param");
3831 } else {
3832 Type *TypeParam;
3833 if (parseType(Result&: TypeParam, /*AllowVoid=*/true))
3834 return true;
3835 TypeParams.push_back(Elt: TypeParam);
3836 }
3837 }
3838
3839 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in target extension type"))
3840 return true;
3841
3842 auto TTy =
3843 TargetExtType::getOrError(Context, Name: TypeName, Types: TypeParams, Ints: IntParams);
3844 if (auto E = TTy.takeError())
3845 return tokError(Msg: toString(E: std::move(E)));
3846
3847 Result = *TTy;
3848 return false;
3849}
3850
3851//===----------------------------------------------------------------------===//
3852// Function Semantic Analysis.
3853//===----------------------------------------------------------------------===//
3854
3855LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3856 int functionNumber,
3857 ArrayRef<unsigned> UnnamedArgNums)
3858 : P(p), F(f), FunctionNumber(functionNumber) {
3859
3860 // Insert unnamed arguments into the NumberedVals list.
3861 auto It = UnnamedArgNums.begin();
3862 for (Argument &A : F.args()) {
3863 if (!A.hasName()) {
3864 unsigned ArgNum = *It++;
3865 NumberedVals.add(ID: ArgNum, V: &A);
3866 }
3867 }
3868}
3869
3870LLParser::PerFunctionState::~PerFunctionState() {
3871 // If there were any forward referenced non-basicblock values, delete them.
3872
3873 for (const auto &P : ForwardRefVals) {
3874 if (isa<BasicBlock>(Val: P.second.first))
3875 continue;
3876 P.second.first->replaceAllUsesWith(
3877 V: PoisonValue::get(T: P.second.first->getType()));
3878 P.second.first->deleteValue();
3879 }
3880
3881 for (const auto &P : ForwardRefValIDs) {
3882 if (isa<BasicBlock>(Val: P.second.first))
3883 continue;
3884 P.second.first->replaceAllUsesWith(
3885 V: PoisonValue::get(T: P.second.first->getType()));
3886 P.second.first->deleteValue();
3887 }
3888}
3889
3890bool LLParser::PerFunctionState::finishFunction() {
3891 if (!ForwardRefVals.empty())
3892 return P.error(L: ForwardRefVals.begin()->second.second,
3893 Msg: "use of undefined value '%" + ForwardRefVals.begin()->first +
3894 "'");
3895 if (!ForwardRefValIDs.empty())
3896 return P.error(L: ForwardRefValIDs.begin()->second.second,
3897 Msg: "use of undefined value '%" +
3898 Twine(ForwardRefValIDs.begin()->first) + "'");
3899 return false;
3900}
3901
3902/// getVal - Get a value with the specified name or ID, creating a
3903/// forward reference record if needed. This can return null if the value
3904/// exists but does not have the right type.
3905Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3906 LocTy Loc) {
3907 // Look this name up in the normal function symbol table.
3908 Value *Val = F.getValueSymbolTable()->lookup(Name);
3909
3910 // If this is a forward reference for the value, see if we already created a
3911 // forward ref record.
3912 if (!Val) {
3913 auto I = ForwardRefVals.find(x: Name);
3914 if (I != ForwardRefVals.end())
3915 Val = I->second.first;
3916 }
3917
3918 // If we have the value in the symbol table or fwd-ref table, return it.
3919 if (Val)
3920 return P.checkValidVariableType(Loc, Name: "%" + Name, Ty, Val);
3921
3922 // Don't make placeholders with invalid type.
3923 if (!Ty->isFirstClassType()) {
3924 P.error(L: Loc, Msg: "invalid use of a non-first-class type");
3925 return nullptr;
3926 }
3927
3928 // Otherwise, create a new forward reference for this value and remember it.
3929 Value *FwdVal;
3930 if (Ty->isLabelTy()) {
3931 FwdVal = BasicBlock::Create(Context&: F.getContext(), Name, Parent: &F);
3932 } else {
3933 FwdVal = new Argument(Ty, Name);
3934 }
3935 if (FwdVal->getName() != Name) {
3936 P.error(L: Loc, Msg: "name is too long which can result in name collisions, "
3937 "consider making the name shorter or "
3938 "increasing -non-global-value-max-name-size");
3939 return nullptr;
3940 }
3941
3942 ForwardRefVals[Name] = std::make_pair(x&: FwdVal, y&: Loc);
3943 return FwdVal;
3944}
3945
3946Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3947 // Look this name up in the normal function symbol table.
3948 Value *Val = NumberedVals.get(ID);
3949
3950 // If this is a forward reference for the value, see if we already created a
3951 // forward ref record.
3952 if (!Val) {
3953 auto I = ForwardRefValIDs.find(x: ID);
3954 if (I != ForwardRefValIDs.end())
3955 Val = I->second.first;
3956 }
3957
3958 // If we have the value in the symbol table or fwd-ref table, return it.
3959 if (Val)
3960 return P.checkValidVariableType(Loc, Name: "%" + Twine(ID), Ty, Val);
3961
3962 if (!Ty->isFirstClassType()) {
3963 P.error(L: Loc, Msg: "invalid use of a non-first-class type");
3964 return nullptr;
3965 }
3966
3967 // Otherwise, create a new forward reference for this value and remember it.
3968 Value *FwdVal;
3969 if (Ty->isLabelTy()) {
3970 FwdVal = BasicBlock::Create(Context&: F.getContext(), Name: "", Parent: &F);
3971 } else {
3972 FwdVal = new Argument(Ty);
3973 }
3974
3975 ForwardRefValIDs[ID] = std::make_pair(x&: FwdVal, y&: Loc);
3976 return FwdVal;
3977}
3978
3979/// setInstName - After an instruction is parsed and inserted into its
3980/// basic block, this installs its name.
3981bool LLParser::PerFunctionState::setInstName(int NameID,
3982 const std::string &NameStr,
3983 LocTy NameLoc, Instruction *Inst) {
3984 // If this instruction has void type, it cannot have a name or ID specified.
3985 if (Inst->getType()->isVoidTy()) {
3986 if (NameID != -1 || !NameStr.empty())
3987 return P.error(L: NameLoc, Msg: "instructions returning void cannot have a name");
3988 return false;
3989 }
3990
3991 // If this was a numbered instruction, verify that the instruction is the
3992 // expected value and resolve any forward references.
3993 if (NameStr.empty()) {
3994 // If neither a name nor an ID was specified, just use the next ID.
3995 if (NameID == -1)
3996 NameID = NumberedVals.getNext();
3997
3998 if (P.checkValueID(Loc: NameLoc, Kind: "instruction", Prefix: "%", NextID: NumberedVals.getNext(),
3999 ID: NameID))
4000 return true;
4001
4002 auto FI = ForwardRefValIDs.find(x: NameID);
4003 if (FI != ForwardRefValIDs.end()) {
4004 Value *Sentinel = FI->second.first;
4005 if (Sentinel->getType() != Inst->getType())
4006 return P.error(L: NameLoc, Msg: "instruction forward referenced with type '" +
4007 getTypeString(T: FI->second.first->getType()) +
4008 "'");
4009
4010 Sentinel->replaceAllUsesWith(V: Inst);
4011 Sentinel->deleteValue();
4012 ForwardRefValIDs.erase(position: FI);
4013 }
4014
4015 NumberedVals.add(ID: NameID, V: Inst);
4016 return false;
4017 }
4018
4019 // Otherwise, the instruction had a name. Resolve forward refs and set it.
4020 auto FI = ForwardRefVals.find(x: NameStr);
4021 if (FI != ForwardRefVals.end()) {
4022 Value *Sentinel = FI->second.first;
4023 if (Sentinel->getType() != Inst->getType())
4024 return P.error(L: NameLoc, Msg: "instruction forward referenced with type '" +
4025 getTypeString(T: FI->second.first->getType()) +
4026 "'");
4027
4028 Sentinel->replaceAllUsesWith(V: Inst);
4029 Sentinel->deleteValue();
4030 ForwardRefVals.erase(position: FI);
4031 }
4032
4033 // Set the name on the instruction.
4034 Inst->setName(NameStr);
4035
4036 if (Inst->getName() != NameStr)
4037 return P.error(L: NameLoc, Msg: "multiple definition of local value named '" +
4038 NameStr + "'");
4039 return false;
4040}
4041
4042/// getBB - Get a basic block with the specified name or ID, creating a
4043/// forward reference record if needed.
4044BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
4045 LocTy Loc) {
4046 return dyn_cast_or_null<BasicBlock>(
4047 Val: getVal(Name, Ty: Type::getLabelTy(C&: F.getContext()), Loc));
4048}
4049
4050BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
4051 return dyn_cast_or_null<BasicBlock>(
4052 Val: getVal(ID, Ty: Type::getLabelTy(C&: F.getContext()), Loc));
4053}
4054
4055/// defineBB - Define the specified basic block, which is either named or
4056/// unnamed. If there is an error, this returns null otherwise it returns
4057/// the block being defined.
4058BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
4059 int NameID, LocTy Loc) {
4060 BasicBlock *BB;
4061 if (Name.empty()) {
4062 if (NameID != -1) {
4063 if (P.checkValueID(Loc, Kind: "label", Prefix: "", NextID: NumberedVals.getNext(), ID: NameID))
4064 return nullptr;
4065 } else {
4066 NameID = NumberedVals.getNext();
4067 }
4068 BB = getBB(ID: NameID, Loc);
4069 if (!BB) {
4070 P.error(L: Loc, Msg: "unable to create block numbered '" + Twine(NameID) + "'");
4071 return nullptr;
4072 }
4073 } else {
4074 BB = getBB(Name, Loc);
4075 if (!BB) {
4076 P.error(L: Loc, Msg: "unable to create block named '" + Name + "'");
4077 return nullptr;
4078 }
4079 }
4080
4081 // Move the block to the end of the function. Forward ref'd blocks are
4082 // inserted wherever they happen to be referenced.
4083 F.splice(ToIt: F.end(), FromF: &F, FromIt: BB->getIterator());
4084
4085 // Remove the block from forward ref sets.
4086 if (Name.empty()) {
4087 ForwardRefValIDs.erase(x: NameID);
4088 NumberedVals.add(ID: NameID, V: BB);
4089 } else {
4090 // BB forward references are already in the function symbol table.
4091 ForwardRefVals.erase(x: Name);
4092 }
4093
4094 return BB;
4095}
4096
4097//===----------------------------------------------------------------------===//
4098// Constants.
4099//===----------------------------------------------------------------------===//
4100
4101/// parseValID - parse an abstract value that doesn't necessarily have a
4102/// type implied. For example, if we parse "4" we don't know what integer type
4103/// it has. The value will later be combined with its type and checked for
4104/// basic correctness. PFS is used to convert function-local operands of
4105/// metadata (since metadata operands are not just parsed here but also
4106/// converted to values). PFS can be null when we are not parsing metadata
4107/// values inside a function.
4108bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
4109 ID.Loc = Lex.getLoc();
4110 switch (Lex.getKind()) {
4111 default:
4112 return tokError(Msg: "expected value token");
4113 case lltok::GlobalID: // @42
4114 ID.UIntVal = Lex.getUIntVal();
4115 ID.Kind = ValID::t_GlobalID;
4116 break;
4117 case lltok::GlobalVar: // @foo
4118 ID.StrVal = Lex.getStrVal();
4119 ID.Kind = ValID::t_GlobalName;
4120 break;
4121 case lltok::LocalVarID: // %42
4122 ID.UIntVal = Lex.getUIntVal();
4123 ID.Kind = ValID::t_LocalID;
4124 break;
4125 case lltok::LocalVar: // %foo
4126 ID.StrVal = Lex.getStrVal();
4127 ID.Kind = ValID::t_LocalName;
4128 break;
4129 case lltok::APSInt:
4130 ID.APSIntVal = Lex.getAPSIntVal();
4131 ID.Kind = ValID::t_APSInt;
4132 break;
4133 case lltok::APFloat:
4134 ID.APFloatVal = Lex.getAPFloatVal();
4135 ID.Kind = ValID::t_APFloat;
4136 break;
4137 case lltok::kw_true:
4138 ID.ConstantVal = ConstantInt::getTrue(Context);
4139 ID.Kind = ValID::t_Constant;
4140 break;
4141 case lltok::kw_false:
4142 ID.ConstantVal = ConstantInt::getFalse(Context);
4143 ID.Kind = ValID::t_Constant;
4144 break;
4145 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
4146 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
4147 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
4148 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
4149 case lltok::kw_none: ID.Kind = ValID::t_None; break;
4150
4151 case lltok::lbrace: {
4152 // ValID ::= '{' ConstVector '}'
4153 Lex.Lex();
4154 SmallVector<Constant*, 16> Elts;
4155 if (parseGlobalValueVector(Elts) ||
4156 parseToken(T: lltok::rbrace, ErrMsg: "expected end of struct constant"))
4157 return true;
4158
4159 ID.ConstantStructElts = std::make_unique<Constant *[]>(num: Elts.size());
4160 ID.UIntVal = Elts.size();
4161 memcpy(dest: ID.ConstantStructElts.get(), src: Elts.data(),
4162 n: Elts.size() * sizeof(Elts[0]));
4163 ID.Kind = ValID::t_ConstantStruct;
4164 return false;
4165 }
4166 case lltok::less: {
4167 // ValID ::= '<' ConstVector '>' --> Vector.
4168 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
4169 Lex.Lex();
4170 bool isPackedStruct = EatIfPresent(T: lltok::lbrace);
4171
4172 SmallVector<Constant*, 16> Elts;
4173 LocTy FirstEltLoc = Lex.getLoc();
4174 if (parseGlobalValueVector(Elts) ||
4175 (isPackedStruct &&
4176 parseToken(T: lltok::rbrace, ErrMsg: "expected end of packed struct")) ||
4177 parseToken(T: lltok::greater, ErrMsg: "expected end of constant"))
4178 return true;
4179
4180 if (isPackedStruct) {
4181 ID.ConstantStructElts = std::make_unique<Constant *[]>(num: Elts.size());
4182 memcpy(dest: ID.ConstantStructElts.get(), src: Elts.data(),
4183 n: Elts.size() * sizeof(Elts[0]));
4184 ID.UIntVal = Elts.size();
4185 ID.Kind = ValID::t_PackedConstantStruct;
4186 return false;
4187 }
4188
4189 if (Elts.empty())
4190 return error(L: ID.Loc, Msg: "constant vector must not be empty");
4191
4192 if (!Elts[0]->getType()->isIntegerTy() && !Elts[0]->getType()->isByteTy() &&
4193 !Elts[0]->getType()->isFloatingPointTy() &&
4194 !Elts[0]->getType()->isPointerTy())
4195 return error(
4196 L: FirstEltLoc,
4197 Msg: "vector elements must have integer, byte, pointer or floating point "
4198 "type");
4199
4200 // Verify that all the vector elements have the same type.
4201 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4202 if (Elts[i]->getType() != Elts[0]->getType())
4203 return error(L: FirstEltLoc, Msg: "vector element #" + Twine(i) +
4204 " is not of type '" +
4205 getTypeString(T: Elts[0]->getType()));
4206
4207 ID.ConstantVal = ConstantVector::get(V: Elts);
4208 ID.Kind = ValID::t_Constant;
4209 return false;
4210 }
4211 case lltok::lsquare: { // Array Constant
4212 Lex.Lex();
4213 SmallVector<Constant*, 16> Elts;
4214 LocTy FirstEltLoc = Lex.getLoc();
4215 if (parseGlobalValueVector(Elts) ||
4216 parseToken(T: lltok::rsquare, ErrMsg: "expected end of array constant"))
4217 return true;
4218
4219 // Handle empty element.
4220 if (Elts.empty()) {
4221 // Use undef instead of an array because it's inconvenient to determine
4222 // the element type at this point, there being no elements to examine.
4223 ID.Kind = ValID::t_EmptyArray;
4224 return false;
4225 }
4226
4227 if (!Elts[0]->getType()->isFirstClassType())
4228 return error(L: FirstEltLoc, Msg: "invalid array element type: " +
4229 getTypeString(T: Elts[0]->getType()));
4230
4231 ArrayType *ATy = ArrayType::get(ElementType: Elts[0]->getType(), NumElements: Elts.size());
4232
4233 // Verify all elements are correct type!
4234 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4235 if (Elts[i]->getType() != Elts[0]->getType())
4236 return error(L: FirstEltLoc, Msg: "array element #" + Twine(i) +
4237 " is not of type '" +
4238 getTypeString(T: Elts[0]->getType()));
4239 }
4240
4241 ID.ConstantVal = ConstantArray::get(T: ATy, V: Elts);
4242 ID.Kind = ValID::t_Constant;
4243 return false;
4244 }
4245 case lltok::kw_c: { // c "foo"
4246 Lex.Lex();
4247 ArrayType *ATy = cast<ArrayType>(Val: ExpectedTy);
4248 ID.ConstantVal = ConstantDataArray::getString(
4249 Context, Initializer: Lex.getStrVal(), AddNull: false, ByteString: ATy->getElementType()->isByteTy());
4250 if (parseToken(T: lltok::StringConstant, ErrMsg: "expected string"))
4251 return true;
4252 ID.Kind = ValID::t_Constant;
4253 return false;
4254 }
4255 case lltok::kw_asm: {
4256 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4257 // STRINGCONSTANT
4258 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4259 Lex.Lex();
4260 if (parseOptionalToken(T: lltok::kw_sideeffect, Present&: HasSideEffect) ||
4261 parseOptionalToken(T: lltok::kw_alignstack, Present&: AlignStack) ||
4262 parseOptionalToken(T: lltok::kw_inteldialect, Present&: AsmDialect) ||
4263 parseOptionalToken(T: lltok::kw_unwind, Present&: CanThrow) ||
4264 parseStringConstant(Result&: ID.StrVal) ||
4265 parseToken(T: lltok::comma, ErrMsg: "expected comma in inline asm expression") ||
4266 parseToken(T: lltok::StringConstant, ErrMsg: "expected constraint string"))
4267 return true;
4268 ID.StrVal2 = Lex.getStrVal();
4269 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4270 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4271 ID.Kind = ValID::t_InlineAsm;
4272 return false;
4273 }
4274
4275 case lltok::kw_blockaddress: {
4276 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4277 Lex.Lex();
4278
4279 ValID Fn, Label;
4280
4281 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in block address expression") ||
4282 parseValID(ID&: Fn, PFS) ||
4283 parseToken(T: lltok::comma,
4284 ErrMsg: "expected comma in block address expression") ||
4285 parseValID(ID&: Label, PFS) ||
4286 parseToken(T: lltok::rparen, ErrMsg: "expected ')' in block address expression"))
4287 return true;
4288
4289 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
4290 return error(L: Fn.Loc, Msg: "expected function name in blockaddress");
4291 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4292 return error(L: Label.Loc, Msg: "expected basic block name in blockaddress");
4293
4294 // Try to find the function (but skip it if it's forward-referenced).
4295 GlobalValue *GV = nullptr;
4296 if (Fn.Kind == ValID::t_GlobalID) {
4297 GV = NumberedVals.get(ID: Fn.UIntVal);
4298 } else if (!ForwardRefVals.count(x: Fn.StrVal)) {
4299 GV = M->getNamedValue(Name: Fn.StrVal);
4300 }
4301 Function *F = nullptr;
4302 if (GV) {
4303 // Confirm that it's actually a function with a definition.
4304 if (!isa<Function>(Val: GV))
4305 return error(L: Fn.Loc, Msg: "expected function name in blockaddress");
4306 F = cast<Function>(Val: GV);
4307 if (F->isDeclaration())
4308 return error(L: Fn.Loc, Msg: "cannot take blockaddress inside a declaration");
4309 }
4310
4311 if (!F) {
4312 // Make a global variable as a placeholder for this reference.
4313 GlobalValue *&FwdRef =
4314 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4315 if (!FwdRef) {
4316 unsigned FwdDeclAS;
4317 if (ExpectedTy) {
4318 // If we know the type that the blockaddress is being assigned to,
4319 // we can use the address space of that type.
4320 if (!ExpectedTy->isPointerTy())
4321 return error(L: ID.Loc,
4322 Msg: "type of blockaddress must be a pointer and not '" +
4323 getTypeString(T: ExpectedTy) + "'");
4324 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4325 } else if (PFS) {
4326 // Otherwise, we default the address space of the current function.
4327 FwdDeclAS = PFS->getFunction().getAddressSpace();
4328 } else {
4329 llvm_unreachable("Unknown address space for blockaddress");
4330 }
4331 FwdRef = new GlobalVariable(
4332 *M, Type::getInt8Ty(C&: Context), false, GlobalValue::InternalLinkage,
4333 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4334 }
4335
4336 ID.ConstantVal = FwdRef;
4337 ID.Kind = ValID::t_Constant;
4338 return false;
4339 }
4340
4341 // We found the function; now find the basic block. Don't use PFS, since we
4342 // might be inside a constant expression.
4343 BasicBlock *BB;
4344 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4345 if (Label.Kind == ValID::t_LocalID)
4346 BB = BlockAddressPFS->getBB(ID: Label.UIntVal, Loc: Label.Loc);
4347 else
4348 BB = BlockAddressPFS->getBB(Name: Label.StrVal, Loc: Label.Loc);
4349 if (!BB)
4350 return error(L: Label.Loc, Msg: "referenced value is not a basic block");
4351 } else {
4352 if (Label.Kind == ValID::t_LocalID)
4353 return error(L: Label.Loc, Msg: "cannot take address of numeric label after "
4354 "the function is defined");
4355 BB = dyn_cast_or_null<BasicBlock>(
4356 Val: F->getValueSymbolTable()->lookup(Name: Label.StrVal));
4357 if (!BB)
4358 return error(L: Label.Loc, Msg: "referenced value is not a basic block");
4359 }
4360
4361 ID.ConstantVal = BlockAddress::get(F, BB);
4362 ID.Kind = ValID::t_Constant;
4363 return false;
4364 }
4365
4366 case lltok::kw_dso_local_equivalent: {
4367 // ValID ::= 'dso_local_equivalent' @foo
4368 Lex.Lex();
4369
4370 ValID Fn;
4371
4372 if (parseValID(ID&: Fn, PFS))
4373 return true;
4374
4375 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
4376 return error(L: Fn.Loc,
4377 Msg: "expected global value name in dso_local_equivalent");
4378
4379 // Try to find the function (but skip it if it's forward-referenced).
4380 GlobalValue *GV = nullptr;
4381 if (Fn.Kind == ValID::t_GlobalID) {
4382 GV = NumberedVals.get(ID: Fn.UIntVal);
4383 } else if (!ForwardRefVals.count(x: Fn.StrVal)) {
4384 GV = M->getNamedValue(Name: Fn.StrVal);
4385 }
4386
4387 if (!GV) {
4388 // Make a placeholder global variable as a placeholder for this reference.
4389 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4390 ? ForwardRefDSOLocalEquivalentIDs
4391 : ForwardRefDSOLocalEquivalentNames;
4392 GlobalValue *&FwdRef = FwdRefMap[Fn];
4393 if (!FwdRef) {
4394 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(C&: Context), false,
4395 GlobalValue::InternalLinkage, nullptr, "",
4396 nullptr, GlobalValue::NotThreadLocal);
4397 }
4398
4399 ID.ConstantVal = FwdRef;
4400 ID.Kind = ValID::t_Constant;
4401 return false;
4402 }
4403
4404 if (!GV->getValueType()->isFunctionTy())
4405 return error(L: Fn.Loc, Msg: "expected a function, alias to function, or ifunc "
4406 "in dso_local_equivalent");
4407
4408 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4409 ID.Kind = ValID::t_Constant;
4410 return false;
4411 }
4412
4413 case lltok::kw_no_cfi: {
4414 // ValID ::= 'no_cfi' @foo
4415 Lex.Lex();
4416
4417 if (parseValID(ID, PFS))
4418 return true;
4419
4420 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4421 return error(L: ID.Loc, Msg: "expected global value name in no_cfi");
4422
4423 ID.NoCFI = true;
4424 return false;
4425 }
4426 case lltok::kw_ptrauth: {
4427 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4428 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4429 // )? )? ')'
4430 Lex.Lex();
4431
4432 Constant *Ptr, *Key;
4433 Constant *Disc = nullptr, *AddrDisc = nullptr,
4434 *DeactivationSymbol = nullptr;
4435
4436 if (parseToken(T: lltok::lparen,
4437 ErrMsg: "expected '(' in constant ptrauth expression") ||
4438 parseGlobalTypeAndValue(V&: Ptr) ||
4439 parseToken(T: lltok::comma,
4440 ErrMsg: "expected comma in constant ptrauth expression") ||
4441 parseGlobalTypeAndValue(V&: Key))
4442 return true;
4443 // If present, parse the optional disc/addrdisc/ds.
4444 if (EatIfPresent(T: lltok::comma) && parseGlobalTypeAndValue(V&: Disc))
4445 return true;
4446 if (EatIfPresent(T: lltok::comma) && parseGlobalTypeAndValue(V&: AddrDisc))
4447 return true;
4448 if (EatIfPresent(T: lltok::comma) &&
4449 parseGlobalTypeAndValue(V&: DeactivationSymbol))
4450 return true;
4451 if (parseToken(T: lltok::rparen,
4452 ErrMsg: "expected ')' in constant ptrauth expression"))
4453 return true;
4454
4455 if (!Ptr->getType()->isPointerTy())
4456 return error(L: ID.Loc, Msg: "constant ptrauth base pointer must be a pointer");
4457
4458 auto *KeyC = dyn_cast<ConstantInt>(Val: Key);
4459 if (!KeyC || KeyC->getBitWidth() != 32)
4460 return error(L: ID.Loc, Msg: "constant ptrauth key must be i32 constant");
4461
4462 ConstantInt *DiscC = nullptr;
4463 if (Disc) {
4464 DiscC = dyn_cast<ConstantInt>(Val: Disc);
4465 if (!DiscC || DiscC->getBitWidth() != 64)
4466 return error(
4467 L: ID.Loc,
4468 Msg: "constant ptrauth integer discriminator must be i64 constant");
4469 } else {
4470 DiscC = ConstantInt::get(Ty: Type::getInt64Ty(C&: Context), V: 0);
4471 }
4472
4473 if (AddrDisc) {
4474 if (!AddrDisc->getType()->isPointerTy())
4475 return error(
4476 L: ID.Loc, Msg: "constant ptrauth address discriminator must be a pointer");
4477 } else {
4478 AddrDisc = ConstantPointerNull::get(T: PointerType::get(C&: Context, AddressSpace: 0));
4479 }
4480
4481 if (!DeactivationSymbol)
4482 DeactivationSymbol =
4483 ConstantPointerNull::get(T: PointerType::get(C&: Context, AddressSpace: 0));
4484 if (!DeactivationSymbol->getType()->isPointerTy())
4485 return error(L: ID.Loc,
4486 Msg: "constant ptrauth deactivation symbol must be a pointer");
4487
4488 ID.ConstantVal =
4489 ConstantPtrAuth::get(Ptr, Key: KeyC, Disc: DiscC, AddrDisc, DeactivationSymbol);
4490 ID.Kind = ValID::t_Constant;
4491 return false;
4492 }
4493
4494 case lltok::kw_trunc:
4495 case lltok::kw_bitcast:
4496 case lltok::kw_addrspacecast:
4497 case lltok::kw_inttoptr:
4498 case lltok::kw_ptrtoaddr:
4499 case lltok::kw_ptrtoint: {
4500 unsigned Opc = Lex.getUIntVal();
4501 Type *DestTy = nullptr;
4502 Constant *SrcVal;
4503 Lex.Lex();
4504 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' after constantexpr cast") ||
4505 parseGlobalTypeAndValue(V&: SrcVal) ||
4506 parseToken(T: lltok::kw_to, ErrMsg: "expected 'to' in constantexpr cast") ||
4507 parseType(Result&: DestTy) ||
4508 parseToken(T: lltok::rparen, ErrMsg: "expected ')' at end of constantexpr cast"))
4509 return true;
4510 if (!CastInst::castIsValid(op: (Instruction::CastOps)Opc, S: SrcVal, DstTy: DestTy))
4511 return error(L: ID.Loc, Msg: "invalid cast opcode for cast from '" +
4512 getTypeString(T: SrcVal->getType()) + "' to '" +
4513 getTypeString(T: DestTy) + "'");
4514 ID.ConstantVal = ConstantExpr::getCast(ops: (Instruction::CastOps)Opc,
4515 C: SrcVal, Ty: DestTy);
4516 ID.Kind = ValID::t_Constant;
4517 return false;
4518 }
4519 case lltok::kw_extractvalue:
4520 return error(L: ID.Loc, Msg: "extractvalue constexprs are no longer supported");
4521 case lltok::kw_insertvalue:
4522 return error(L: ID.Loc, Msg: "insertvalue constexprs are no longer supported");
4523 case lltok::kw_udiv:
4524 return error(L: ID.Loc, Msg: "udiv constexprs are no longer supported");
4525 case lltok::kw_sdiv:
4526 return error(L: ID.Loc, Msg: "sdiv constexprs are no longer supported");
4527 case lltok::kw_urem:
4528 return error(L: ID.Loc, Msg: "urem constexprs are no longer supported");
4529 case lltok::kw_srem:
4530 return error(L: ID.Loc, Msg: "srem constexprs are no longer supported");
4531 case lltok::kw_fadd:
4532 return error(L: ID.Loc, Msg: "fadd constexprs are no longer supported");
4533 case lltok::kw_fsub:
4534 return error(L: ID.Loc, Msg: "fsub constexprs are no longer supported");
4535 case lltok::kw_fmul:
4536 return error(L: ID.Loc, Msg: "fmul constexprs are no longer supported");
4537 case lltok::kw_fdiv:
4538 return error(L: ID.Loc, Msg: "fdiv constexprs are no longer supported");
4539 case lltok::kw_frem:
4540 return error(L: ID.Loc, Msg: "frem constexprs are no longer supported");
4541 case lltok::kw_and:
4542 return error(L: ID.Loc, Msg: "and constexprs are no longer supported");
4543 case lltok::kw_or:
4544 return error(L: ID.Loc, Msg: "or constexprs are no longer supported");
4545 case lltok::kw_lshr:
4546 return error(L: ID.Loc, Msg: "lshr constexprs are no longer supported");
4547 case lltok::kw_ashr:
4548 return error(L: ID.Loc, Msg: "ashr constexprs are no longer supported");
4549 case lltok::kw_shl:
4550 return error(L: ID.Loc, Msg: "shl constexprs are no longer supported");
4551 case lltok::kw_mul:
4552 return error(L: ID.Loc, Msg: "mul constexprs are no longer supported");
4553 case lltok::kw_fneg:
4554 return error(L: ID.Loc, Msg: "fneg constexprs are no longer supported");
4555 case lltok::kw_select:
4556 return error(L: ID.Loc, Msg: "select constexprs are no longer supported");
4557 case lltok::kw_zext:
4558 return error(L: ID.Loc, Msg: "zext constexprs are no longer supported");
4559 case lltok::kw_sext:
4560 return error(L: ID.Loc, Msg: "sext constexprs are no longer supported");
4561 case lltok::kw_fptrunc:
4562 return error(L: ID.Loc, Msg: "fptrunc constexprs are no longer supported");
4563 case lltok::kw_fpext:
4564 return error(L: ID.Loc, Msg: "fpext constexprs are no longer supported");
4565 case lltok::kw_uitofp:
4566 return error(L: ID.Loc, Msg: "uitofp constexprs are no longer supported");
4567 case lltok::kw_sitofp:
4568 return error(L: ID.Loc, Msg: "sitofp constexprs are no longer supported");
4569 case lltok::kw_fptoui:
4570 return error(L: ID.Loc, Msg: "fptoui constexprs are no longer supported");
4571 case lltok::kw_fptosi:
4572 return error(L: ID.Loc, Msg: "fptosi constexprs are no longer supported");
4573 case lltok::kw_icmp:
4574 return error(L: ID.Loc, Msg: "icmp constexprs are no longer supported");
4575 case lltok::kw_fcmp:
4576 return error(L: ID.Loc, Msg: "fcmp constexprs are no longer supported");
4577
4578 // Binary Operators.
4579 case lltok::kw_add:
4580 case lltok::kw_sub:
4581 case lltok::kw_xor: {
4582 bool NUW = false;
4583 bool NSW = false;
4584 unsigned Opc = Lex.getUIntVal();
4585 Constant *Val0, *Val1;
4586 Lex.Lex();
4587 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4588 Opc == Instruction::Mul) {
4589 if (EatIfPresent(T: lltok::kw_nuw))
4590 NUW = true;
4591 if (EatIfPresent(T: lltok::kw_nsw)) {
4592 NSW = true;
4593 if (EatIfPresent(T: lltok::kw_nuw))
4594 NUW = true;
4595 }
4596 }
4597 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in binary constantexpr") ||
4598 parseGlobalTypeAndValue(V&: Val0) ||
4599 parseToken(T: lltok::comma, ErrMsg: "expected comma in binary constantexpr") ||
4600 parseGlobalTypeAndValue(V&: Val1) ||
4601 parseToken(T: lltok::rparen, ErrMsg: "expected ')' in binary constantexpr"))
4602 return true;
4603 if (Val0->getType() != Val1->getType())
4604 return error(L: ID.Loc, Msg: "operands of constexpr must have same type");
4605 // Check that the type is valid for the operator.
4606 if (!Val0->getType()->isIntOrIntVectorTy())
4607 return error(L: ID.Loc,
4608 Msg: "constexpr requires integer or integer vector operands");
4609 unsigned Flags = 0;
4610 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
4611 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
4612 ID.ConstantVal = ConstantExpr::get(Opcode: Opc, C1: Val0, C2: Val1, Flags);
4613 ID.Kind = ValID::t_Constant;
4614 return false;
4615 }
4616
4617 case lltok::kw_splat: {
4618 Lex.Lex();
4619 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' after vector splat"))
4620 return true;
4621 Constant *C;
4622 if (parseGlobalTypeAndValue(V&: C))
4623 return true;
4624 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' at end of vector splat"))
4625 return true;
4626
4627 ID.ConstantVal = C;
4628 ID.Kind = ValID::t_ConstantSplat;
4629 return false;
4630 }
4631
4632 case lltok::kw_getelementptr:
4633 case lltok::kw_shufflevector:
4634 case lltok::kw_insertelement:
4635 case lltok::kw_extractelement: {
4636 unsigned Opc = Lex.getUIntVal();
4637 SmallVector<Constant*, 16> Elts;
4638 GEPNoWrapFlags NW;
4639 bool HasInRange = false;
4640 APSInt InRangeStart;
4641 APSInt InRangeEnd;
4642 Type *Ty;
4643 Lex.Lex();
4644
4645 if (Opc == Instruction::GetElementPtr) {
4646 while (true) {
4647 if (EatIfPresent(T: lltok::kw_inbounds))
4648 NW |= GEPNoWrapFlags::inBounds();
4649 else if (EatIfPresent(T: lltok::kw_nusw))
4650 NW |= GEPNoWrapFlags::noUnsignedSignedWrap();
4651 else if (EatIfPresent(T: lltok::kw_nuw))
4652 NW |= GEPNoWrapFlags::noUnsignedWrap();
4653 else
4654 break;
4655 }
4656
4657 if (EatIfPresent(T: lltok::kw_inrange)) {
4658 if (parseToken(T: lltok::lparen, ErrMsg: "expected '('"))
4659 return true;
4660 if (Lex.getKind() != lltok::APSInt)
4661 return tokError(Msg: "expected integer");
4662 InRangeStart = Lex.getAPSIntVal();
4663 Lex.Lex();
4664 if (parseToken(T: lltok::comma, ErrMsg: "expected ','"))
4665 return true;
4666 if (Lex.getKind() != lltok::APSInt)
4667 return tokError(Msg: "expected integer");
4668 InRangeEnd = Lex.getAPSIntVal();
4669 Lex.Lex();
4670 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')'"))
4671 return true;
4672 HasInRange = true;
4673 }
4674 }
4675
4676 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in constantexpr"))
4677 return true;
4678
4679 if (Opc == Instruction::GetElementPtr) {
4680 if (parseType(Result&: Ty) ||
4681 parseToken(T: lltok::comma, ErrMsg: "expected comma after getelementptr's type"))
4682 return true;
4683 }
4684
4685 if (parseGlobalValueVector(Elts) ||
4686 parseToken(T: lltok::rparen, ErrMsg: "expected ')' in constantexpr"))
4687 return true;
4688
4689 if (Opc == Instruction::GetElementPtr) {
4690 if (Elts.size() == 0 ||
4691 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4692 return error(L: ID.Loc, Msg: "base of getelementptr must be a pointer");
4693
4694 Type *BaseType = Elts[0]->getType();
4695 std::optional<ConstantRange> InRange;
4696 if (HasInRange) {
4697 unsigned IndexWidth =
4698 M->getDataLayout().getIndexTypeSizeInBits(Ty: BaseType);
4699 InRangeStart = InRangeStart.extOrTrunc(width: IndexWidth);
4700 InRangeEnd = InRangeEnd.extOrTrunc(width: IndexWidth);
4701 if (InRangeStart.sge(RHS: InRangeEnd))
4702 return error(L: ID.Loc, Msg: "expected end to be larger than start");
4703 InRange = ConstantRange::getNonEmpty(Lower: InRangeStart, Upper: InRangeEnd);
4704 }
4705
4706 unsigned GEPWidth =
4707 BaseType->isVectorTy()
4708 ? cast<FixedVectorType>(Val: BaseType)->getNumElements()
4709 : 0;
4710
4711 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4712 for (Constant *Val : Indices) {
4713 Type *ValTy = Val->getType();
4714 if (!ValTy->isIntOrIntVectorTy())
4715 return error(L: ID.Loc, Msg: "getelementptr index must be an integer");
4716 if (auto *ValVTy = dyn_cast<VectorType>(Val: ValTy)) {
4717 unsigned ValNumEl = cast<FixedVectorType>(Val: ValVTy)->getNumElements();
4718 if (GEPWidth && (ValNumEl != GEPWidth))
4719 return error(
4720 L: ID.Loc,
4721 Msg: "getelementptr vector index has a wrong number of elements");
4722 // GEPWidth may have been unknown because the base is a scalar,
4723 // but it is known now.
4724 GEPWidth = ValNumEl;
4725 }
4726 }
4727
4728 SmallPtrSet<Type*, 4> Visited;
4729 if (!Indices.empty() && !Ty->isSized(Visited: &Visited))
4730 return error(L: ID.Loc, Msg: "base element of getelementptr must be sized");
4731
4732 if (!ConstantExpr::isSupportedGetElementPtr(SrcElemTy: Ty))
4733 return error(L: ID.Loc, Msg: "invalid base element for constant getelementptr");
4734
4735 if (!GetElementPtrInst::getIndexedType(Ty, IdxList: Indices))
4736 return error(L: ID.Loc, Msg: "invalid getelementptr indices");
4737
4738 ID.ConstantVal =
4739 ConstantExpr::getGetElementPtr(Ty, C: Elts[0], IdxList: Indices, NW, InRange);
4740 } else if (Opc == Instruction::ShuffleVector) {
4741 if (Elts.size() != 3)
4742 return error(L: ID.Loc, Msg: "expected three operands to shufflevector");
4743 if (!ShuffleVectorInst::isValidOperands(V1: Elts[0], V2: Elts[1], Mask: Elts[2]))
4744 return error(L: ID.Loc, Msg: "invalid operands to shufflevector");
4745 SmallVector<int, 16> Mask;
4746 ShuffleVectorInst::getShuffleMask(Mask: cast<Constant>(Val: Elts[2]), Result&: Mask);
4747 ID.ConstantVal = ConstantExpr::getShuffleVector(V1: Elts[0], V2: Elts[1], Mask);
4748 } else if (Opc == Instruction::ExtractElement) {
4749 if (Elts.size() != 2)
4750 return error(L: ID.Loc, Msg: "expected two operands to extractelement");
4751 if (!ExtractElementInst::isValidOperands(Vec: Elts[0], Idx: Elts[1]))
4752 return error(L: ID.Loc, Msg: "invalid extractelement operands");
4753 ID.ConstantVal = ConstantExpr::getExtractElement(Vec: Elts[0], Idx: Elts[1]);
4754 } else {
4755 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4756 if (Elts.size() != 3)
4757 return error(L: ID.Loc, Msg: "expected three operands to insertelement");
4758 if (!InsertElementInst::isValidOperands(Vec: Elts[0], NewElt: Elts[1], Idx: Elts[2]))
4759 return error(L: ID.Loc, Msg: "invalid insertelement operands");
4760 ID.ConstantVal =
4761 ConstantExpr::getInsertElement(Vec: Elts[0], Elt: Elts[1],Idx: Elts[2]);
4762 }
4763
4764 ID.Kind = ValID::t_Constant;
4765 return false;
4766 }
4767 }
4768
4769 Lex.Lex();
4770 return false;
4771}
4772
4773/// parseGlobalValue - parse a global value with the specified type.
4774bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4775 C = nullptr;
4776 ValID ID;
4777 Value *V = nullptr;
4778 bool Parsed = parseValID(ID, /*PFS=*/nullptr, ExpectedTy: Ty) ||
4779 convertValIDToValue(Ty, ID, V, PFS: nullptr);
4780 if (V && !(C = dyn_cast<Constant>(Val: V)))
4781 return error(L: ID.Loc, Msg: "global values must be constants");
4782 return Parsed;
4783}
4784
4785bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4786 Type *Ty = nullptr;
4787 return parseType(Result&: Ty) || parseGlobalValue(Ty, C&: V);
4788}
4789
4790bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4791 C = nullptr;
4792
4793 LocTy KwLoc = Lex.getLoc();
4794 if (!EatIfPresent(T: lltok::kw_comdat))
4795 return false;
4796
4797 if (EatIfPresent(T: lltok::lparen)) {
4798 if (Lex.getKind() != lltok::ComdatVar)
4799 return tokError(Msg: "expected comdat variable");
4800 C = getComdat(Name: Lex.getStrVal(), Loc: Lex.getLoc());
4801 Lex.Lex();
4802 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' after comdat var"))
4803 return true;
4804 } else {
4805 if (GlobalName.empty())
4806 return tokError(Msg: "comdat cannot be unnamed");
4807 C = getComdat(Name: std::string(GlobalName), Loc: KwLoc);
4808 }
4809
4810 return false;
4811}
4812
4813/// parseGlobalValueVector
4814/// ::= /*empty*/
4815/// ::= TypeAndValue (',' TypeAndValue)*
4816bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4817 // Empty list.
4818 if (Lex.getKind() == lltok::rbrace ||
4819 Lex.getKind() == lltok::rsquare ||
4820 Lex.getKind() == lltok::greater ||
4821 Lex.getKind() == lltok::rparen)
4822 return false;
4823
4824 do {
4825 // Let the caller deal with inrange.
4826 if (Lex.getKind() == lltok::kw_inrange)
4827 return false;
4828
4829 Constant *C;
4830 if (parseGlobalTypeAndValue(V&: C))
4831 return true;
4832 Elts.push_back(Elt: C);
4833 } while (EatIfPresent(T: lltok::comma));
4834
4835 return false;
4836}
4837
4838bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4839 SmallVector<Metadata *, 16> Elts;
4840 if (parseMDNodeVector(Elts))
4841 return true;
4842
4843 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4844 return false;
4845}
4846
4847/// MDNode:
4848/// ::= !{ ... }
4849/// ::= !7
4850/// ::= !DILocation(...)
4851bool LLParser::parseMDNode(MDNode *&N) {
4852 if (Lex.getKind() == lltok::MetadataVar)
4853 return parseSpecializedMDNode(N);
4854
4855 return parseToken(T: lltok::exclaim, ErrMsg: "expected '!' here") || parseMDNodeTail(N);
4856}
4857
4858bool LLParser::parseMDNodeTail(MDNode *&N) {
4859 // !{ ... }
4860 if (Lex.getKind() == lltok::lbrace)
4861 return parseMDTuple(MD&: N);
4862
4863 // !42
4864 return parseMDNodeID(Result&: N);
4865}
4866
4867namespace {
4868
4869/// Structure to represent an optional metadata field.
4870template <class FieldTy> struct MDFieldImpl {
4871 typedef MDFieldImpl ImplTy;
4872 FieldTy Val;
4873 bool Seen;
4874
4875 void assign(FieldTy Val) {
4876 Seen = true;
4877 this->Val = std::move(Val);
4878 }
4879
4880 explicit MDFieldImpl(FieldTy Default)
4881 : Val(std::move(Default)), Seen(false) {}
4882};
4883
4884/// Structure to represent an optional metadata field that
4885/// can be of either type (A or B) and encapsulates the
4886/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4887/// to reimplement the specifics for representing each Field.
4888template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4889 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4890 FieldTypeA A;
4891 FieldTypeB B;
4892 bool Seen;
4893
4894 enum {
4895 IsInvalid = 0,
4896 IsTypeA = 1,
4897 IsTypeB = 2
4898 } WhatIs;
4899
4900 void assign(FieldTypeA A) {
4901 Seen = true;
4902 this->A = std::move(A);
4903 WhatIs = IsTypeA;
4904 }
4905
4906 void assign(FieldTypeB B) {
4907 Seen = true;
4908 this->B = std::move(B);
4909 WhatIs = IsTypeB;
4910 }
4911
4912 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4913 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4914 WhatIs(IsInvalid) {}
4915};
4916
4917struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4918 uint64_t Max;
4919
4920 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4921 : ImplTy(Default), Max(Max) {}
4922};
4923
4924struct LineField : public MDUnsignedField {
4925 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4926};
4927
4928struct ColumnField : public MDUnsignedField {
4929 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4930};
4931
4932struct DwarfTagField : public MDUnsignedField {
4933 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4934 DwarfTagField(dwarf::Tag DefaultTag)
4935 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4936};
4937
4938struct DwarfMacinfoTypeField : public MDUnsignedField {
4939 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4940 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4941 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4942};
4943
4944struct DwarfAttEncodingField : public MDUnsignedField {
4945 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4946};
4947
4948struct DwarfVirtualityField : public MDUnsignedField {
4949 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4950};
4951
4952struct DwarfLangField : public MDUnsignedField {
4953 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4954};
4955
4956struct DwarfSourceLangNameField : public MDUnsignedField {
4957 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
4958};
4959
4960struct DwarfCCField : public MDUnsignedField {
4961 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4962};
4963
4964struct DwarfEnumKindField : public MDUnsignedField {
4965 DwarfEnumKindField()
4966 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
4967 dwarf::DW_APPLE_ENUM_KIND_max) {}
4968};
4969
4970struct EmissionKindField : public MDUnsignedField {
4971 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4972};
4973
4974struct FixedPointKindField : public MDUnsignedField {
4975 FixedPointKindField()
4976 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
4977};
4978
4979struct NameTableKindField : public MDUnsignedField {
4980 NameTableKindField()
4981 : MDUnsignedField(
4982 0, (unsigned)
4983 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4984};
4985
4986struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4987 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4988};
4989
4990struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4991 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4992};
4993
4994struct MDAPSIntField : public MDFieldImpl<APSInt> {
4995 MDAPSIntField() : ImplTy(APSInt()) {}
4996};
4997
4998struct MDSignedField : public MDFieldImpl<int64_t> {
4999 int64_t Min = INT64_MIN;
5000 int64_t Max = INT64_MAX;
5001
5002 MDSignedField(int64_t Default = 0)
5003 : ImplTy(Default) {}
5004 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
5005 : ImplTy(Default), Min(Min), Max(Max) {}
5006};
5007
5008struct MDBoolField : public MDFieldImpl<bool> {
5009 MDBoolField(bool Default = false) : ImplTy(Default) {}
5010};
5011
5012struct MDField : public MDFieldImpl<Metadata *> {
5013 bool AllowNull;
5014
5015 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5016};
5017
5018struct MDStringField : public MDFieldImpl<MDString *> {
5019 enum class EmptyIs {
5020 Null, //< Allow empty input string, map to nullptr
5021 Empty, //< Allow empty input string, map to an empty MDString
5022 Error, //< Disallow empty string, map to an error
5023 } EmptyIs;
5024 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
5025 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5026};
5027
5028struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
5029 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
5030};
5031
5032struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
5033 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
5034};
5035
5036struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5037 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
5038 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
5039
5040 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
5041 bool AllowNull = true)
5042 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
5043
5044 bool isMDSignedField() const { return WhatIs == IsTypeA; }
5045 bool isMDField() const { return WhatIs == IsTypeB; }
5046 int64_t getMDSignedValue() const {
5047 assert(isMDSignedField() && "Wrong field type");
5048 return A.Val;
5049 }
5050 Metadata *getMDFieldValue() const {
5051 assert(isMDField() && "Wrong field type");
5052 return B.Val;
5053 }
5054};
5055
5056struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5057 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
5058 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
5059
5060 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
5061 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
5062
5063 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
5064 bool isMDField() const { return WhatIs == IsTypeB; }
5065 uint64_t getMDUnsignedValue() const {
5066 assert(isMDUnsignedField() && "Wrong field type");
5067 return A.Val;
5068 }
5069 Metadata *getMDFieldValue() const {
5070 assert(isMDField() && "Wrong field type");
5071 return B.Val;
5072 }
5073
5074 Metadata *getValueAsMetadata(LLVMContext &Context) const {
5075 if (isMDUnsignedField())
5076 return ConstantAsMetadata::get(
5077 C: ConstantInt::get(Ty: Type::getInt64Ty(C&: Context), V: getMDUnsignedValue()));
5078 if (isMDField())
5079 return getMDFieldValue();
5080 return nullptr;
5081 }
5082};
5083
5084} // end anonymous namespace
5085
5086namespace llvm {
5087
5088template <>
5089bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
5090 if (Lex.getKind() != lltok::APSInt)
5091 return tokError(Msg: "expected integer");
5092
5093 Result.assign(Val: Lex.getAPSIntVal());
5094 Lex.Lex();
5095 return false;
5096}
5097
5098template <>
5099bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5100 MDUnsignedField &Result) {
5101 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5102 return tokError(Msg: "expected unsigned integer");
5103
5104 auto &U = Lex.getAPSIntVal();
5105 if (U.ugt(RHS: Result.Max))
5106 return tokError(Msg: "value for '" + Name + "' too large, limit is " +
5107 Twine(Result.Max));
5108 Result.assign(Val: U.getZExtValue());
5109 assert(Result.Val <= Result.Max && "Expected value in range");
5110 Lex.Lex();
5111 return false;
5112}
5113
5114template <>
5115bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
5116 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5117}
5118template <>
5119bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
5120 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5121}
5122
5123template <>
5124bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
5125 if (Lex.getKind() == lltok::APSInt)
5126 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5127
5128 if (Lex.getKind() != lltok::DwarfTag)
5129 return tokError(Msg: "expected DWARF tag");
5130
5131 unsigned Tag = dwarf::getTag(TagString: Lex.getStrVal());
5132 if (Tag == dwarf::DW_TAG_invalid)
5133 return tokError(Msg: "invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
5134 assert(Tag <= Result.Max && "Expected valid DWARF tag");
5135
5136 Result.assign(Val: Tag);
5137 Lex.Lex();
5138 return false;
5139}
5140
5141template <>
5142bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5143 DwarfMacinfoTypeField &Result) {
5144 if (Lex.getKind() == lltok::APSInt)
5145 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5146
5147 if (Lex.getKind() != lltok::DwarfMacinfo)
5148 return tokError(Msg: "expected DWARF macinfo type");
5149
5150 unsigned Macinfo = dwarf::getMacinfo(MacinfoString: Lex.getStrVal());
5151 if (Macinfo == dwarf::DW_MACINFO_invalid)
5152 return tokError(Msg: "invalid DWARF macinfo type" + Twine(" '") +
5153 Lex.getStrVal() + "'");
5154 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
5155
5156 Result.assign(Val: Macinfo);
5157 Lex.Lex();
5158 return false;
5159}
5160
5161template <>
5162bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5163 DwarfVirtualityField &Result) {
5164 if (Lex.getKind() == lltok::APSInt)
5165 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5166
5167 if (Lex.getKind() != lltok::DwarfVirtuality)
5168 return tokError(Msg: "expected DWARF virtuality code");
5169
5170 unsigned Virtuality = dwarf::getVirtuality(VirtualityString: Lex.getStrVal());
5171 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5172 return tokError(Msg: "invalid DWARF virtuality code" + Twine(" '") +
5173 Lex.getStrVal() + "'");
5174 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5175 Result.assign(Val: Virtuality);
5176 Lex.Lex();
5177 return false;
5178}
5179
5180template <>
5181bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5182 DwarfEnumKindField &Result) {
5183 if (Lex.getKind() == lltok::APSInt)
5184 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5185
5186 if (Lex.getKind() != lltok::DwarfEnumKind)
5187 return tokError(Msg: "expected DWARF enum kind code");
5188
5189 unsigned EnumKind = dwarf::getEnumKind(EnumKindString: Lex.getStrVal());
5190 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5191 return tokError(Msg: "invalid DWARF enum kind code" + Twine(" '") +
5192 Lex.getStrVal() + "'");
5193 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5194 Result.assign(Val: EnumKind);
5195 Lex.Lex();
5196 return false;
5197}
5198
5199template <>
5200bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5201 if (Lex.getKind() == lltok::APSInt)
5202 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5203
5204 if (Lex.getKind() != lltok::DwarfLang)
5205 return tokError(Msg: "expected DWARF language");
5206
5207 unsigned Lang = dwarf::getLanguage(LanguageString: Lex.getStrVal());
5208 if (!Lang)
5209 return tokError(Msg: "invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5210 "'");
5211 assert(Lang <= Result.Max && "Expected valid DWARF language");
5212 Result.assign(Val: Lang);
5213 Lex.Lex();
5214 return false;
5215}
5216
5217template <>
5218bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5219 DwarfSourceLangNameField &Result) {
5220 if (Lex.getKind() == lltok::APSInt)
5221 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5222
5223 if (Lex.getKind() != lltok::DwarfSourceLangName)
5224 return tokError(Msg: "expected DWARF source language name");
5225
5226 unsigned Lang = dwarf::getSourceLanguageName(SourceLanguageNameString: Lex.getStrVal());
5227 if (!Lang)
5228 return tokError(Msg: "invalid DWARF source language name" + Twine(" '") +
5229 Lex.getStrVal() + "'");
5230 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5231 Result.assign(Val: Lang);
5232 Lex.Lex();
5233 return false;
5234}
5235
5236template <>
5237bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5238 if (Lex.getKind() == lltok::APSInt)
5239 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5240
5241 if (Lex.getKind() != lltok::DwarfCC)
5242 return tokError(Msg: "expected DWARF calling convention");
5243
5244 unsigned CC = dwarf::getCallingConvention(LanguageString: Lex.getStrVal());
5245 if (!CC)
5246 return tokError(Msg: "invalid DWARF calling convention" + Twine(" '") +
5247 Lex.getStrVal() + "'");
5248 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5249 Result.assign(Val: CC);
5250 Lex.Lex();
5251 return false;
5252}
5253
5254template <>
5255bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5256 EmissionKindField &Result) {
5257 if (Lex.getKind() == lltok::APSInt)
5258 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5259
5260 if (Lex.getKind() != lltok::EmissionKind)
5261 return tokError(Msg: "expected emission kind");
5262
5263 auto Kind = DICompileUnit::getEmissionKind(Str: Lex.getStrVal());
5264 if (!Kind)
5265 return tokError(Msg: "invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5266 "'");
5267 assert(*Kind <= Result.Max && "Expected valid emission kind");
5268 Result.assign(Val: *Kind);
5269 Lex.Lex();
5270 return false;
5271}
5272
5273template <>
5274bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5275 FixedPointKindField &Result) {
5276 if (Lex.getKind() == lltok::APSInt)
5277 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5278
5279 if (Lex.getKind() != lltok::FixedPointKind)
5280 return tokError(Msg: "expected fixed-point kind");
5281
5282 auto Kind = DIFixedPointType::getFixedPointKind(Str: Lex.getStrVal());
5283 if (!Kind)
5284 return tokError(Msg: "invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5285 "'");
5286 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5287 Result.assign(Val: *Kind);
5288 Lex.Lex();
5289 return false;
5290}
5291
5292template <>
5293bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5294 NameTableKindField &Result) {
5295 if (Lex.getKind() == lltok::APSInt)
5296 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5297
5298 if (Lex.getKind() != lltok::NameTableKind)
5299 return tokError(Msg: "expected nameTable kind");
5300
5301 auto Kind = DICompileUnit::getNameTableKind(Str: Lex.getStrVal());
5302 if (!Kind)
5303 return tokError(Msg: "invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5304 "'");
5305 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5306 Result.assign(Val: (unsigned)*Kind);
5307 Lex.Lex();
5308 return false;
5309}
5310
5311template <>
5312bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5313 DwarfAttEncodingField &Result) {
5314 if (Lex.getKind() == lltok::APSInt)
5315 return parseMDField(Loc, Name, Result&: static_cast<MDUnsignedField &>(Result));
5316
5317 if (Lex.getKind() != lltok::DwarfAttEncoding)
5318 return tokError(Msg: "expected DWARF type attribute encoding");
5319
5320 unsigned Encoding = dwarf::getAttributeEncoding(EncodingString: Lex.getStrVal());
5321 if (!Encoding)
5322 return tokError(Msg: "invalid DWARF type attribute encoding" + Twine(" '") +
5323 Lex.getStrVal() + "'");
5324 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5325 Result.assign(Val: Encoding);
5326 Lex.Lex();
5327 return false;
5328}
5329
5330/// DIFlagField
5331/// ::= uint32
5332/// ::= DIFlagVector
5333/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5334template <>
5335bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5336
5337 // parser for a single flag.
5338 auto parseFlag = [&](DINode::DIFlags &Val) {
5339 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5340 uint32_t TempVal = static_cast<uint32_t>(Val);
5341 bool Res = parseUInt32(Val&: TempVal);
5342 Val = static_cast<DINode::DIFlags>(TempVal);
5343 return Res;
5344 }
5345
5346 if (Lex.getKind() != lltok::DIFlag)
5347 return tokError(Msg: "expected debug info flag");
5348
5349 Val = DINode::getFlag(Flag: Lex.getStrVal());
5350 if (!Val)
5351 return tokError(Msg: Twine("invalid debug info flag '") + Lex.getStrVal() +
5352 "'");
5353 Lex.Lex();
5354 return false;
5355 };
5356
5357 // parse the flags and combine them together.
5358 DINode::DIFlags Combined = DINode::FlagZero;
5359 do {
5360 DINode::DIFlags Val;
5361 if (parseFlag(Val))
5362 return true;
5363 Combined |= Val;
5364 } while (EatIfPresent(T: lltok::bar));
5365
5366 Result.assign(Val: Combined);
5367 return false;
5368}
5369
5370/// DISPFlagField
5371/// ::= uint32
5372/// ::= DISPFlagVector
5373/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5374template <>
5375bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5376
5377 // parser for a single flag.
5378 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5379 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5380 uint32_t TempVal = static_cast<uint32_t>(Val);
5381 bool Res = parseUInt32(Val&: TempVal);
5382 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5383 return Res;
5384 }
5385
5386 if (Lex.getKind() != lltok::DISPFlag)
5387 return tokError(Msg: "expected debug info flag");
5388
5389 Val = DISubprogram::getFlag(Flag: Lex.getStrVal());
5390 if (!Val)
5391 return tokError(Msg: Twine("invalid subprogram debug info flag '") +
5392 Lex.getStrVal() + "'");
5393 Lex.Lex();
5394 return false;
5395 };
5396
5397 // parse the flags and combine them together.
5398 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5399 do {
5400 DISubprogram::DISPFlags Val;
5401 if (parseFlag(Val))
5402 return true;
5403 Combined |= Val;
5404 } while (EatIfPresent(T: lltok::bar));
5405
5406 Result.assign(Val: Combined);
5407 return false;
5408}
5409
5410template <>
5411bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5412 if (Lex.getKind() != lltok::APSInt)
5413 return tokError(Msg: "expected signed integer");
5414
5415 auto &S = Lex.getAPSIntVal();
5416 if (S < Result.Min)
5417 return tokError(Msg: "value for '" + Name + "' too small, limit is " +
5418 Twine(Result.Min));
5419 if (S > Result.Max)
5420 return tokError(Msg: "value for '" + Name + "' too large, limit is " +
5421 Twine(Result.Max));
5422 Result.assign(Val: S.getExtValue());
5423 assert(Result.Val >= Result.Min && "Expected value in range");
5424 assert(Result.Val <= Result.Max && "Expected value in range");
5425 Lex.Lex();
5426 return false;
5427}
5428
5429template <>
5430bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5431 switch (Lex.getKind()) {
5432 default:
5433 return tokError(Msg: "expected 'true' or 'false'");
5434 case lltok::kw_true:
5435 Result.assign(Val: true);
5436 break;
5437 case lltok::kw_false:
5438 Result.assign(Val: false);
5439 break;
5440 }
5441 Lex.Lex();
5442 return false;
5443}
5444
5445template <>
5446bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5447 if (Lex.getKind() == lltok::kw_null) {
5448 if (!Result.AllowNull)
5449 return tokError(Msg: "'" + Name + "' cannot be null");
5450 Lex.Lex();
5451 Result.assign(Val: nullptr);
5452 return false;
5453 }
5454
5455 Metadata *MD;
5456 if (parseMetadata(MD, PFS: nullptr))
5457 return true;
5458
5459 Result.assign(Val: MD);
5460 return false;
5461}
5462
5463template <>
5464bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5465 MDSignedOrMDField &Result) {
5466 // Try to parse a signed int.
5467 if (Lex.getKind() == lltok::APSInt) {
5468 MDSignedField Res = Result.A;
5469 if (!parseMDField(Loc, Name, Result&: Res)) {
5470 Result.assign(A: Res);
5471 return false;
5472 }
5473 return true;
5474 }
5475
5476 // Otherwise, try to parse as an MDField.
5477 MDField Res = Result.B;
5478 if (!parseMDField(Loc, Name, Result&: Res)) {
5479 Result.assign(B: Res);
5480 return false;
5481 }
5482
5483 return true;
5484}
5485
5486template <>
5487bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5488 MDUnsignedOrMDField &Result) {
5489 // Try to parse an unsigned int.
5490 if (Lex.getKind() == lltok::APSInt) {
5491 MDUnsignedField Res = Result.A;
5492 if (!parseMDField(Loc, Name, Result&: Res)) {
5493 Result.assign(A: Res);
5494 return false;
5495 }
5496 return true;
5497 }
5498
5499 // Otherwise, try to parse as an MDField.
5500 MDField Res = Result.B;
5501 if (!parseMDField(Loc, Name, Result&: Res)) {
5502 Result.assign(B: Res);
5503 return false;
5504 }
5505
5506 return true;
5507}
5508
5509template <>
5510bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5511 LocTy ValueLoc = Lex.getLoc();
5512 std::string S;
5513 if (parseStringConstant(Result&: S))
5514 return true;
5515
5516 if (S.empty()) {
5517 switch (Result.EmptyIs) {
5518 case MDStringField::EmptyIs::Null:
5519 Result.assign(Val: nullptr);
5520 return false;
5521 case MDStringField::EmptyIs::Empty:
5522 break;
5523 case MDStringField::EmptyIs::Error:
5524 return error(L: ValueLoc, Msg: "'" + Name + "' cannot be empty");
5525 }
5526 }
5527
5528 Result.assign(Val: MDString::get(Context, Str: S));
5529 return false;
5530}
5531
5532template <>
5533bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5534 SmallVector<Metadata *, 4> MDs;
5535 if (parseMDNodeVector(Elts&: MDs))
5536 return true;
5537
5538 Result.assign(Val: std::move(MDs));
5539 return false;
5540}
5541
5542template <>
5543bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5544 ChecksumKindField &Result) {
5545 std::optional<DIFile::ChecksumKind> CSKind =
5546 DIFile::getChecksumKind(CSKindStr: Lex.getStrVal());
5547
5548 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5549 return tokError(Msg: "invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5550 "'");
5551
5552 Result.assign(Val: *CSKind);
5553 Lex.Lex();
5554 return false;
5555}
5556
5557} // end namespace llvm
5558
5559template <class ParserTy>
5560bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5561 do {
5562 if (Lex.getKind() != lltok::LabelStr)
5563 return tokError(Msg: "expected field label here");
5564
5565 if (ParseField())
5566 return true;
5567 } while (EatIfPresent(T: lltok::comma));
5568
5569 return false;
5570}
5571
5572template <class ParserTy>
5573bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5574 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5575 Lex.Lex();
5576
5577 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
5578 return true;
5579 if (Lex.getKind() != lltok::rparen)
5580 if (parseMDFieldsImplBody(ParseField))
5581 return true;
5582
5583 ClosingLoc = Lex.getLoc();
5584 return parseToken(T: lltok::rparen, ErrMsg: "expected ')' here");
5585}
5586
5587template <class FieldTy>
5588bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5589 if (Result.Seen)
5590 return tokError(Msg: "field '" + Name + "' cannot be specified more than once");
5591
5592 LocTy Loc = Lex.getLoc();
5593 Lex.Lex();
5594 return parseMDField(Loc, Name, Result);
5595}
5596
5597bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5598 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5599
5600#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5601 if (Lex.getStrVal() == #CLASS) \
5602 return parse##CLASS(N, IsDistinct);
5603#include "llvm/IR/Metadata.def"
5604
5605 return tokError(Msg: "expected metadata type");
5606}
5607
5608#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5609#define NOP_FIELD(NAME, TYPE, INIT)
5610#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5611 if (!NAME.Seen) \
5612 return error(ClosingLoc, "missing required field '" #NAME "'");
5613#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5614 if (Lex.getStrVal() == #NAME) \
5615 return parseMDField(#NAME, NAME);
5616#define PARSE_MD_FIELDS() \
5617 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5618 do { \
5619 LocTy ClosingLoc; \
5620 if (parseMDFieldsImpl( \
5621 [&]() -> bool { \
5622 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5623 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5624 "'"); \
5625 }, \
5626 ClosingLoc)) \
5627 return true; \
5628 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5629 } while (false)
5630#define GET_OR_DISTINCT(CLASS, ARGS) \
5631 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5632
5633/// parseDILocationFields:
5634/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5635/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5636bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5637#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5638 OPTIONAL(line, LineField, ); \
5639 OPTIONAL(column, ColumnField, ); \
5640 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5641 OPTIONAL(inlinedAt, MDField, ); \
5642 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5643 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5644 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5645 PARSE_MD_FIELDS();
5646#undef VISIT_MD_FIELDS
5647
5648 Result = GET_OR_DISTINCT(
5649 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5650 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5651 return false;
5652}
5653
5654/// parseDIAssignID:
5655/// ::= distinct !DIAssignID()
5656bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5657 if (!IsDistinct)
5658 return tokError(Msg: "missing 'distinct', required for !DIAssignID()");
5659
5660 Lex.Lex();
5661
5662 // Now eat the parens.
5663 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
5664 return true;
5665 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
5666 return true;
5667
5668 Result = DIAssignID::getDistinct(Context);
5669 return false;
5670}
5671
5672/// parseGenericDINode:
5673/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5674bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5675#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5676 REQUIRED(tag, DwarfTagField, ); \
5677 OPTIONAL(header, MDStringField, ); \
5678 OPTIONAL(operands, MDFieldList, );
5679 PARSE_MD_FIELDS();
5680#undef VISIT_MD_FIELDS
5681
5682 Result = GET_OR_DISTINCT(GenericDINode,
5683 (Context, tag.Val, header.Val, operands.Val));
5684 return false;
5685}
5686
5687/// parseDISubrangeType:
5688/// ::= !DISubrangeType(name: "whatever", file: !0,
5689/// line: 7, scope: !1, baseType: !2, size: 32,
5690/// align: 32, flags: 0, lowerBound: !3
5691/// upperBound: !4, stride: !5, bias: !6)
5692bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5693#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5694 OPTIONAL(name, MDStringField, ); \
5695 OPTIONAL(file, MDField, ); \
5696 OPTIONAL(line, LineField, ); \
5697 OPTIONAL(scope, MDField, ); \
5698 OPTIONAL(baseType, MDField, ); \
5699 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5700 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5701 OPTIONAL(flags, DIFlagField, ); \
5702 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5703 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5704 OPTIONAL(stride, MDSignedOrMDField, ); \
5705 OPTIONAL(bias, MDSignedOrMDField, );
5706 PARSE_MD_FIELDS();
5707#undef VISIT_MD_FIELDS
5708
5709 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5710 if (Bound.isMDSignedField())
5711 return ConstantAsMetadata::get(C: ConstantInt::getSigned(
5712 Ty: Type::getInt64Ty(C&: Context), V: Bound.getMDSignedValue()));
5713 if (Bound.isMDField())
5714 return Bound.getMDFieldValue();
5715 return nullptr;
5716 };
5717
5718 Metadata *LowerBound = convToMetadata(lowerBound);
5719 Metadata *UpperBound = convToMetadata(upperBound);
5720 Metadata *Stride = convToMetadata(stride);
5721 Metadata *Bias = convToMetadata(bias);
5722
5723 Result = GET_OR_DISTINCT(
5724 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5725 size.getValueAsMetadata(Context), align.Val, flags.Val,
5726 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5727
5728 return false;
5729}
5730
5731/// parseDISubrange:
5732/// ::= !DISubrange(count: 30, lowerBound: 2)
5733/// ::= !DISubrange(count: !node, lowerBound: 2)
5734/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5735bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5736#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5737 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5738 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5739 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5740 OPTIONAL(stride, MDSignedOrMDField, );
5741 PARSE_MD_FIELDS();
5742#undef VISIT_MD_FIELDS
5743
5744 Metadata *Count = nullptr;
5745 Metadata *LowerBound = nullptr;
5746 Metadata *UpperBound = nullptr;
5747 Metadata *Stride = nullptr;
5748
5749 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5750 if (Bound.isMDSignedField())
5751 return ConstantAsMetadata::get(C: ConstantInt::getSigned(
5752 Ty: Type::getInt64Ty(C&: Context), V: Bound.getMDSignedValue()));
5753 if (Bound.isMDField())
5754 return Bound.getMDFieldValue();
5755 return nullptr;
5756 };
5757
5758 Count = convToMetadata(count);
5759 LowerBound = convToMetadata(lowerBound);
5760 UpperBound = convToMetadata(upperBound);
5761 Stride = convToMetadata(stride);
5762
5763 Result = GET_OR_DISTINCT(DISubrange,
5764 (Context, Count, LowerBound, UpperBound, Stride));
5765
5766 return false;
5767}
5768
5769/// parseDIGenericSubrange:
5770/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5771/// !node3)
5772bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5773#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5774 OPTIONAL(count, MDSignedOrMDField, ); \
5775 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5776 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5777 OPTIONAL(stride, MDSignedOrMDField, );
5778 PARSE_MD_FIELDS();
5779#undef VISIT_MD_FIELDS
5780
5781 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5782 if (Bound.isMDSignedField())
5783 return DIExpression::get(
5784 Context, Elements: {dwarf::DW_OP_consts,
5785 static_cast<uint64_t>(Bound.getMDSignedValue())});
5786 if (Bound.isMDField())
5787 return Bound.getMDFieldValue();
5788 return nullptr;
5789 };
5790
5791 Metadata *Count = ConvToMetadata(count);
5792 Metadata *LowerBound = ConvToMetadata(lowerBound);
5793 Metadata *UpperBound = ConvToMetadata(upperBound);
5794 Metadata *Stride = ConvToMetadata(stride);
5795
5796 Result = GET_OR_DISTINCT(DIGenericSubrange,
5797 (Context, Count, LowerBound, UpperBound, Stride));
5798
5799 return false;
5800}
5801
5802/// parseDIEnumerator:
5803/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5804bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5805#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5806 REQUIRED(name, MDStringField, ); \
5807 REQUIRED(value, MDAPSIntField, ); \
5808 OPTIONAL(isUnsigned, MDBoolField, (false));
5809 PARSE_MD_FIELDS();
5810#undef VISIT_MD_FIELDS
5811
5812 if (isUnsigned.Val && value.Val.isNegative())
5813 return tokError(Msg: "unsigned enumerator with negative value");
5814
5815 APSInt Value(value.Val);
5816 // Add a leading zero so that unsigned values with the msb set are not
5817 // mistaken for negative values when used for signed enumerators.
5818 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5819 Value = Value.zext(width: Value.getBitWidth() + 1);
5820
5821 Result =
5822 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5823
5824 return false;
5825}
5826
5827/// parseDIBasicType:
5828/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5829/// encoding: DW_ATE_encoding, flags: 0)
5830bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5831#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5832 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5833 OPTIONAL(name, MDStringField, ); \
5834 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5835 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5836 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5837 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5838 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5839 OPTIONAL(flags, DIFlagField, );
5840 PARSE_MD_FIELDS();
5841#undef VISIT_MD_FIELDS
5842
5843 Result = GET_OR_DISTINCT(
5844 DIBasicType,
5845 (Context, tag.Val, name.Val, size.getValueAsMetadata(Context), align.Val,
5846 encoding.Val, num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5847 return false;
5848}
5849
5850/// parseDIFixedPointType:
5851/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5852/// align: 32, encoding: DW_ATE_signed_fixed,
5853/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5854/// denominator: 8)
5855bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5856#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5857 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5858 OPTIONAL(name, MDStringField, ); \
5859 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5860 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5861 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5862 OPTIONAL(flags, DIFlagField, ); \
5863 OPTIONAL(kind, FixedPointKindField, ); \
5864 OPTIONAL(factor, MDSignedField, ); \
5865 OPTIONAL(numerator, MDAPSIntField, ); \
5866 OPTIONAL(denominator, MDAPSIntField, );
5867 PARSE_MD_FIELDS();
5868#undef VISIT_MD_FIELDS
5869
5870 Result = GET_OR_DISTINCT(DIFixedPointType,
5871 (Context, tag.Val, name.Val,
5872 size.getValueAsMetadata(Context), align.Val,
5873 encoding.Val, flags.Val, kind.Val, factor.Val,
5874 numerator.Val, denominator.Val));
5875 return false;
5876}
5877
5878/// parseDIStringType:
5879/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5880bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5881#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5882 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5883 OPTIONAL(name, MDStringField, ); \
5884 OPTIONAL(stringLength, MDField, ); \
5885 OPTIONAL(stringLengthExpression, MDField, ); \
5886 OPTIONAL(stringLocationExpression, MDField, ); \
5887 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5888 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5889 OPTIONAL(encoding, DwarfAttEncodingField, );
5890 PARSE_MD_FIELDS();
5891#undef VISIT_MD_FIELDS
5892
5893 Result = GET_OR_DISTINCT(
5894 DIStringType,
5895 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5896 stringLocationExpression.Val, size.getValueAsMetadata(Context),
5897 align.Val, encoding.Val));
5898 return false;
5899}
5900
5901/// parseDIDerivedType:
5902/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5903/// line: 7, scope: !1, baseType: !2, size: 32,
5904/// align: 32, offset: 0, flags: 0, extraData: !3,
5905/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5906/// ptrAuthIsAddressDiscriminated: true,
5907/// ptrAuthExtraDiscriminator: 0x1234,
5908/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5909/// )
5910bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5911#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5912 REQUIRED(tag, DwarfTagField, ); \
5913 OPTIONAL(name, MDStringField, ); \
5914 OPTIONAL(file, MDField, ); \
5915 OPTIONAL(line, LineField, ); \
5916 OPTIONAL(scope, MDField, ); \
5917 REQUIRED(baseType, MDField, ); \
5918 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5919 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5920 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5921 OPTIONAL(flags, DIFlagField, ); \
5922 OPTIONAL(extraData, MDField, ); \
5923 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5924 OPTIONAL(annotations, MDField, ); \
5925 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5926 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5927 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5928 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5929 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5930 PARSE_MD_FIELDS();
5931#undef VISIT_MD_FIELDS
5932
5933 std::optional<unsigned> DWARFAddressSpace;
5934 if (dwarfAddressSpace.Val != UINT32_MAX)
5935 DWARFAddressSpace = dwarfAddressSpace.Val;
5936 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5937 if (ptrAuthKey.Val)
5938 PtrAuthData.emplace(
5939 args: (unsigned)ptrAuthKey.Val, args&: ptrAuthIsAddressDiscriminated.Val,
5940 args: (unsigned)ptrAuthExtraDiscriminator.Val, args&: ptrAuthIsaPointer.Val,
5941 args&: ptrAuthAuthenticatesNullValues.Val);
5942
5943 Result = GET_OR_DISTINCT(
5944 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5945 baseType.Val, size.getValueAsMetadata(Context), align.Val,
5946 offset.getValueAsMetadata(Context), DWARFAddressSpace,
5947 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
5948 return false;
5949}
5950
5951bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5952#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5953 REQUIRED(tag, DwarfTagField, ); \
5954 OPTIONAL(name, MDStringField, ); \
5955 OPTIONAL(file, MDField, ); \
5956 OPTIONAL(line, LineField, ); \
5957 OPTIONAL(scope, MDField, ); \
5958 OPTIONAL(baseType, MDField, ); \
5959 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5960 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5961 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5962 OPTIONAL(flags, DIFlagField, ); \
5963 OPTIONAL(elements, MDField, ); \
5964 OPTIONAL(runtimeLang, DwarfLangField, ); \
5965 OPTIONAL(enumKind, DwarfEnumKindField, ); \
5966 OPTIONAL(vtableHolder, MDField, ); \
5967 OPTIONAL(templateParams, MDField, ); \
5968 OPTIONAL(identifier, MDStringField, ); \
5969 OPTIONAL(discriminator, MDField, ); \
5970 OPTIONAL(dataLocation, MDField, ); \
5971 OPTIONAL(associated, MDField, ); \
5972 OPTIONAL(allocated, MDField, ); \
5973 OPTIONAL(rank, MDSignedOrMDField, ); \
5974 OPTIONAL(annotations, MDField, ); \
5975 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5976 OPTIONAL(specification, MDField, ); \
5977 OPTIONAL(bitStride, MDField, );
5978 PARSE_MD_FIELDS();
5979#undef VISIT_MD_FIELDS
5980
5981 Metadata *Rank = nullptr;
5982 if (rank.isMDSignedField())
5983 Rank = ConstantAsMetadata::get(C: ConstantInt::getSigned(
5984 Ty: Type::getInt64Ty(C&: Context), V: rank.getMDSignedValue()));
5985 else if (rank.isMDField())
5986 Rank = rank.getMDFieldValue();
5987
5988 std::optional<unsigned> EnumKind;
5989 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
5990 EnumKind = enumKind.Val;
5991
5992 // If this has an identifier try to build an ODR type.
5993 if (identifier.Val)
5994 if (auto *CT = DICompositeType::buildODRType(
5995 Context, Identifier&: *identifier.Val, Tag: tag.Val, Name: name.Val, File: file.Val, Line: line.Val,
5996 Scope: scope.Val, BaseType: baseType.Val, SizeInBits: size.getValueAsMetadata(Context),
5997 AlignInBits: align.Val, OffsetInBits: offset.getValueAsMetadata(Context), Specification: specification.Val,
5998 NumExtraInhabitants: num_extra_inhabitants.Val, Flags: flags.Val, Elements: elements.Val, RuntimeLang: runtimeLang.Val,
5999 EnumKind, VTableHolder: vtableHolder.Val, TemplateParams: templateParams.Val, Discriminator: discriminator.Val,
6000 DataLocation: dataLocation.Val, Associated: associated.Val, Allocated: allocated.Val, Rank,
6001 Annotations: annotations.Val, BitStride: bitStride.Val)) {
6002 Result = CT;
6003 return false;
6004 }
6005
6006 // Create a new node, and save it in the context if it belongs in the type
6007 // map.
6008 Result = GET_OR_DISTINCT(
6009 DICompositeType,
6010 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
6011 size.getValueAsMetadata(Context), align.Val,
6012 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6013 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6014 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6015 allocated.Val, Rank, annotations.Val, specification.Val,
6016 num_extra_inhabitants.Val, bitStride.Val));
6017 return false;
6018}
6019
6020bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
6021#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6022 OPTIONAL(flags, DIFlagField, ); \
6023 OPTIONAL(cc, DwarfCCField, ); \
6024 REQUIRED(types, MDField, );
6025 PARSE_MD_FIELDS();
6026#undef VISIT_MD_FIELDS
6027
6028 Result = GET_OR_DISTINCT(DISubroutineType,
6029 (Context, flags.Val, cc.Val, types.Val));
6030 return false;
6031}
6032
6033/// parseDIFileType:
6034/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
6035/// checksumkind: CSK_MD5,
6036/// checksum: "000102030405060708090a0b0c0d0e0f",
6037/// source: "source file contents")
6038bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
6039 // The default constructed value for checksumkind is required, but will never
6040 // be used, as the parser checks if the field was actually Seen before using
6041 // the Val.
6042#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6043 REQUIRED(filename, MDStringField, ); \
6044 REQUIRED(directory, MDStringField, ); \
6045 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6046 OPTIONAL(checksum, MDStringField, ); \
6047 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6048 PARSE_MD_FIELDS();
6049#undef VISIT_MD_FIELDS
6050
6051 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6052 if (checksumkind.Seen && checksum.Seen)
6053 OptChecksum.emplace(args&: checksumkind.Val, args&: checksum.Val);
6054 else if (checksumkind.Seen || checksum.Seen)
6055 return tokError(Msg: "'checksumkind' and 'checksum' must be provided together");
6056
6057 MDString *Source = nullptr;
6058 if (source.Seen)
6059 Source = source.Val;
6060 Result = GET_OR_DISTINCT(
6061 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
6062 return false;
6063}
6064
6065/// parseDICompileUnit:
6066/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
6067/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
6068/// splitDebugFilename: "abc.debug",
6069/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
6070/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
6071/// sysroot: "/", sdk: "MacOSX.sdk")
6072bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
6073 if (!IsDistinct)
6074 return tokError(Msg: "missing 'distinct', required for !DICompileUnit");
6075
6076 LocTy Loc = Lex.getLoc();
6077
6078#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6079 REQUIRED(file, MDField, (/* AllowNull */ false)); \
6080 OPTIONAL(language, DwarfLangField, ); \
6081 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6082 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6083 OPTIONAL(producer, MDStringField, ); \
6084 OPTIONAL(isOptimized, MDBoolField, ); \
6085 OPTIONAL(flags, MDStringField, ); \
6086 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6087 OPTIONAL(splitDebugFilename, MDStringField, ); \
6088 OPTIONAL(emissionKind, EmissionKindField, ); \
6089 OPTIONAL(enums, MDField, ); \
6090 OPTIONAL(retainedTypes, MDField, ); \
6091 OPTIONAL(globals, MDField, ); \
6092 OPTIONAL(imports, MDField, ); \
6093 OPTIONAL(macros, MDField, ); \
6094 OPTIONAL(dwoId, MDUnsignedField, ); \
6095 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6096 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6097 OPTIONAL(nameTableKind, NameTableKindField, ); \
6098 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6099 OPTIONAL(sysroot, MDStringField, ); \
6100 OPTIONAL(sdk, MDStringField, );
6101 PARSE_MD_FIELDS();
6102#undef VISIT_MD_FIELDS
6103
6104 if (!language.Seen && !sourceLanguageName.Seen)
6105 return error(L: Loc, Msg: "missing one of 'language' or 'sourceLanguageName', "
6106 "required for !DICompileUnit");
6107
6108 if (language.Seen && sourceLanguageName.Seen)
6109 return error(L: Loc, Msg: "can only specify one of 'language' and "
6110 "'sourceLanguageName' on !DICompileUnit");
6111
6112 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6113 return error(L: Loc, Msg: "'sourceLanguageVersion' requires an associated "
6114 "'sourceLanguageName' on !DICompileUnit");
6115
6116 Result = DICompileUnit::getDistinct(
6117 Context,
6118 SourceLanguage: language.Seen ? DISourceLanguageName(language.Val)
6119 : DISourceLanguageName(sourceLanguageName.Val,
6120 sourceLanguageVersion.Val),
6121 File: file.Val, Producer: producer.Val, IsOptimized: isOptimized.Val, Flags: flags.Val, RuntimeVersion: runtimeVersion.Val,
6122 SplitDebugFilename: splitDebugFilename.Val, EmissionKind: emissionKind.Val, EnumTypes: enums.Val, RetainedTypes: retainedTypes.Val,
6123 GlobalVariables: globals.Val, ImportedEntities: imports.Val, Macros: macros.Val, DWOId: dwoId.Val, SplitDebugInlining: splitDebugInlining.Val,
6124 DebugInfoForProfiling: debugInfoForProfiling.Val, NameTableKind: nameTableKind.Val, RangesBaseAddress: rangesBaseAddress.Val,
6125 SysRoot: sysroot.Val, SDK: sdk.Val);
6126 return false;
6127}
6128
6129/// parseDISubprogram:
6130/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
6131/// file: !1, line: 7, type: !2, isLocal: false,
6132/// isDefinition: true, scopeLine: 8, containingType: !3,
6133/// virtuality: DW_VIRTUALTIY_pure_virtual,
6134/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
6135/// spFlags: 10, isOptimized: false, templateParams: !4,
6136/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
6137/// annotations: !8)
6138bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
6139 auto Loc = Lex.getLoc();
6140#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6141 OPTIONAL(scope, MDField, ); \
6142 OPTIONAL(name, MDStringField, ); \
6143 OPTIONAL(linkageName, MDStringField, ); \
6144 OPTIONAL(file, MDField, ); \
6145 OPTIONAL(line, LineField, ); \
6146 OPTIONAL(type, MDField, ); \
6147 OPTIONAL(isLocal, MDBoolField, ); \
6148 OPTIONAL(isDefinition, MDBoolField, (true)); \
6149 OPTIONAL(scopeLine, LineField, ); \
6150 OPTIONAL(containingType, MDField, ); \
6151 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6152 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6153 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6154 OPTIONAL(flags, DIFlagField, ); \
6155 OPTIONAL(spFlags, DISPFlagField, ); \
6156 OPTIONAL(isOptimized, MDBoolField, ); \
6157 OPTIONAL(unit, MDField, ); \
6158 OPTIONAL(templateParams, MDField, ); \
6159 OPTIONAL(declaration, MDField, ); \
6160 OPTIONAL(retainedNodes, MDField, ); \
6161 OPTIONAL(thrownTypes, MDField, ); \
6162 OPTIONAL(annotations, MDField, ); \
6163 OPTIONAL(targetFuncName, MDStringField, ); \
6164 OPTIONAL(keyInstructions, MDBoolField, );
6165 PARSE_MD_FIELDS();
6166#undef VISIT_MD_FIELDS
6167
6168 // An explicit spFlags field takes precedence over individual fields in
6169 // older IR versions.
6170 DISubprogram::DISPFlags SPFlags =
6171 spFlags.Seen ? spFlags.Val
6172 : DISubprogram::toSPFlags(IsLocalToUnit: isLocal.Val, IsDefinition: isDefinition.Val,
6173 IsOptimized: isOptimized.Val, Virtuality: virtuality.Val);
6174 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6175 return error(
6176 L: Loc,
6177 Msg: "missing 'distinct', required for !DISubprogram that is a Definition");
6178 Result = GET_OR_DISTINCT(
6179 DISubprogram,
6180 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6181 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6182 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6183 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6184 targetFuncName.Val, keyInstructions.Val));
6185
6186 if (IsDistinct)
6187 NewDistinctSPs.push_back(Elt: cast<DISubprogram>(Val: Result));
6188
6189 return false;
6190}
6191
6192/// parseDILexicalBlock:
6193/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6194bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6195#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6196 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6197 OPTIONAL(file, MDField, ); \
6198 OPTIONAL(line, LineField, ); \
6199 OPTIONAL(column, ColumnField, );
6200 PARSE_MD_FIELDS();
6201#undef VISIT_MD_FIELDS
6202
6203 Result = GET_OR_DISTINCT(
6204 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6205 return false;
6206}
6207
6208/// parseDILexicalBlockFile:
6209/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6210bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6211#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6212 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6213 OPTIONAL(file, MDField, ); \
6214 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6215 PARSE_MD_FIELDS();
6216#undef VISIT_MD_FIELDS
6217
6218 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6219 (Context, scope.Val, file.Val, discriminator.Val));
6220 return false;
6221}
6222
6223/// parseDICommonBlock:
6224/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6225bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6226#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6227 REQUIRED(scope, MDField, ); \
6228 OPTIONAL(declaration, MDField, ); \
6229 OPTIONAL(name, MDStringField, ); \
6230 OPTIONAL(file, MDField, ); \
6231 OPTIONAL(line, LineField, );
6232 PARSE_MD_FIELDS();
6233#undef VISIT_MD_FIELDS
6234
6235 Result = GET_OR_DISTINCT(DICommonBlock,
6236 (Context, scope.Val, declaration.Val, name.Val,
6237 file.Val, line.Val));
6238 return false;
6239}
6240
6241/// parseDINamespace:
6242/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6243bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6244#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6245 REQUIRED(scope, MDField, ); \
6246 OPTIONAL(name, MDStringField, ); \
6247 OPTIONAL(exportSymbols, MDBoolField, );
6248 PARSE_MD_FIELDS();
6249#undef VISIT_MD_FIELDS
6250
6251 Result = GET_OR_DISTINCT(DINamespace,
6252 (Context, scope.Val, name.Val, exportSymbols.Val));
6253 return false;
6254}
6255
6256/// parseDIMacro:
6257/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6258/// "SomeValue")
6259bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6260#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6261 REQUIRED(type, DwarfMacinfoTypeField, ); \
6262 OPTIONAL(line, LineField, ); \
6263 REQUIRED(name, MDStringField, ); \
6264 OPTIONAL(value, MDStringField, );
6265 PARSE_MD_FIELDS();
6266#undef VISIT_MD_FIELDS
6267
6268 Result = GET_OR_DISTINCT(DIMacro,
6269 (Context, type.Val, line.Val, name.Val, value.Val));
6270 return false;
6271}
6272
6273/// parseDIMacroFile:
6274/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6275bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6276#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6277 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6278 OPTIONAL(line, LineField, ); \
6279 REQUIRED(file, MDField, ); \
6280 OPTIONAL(nodes, MDField, );
6281 PARSE_MD_FIELDS();
6282#undef VISIT_MD_FIELDS
6283
6284 Result = GET_OR_DISTINCT(DIMacroFile,
6285 (Context, type.Val, line.Val, file.Val, nodes.Val));
6286 return false;
6287}
6288
6289/// parseDIModule:
6290/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6291/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6292/// file: !1, line: 4, isDecl: false)
6293bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6294#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6295 REQUIRED(scope, MDField, ); \
6296 REQUIRED(name, MDStringField, ); \
6297 OPTIONAL(configMacros, MDStringField, ); \
6298 OPTIONAL(includePath, MDStringField, ); \
6299 OPTIONAL(apinotes, MDStringField, ); \
6300 OPTIONAL(file, MDField, ); \
6301 OPTIONAL(line, LineField, ); \
6302 OPTIONAL(isDecl, MDBoolField, );
6303 PARSE_MD_FIELDS();
6304#undef VISIT_MD_FIELDS
6305
6306 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6307 configMacros.Val, includePath.Val,
6308 apinotes.Val, line.Val, isDecl.Val));
6309 return false;
6310}
6311
6312/// parseDITemplateTypeParameter:
6313/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6314bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6315#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6316 OPTIONAL(name, MDStringField, ); \
6317 REQUIRED(type, MDField, ); \
6318 OPTIONAL(defaulted, MDBoolField, );
6319 PARSE_MD_FIELDS();
6320#undef VISIT_MD_FIELDS
6321
6322 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6323 (Context, name.Val, type.Val, defaulted.Val));
6324 return false;
6325}
6326
6327/// parseDITemplateValueParameter:
6328/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6329/// name: "V", type: !1, defaulted: false,
6330/// value: i32 7)
6331bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6332#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6333 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6334 OPTIONAL(name, MDStringField, ); \
6335 OPTIONAL(type, MDField, ); \
6336 OPTIONAL(defaulted, MDBoolField, ); \
6337 REQUIRED(value, MDField, );
6338
6339 PARSE_MD_FIELDS();
6340#undef VISIT_MD_FIELDS
6341
6342 Result = GET_OR_DISTINCT(
6343 DITemplateValueParameter,
6344 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6345 return false;
6346}
6347
6348/// parseDIGlobalVariable:
6349/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6350/// file: !1, line: 7, type: !2, isLocal: false,
6351/// isDefinition: true, templateParams: !3,
6352/// declaration: !4, align: 8)
6353bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6354#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6355 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6356 OPTIONAL(scope, MDField, ); \
6357 OPTIONAL(linkageName, MDStringField, ); \
6358 OPTIONAL(file, MDField, ); \
6359 OPTIONAL(line, LineField, ); \
6360 OPTIONAL(type, MDField, ); \
6361 OPTIONAL(isLocal, MDBoolField, ); \
6362 OPTIONAL(isDefinition, MDBoolField, (true)); \
6363 OPTIONAL(templateParams, MDField, ); \
6364 OPTIONAL(declaration, MDField, ); \
6365 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6366 OPTIONAL(annotations, MDField, );
6367 PARSE_MD_FIELDS();
6368#undef VISIT_MD_FIELDS
6369
6370 Result =
6371 GET_OR_DISTINCT(DIGlobalVariable,
6372 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6373 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6374 declaration.Val, templateParams.Val, align.Val,
6375 annotations.Val));
6376 return false;
6377}
6378
6379/// parseDILocalVariable:
6380/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6381/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6382/// align: 8)
6383/// ::= !DILocalVariable(scope: !0, name: "foo",
6384/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6385/// align: 8)
6386bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6387#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6388 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6389 OPTIONAL(name, MDStringField, ); \
6390 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6391 OPTIONAL(file, MDField, ); \
6392 OPTIONAL(line, LineField, ); \
6393 OPTIONAL(type, MDField, ); \
6394 OPTIONAL(flags, DIFlagField, ); \
6395 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6396 OPTIONAL(annotations, MDField, );
6397 PARSE_MD_FIELDS();
6398#undef VISIT_MD_FIELDS
6399
6400 Result = GET_OR_DISTINCT(DILocalVariable,
6401 (Context, scope.Val, name.Val, file.Val, line.Val,
6402 type.Val, arg.Val, flags.Val, align.Val,
6403 annotations.Val));
6404 return false;
6405}
6406
6407/// parseDILabel:
6408/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6409bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6410#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6411 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6412 REQUIRED(name, MDStringField, ); \
6413 REQUIRED(file, MDField, ); \
6414 REQUIRED(line, LineField, ); \
6415 OPTIONAL(column, ColumnField, ); \
6416 OPTIONAL(isArtificial, MDBoolField, ); \
6417 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6418 PARSE_MD_FIELDS();
6419#undef VISIT_MD_FIELDS
6420
6421 std::optional<unsigned> CoroSuspendIdx =
6422 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6423 : std::nullopt;
6424
6425 Result = GET_OR_DISTINCT(DILabel,
6426 (Context, scope.Val, name.Val, file.Val, line.Val,
6427 column.Val, isArtificial.Val, CoroSuspendIdx));
6428 return false;
6429}
6430
6431/// parseDIExpressionBody:
6432/// ::= (0, 7, -1)
6433bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6434 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
6435 return true;
6436
6437 SmallVector<uint64_t, 8> Elements;
6438 if (Lex.getKind() != lltok::rparen)
6439 do {
6440 if (Lex.getKind() == lltok::DwarfOp) {
6441 if (unsigned Op = dwarf::getOperationEncoding(OperationEncodingString: Lex.getStrVal())) {
6442 Lex.Lex();
6443 Elements.push_back(Elt: Op);
6444 continue;
6445 }
6446 return tokError(Msg: Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6447 }
6448
6449 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6450 if (unsigned Op = dwarf::getAttributeEncoding(EncodingString: Lex.getStrVal())) {
6451 Lex.Lex();
6452 Elements.push_back(Elt: Op);
6453 continue;
6454 }
6455 return tokError(Msg: Twine("invalid DWARF attribute encoding '") +
6456 Lex.getStrVal() + "'");
6457 }
6458
6459 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6460 return tokError(Msg: "expected unsigned integer");
6461
6462 auto &U = Lex.getAPSIntVal();
6463 if (U.ugt(UINT64_MAX))
6464 return tokError(Msg: "element too large, limit is " + Twine(UINT64_MAX));
6465 Elements.push_back(Elt: U.getZExtValue());
6466 Lex.Lex();
6467 } while (EatIfPresent(T: lltok::comma));
6468
6469 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
6470 return true;
6471
6472 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6473 return false;
6474}
6475
6476/// parseDIExpression:
6477/// ::= !DIExpression(0, 7, -1)
6478bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6479 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6480 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6481 Lex.Lex();
6482
6483 return parseDIExpressionBody(Result, IsDistinct);
6484}
6485
6486/// ParseDIArgList:
6487/// ::= !DIArgList(i32 7, i64 %0)
6488bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6489 assert(PFS && "Expected valid function state");
6490 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6491 Lex.Lex();
6492
6493 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
6494 return true;
6495
6496 SmallVector<ValueAsMetadata *, 4> Args;
6497 if (Lex.getKind() != lltok::rparen)
6498 do {
6499 Metadata *MD;
6500 if (parseValueAsMetadata(MD, TypeMsg: "expected value-as-metadata operand", PFS))
6501 return true;
6502 Args.push_back(Elt: dyn_cast<ValueAsMetadata>(Val: MD));
6503 } while (EatIfPresent(T: lltok::comma));
6504
6505 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
6506 return true;
6507
6508 MD = DIArgList::get(Context, Args);
6509 return false;
6510}
6511
6512/// parseDIGlobalVariableExpression:
6513/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6514bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6515 bool IsDistinct) {
6516#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6517 REQUIRED(var, MDField, ); \
6518 REQUIRED(expr, MDField, );
6519 PARSE_MD_FIELDS();
6520#undef VISIT_MD_FIELDS
6521
6522 Result =
6523 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6524 return false;
6525}
6526
6527/// parseDIObjCProperty:
6528/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6529/// getter: "getFoo", attributes: 7, type: !2)
6530bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6531#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6532 OPTIONAL(name, MDStringField, ); \
6533 OPTIONAL(file, MDField, ); \
6534 OPTIONAL(line, LineField, ); \
6535 OPTIONAL(setter, MDStringField, ); \
6536 OPTIONAL(getter, MDStringField, ); \
6537 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6538 OPTIONAL(type, MDField, );
6539 PARSE_MD_FIELDS();
6540#undef VISIT_MD_FIELDS
6541
6542 Result = GET_OR_DISTINCT(DIObjCProperty,
6543 (Context, name.Val, file.Val, line.Val, getter.Val,
6544 setter.Val, attributes.Val, type.Val));
6545 return false;
6546}
6547
6548/// parseDIImportedEntity:
6549/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6550/// line: 7, name: "foo", elements: !2)
6551bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6552#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6553 REQUIRED(tag, DwarfTagField, ); \
6554 REQUIRED(scope, MDField, ); \
6555 OPTIONAL(entity, MDField, ); \
6556 OPTIONAL(file, MDField, ); \
6557 OPTIONAL(line, LineField, ); \
6558 OPTIONAL(name, MDStringField, ); \
6559 OPTIONAL(elements, MDField, );
6560 PARSE_MD_FIELDS();
6561#undef VISIT_MD_FIELDS
6562
6563 Result = GET_OR_DISTINCT(DIImportedEntity,
6564 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6565 line.Val, name.Val, elements.Val));
6566 return false;
6567}
6568
6569#undef PARSE_MD_FIELD
6570#undef NOP_FIELD
6571#undef REQUIRE_FIELD
6572#undef DECLARE_FIELD
6573
6574/// parseMetadataAsValue
6575/// ::= metadata i32 %local
6576/// ::= metadata i32 @global
6577/// ::= metadata i32 7
6578/// ::= metadata !0
6579/// ::= metadata !{...}
6580/// ::= metadata !"string"
6581bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6582 // Note: the type 'metadata' has already been parsed.
6583 Metadata *MD;
6584 if (parseMetadata(MD, PFS: &PFS))
6585 return true;
6586
6587 V = MetadataAsValue::get(Context, MD);
6588 return false;
6589}
6590
6591/// parseValueAsMetadata
6592/// ::= i32 %local
6593/// ::= i32 @global
6594/// ::= i32 7
6595bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6596 PerFunctionState *PFS) {
6597 Type *Ty;
6598 LocTy Loc;
6599 if (parseType(Result&: Ty, Msg: TypeMsg, Loc))
6600 return true;
6601 if (Ty->isMetadataTy())
6602 return error(L: Loc, Msg: "invalid metadata-value-metadata roundtrip");
6603
6604 Value *V;
6605 if (parseValue(Ty, V, PFS))
6606 return true;
6607
6608 MD = ValueAsMetadata::get(V);
6609 return false;
6610}
6611
6612/// parseMetadata
6613/// ::= i32 %local
6614/// ::= i32 @global
6615/// ::= i32 7
6616/// ::= !42
6617/// ::= !{...}
6618/// ::= !"string"
6619/// ::= !DILocation(...)
6620bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6621 if (Lex.getKind() == lltok::MetadataVar) {
6622 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6623 // so parsing this requires a Function State.
6624 if (Lex.getStrVal() == "DIArgList") {
6625 Metadata *AL;
6626 if (parseDIArgList(MD&: AL, PFS))
6627 return true;
6628 MD = AL;
6629 return false;
6630 }
6631 MDNode *N;
6632 if (parseSpecializedMDNode(N)) {
6633 return true;
6634 }
6635 MD = N;
6636 return false;
6637 }
6638
6639 // ValueAsMetadata:
6640 // <type> <value>
6641 if (Lex.getKind() != lltok::exclaim)
6642 return parseValueAsMetadata(MD, TypeMsg: "expected metadata operand", PFS);
6643
6644 // '!'.
6645 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6646 Lex.Lex();
6647
6648 // MDString:
6649 // ::= '!' STRINGCONSTANT
6650 if (Lex.getKind() == lltok::StringConstant) {
6651 MDString *S;
6652 if (parseMDString(Result&: S))
6653 return true;
6654 MD = S;
6655 return false;
6656 }
6657
6658 // MDNode:
6659 // !{ ... }
6660 // !7
6661 MDNode *N;
6662 if (parseMDNodeTail(N))
6663 return true;
6664 MD = N;
6665 return false;
6666}
6667
6668//===----------------------------------------------------------------------===//
6669// Function Parsing.
6670//===----------------------------------------------------------------------===//
6671
6672bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6673 PerFunctionState *PFS) {
6674 if (Ty->isFunctionTy())
6675 return error(L: ID.Loc, Msg: "functions are not values, refer to them as pointers");
6676
6677 switch (ID.Kind) {
6678 case ValID::t_LocalID:
6679 if (!PFS)
6680 return error(L: ID.Loc, Msg: "invalid use of function-local name");
6681 V = PFS->getVal(ID: ID.UIntVal, Ty, Loc: ID.Loc);
6682 return V == nullptr;
6683 case ValID::t_LocalName:
6684 if (!PFS)
6685 return error(L: ID.Loc, Msg: "invalid use of function-local name");
6686 V = PFS->getVal(Name: ID.StrVal, Ty, Loc: ID.Loc);
6687 return V == nullptr;
6688 case ValID::t_InlineAsm: {
6689 if (!ID.FTy)
6690 return error(L: ID.Loc, Msg: "invalid type for inline asm constraint string");
6691 if (Error Err = InlineAsm::verify(Ty: ID.FTy, Constraints: ID.StrVal2))
6692 return error(L: ID.Loc, Msg: toString(E: std::move(Err)));
6693 V = InlineAsm::get(
6694 Ty: ID.FTy, AsmString: ID.StrVal, Constraints: ID.StrVal2, hasSideEffects: ID.UIntVal & 1, isAlignStack: (ID.UIntVal >> 1) & 1,
6695 asmDialect: InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), canThrow: (ID.UIntVal >> 3) & 1);
6696 return false;
6697 }
6698 case ValID::t_GlobalName:
6699 V = getGlobalVal(Name: ID.StrVal, Ty, Loc: ID.Loc);
6700 if (V && ID.NoCFI)
6701 V = NoCFIValue::get(GV: cast<GlobalValue>(Val: V));
6702 return V == nullptr;
6703 case ValID::t_GlobalID:
6704 V = getGlobalVal(ID: ID.UIntVal, Ty, Loc: ID.Loc);
6705 if (V && ID.NoCFI)
6706 V = NoCFIValue::get(GV: cast<GlobalValue>(Val: V));
6707 return V == nullptr;
6708 case ValID::t_APSInt:
6709 if (!Ty->isIntegerTy() && !Ty->isByteTy())
6710 return error(L: ID.Loc, Msg: "integer/byte constant must have integer/byte type");
6711 ID.APSIntVal = ID.APSIntVal.extOrTrunc(width: Ty->getPrimitiveSizeInBits());
6712 Ty->isIntegerTy() ? V = ConstantInt::get(Context, V: ID.APSIntVal)
6713 : V = ConstantByte::get(Context, V: ID.APSIntVal);
6714 return false;
6715 case ValID::t_APFloat:
6716 if (!Ty->isFloatingPointTy() ||
6717 !ConstantFP::isValueValidForType(Ty, V: ID.APFloatVal))
6718 return error(L: ID.Loc, Msg: "floating point constant invalid for type");
6719
6720 // The lexer has no type info, so builds all half, bfloat, float, and double
6721 // FP constants as double. Fix this here. Long double does not need this.
6722 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6723 // Check for signaling before potentially converting and losing that info.
6724 bool IsSNAN = ID.APFloatVal.isSignaling();
6725 bool Ignored;
6726 if (Ty->isHalfTy())
6727 ID.APFloatVal.convert(ToSemantics: APFloat::IEEEhalf(), RM: APFloat::rmNearestTiesToEven,
6728 losesInfo: &Ignored);
6729 else if (Ty->isBFloatTy())
6730 ID.APFloatVal.convert(ToSemantics: APFloat::BFloat(), RM: APFloat::rmNearestTiesToEven,
6731 losesInfo: &Ignored);
6732 else if (Ty->isFloatTy())
6733 ID.APFloatVal.convert(ToSemantics: APFloat::IEEEsingle(), RM: APFloat::rmNearestTiesToEven,
6734 losesInfo: &Ignored);
6735 if (IsSNAN) {
6736 // The convert call above may quiet an SNaN, so manufacture another
6737 // SNaN. The bitcast works because the payload (significand) parameter
6738 // is truncated to fit.
6739 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6740 ID.APFloatVal = APFloat::getSNaN(Sem: ID.APFloatVal.getSemantics(),
6741 Negative: ID.APFloatVal.isNegative(), payload: &Payload);
6742 }
6743 }
6744 V = ConstantFP::get(Context, V: ID.APFloatVal);
6745
6746 if (V->getType() != Ty)
6747 return error(L: ID.Loc, Msg: "floating point constant does not have type '" +
6748 getTypeString(T: Ty) + "'");
6749
6750 return false;
6751 case ValID::t_Null:
6752 if (!Ty->isPointerTy())
6753 return error(L: ID.Loc, Msg: "null must be a pointer type");
6754 V = ConstantPointerNull::get(T: cast<PointerType>(Val: Ty));
6755 return false;
6756 case ValID::t_Undef:
6757 // FIXME: LabelTy should not be a first-class type.
6758 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6759 return error(L: ID.Loc, Msg: "invalid type for undef constant");
6760 V = UndefValue::get(T: Ty);
6761 return false;
6762 case ValID::t_EmptyArray:
6763 if (!Ty->isArrayTy() || cast<ArrayType>(Val: Ty)->getNumElements() != 0)
6764 return error(L: ID.Loc, Msg: "invalid empty array initializer");
6765 V = PoisonValue::get(T: Ty);
6766 return false;
6767 case ValID::t_Zero:
6768 // FIXME: LabelTy should not be a first-class type.
6769 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6770 return error(L: ID.Loc, Msg: "invalid type for null constant");
6771 if (auto *TETy = dyn_cast<TargetExtType>(Val: Ty))
6772 if (!TETy->hasProperty(Prop: TargetExtType::HasZeroInit))
6773 return error(L: ID.Loc, Msg: "invalid type for null constant");
6774 V = Constant::getNullValue(Ty);
6775 return false;
6776 case ValID::t_None:
6777 if (!Ty->isTokenTy())
6778 return error(L: ID.Loc, Msg: "invalid type for none constant");
6779 V = Constant::getNullValue(Ty);
6780 return false;
6781 case ValID::t_Poison:
6782 // FIXME: LabelTy should not be a first-class type.
6783 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6784 return error(L: ID.Loc, Msg: "invalid type for poison constant");
6785 V = PoisonValue::get(T: Ty);
6786 return false;
6787 case ValID::t_Constant:
6788 if (ID.ConstantVal->getType() != Ty)
6789 return error(L: ID.Loc, Msg: "constant expression type mismatch: got type '" +
6790 getTypeString(T: ID.ConstantVal->getType()) +
6791 "' but expected '" + getTypeString(T: Ty) + "'");
6792 V = ID.ConstantVal;
6793 return false;
6794 case ValID::t_ConstantSplat:
6795 if (!Ty->isVectorTy())
6796 return error(L: ID.Loc, Msg: "vector constant must have vector type");
6797 if (ID.ConstantVal->getType() != Ty->getScalarType())
6798 return error(L: ID.Loc, Msg: "constant expression type mismatch: got type '" +
6799 getTypeString(T: ID.ConstantVal->getType()) +
6800 "' but expected '" +
6801 getTypeString(T: Ty->getScalarType()) + "'");
6802 V = ConstantVector::getSplat(EC: cast<VectorType>(Val: Ty)->getElementCount(),
6803 Elt: ID.ConstantVal);
6804 return false;
6805 case ValID::t_ConstantStruct:
6806 case ValID::t_PackedConstantStruct:
6807 if (StructType *ST = dyn_cast<StructType>(Val: Ty)) {
6808 if (ST->getNumElements() != ID.UIntVal)
6809 return error(L: ID.Loc,
6810 Msg: "initializer with struct type has wrong # elements");
6811 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6812 return error(L: ID.Loc, Msg: "packed'ness of initializer and type don't match");
6813
6814 // Verify that the elements are compatible with the structtype.
6815 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6816 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(N: i))
6817 return error(
6818 L: ID.Loc,
6819 Msg: "element " + Twine(i) +
6820 " of struct initializer doesn't match struct element type");
6821
6822 V = ConstantStruct::get(
6823 T: ST, V: ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6824 } else
6825 return error(L: ID.Loc, Msg: "constant expression type mismatch");
6826 return false;
6827 }
6828 llvm_unreachable("Invalid ValID");
6829}
6830
6831bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6832 C = nullptr;
6833 ValID ID;
6834 auto Loc = Lex.getLoc();
6835 if (parseValID(ID, /*PFS=*/nullptr))
6836 return true;
6837 switch (ID.Kind) {
6838 case ValID::t_APSInt:
6839 case ValID::t_APFloat:
6840 case ValID::t_Undef:
6841 case ValID::t_Poison:
6842 case ValID::t_Zero:
6843 case ValID::t_Constant:
6844 case ValID::t_ConstantSplat:
6845 case ValID::t_ConstantStruct:
6846 case ValID::t_PackedConstantStruct: {
6847 Value *V;
6848 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6849 return true;
6850 assert(isa<Constant>(V) && "Expected a constant value");
6851 C = cast<Constant>(Val: V);
6852 return false;
6853 }
6854 case ValID::t_Null:
6855 C = Constant::getNullValue(Ty);
6856 return false;
6857 default:
6858 return error(L: Loc, Msg: "expected a constant value");
6859 }
6860}
6861
6862bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6863 V = nullptr;
6864 ValID ID;
6865
6866 FileLoc Start = getTokLineColumnPos();
6867 bool Ret = parseValID(ID, PFS, ExpectedTy: Ty) || convertValIDToValue(Ty, ID, V, PFS);
6868 if (!Ret && ParserContext) {
6869 FileLoc End = getPrevTokEndLineColumnPos();
6870 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
6871 }
6872 return Ret;
6873}
6874
6875bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6876 Type *Ty = nullptr;
6877 return parseType(Result&: Ty) || parseValue(Ty, V, PFS);
6878}
6879
6880bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6881 PerFunctionState &PFS) {
6882 Value *V;
6883 Loc = Lex.getLoc();
6884 if (parseTypeAndValue(V, PFS))
6885 return true;
6886 if (!isa<BasicBlock>(Val: V))
6887 return error(L: Loc, Msg: "expected a basic block");
6888 BB = cast<BasicBlock>(Val: V);
6889 return false;
6890}
6891
6892bool isOldDbgFormatIntrinsic(StringRef Name) {
6893 // Exit early for the common (non-debug-intrinsic) case.
6894 // We can make this the only check when we begin supporting all "llvm.dbg"
6895 // intrinsics in the new debug info format.
6896 if (!Name.starts_with(Prefix: "llvm.dbg."))
6897 return false;
6898 Intrinsic::ID FnID = Intrinsic::lookupIntrinsicID(Name);
6899 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6900 FnID == Intrinsic::dbg_assign;
6901}
6902
6903/// FunctionHeader
6904/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6905/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6906/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6907/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6908bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6909 unsigned &FunctionNumber,
6910 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6911 // parse the linkage.
6912 LocTy LinkageLoc = Lex.getLoc();
6913 unsigned Linkage;
6914 unsigned Visibility;
6915 unsigned DLLStorageClass;
6916 bool DSOLocal;
6917 AttrBuilder RetAttrs(M->getContext());
6918 unsigned CC;
6919 bool HasLinkage;
6920 Type *RetType = nullptr;
6921 LocTy RetTypeLoc = Lex.getLoc();
6922 if (parseOptionalLinkage(Res&: Linkage, HasLinkage, Visibility, DLLStorageClass,
6923 DSOLocal) ||
6924 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(B&: RetAttrs) ||
6925 parseType(Result&: RetType, Loc&: RetTypeLoc, AllowVoid: true /*void allowed*/))
6926 return true;
6927
6928 // Verify that the linkage is ok.
6929 switch ((GlobalValue::LinkageTypes)Linkage) {
6930 case GlobalValue::ExternalLinkage:
6931 break; // always ok.
6932 case GlobalValue::ExternalWeakLinkage:
6933 if (IsDefine)
6934 return error(L: LinkageLoc, Msg: "invalid linkage for function definition");
6935 break;
6936 case GlobalValue::PrivateLinkage:
6937 case GlobalValue::InternalLinkage:
6938 case GlobalValue::AvailableExternallyLinkage:
6939 case GlobalValue::LinkOnceAnyLinkage:
6940 case GlobalValue::LinkOnceODRLinkage:
6941 case GlobalValue::WeakAnyLinkage:
6942 case GlobalValue::WeakODRLinkage:
6943 if (!IsDefine)
6944 return error(L: LinkageLoc, Msg: "invalid linkage for function declaration");
6945 break;
6946 case GlobalValue::AppendingLinkage:
6947 case GlobalValue::CommonLinkage:
6948 return error(L: LinkageLoc, Msg: "invalid function linkage type");
6949 }
6950
6951 if (!isValidVisibilityForLinkage(V: Visibility, L: Linkage))
6952 return error(L: LinkageLoc,
6953 Msg: "symbol with local linkage must have default visibility");
6954
6955 if (!isValidDLLStorageClassForLinkage(S: DLLStorageClass, L: Linkage))
6956 return error(L: LinkageLoc,
6957 Msg: "symbol with local linkage cannot have a DLL storage class");
6958
6959 if (!FunctionType::isValidReturnType(RetTy: RetType))
6960 return error(L: RetTypeLoc, Msg: "invalid function return type");
6961
6962 LocTy NameLoc = Lex.getLoc();
6963
6964 std::string FunctionName;
6965 if (Lex.getKind() == lltok::GlobalVar) {
6966 FunctionName = Lex.getStrVal();
6967 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6968 FunctionNumber = Lex.getUIntVal();
6969 if (checkValueID(Loc: NameLoc, Kind: "function", Prefix: "@", NextID: NumberedVals.getNext(),
6970 ID: FunctionNumber))
6971 return true;
6972 } else {
6973 return tokError(Msg: "expected function name");
6974 }
6975
6976 Lex.Lex();
6977
6978 if (Lex.getKind() != lltok::lparen)
6979 return tokError(Msg: "expected '(' in function argument list");
6980
6981 SmallVector<ArgInfo, 8> ArgList;
6982 bool IsVarArg;
6983 AttrBuilder FuncAttrs(M->getContext());
6984 std::vector<unsigned> FwdRefAttrGrps;
6985 LocTy BuiltinLoc;
6986 std::string Section;
6987 std::string Partition;
6988 MaybeAlign Alignment, PrefAlignment;
6989 std::string GC;
6990 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
6991 unsigned AddrSpace = 0;
6992 Constant *Prefix = nullptr;
6993 Constant *Prologue = nullptr;
6994 Constant *PersonalityFn = nullptr;
6995 Comdat *C;
6996
6997 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6998 parseOptionalUnnamedAddr(UnnamedAddr) ||
6999 parseOptionalProgramAddrSpace(AddrSpace) ||
7000 parseFnAttributeValuePairs(B&: FuncAttrs, FwdRefAttrGrps, InAttrGrp: false,
7001 BuiltinLoc) ||
7002 (EatIfPresent(T: lltok::kw_section) && parseStringConstant(Result&: Section)) ||
7003 (EatIfPresent(T: lltok::kw_partition) && parseStringConstant(Result&: Partition)) ||
7004 parseOptionalComdat(GlobalName: FunctionName, C) ||
7005 parseOptionalAlignment(Alignment) ||
7006 parseOptionalPrefAlignment(Alignment&: PrefAlignment) ||
7007 (EatIfPresent(T: lltok::kw_gc) && parseStringConstant(Result&: GC)) ||
7008 (EatIfPresent(T: lltok::kw_prefix) && parseGlobalTypeAndValue(V&: Prefix)) ||
7009 (EatIfPresent(T: lltok::kw_prologue) && parseGlobalTypeAndValue(V&: Prologue)) ||
7010 (EatIfPresent(T: lltok::kw_personality) &&
7011 parseGlobalTypeAndValue(V&: PersonalityFn)))
7012 return true;
7013
7014 if (FuncAttrs.contains(A: Attribute::Builtin))
7015 return error(L: BuiltinLoc, Msg: "'builtin' attribute not valid on function");
7016
7017 // If the alignment was parsed as an attribute, move to the alignment field.
7018 if (MaybeAlign A = FuncAttrs.getAlignment()) {
7019 Alignment = A;
7020 FuncAttrs.removeAttribute(Val: Attribute::Alignment);
7021 }
7022
7023 // Okay, if we got here, the function is syntactically valid. Convert types
7024 // and do semantic checks.
7025 std::vector<Type*> ParamTypeList;
7026 SmallVector<AttributeSet, 8> Attrs;
7027
7028 for (const ArgInfo &Arg : ArgList) {
7029 ParamTypeList.push_back(x: Arg.Ty);
7030 Attrs.push_back(Elt: Arg.Attrs);
7031 }
7032
7033 AttributeList PAL =
7034 AttributeList::get(C&: Context, FnAttrs: AttributeSet::get(C&: Context, B: FuncAttrs),
7035 RetAttrs: AttributeSet::get(C&: Context, B: RetAttrs), ArgAttrs: Attrs);
7036
7037 if (PAL.hasParamAttr(ArgNo: 0, Kind: Attribute::StructRet) && !RetType->isVoidTy())
7038 return error(L: RetTypeLoc, Msg: "functions with 'sret' argument must return void");
7039
7040 FunctionType *FT = FunctionType::get(Result: RetType, Params: ParamTypeList, isVarArg: IsVarArg);
7041 PointerType *PFT = PointerType::get(C&: Context, AddressSpace: AddrSpace);
7042
7043 Fn = nullptr;
7044 GlobalValue *FwdFn = nullptr;
7045 if (!FunctionName.empty()) {
7046 // If this was a definition of a forward reference, remove the definition
7047 // from the forward reference table and fill in the forward ref.
7048 auto FRVI = ForwardRefVals.find(x: FunctionName);
7049 if (FRVI != ForwardRefVals.end()) {
7050 FwdFn = FRVI->second.first;
7051 if (FwdFn->getType() != PFT)
7052 return error(L: FRVI->second.second,
7053 Msg: "invalid forward reference to "
7054 "function '" +
7055 FunctionName +
7056 "' with wrong type: "
7057 "expected '" +
7058 getTypeString(T: PFT) + "' but was '" +
7059 getTypeString(T: FwdFn->getType()) + "'");
7060 ForwardRefVals.erase(position: FRVI);
7061 } else if ((Fn = M->getFunction(Name: FunctionName))) {
7062 // Reject redefinitions.
7063 return error(L: NameLoc,
7064 Msg: "invalid redefinition of function '" + FunctionName + "'");
7065 } else if (M->getNamedValue(Name: FunctionName)) {
7066 return error(L: NameLoc, Msg: "redefinition of function '@" + FunctionName + "'");
7067 }
7068
7069 } else {
7070 // Handle @"", where a name is syntactically specified, but semantically
7071 // missing.
7072 if (FunctionNumber == (unsigned)-1)
7073 FunctionNumber = NumberedVals.getNext();
7074
7075 // If this is a definition of a forward referenced function, make sure the
7076 // types agree.
7077 auto I = ForwardRefValIDs.find(x: FunctionNumber);
7078 if (I != ForwardRefValIDs.end()) {
7079 FwdFn = I->second.first;
7080 if (FwdFn->getType() != PFT)
7081 return error(L: NameLoc, Msg: "type of definition and forward reference of '@" +
7082 Twine(FunctionNumber) +
7083 "' disagree: "
7084 "expected '" +
7085 getTypeString(T: PFT) + "' but was '" +
7086 getTypeString(T: FwdFn->getType()) + "'");
7087 ForwardRefValIDs.erase(position: I);
7088 }
7089 }
7090
7091 Fn = Function::Create(Ty: FT, Linkage: GlobalValue::ExternalLinkage, AddrSpace,
7092 N: FunctionName, M);
7093
7094 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
7095
7096 if (FunctionName.empty())
7097 NumberedVals.add(ID: FunctionNumber, V: Fn);
7098
7099 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
7100 maybeSetDSOLocal(DSOLocal, GV&: *Fn);
7101 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
7102 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
7103 Fn->setCallingConv(CC);
7104 Fn->setAttributes(PAL);
7105 Fn->setUnnamedAddr(UnnamedAddr);
7106 if (Alignment)
7107 Fn->setAlignment(*Alignment);
7108 Fn->setPreferredAlignment(PrefAlignment);
7109 Fn->setSection(Section);
7110 Fn->setPartition(Partition);
7111 Fn->setComdat(C);
7112 Fn->setPersonalityFn(PersonalityFn);
7113 if (!GC.empty()) Fn->setGC(GC);
7114 Fn->setPrefixData(Prefix);
7115 Fn->setPrologueData(Prologue);
7116 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7117
7118 // Add all of the arguments we parsed to the function.
7119 Function::arg_iterator ArgIt = Fn->arg_begin();
7120 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7121 if (ParserContext && ArgList[i].IdentLoc)
7122 ParserContext->addInstructionOrArgumentLocation(
7123 &*ArgIt, ArgList[i].IdentLoc.value());
7124 // If the argument has a name, insert it into the argument symbol table.
7125 if (ArgList[i].Name.empty()) continue;
7126
7127 // Set the name, if it conflicted, it will be auto-renamed.
7128 ArgIt->setName(ArgList[i].Name);
7129
7130 if (ArgIt->getName() != ArgList[i].Name)
7131 return error(L: ArgList[i].Loc,
7132 Msg: "redefinition of argument '%" + ArgList[i].Name + "'");
7133 }
7134
7135 if (FwdFn) {
7136 FwdFn->replaceAllUsesWith(V: Fn);
7137 FwdFn->eraseFromParent();
7138 }
7139
7140 if (IsDefine)
7141 return false;
7142
7143 // Check the declaration has no block address forward references.
7144 ValID ID;
7145 if (FunctionName.empty()) {
7146 ID.Kind = ValID::t_GlobalID;
7147 ID.UIntVal = FunctionNumber;
7148 } else {
7149 ID.Kind = ValID::t_GlobalName;
7150 ID.StrVal = FunctionName;
7151 }
7152 auto Blocks = ForwardRefBlockAddresses.find(x: ID);
7153 if (Blocks != ForwardRefBlockAddresses.end())
7154 return error(L: Blocks->first.Loc,
7155 Msg: "cannot take blockaddress inside a declaration");
7156 return false;
7157}
7158
7159bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7160 ValID ID;
7161 if (FunctionNumber == -1) {
7162 ID.Kind = ValID::t_GlobalName;
7163 ID.StrVal = std::string(F.getName());
7164 } else {
7165 ID.Kind = ValID::t_GlobalID;
7166 ID.UIntVal = FunctionNumber;
7167 }
7168
7169 auto Blocks = P.ForwardRefBlockAddresses.find(x: ID);
7170 if (Blocks == P.ForwardRefBlockAddresses.end())
7171 return false;
7172
7173 for (const auto &I : Blocks->second) {
7174 const ValID &BBID = I.first;
7175 GlobalValue *GV = I.second;
7176
7177 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7178 "Expected local id or name");
7179 BasicBlock *BB;
7180 if (BBID.Kind == ValID::t_LocalName)
7181 BB = getBB(Name: BBID.StrVal, Loc: BBID.Loc);
7182 else
7183 BB = getBB(ID: BBID.UIntVal, Loc: BBID.Loc);
7184 if (!BB)
7185 return P.error(L: BBID.Loc, Msg: "referenced value is not a basic block");
7186
7187 Value *ResolvedVal = BlockAddress::get(F: &F, BB);
7188 ResolvedVal = P.checkValidVariableType(Loc: BBID.Loc, Name: BBID.StrVal, Ty: GV->getType(),
7189 Val: ResolvedVal);
7190 if (!ResolvedVal)
7191 return true;
7192 GV->replaceAllUsesWith(V: ResolvedVal);
7193 GV->eraseFromParent();
7194 }
7195
7196 P.ForwardRefBlockAddresses.erase(position: Blocks);
7197 return false;
7198}
7199
7200/// parseFunctionBody
7201/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7202bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7203 ArrayRef<unsigned> UnnamedArgNums) {
7204 if (Lex.getKind() != lltok::lbrace)
7205 return tokError(Msg: "expected '{' in function body");
7206 Lex.Lex(); // eat the {.
7207
7208 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7209
7210 // Resolve block addresses and allow basic blocks to be forward-declared
7211 // within this function.
7212 if (PFS.resolveForwardRefBlockAddresses())
7213 return true;
7214 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7215
7216 // We need at least one basic block.
7217 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7218 return tokError(Msg: "function body requires at least one basic block");
7219
7220 while (Lex.getKind() != lltok::rbrace &&
7221 Lex.getKind() != lltok::kw_uselistorder)
7222 if (parseBasicBlock(PFS))
7223 return true;
7224
7225 while (Lex.getKind() != lltok::rbrace)
7226 if (parseUseListOrder(PFS: &PFS))
7227 return true;
7228
7229 // Eat the }.
7230 Lex.Lex();
7231
7232 // Verify function is ok.
7233 return PFS.finishFunction();
7234}
7235
7236/// parseBasicBlock
7237/// ::= (LabelStr|LabelID)? Instruction*
7238bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7239 FileLoc BBStart = getTokLineColumnPos();
7240
7241 // If this basic block starts out with a name, remember it.
7242 std::string Name;
7243 int NameID = -1;
7244 LocTy NameLoc = Lex.getLoc();
7245 if (Lex.getKind() == lltok::LabelStr) {
7246 Name = Lex.getStrVal();
7247 Lex.Lex();
7248 } else if (Lex.getKind() == lltok::LabelID) {
7249 NameID = Lex.getUIntVal();
7250 Lex.Lex();
7251 }
7252
7253 BasicBlock *BB = PFS.defineBB(Name, NameID, Loc: NameLoc);
7254 if (!BB)
7255 return true;
7256
7257 std::string NameStr;
7258
7259 // Parse the instructions and debug values in this block until we get a
7260 // terminator.
7261 Instruction *Inst;
7262 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7263 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7264 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7265 do {
7266 // Handle debug records first - there should always be an instruction
7267 // following the debug records, i.e. they cannot appear after the block
7268 // terminator.
7269 while (Lex.getKind() == lltok::hash) {
7270 if (SeenOldDbgInfoFormat)
7271 return error(L: Lex.getLoc(), Msg: "debug record should not appear in a module "
7272 "containing debug info intrinsics");
7273 SeenNewDbgInfoFormat = true;
7274 Lex.Lex();
7275
7276 DbgRecord *DR;
7277 if (parseDebugRecord(DR, PFS))
7278 return true;
7279 TrailingDbgRecord.emplace_back(Args&: DR, Args&: DeleteDbgRecord);
7280 }
7281
7282 FileLoc InstStart = getTokLineColumnPos();
7283 // This instruction may have three possibilities for a name: a) none
7284 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7285 LocTy NameLoc = Lex.getLoc();
7286 int NameID = -1;
7287 NameStr = "";
7288
7289 if (Lex.getKind() == lltok::LocalVarID) {
7290 NameID = Lex.getUIntVal();
7291 Lex.Lex();
7292 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after instruction id"))
7293 return true;
7294 } else if (Lex.getKind() == lltok::LocalVar) {
7295 NameStr = Lex.getStrVal();
7296 Lex.Lex();
7297 if (parseToken(T: lltok::equal, ErrMsg: "expected '=' after instruction name"))
7298 return true;
7299 }
7300
7301 switch (parseInstruction(Inst, BB, PFS)) {
7302 default:
7303 llvm_unreachable("Unknown parseInstruction result!");
7304 case InstError: return true;
7305 case InstNormal:
7306 Inst->insertInto(ParentBB: BB, It: BB->end());
7307
7308 // With a normal result, we check to see if the instruction is followed by
7309 // a comma and metadata.
7310 if (EatIfPresent(T: lltok::comma))
7311 if (parseInstructionMetadata(Inst&: *Inst))
7312 return true;
7313 break;
7314 case InstExtraComma:
7315 Inst->insertInto(ParentBB: BB, It: BB->end());
7316
7317 // If the instruction parser ate an extra comma at the end of it, it
7318 // *must* be followed by metadata.
7319 if (parseInstructionMetadata(Inst&: *Inst))
7320 return true;
7321 break;
7322 }
7323
7324 // Set the name on the instruction.
7325 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7326 return true;
7327
7328 // Attach any preceding debug values to this instruction.
7329 for (DbgRecordPtr &DR : TrailingDbgRecord)
7330 BB->insertDbgRecordBefore(DR: DR.release(), Here: Inst->getIterator());
7331 TrailingDbgRecord.clear();
7332 if (ParserContext) {
7333 ParserContext->addInstructionOrArgumentLocation(
7334 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7335 }
7336 } while (!Inst->isTerminator());
7337
7338 if (ParserContext)
7339 ParserContext->addBlockLocation(
7340 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7341
7342 assert(TrailingDbgRecord.empty() &&
7343 "All debug values should have been attached to an instruction.");
7344
7345 return false;
7346}
7347
7348/// parseDebugRecord
7349/// ::= #dbg_label '(' MDNode ')'
7350/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7351/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7352bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7353 using RecordKind = DbgRecord::Kind;
7354 using LocType = DbgVariableRecord::LocationType;
7355 LocTy DVRLoc = Lex.getLoc();
7356 if (Lex.getKind() != lltok::DbgRecordType)
7357 return error(L: DVRLoc, Msg: "expected debug record type here");
7358 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7359 .Case(S: "declare", Value: RecordKind::ValueKind)
7360 .Case(S: "value", Value: RecordKind::ValueKind)
7361 .Case(S: "assign", Value: RecordKind::ValueKind)
7362 .Case(S: "label", Value: RecordKind::LabelKind)
7363 .Case(S: "declare_value", Value: RecordKind::ValueKind);
7364
7365 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7366 // full DbgVariableRecord processing stage.
7367 if (RecordType == RecordKind::LabelKind) {
7368 Lex.Lex();
7369 if (parseToken(T: lltok::lparen, ErrMsg: "Expected '(' here"))
7370 return true;
7371 MDNode *Label;
7372 if (parseMDNode(N&: Label))
7373 return true;
7374 if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here"))
7375 return true;
7376 MDNode *DbgLoc;
7377 if (parseMDNode(N&: DbgLoc))
7378 return true;
7379 if (parseToken(T: lltok::rparen, ErrMsg: "Expected ')' here"))
7380 return true;
7381 DR = DbgLabelRecord::createUnresolvedDbgLabelRecord(Label, DL: DbgLoc);
7382 return false;
7383 }
7384
7385 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7386 .Case(S: "declare", Value: LocType::Declare)
7387 .Case(S: "value", Value: LocType::Value)
7388 .Case(S: "assign", Value: LocType::Assign)
7389 .Case(S: "declare_value", Value: LocType::DeclareValue);
7390
7391 Lex.Lex();
7392 if (parseToken(T: lltok::lparen, ErrMsg: "Expected '(' here"))
7393 return true;
7394
7395 // Parse Value field.
7396 Metadata *ValLocMD;
7397 if (parseMetadata(MD&: ValLocMD, PFS: &PFS))
7398 return true;
7399 if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here"))
7400 return true;
7401
7402 // Parse Variable field.
7403 MDNode *Variable;
7404 if (parseMDNode(N&: Variable))
7405 return true;
7406 if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here"))
7407 return true;
7408
7409 // Parse Expression field.
7410 MDNode *Expression;
7411 if (parseMDNode(N&: Expression))
7412 return true;
7413 if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here"))
7414 return true;
7415
7416 // Parse additional fields for #dbg_assign.
7417 MDNode *AssignID = nullptr;
7418 Metadata *AddressLocation = nullptr;
7419 MDNode *AddressExpression = nullptr;
7420 if (ValueType == LocType::Assign) {
7421 // Parse DIAssignID.
7422 if (parseMDNode(N&: AssignID))
7423 return true;
7424 if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here"))
7425 return true;
7426
7427 // Parse address ValueAsMetadata.
7428 if (parseMetadata(MD&: AddressLocation, PFS: &PFS))
7429 return true;
7430 if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here"))
7431 return true;
7432
7433 // Parse address DIExpression.
7434 if (parseMDNode(N&: AddressExpression))
7435 return true;
7436 if (parseToken(T: lltok::comma, ErrMsg: "Expected ',' here"))
7437 return true;
7438 }
7439
7440 /// Parse DILocation.
7441 MDNode *DebugLoc;
7442 if (parseMDNode(N&: DebugLoc))
7443 return true;
7444
7445 if (parseToken(T: lltok::rparen, ErrMsg: "Expected ')' here"))
7446 return true;
7447 DR = DbgVariableRecord::createUnresolvedDbgVariableRecord(
7448 Type: ValueType, Val: ValLocMD, Variable, Expression, AssignID, Address: AddressLocation,
7449 AddressExpression, DI: DebugLoc);
7450 return false;
7451}
7452//===----------------------------------------------------------------------===//
7453// Instruction Parsing.
7454//===----------------------------------------------------------------------===//
7455
7456/// parseInstruction - parse one of the many different instructions.
7457///
7458int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7459 PerFunctionState &PFS) {
7460 lltok::Kind Token = Lex.getKind();
7461 if (Token == lltok::Eof)
7462 return tokError(Msg: "found end of file when expecting more instructions");
7463 LocTy Loc = Lex.getLoc();
7464 unsigned KeywordVal = Lex.getUIntVal();
7465 Lex.Lex(); // Eat the keyword.
7466
7467 switch (Token) {
7468 default:
7469 return error(L: Loc, Msg: "expected instruction opcode");
7470 // Terminator Instructions.
7471 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7472 case lltok::kw_ret:
7473 return parseRet(Inst, BB, PFS);
7474 case lltok::kw_br:
7475 return parseBr(Inst, PFS);
7476 case lltok::kw_switch:
7477 return parseSwitch(Inst, PFS);
7478 case lltok::kw_indirectbr:
7479 return parseIndirectBr(Inst, PFS);
7480 case lltok::kw_invoke:
7481 return parseInvoke(Inst, PFS);
7482 case lltok::kw_resume:
7483 return parseResume(Inst, PFS);
7484 case lltok::kw_cleanupret:
7485 return parseCleanupRet(Inst, PFS);
7486 case lltok::kw_catchret:
7487 return parseCatchRet(Inst, PFS);
7488 case lltok::kw_catchswitch:
7489 return parseCatchSwitch(Inst, PFS);
7490 case lltok::kw_catchpad:
7491 return parseCatchPad(Inst, PFS);
7492 case lltok::kw_cleanuppad:
7493 return parseCleanupPad(Inst, PFS);
7494 case lltok::kw_callbr:
7495 return parseCallBr(Inst, PFS);
7496 // Unary Operators.
7497 case lltok::kw_fneg: {
7498 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7499 int Res = parseUnaryOp(Inst, PFS, Opc: KeywordVal, /*IsFP*/ true);
7500 if (Res != 0)
7501 return Res;
7502 if (FMF.any())
7503 Inst->setFastMathFlags(FMF);
7504 return false;
7505 }
7506 // Binary Operators.
7507 case lltok::kw_add:
7508 case lltok::kw_sub:
7509 case lltok::kw_mul:
7510 case lltok::kw_shl: {
7511 bool NUW = EatIfPresent(T: lltok::kw_nuw);
7512 bool NSW = EatIfPresent(T: lltok::kw_nsw);
7513 if (!NUW) NUW = EatIfPresent(T: lltok::kw_nuw);
7514
7515 if (parseArithmetic(Inst, PFS, Opc: KeywordVal, /*IsFP*/ false))
7516 return true;
7517
7518 if (NUW) cast<BinaryOperator>(Val: Inst)->setHasNoUnsignedWrap(true);
7519 if (NSW) cast<BinaryOperator>(Val: Inst)->setHasNoSignedWrap(true);
7520 return false;
7521 }
7522 case lltok::kw_fadd:
7523 case lltok::kw_fsub:
7524 case lltok::kw_fmul:
7525 case lltok::kw_fdiv:
7526 case lltok::kw_frem: {
7527 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7528 int Res = parseArithmetic(Inst, PFS, Opc: KeywordVal, /*IsFP*/ true);
7529 if (Res != 0)
7530 return Res;
7531 if (FMF.any())
7532 Inst->setFastMathFlags(FMF);
7533 return 0;
7534 }
7535
7536 case lltok::kw_sdiv:
7537 case lltok::kw_udiv:
7538 case lltok::kw_lshr:
7539 case lltok::kw_ashr: {
7540 bool Exact = EatIfPresent(T: lltok::kw_exact);
7541
7542 if (parseArithmetic(Inst, PFS, Opc: KeywordVal, /*IsFP*/ false))
7543 return true;
7544 if (Exact) cast<BinaryOperator>(Val: Inst)->setIsExact(true);
7545 return false;
7546 }
7547
7548 case lltok::kw_urem:
7549 case lltok::kw_srem:
7550 return parseArithmetic(Inst, PFS, Opc: KeywordVal,
7551 /*IsFP*/ false);
7552 case lltok::kw_or: {
7553 bool Disjoint = EatIfPresent(T: lltok::kw_disjoint);
7554 if (parseLogical(Inst, PFS, Opc: KeywordVal))
7555 return true;
7556 if (Disjoint)
7557 cast<PossiblyDisjointInst>(Val: Inst)->setIsDisjoint(true);
7558 return false;
7559 }
7560 case lltok::kw_and:
7561 case lltok::kw_xor:
7562 return parseLogical(Inst, PFS, Opc: KeywordVal);
7563 case lltok::kw_icmp: {
7564 bool SameSign = EatIfPresent(T: lltok::kw_samesign);
7565 if (parseCompare(Inst, PFS, Opc: KeywordVal))
7566 return true;
7567 if (SameSign)
7568 cast<ICmpInst>(Val: Inst)->setSameSign();
7569 return false;
7570 }
7571 case lltok::kw_fcmp: {
7572 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7573 int Res = parseCompare(Inst, PFS, Opc: KeywordVal);
7574 if (Res != 0)
7575 return Res;
7576 if (FMF.any())
7577 Inst->setFastMathFlags(FMF);
7578 return 0;
7579 }
7580
7581 // Casts.
7582 case lltok::kw_uitofp:
7583 case lltok::kw_zext: {
7584 bool NonNeg = EatIfPresent(T: lltok::kw_nneg);
7585 bool Res = parseCast(Inst, PFS, Opc: KeywordVal);
7586 if (Res != 0)
7587 return Res;
7588 if (NonNeg)
7589 Inst->setNonNeg();
7590 return 0;
7591 }
7592 case lltok::kw_trunc: {
7593 bool NUW = EatIfPresent(T: lltok::kw_nuw);
7594 bool NSW = EatIfPresent(T: lltok::kw_nsw);
7595 if (!NUW)
7596 NUW = EatIfPresent(T: lltok::kw_nuw);
7597 if (parseCast(Inst, PFS, Opc: KeywordVal))
7598 return true;
7599 if (NUW)
7600 cast<TruncInst>(Val: Inst)->setHasNoUnsignedWrap(true);
7601 if (NSW)
7602 cast<TruncInst>(Val: Inst)->setHasNoSignedWrap(true);
7603 return false;
7604 }
7605 case lltok::kw_sext:
7606 case lltok::kw_bitcast:
7607 case lltok::kw_addrspacecast:
7608 case lltok::kw_sitofp:
7609 case lltok::kw_fptoui:
7610 case lltok::kw_fptosi:
7611 case lltok::kw_inttoptr:
7612 case lltok::kw_ptrtoaddr:
7613 case lltok::kw_ptrtoint:
7614 return parseCast(Inst, PFS, Opc: KeywordVal);
7615 case lltok::kw_fptrunc:
7616 case lltok::kw_fpext: {
7617 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7618 if (parseCast(Inst, PFS, Opc: KeywordVal))
7619 return true;
7620 if (FMF.any())
7621 Inst->setFastMathFlags(FMF);
7622 return false;
7623 }
7624
7625 // Other.
7626 case lltok::kw_select: {
7627 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7628 int Res = parseSelect(Inst, PFS);
7629 if (Res != 0)
7630 return Res;
7631 if (FMF.any()) {
7632 if (!isa<FPMathOperator>(Val: Inst))
7633 return error(L: Loc, Msg: "fast-math-flags specified for select without "
7634 "floating-point scalar or vector return type");
7635 Inst->setFastMathFlags(FMF);
7636 }
7637 return 0;
7638 }
7639 case lltok::kw_va_arg:
7640 return parseVAArg(Inst, PFS);
7641 case lltok::kw_extractelement:
7642 return parseExtractElement(Inst, PFS);
7643 case lltok::kw_insertelement:
7644 return parseInsertElement(Inst, PFS);
7645 case lltok::kw_shufflevector:
7646 return parseShuffleVector(Inst, PFS);
7647 case lltok::kw_phi: {
7648 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7649 int Res = parsePHI(Inst, PFS);
7650 if (Res != 0)
7651 return Res;
7652 if (FMF.any()) {
7653 if (!isa<FPMathOperator>(Val: Inst))
7654 return error(L: Loc, Msg: "fast-math-flags specified for phi without "
7655 "floating-point scalar or vector return type");
7656 Inst->setFastMathFlags(FMF);
7657 }
7658 return 0;
7659 }
7660 case lltok::kw_landingpad:
7661 return parseLandingPad(Inst, PFS);
7662 case lltok::kw_freeze:
7663 return parseFreeze(I&: Inst, PFS);
7664 // Call.
7665 case lltok::kw_call:
7666 return parseCall(Inst, PFS, TCK: CallInst::TCK_None);
7667 case lltok::kw_tail:
7668 return parseCall(Inst, PFS, TCK: CallInst::TCK_Tail);
7669 case lltok::kw_musttail:
7670 return parseCall(Inst, PFS, TCK: CallInst::TCK_MustTail);
7671 case lltok::kw_notail:
7672 return parseCall(Inst, PFS, TCK: CallInst::TCK_NoTail);
7673 // Memory.
7674 case lltok::kw_alloca:
7675 return parseAlloc(Inst, PFS);
7676 case lltok::kw_load:
7677 return parseLoad(Inst, PFS);
7678 case lltok::kw_store:
7679 return parseStore(Inst, PFS);
7680 case lltok::kw_cmpxchg:
7681 return parseCmpXchg(Inst, PFS);
7682 case lltok::kw_atomicrmw:
7683 return parseAtomicRMW(Inst, PFS);
7684 case lltok::kw_fence:
7685 return parseFence(Inst, PFS);
7686 case lltok::kw_getelementptr:
7687 return parseGetElementPtr(Inst, PFS);
7688 case lltok::kw_extractvalue:
7689 return parseExtractValue(Inst, PFS);
7690 case lltok::kw_insertvalue:
7691 return parseInsertValue(Inst, PFS);
7692 }
7693}
7694
7695/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7696bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7697 if (Opc == Instruction::FCmp) {
7698 switch (Lex.getKind()) {
7699 default:
7700 return tokError(Msg: "expected fcmp predicate (e.g. 'oeq')");
7701 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7702 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7703 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7704 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7705 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7706 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7707 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7708 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7709 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7710 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7711 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7712 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7713 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7714 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7715 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7716 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7717 }
7718 } else {
7719 switch (Lex.getKind()) {
7720 default:
7721 return tokError(Msg: "expected icmp predicate (e.g. 'eq')");
7722 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7723 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7724 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7725 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7726 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7727 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7728 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7729 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7730 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7731 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7732 }
7733 }
7734 Lex.Lex();
7735 return false;
7736}
7737
7738//===----------------------------------------------------------------------===//
7739// Terminator Instructions.
7740//===----------------------------------------------------------------------===//
7741
7742/// parseRet - parse a return instruction.
7743/// ::= 'ret' void (',' !dbg, !1)*
7744/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7745bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7746 PerFunctionState &PFS) {
7747 SMLoc TypeLoc = Lex.getLoc();
7748 Type *Ty = nullptr;
7749 if (parseType(Result&: Ty, AllowVoid: true /*void allowed*/))
7750 return true;
7751
7752 Type *ResType = PFS.getFunction().getReturnType();
7753
7754 if (Ty->isVoidTy()) {
7755 if (!ResType->isVoidTy())
7756 return error(L: TypeLoc, Msg: "value doesn't match function result type '" +
7757 getTypeString(T: ResType) + "'");
7758
7759 Inst = ReturnInst::Create(C&: Context);
7760 return false;
7761 }
7762
7763 Value *RV;
7764 if (parseValue(Ty, V&: RV, PFS))
7765 return true;
7766
7767 if (ResType != RV->getType())
7768 return error(L: TypeLoc, Msg: "value doesn't match function result type '" +
7769 getTypeString(T: ResType) + "'");
7770
7771 Inst = ReturnInst::Create(C&: Context, retVal: RV);
7772 return false;
7773}
7774
7775/// parseBr
7776/// ::= 'br' TypeAndValue
7777/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7778bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7779 LocTy Loc, Loc2;
7780 Value *Op0;
7781 BasicBlock *Op1, *Op2;
7782 if (parseTypeAndValue(V&: Op0, Loc, PFS))
7783 return true;
7784
7785 if (BasicBlock *BB = dyn_cast<BasicBlock>(Val: Op0)) {
7786 Inst = UncondBrInst::Create(IfTrue: BB);
7787 return false;
7788 }
7789
7790 if (Op0->getType() != Type::getInt1Ty(C&: Context))
7791 return error(L: Loc, Msg: "branch condition must have 'i1' type");
7792
7793 if (parseToken(T: lltok::comma, ErrMsg: "expected ',' after branch condition") ||
7794 parseTypeAndBasicBlock(BB&: Op1, Loc, PFS) ||
7795 parseToken(T: lltok::comma, ErrMsg: "expected ',' after true destination") ||
7796 parseTypeAndBasicBlock(BB&: Op2, Loc&: Loc2, PFS))
7797 return true;
7798
7799 Inst = CondBrInst::Create(Cond: Op0, IfTrue: Op1, IfFalse: Op2);
7800 return false;
7801}
7802
7803/// parseSwitch
7804/// Instruction
7805/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7806/// JumpTable
7807/// ::= (TypeAndValue ',' TypeAndValue)*
7808bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7809 LocTy CondLoc, BBLoc;
7810 Value *Cond;
7811 BasicBlock *DefaultBB;
7812 if (parseTypeAndValue(V&: Cond, Loc&: CondLoc, PFS) ||
7813 parseToken(T: lltok::comma, ErrMsg: "expected ',' after switch condition") ||
7814 parseTypeAndBasicBlock(BB&: DefaultBB, Loc&: BBLoc, PFS) ||
7815 parseToken(T: lltok::lsquare, ErrMsg: "expected '[' with switch table"))
7816 return true;
7817
7818 if (!Cond->getType()->isIntegerTy())
7819 return error(L: CondLoc, Msg: "switch condition must have integer type");
7820
7821 // parse the jump table pairs.
7822 SmallPtrSet<Value*, 32> SeenCases;
7823 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
7824 while (Lex.getKind() != lltok::rsquare) {
7825 Value *Constant;
7826 BasicBlock *DestBB;
7827
7828 if (parseTypeAndValue(V&: Constant, Loc&: CondLoc, PFS) ||
7829 parseToken(T: lltok::comma, ErrMsg: "expected ',' after case value") ||
7830 parseTypeAndBasicBlock(BB&: DestBB, PFS))
7831 return true;
7832
7833 if (!SeenCases.insert(Ptr: Constant).second)
7834 return error(L: CondLoc, Msg: "duplicate case value in switch");
7835 if (!isa<ConstantInt>(Val: Constant))
7836 return error(L: CondLoc, Msg: "case value is not a constant integer");
7837
7838 Table.push_back(Elt: std::make_pair(x: cast<ConstantInt>(Val: Constant), y&: DestBB));
7839 }
7840
7841 Lex.Lex(); // Eat the ']'.
7842
7843 SwitchInst *SI = SwitchInst::Create(Value: Cond, Default: DefaultBB, NumCases: Table.size());
7844 for (const auto &[OnVal, Dest] : Table)
7845 SI->addCase(OnVal, Dest);
7846 Inst = SI;
7847 return false;
7848}
7849
7850/// parseIndirectBr
7851/// Instruction
7852/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7853bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7854 LocTy AddrLoc;
7855 Value *Address;
7856 if (parseTypeAndValue(V&: Address, Loc&: AddrLoc, PFS) ||
7857 parseToken(T: lltok::comma, ErrMsg: "expected ',' after indirectbr address") ||
7858 parseToken(T: lltok::lsquare, ErrMsg: "expected '[' with indirectbr"))
7859 return true;
7860
7861 if (!Address->getType()->isPointerTy())
7862 return error(L: AddrLoc, Msg: "indirectbr address must have pointer type");
7863
7864 // parse the destination list.
7865 SmallVector<BasicBlock*, 16> DestList;
7866
7867 if (Lex.getKind() != lltok::rsquare) {
7868 BasicBlock *DestBB;
7869 if (parseTypeAndBasicBlock(BB&: DestBB, PFS))
7870 return true;
7871 DestList.push_back(Elt: DestBB);
7872
7873 while (EatIfPresent(T: lltok::comma)) {
7874 if (parseTypeAndBasicBlock(BB&: DestBB, PFS))
7875 return true;
7876 DestList.push_back(Elt: DestBB);
7877 }
7878 }
7879
7880 if (parseToken(T: lltok::rsquare, ErrMsg: "expected ']' at end of block list"))
7881 return true;
7882
7883 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests: DestList.size());
7884 for (BasicBlock *Dest : DestList)
7885 IBI->addDestination(Dest);
7886 Inst = IBI;
7887 return false;
7888}
7889
7890// If RetType is a non-function pointer type, then this is the short syntax
7891// for the call, which means that RetType is just the return type. Infer the
7892// rest of the function argument types from the arguments that are present.
7893bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7894 FunctionType *&FuncTy) {
7895 FuncTy = dyn_cast<FunctionType>(Val: RetType);
7896 if (!FuncTy) {
7897 // Pull out the types of all of the arguments...
7898 SmallVector<Type *, 8> ParamTypes;
7899 ParamTypes.reserve(N: ArgList.size());
7900 for (const ParamInfo &Arg : ArgList)
7901 ParamTypes.push_back(Elt: Arg.V->getType());
7902
7903 if (!FunctionType::isValidReturnType(RetTy: RetType))
7904 return true;
7905
7906 FuncTy = FunctionType::get(Result: RetType, Params: ParamTypes, isVarArg: false);
7907 }
7908 return false;
7909}
7910
7911/// parseInvoke
7912/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7913/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7914bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7915 LocTy CallLoc = Lex.getLoc();
7916 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7917 std::vector<unsigned> FwdRefAttrGrps;
7918 LocTy NoBuiltinLoc;
7919 unsigned CC;
7920 unsigned InvokeAddrSpace;
7921 Type *RetType = nullptr;
7922 LocTy RetTypeLoc;
7923 ValID CalleeID;
7924 SmallVector<ParamInfo, 16> ArgList;
7925 SmallVector<OperandBundleDef, 2> BundleList;
7926
7927 BasicBlock *NormalBB, *UnwindBB;
7928 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(B&: RetAttrs) ||
7929 parseOptionalProgramAddrSpace(AddrSpace&: InvokeAddrSpace) ||
7930 parseType(Result&: RetType, Loc&: RetTypeLoc, AllowVoid: true /*void allowed*/) ||
7931 parseValID(ID&: CalleeID, PFS: &PFS) || parseParameterList(ArgList, PFS) ||
7932 parseFnAttributeValuePairs(B&: FnAttrs, FwdRefAttrGrps, InAttrGrp: false,
7933 BuiltinLoc&: NoBuiltinLoc) ||
7934 parseOptionalOperandBundles(BundleList, PFS) ||
7935 parseToken(T: lltok::kw_to, ErrMsg: "expected 'to' in invoke") ||
7936 parseTypeAndBasicBlock(BB&: NormalBB, PFS) ||
7937 parseToken(T: lltok::kw_unwind, ErrMsg: "expected 'unwind' in invoke") ||
7938 parseTypeAndBasicBlock(BB&: UnwindBB, PFS))
7939 return true;
7940
7941 // If RetType is a non-function pointer type, then this is the short syntax
7942 // for the call, which means that RetType is just the return type. Infer the
7943 // rest of the function argument types from the arguments that are present.
7944 FunctionType *Ty;
7945 if (resolveFunctionType(RetType, ArgList, FuncTy&: Ty))
7946 return error(L: RetTypeLoc, Msg: "Invalid result type for LLVM function");
7947
7948 CalleeID.FTy = Ty;
7949
7950 // Look up the callee.
7951 Value *Callee;
7952 if (convertValIDToValue(Ty: PointerType::get(C&: Context, AddressSpace: InvokeAddrSpace), ID&: CalleeID,
7953 V&: Callee, PFS: &PFS))
7954 return true;
7955
7956 // Set up the Attribute for the function.
7957 SmallVector<Value *, 8> Args;
7958 SmallVector<AttributeSet, 8> ArgAttrs;
7959
7960 // Loop through FunctionType's arguments and ensure they are specified
7961 // correctly. Also, gather any parameter attributes.
7962 FunctionType::param_iterator I = Ty->param_begin();
7963 FunctionType::param_iterator E = Ty->param_end();
7964 for (const ParamInfo &Arg : ArgList) {
7965 Type *ExpectedTy = nullptr;
7966 if (I != E) {
7967 ExpectedTy = *I++;
7968 } else if (!Ty->isVarArg()) {
7969 return error(L: Arg.Loc, Msg: "too many arguments specified");
7970 }
7971
7972 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7973 return error(L: Arg.Loc, Msg: "argument is not of expected type '" +
7974 getTypeString(T: ExpectedTy) + "'");
7975 Args.push_back(Elt: Arg.V);
7976 ArgAttrs.push_back(Elt: Arg.Attrs);
7977 }
7978
7979 if (I != E)
7980 return error(L: CallLoc, Msg: "not enough parameters specified for call");
7981
7982 // Finish off the Attribute and check them
7983 AttributeList PAL =
7984 AttributeList::get(C&: Context, FnAttrs: AttributeSet::get(C&: Context, B: FnAttrs),
7985 RetAttrs: AttributeSet::get(C&: Context, B: RetAttrs), ArgAttrs);
7986
7987 InvokeInst *II =
7988 InvokeInst::Create(Ty, Func: Callee, IfNormal: NormalBB, IfException: UnwindBB, Args, Bundles: BundleList);
7989 II->setCallingConv(CC);
7990 II->setAttributes(PAL);
7991 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7992 Inst = II;
7993 return false;
7994}
7995
7996/// parseResume
7997/// ::= 'resume' TypeAndValue
7998bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7999 Value *Exn; LocTy ExnLoc;
8000 if (parseTypeAndValue(V&: Exn, Loc&: ExnLoc, PFS))
8001 return true;
8002
8003 ResumeInst *RI = ResumeInst::Create(Exn);
8004 Inst = RI;
8005 return false;
8006}
8007
8008bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8009 PerFunctionState &PFS) {
8010 if (parseToken(T: lltok::lsquare, ErrMsg: "expected '[' in catchpad/cleanuppad"))
8011 return true;
8012
8013 while (Lex.getKind() != lltok::rsquare) {
8014 // If this isn't the first argument, we need a comma.
8015 if (!Args.empty() &&
8016 parseToken(T: lltok::comma, ErrMsg: "expected ',' in argument list"))
8017 return true;
8018
8019 // parse the argument.
8020 LocTy ArgLoc;
8021 Type *ArgTy = nullptr;
8022 if (parseType(Result&: ArgTy, Loc&: ArgLoc))
8023 return true;
8024
8025 Value *V;
8026 if (ArgTy->isMetadataTy()) {
8027 if (parseMetadataAsValue(V, PFS))
8028 return true;
8029 } else {
8030 if (parseValue(Ty: ArgTy, V, PFS))
8031 return true;
8032 }
8033 Args.push_back(Elt: V);
8034 }
8035
8036 Lex.Lex(); // Lex the ']'.
8037 return false;
8038}
8039
8040/// parseCleanupRet
8041/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
8042bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8043 Value *CleanupPad = nullptr;
8044
8045 if (parseToken(T: lltok::kw_from, ErrMsg: "expected 'from' after cleanupret"))
8046 return true;
8047
8048 if (parseValue(Ty: Type::getTokenTy(C&: Context), V&: CleanupPad, PFS))
8049 return true;
8050
8051 if (parseToken(T: lltok::kw_unwind, ErrMsg: "expected 'unwind' in cleanupret"))
8052 return true;
8053
8054 BasicBlock *UnwindBB = nullptr;
8055 if (Lex.getKind() == lltok::kw_to) {
8056 Lex.Lex();
8057 if (parseToken(T: lltok::kw_caller, ErrMsg: "expected 'caller' in cleanupret"))
8058 return true;
8059 } else {
8060 if (parseTypeAndBasicBlock(BB&: UnwindBB, PFS)) {
8061 return true;
8062 }
8063 }
8064
8065 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
8066 return false;
8067}
8068
8069/// parseCatchRet
8070/// ::= 'catchret' from Parent Value 'to' TypeAndValue
8071bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8072 Value *CatchPad = nullptr;
8073
8074 if (parseToken(T: lltok::kw_from, ErrMsg: "expected 'from' after catchret"))
8075 return true;
8076
8077 if (parseValue(Ty: Type::getTokenTy(C&: Context), V&: CatchPad, PFS))
8078 return true;
8079
8080 BasicBlock *BB;
8081 if (parseToken(T: lltok::kw_to, ErrMsg: "expected 'to' in catchret") ||
8082 parseTypeAndBasicBlock(BB, PFS))
8083 return true;
8084
8085 Inst = CatchReturnInst::Create(CatchPad, BB);
8086 return false;
8087}
8088
8089/// parseCatchSwitch
8090/// ::= 'catchswitch' within Parent
8091bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8092 Value *ParentPad;
8093
8094 if (parseToken(T: lltok::kw_within, ErrMsg: "expected 'within' after catchswitch"))
8095 return true;
8096
8097 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8098 Lex.getKind() != lltok::LocalVarID)
8099 return tokError(Msg: "expected scope value for catchswitch");
8100
8101 if (parseValue(Ty: Type::getTokenTy(C&: Context), V&: ParentPad, PFS))
8102 return true;
8103
8104 if (parseToken(T: lltok::lsquare, ErrMsg: "expected '[' with catchswitch labels"))
8105 return true;
8106
8107 SmallVector<BasicBlock *, 32> Table;
8108 do {
8109 BasicBlock *DestBB;
8110 if (parseTypeAndBasicBlock(BB&: DestBB, PFS))
8111 return true;
8112 Table.push_back(Elt: DestBB);
8113 } while (EatIfPresent(T: lltok::comma));
8114
8115 if (parseToken(T: lltok::rsquare, ErrMsg: "expected ']' after catchswitch labels"))
8116 return true;
8117
8118 if (parseToken(T: lltok::kw_unwind, ErrMsg: "expected 'unwind' after catchswitch scope"))
8119 return true;
8120
8121 BasicBlock *UnwindBB = nullptr;
8122 if (EatIfPresent(T: lltok::kw_to)) {
8123 if (parseToken(T: lltok::kw_caller, ErrMsg: "expected 'caller' in catchswitch"))
8124 return true;
8125 } else {
8126 if (parseTypeAndBasicBlock(BB&: UnwindBB, PFS))
8127 return true;
8128 }
8129
8130 auto *CatchSwitch =
8131 CatchSwitchInst::Create(ParentPad, UnwindDest: UnwindBB, NumHandlers: Table.size());
8132 for (BasicBlock *DestBB : Table)
8133 CatchSwitch->addHandler(Dest: DestBB);
8134 Inst = CatchSwitch;
8135 return false;
8136}
8137
8138/// parseCatchPad
8139/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
8140bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8141 Value *CatchSwitch = nullptr;
8142
8143 if (parseToken(T: lltok::kw_within, ErrMsg: "expected 'within' after catchpad"))
8144 return true;
8145
8146 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
8147 return tokError(Msg: "expected scope value for catchpad");
8148
8149 if (parseValue(Ty: Type::getTokenTy(C&: Context), V&: CatchSwitch, PFS))
8150 return true;
8151
8152 SmallVector<Value *, 8> Args;
8153 if (parseExceptionArgs(Args, PFS))
8154 return true;
8155
8156 Inst = CatchPadInst::Create(CatchSwitch, Args);
8157 return false;
8158}
8159
8160/// parseCleanupPad
8161/// ::= 'cleanuppad' within Parent ParamList
8162bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8163 Value *ParentPad = nullptr;
8164
8165 if (parseToken(T: lltok::kw_within, ErrMsg: "expected 'within' after cleanuppad"))
8166 return true;
8167
8168 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8169 Lex.getKind() != lltok::LocalVarID)
8170 return tokError(Msg: "expected scope value for cleanuppad");
8171
8172 if (parseValue(Ty: Type::getTokenTy(C&: Context), V&: ParentPad, PFS))
8173 return true;
8174
8175 SmallVector<Value *, 8> Args;
8176 if (parseExceptionArgs(Args, PFS))
8177 return true;
8178
8179 Inst = CleanupPadInst::Create(ParentPad, Args);
8180 return false;
8181}
8182
8183//===----------------------------------------------------------------------===//
8184// Unary Operators.
8185//===----------------------------------------------------------------------===//
8186
8187/// parseUnaryOp
8188/// ::= UnaryOp TypeAndValue ',' Value
8189///
8190/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8191/// operand is allowed.
8192bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8193 unsigned Opc, bool IsFP) {
8194 LocTy Loc; Value *LHS;
8195 if (parseTypeAndValue(V&: LHS, Loc, PFS))
8196 return true;
8197
8198 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8199 : LHS->getType()->isIntOrIntVectorTy();
8200
8201 if (!Valid)
8202 return error(L: Loc, Msg: "invalid operand type for instruction");
8203
8204 Inst = UnaryOperator::Create(Op: (Instruction::UnaryOps)Opc, S: LHS);
8205 return false;
8206}
8207
8208/// parseCallBr
8209/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8210/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8211/// '[' LabelList ']'
8212bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8213 LocTy CallLoc = Lex.getLoc();
8214 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8215 std::vector<unsigned> FwdRefAttrGrps;
8216 LocTy NoBuiltinLoc;
8217 unsigned CC;
8218 Type *RetType = nullptr;
8219 LocTy RetTypeLoc;
8220 ValID CalleeID;
8221 SmallVector<ParamInfo, 16> ArgList;
8222 SmallVector<OperandBundleDef, 2> BundleList;
8223
8224 BasicBlock *DefaultDest;
8225 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(B&: RetAttrs) ||
8226 parseType(Result&: RetType, Loc&: RetTypeLoc, AllowVoid: true /*void allowed*/) ||
8227 parseValID(ID&: CalleeID, PFS: &PFS) || parseParameterList(ArgList, PFS) ||
8228 parseFnAttributeValuePairs(B&: FnAttrs, FwdRefAttrGrps, InAttrGrp: false,
8229 BuiltinLoc&: NoBuiltinLoc) ||
8230 parseOptionalOperandBundles(BundleList, PFS) ||
8231 parseToken(T: lltok::kw_to, ErrMsg: "expected 'to' in callbr") ||
8232 parseTypeAndBasicBlock(BB&: DefaultDest, PFS) ||
8233 parseToken(T: lltok::lsquare, ErrMsg: "expected '[' in callbr"))
8234 return true;
8235
8236 // parse the destination list.
8237 SmallVector<BasicBlock *, 16> IndirectDests;
8238
8239 if (Lex.getKind() != lltok::rsquare) {
8240 BasicBlock *DestBB;
8241 if (parseTypeAndBasicBlock(BB&: DestBB, PFS))
8242 return true;
8243 IndirectDests.push_back(Elt: DestBB);
8244
8245 while (EatIfPresent(T: lltok::comma)) {
8246 if (parseTypeAndBasicBlock(BB&: DestBB, PFS))
8247 return true;
8248 IndirectDests.push_back(Elt: DestBB);
8249 }
8250 }
8251
8252 if (parseToken(T: lltok::rsquare, ErrMsg: "expected ']' at end of block list"))
8253 return true;
8254
8255 // If RetType is a non-function pointer type, then this is the short syntax
8256 // for the call, which means that RetType is just the return type. Infer the
8257 // rest of the function argument types from the arguments that are present.
8258 FunctionType *Ty;
8259 if (resolveFunctionType(RetType, ArgList, FuncTy&: Ty))
8260 return error(L: RetTypeLoc, Msg: "Invalid result type for LLVM function");
8261
8262 CalleeID.FTy = Ty;
8263
8264 // Look up the callee.
8265 Value *Callee;
8266 if (convertValIDToValue(Ty: PointerType::getUnqual(C&: Context), ID&: CalleeID, V&: Callee,
8267 PFS: &PFS))
8268 return true;
8269
8270 // Set up the Attribute for the function.
8271 SmallVector<Value *, 8> Args;
8272 SmallVector<AttributeSet, 8> ArgAttrs;
8273
8274 // Loop through FunctionType's arguments and ensure they are specified
8275 // correctly. Also, gather any parameter attributes.
8276 FunctionType::param_iterator I = Ty->param_begin();
8277 FunctionType::param_iterator E = Ty->param_end();
8278 for (const ParamInfo &Arg : ArgList) {
8279 Type *ExpectedTy = nullptr;
8280 if (I != E) {
8281 ExpectedTy = *I++;
8282 } else if (!Ty->isVarArg()) {
8283 return error(L: Arg.Loc, Msg: "too many arguments specified");
8284 }
8285
8286 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8287 return error(L: Arg.Loc, Msg: "argument is not of expected type '" +
8288 getTypeString(T: ExpectedTy) + "'");
8289 Args.push_back(Elt: Arg.V);
8290 ArgAttrs.push_back(Elt: Arg.Attrs);
8291 }
8292
8293 if (I != E)
8294 return error(L: CallLoc, Msg: "not enough parameters specified for call");
8295
8296 // Finish off the Attribute and check them
8297 AttributeList PAL =
8298 AttributeList::get(C&: Context, FnAttrs: AttributeSet::get(C&: Context, B: FnAttrs),
8299 RetAttrs: AttributeSet::get(C&: Context, B: RetAttrs), ArgAttrs);
8300
8301 CallBrInst *CBI =
8302 CallBrInst::Create(Ty, Func: Callee, DefaultDest, IndirectDests, Args,
8303 Bundles: BundleList);
8304 CBI->setCallingConv(CC);
8305 CBI->setAttributes(PAL);
8306 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8307 Inst = CBI;
8308 return false;
8309}
8310
8311//===----------------------------------------------------------------------===//
8312// Binary Operators.
8313//===----------------------------------------------------------------------===//
8314
8315/// parseArithmetic
8316/// ::= ArithmeticOps TypeAndValue ',' Value
8317///
8318/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8319/// operand is allowed.
8320bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8321 unsigned Opc, bool IsFP) {
8322 LocTy Loc; Value *LHS, *RHS;
8323 if (parseTypeAndValue(V&: LHS, Loc, PFS) ||
8324 parseToken(T: lltok::comma, ErrMsg: "expected ',' in arithmetic operation") ||
8325 parseValue(Ty: LHS->getType(), V&: RHS, PFS))
8326 return true;
8327
8328 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8329 : LHS->getType()->isIntOrIntVectorTy();
8330
8331 if (!Valid)
8332 return error(L: Loc, Msg: "invalid operand type for instruction");
8333
8334 Inst = BinaryOperator::Create(Op: (Instruction::BinaryOps)Opc, S1: LHS, S2: RHS);
8335 return false;
8336}
8337
8338/// parseLogical
8339/// ::= ArithmeticOps TypeAndValue ',' Value {
8340bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8341 unsigned Opc) {
8342 LocTy Loc; Value *LHS, *RHS;
8343 if (parseTypeAndValue(V&: LHS, Loc, PFS) ||
8344 parseToken(T: lltok::comma, ErrMsg: "expected ',' in logical operation") ||
8345 parseValue(Ty: LHS->getType(), V&: RHS, PFS))
8346 return true;
8347
8348 if (!LHS->getType()->isIntOrIntVectorTy())
8349 return error(L: Loc,
8350 Msg: "instruction requires integer or integer vector operands");
8351
8352 Inst = BinaryOperator::Create(Op: (Instruction::BinaryOps)Opc, S1: LHS, S2: RHS);
8353 return false;
8354}
8355
8356/// parseCompare
8357/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8358/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8359bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8360 unsigned Opc) {
8361 // parse the integer/fp comparison predicate.
8362 LocTy Loc;
8363 unsigned Pred;
8364 Value *LHS, *RHS;
8365 if (parseCmpPredicate(P&: Pred, Opc) || parseTypeAndValue(V&: LHS, Loc, PFS) ||
8366 parseToken(T: lltok::comma, ErrMsg: "expected ',' after compare value") ||
8367 parseValue(Ty: LHS->getType(), V&: RHS, PFS))
8368 return true;
8369
8370 if (Opc == Instruction::FCmp) {
8371 if (!LHS->getType()->isFPOrFPVectorTy())
8372 return error(L: Loc, Msg: "fcmp requires floating point operands");
8373 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8374 } else {
8375 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8376 if (!LHS->getType()->isIntOrIntVectorTy() &&
8377 !LHS->getType()->isPtrOrPtrVectorTy())
8378 return error(L: Loc, Msg: "icmp requires integer operands");
8379 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8380 }
8381 return false;
8382}
8383
8384//===----------------------------------------------------------------------===//
8385// Other Instructions.
8386//===----------------------------------------------------------------------===//
8387
8388/// parseCast
8389/// ::= CastOpc TypeAndValue 'to' Type
8390bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8391 unsigned Opc) {
8392 LocTy Loc;
8393 Value *Op;
8394 Type *DestTy = nullptr;
8395 if (parseTypeAndValue(V&: Op, Loc, PFS) ||
8396 parseToken(T: lltok::kw_to, ErrMsg: "expected 'to' after cast value") ||
8397 parseType(Result&: DestTy))
8398 return true;
8399
8400 if (!CastInst::castIsValid(op: (Instruction::CastOps)Opc, S: Op, DstTy: DestTy))
8401 return error(L: Loc, Msg: "invalid cast opcode for cast from '" +
8402 getTypeString(T: Op->getType()) + "' to '" +
8403 getTypeString(T: DestTy) + "'");
8404 Inst = CastInst::Create((Instruction::CastOps)Opc, S: Op, Ty: DestTy);
8405 return false;
8406}
8407
8408/// parseSelect
8409/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8410bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8411 LocTy Loc;
8412 Value *Op0, *Op1, *Op2;
8413 if (parseTypeAndValue(V&: Op0, Loc, PFS) ||
8414 parseToken(T: lltok::comma, ErrMsg: "expected ',' after select condition") ||
8415 parseTypeAndValue(V&: Op1, PFS) ||
8416 parseToken(T: lltok::comma, ErrMsg: "expected ',' after select value") ||
8417 parseTypeAndValue(V&: Op2, PFS))
8418 return true;
8419
8420 if (const char *Reason = SelectInst::areInvalidOperands(Cond: Op0, True: Op1, False: Op2))
8421 return error(L: Loc, Msg: Reason);
8422
8423 Inst = SelectInst::Create(C: Op0, S1: Op1, S2: Op2);
8424 return false;
8425}
8426
8427/// parseVAArg
8428/// ::= 'va_arg' TypeAndValue ',' Type
8429bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8430 Value *Op;
8431 Type *EltTy = nullptr;
8432 LocTy TypeLoc;
8433 if (parseTypeAndValue(V&: Op, PFS) ||
8434 parseToken(T: lltok::comma, ErrMsg: "expected ',' after vaarg operand") ||
8435 parseType(Result&: EltTy, Loc&: TypeLoc))
8436 return true;
8437
8438 if (!EltTy->isFirstClassType())
8439 return error(L: TypeLoc, Msg: "va_arg requires operand with first class type");
8440
8441 Inst = new VAArgInst(Op, EltTy);
8442 return false;
8443}
8444
8445/// parseExtractElement
8446/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8447bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8448 LocTy Loc;
8449 Value *Op0, *Op1;
8450 if (parseTypeAndValue(V&: Op0, Loc, PFS) ||
8451 parseToken(T: lltok::comma, ErrMsg: "expected ',' after extract value") ||
8452 parseTypeAndValue(V&: Op1, PFS))
8453 return true;
8454
8455 if (!ExtractElementInst::isValidOperands(Vec: Op0, Idx: Op1))
8456 return error(L: Loc, Msg: "invalid extractelement operands");
8457
8458 Inst = ExtractElementInst::Create(Vec: Op0, Idx: Op1);
8459 return false;
8460}
8461
8462/// parseInsertElement
8463/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8464bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8465 LocTy Loc;
8466 Value *Op0, *Op1, *Op2;
8467 if (parseTypeAndValue(V&: Op0, Loc, PFS) ||
8468 parseToken(T: lltok::comma, ErrMsg: "expected ',' after insertelement value") ||
8469 parseTypeAndValue(V&: Op1, PFS) ||
8470 parseToken(T: lltok::comma, ErrMsg: "expected ',' after insertelement value") ||
8471 parseTypeAndValue(V&: Op2, PFS))
8472 return true;
8473
8474 if (!InsertElementInst::isValidOperands(Vec: Op0, NewElt: Op1, Idx: Op2))
8475 return error(L: Loc, Msg: "invalid insertelement operands");
8476
8477 Inst = InsertElementInst::Create(Vec: Op0, NewElt: Op1, Idx: Op2);
8478 return false;
8479}
8480
8481/// parseShuffleVector
8482/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8483bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8484 LocTy Loc;
8485 Value *Op0, *Op1, *Op2;
8486 if (parseTypeAndValue(V&: Op0, Loc, PFS) ||
8487 parseToken(T: lltok::comma, ErrMsg: "expected ',' after shuffle mask") ||
8488 parseTypeAndValue(V&: Op1, PFS) ||
8489 parseToken(T: lltok::comma, ErrMsg: "expected ',' after shuffle value") ||
8490 parseTypeAndValue(V&: Op2, PFS))
8491 return true;
8492
8493 if (!ShuffleVectorInst::isValidOperands(V1: Op0, V2: Op1, Mask: Op2))
8494 return error(L: Loc, Msg: "invalid shufflevector operands");
8495
8496 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8497 return false;
8498}
8499
8500/// parsePHI
8501/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8502int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8503 Type *Ty = nullptr; LocTy TypeLoc;
8504 Value *Op0, *Op1;
8505
8506 if (parseType(Result&: Ty, Loc&: TypeLoc))
8507 return true;
8508
8509 if (!Ty->isFirstClassType())
8510 return error(L: TypeLoc, Msg: "phi node must have first class type");
8511
8512 bool First = true;
8513 bool AteExtraComma = false;
8514 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
8515
8516 while (true) {
8517 if (First) {
8518 if (Lex.getKind() != lltok::lsquare)
8519 break;
8520 First = false;
8521 } else if (!EatIfPresent(T: lltok::comma))
8522 break;
8523
8524 if (Lex.getKind() == lltok::MetadataVar) {
8525 AteExtraComma = true;
8526 break;
8527 }
8528
8529 if (parseToken(T: lltok::lsquare, ErrMsg: "expected '[' in phi value list") ||
8530 parseValue(Ty, V&: Op0, PFS) ||
8531 parseToken(T: lltok::comma, ErrMsg: "expected ',' after insertelement value") ||
8532 parseValue(Ty: Type::getLabelTy(C&: Context), V&: Op1, PFS) ||
8533 parseToken(T: lltok::rsquare, ErrMsg: "expected ']' in phi value list"))
8534 return true;
8535
8536 PHIVals.push_back(Elt: std::make_pair(x&: Op0, y: cast<BasicBlock>(Val: Op1)));
8537 }
8538
8539 PHINode *PN = PHINode::Create(Ty, NumReservedValues: PHIVals.size());
8540 for (const auto &[Val, BB] : PHIVals)
8541 PN->addIncoming(V: Val, BB);
8542 Inst = PN;
8543 return AteExtraComma ? InstExtraComma : InstNormal;
8544}
8545
8546/// parseLandingPad
8547/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8548/// Clause
8549/// ::= 'catch' TypeAndValue
8550/// ::= 'filter'
8551/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8552bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8553 Type *Ty = nullptr; LocTy TyLoc;
8554
8555 if (parseType(Result&: Ty, Loc&: TyLoc))
8556 return true;
8557
8558 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(RetTy: Ty, NumReservedClauses: 0));
8559 LP->setCleanup(EatIfPresent(T: lltok::kw_cleanup));
8560
8561 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8562 LandingPadInst::ClauseType CT;
8563 if (EatIfPresent(T: lltok::kw_catch))
8564 CT = LandingPadInst::Catch;
8565 else if (EatIfPresent(T: lltok::kw_filter))
8566 CT = LandingPadInst::Filter;
8567 else
8568 return tokError(Msg: "expected 'catch' or 'filter' clause type");
8569
8570 Value *V;
8571 LocTy VLoc;
8572 if (parseTypeAndValue(V, Loc&: VLoc, PFS))
8573 return true;
8574
8575 // A 'catch' type expects a non-array constant. A filter clause expects an
8576 // array constant.
8577 if (CT == LandingPadInst::Catch) {
8578 if (isa<ArrayType>(Val: V->getType()))
8579 return error(L: VLoc, Msg: "'catch' clause has an invalid type");
8580 } else {
8581 if (!isa<ArrayType>(Val: V->getType()))
8582 return error(L: VLoc, Msg: "'filter' clause has an invalid type");
8583 }
8584
8585 Constant *CV = dyn_cast<Constant>(Val: V);
8586 if (!CV)
8587 return error(L: VLoc, Msg: "clause argument must be a constant");
8588 LP->addClause(ClauseVal: CV);
8589 }
8590
8591 Inst = LP.release();
8592 return false;
8593}
8594
8595/// parseFreeze
8596/// ::= 'freeze' Type Value
8597bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8598 LocTy Loc;
8599 Value *Op;
8600 if (parseTypeAndValue(V&: Op, Loc, PFS))
8601 return true;
8602
8603 Inst = new FreezeInst(Op);
8604 return false;
8605}
8606
8607/// parseCall
8608/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8609/// OptionalAttrs Type Value ParameterList OptionalAttrs
8610/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8611/// OptionalAttrs Type Value ParameterList OptionalAttrs
8612/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8613/// OptionalAttrs Type Value ParameterList OptionalAttrs
8614/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8615/// OptionalAttrs Type Value ParameterList OptionalAttrs
8616bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8617 CallInst::TailCallKind TCK) {
8618 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8619 std::vector<unsigned> FwdRefAttrGrps;
8620 LocTy BuiltinLoc;
8621 unsigned CallAddrSpace;
8622 unsigned CC;
8623 Type *RetType = nullptr;
8624 LocTy RetTypeLoc;
8625 ValID CalleeID;
8626 SmallVector<ParamInfo, 16> ArgList;
8627 SmallVector<OperandBundleDef, 2> BundleList;
8628 LocTy CallLoc = Lex.getLoc();
8629
8630 if (TCK != CallInst::TCK_None &&
8631 parseToken(T: lltok::kw_call,
8632 ErrMsg: "expected 'tail call', 'musttail call', or 'notail call'"))
8633 return true;
8634
8635 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8636
8637 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(B&: RetAttrs) ||
8638 parseOptionalProgramAddrSpace(AddrSpace&: CallAddrSpace) ||
8639 parseType(Result&: RetType, Loc&: RetTypeLoc, AllowVoid: true /*void allowed*/) ||
8640 parseValID(ID&: CalleeID, PFS: &PFS) ||
8641 parseParameterList(ArgList, PFS, IsMustTailCall: TCK == CallInst::TCK_MustTail,
8642 InVarArgsFunc: PFS.getFunction().isVarArg()) ||
8643 parseFnAttributeValuePairs(B&: FnAttrs, FwdRefAttrGrps, InAttrGrp: false, BuiltinLoc) ||
8644 parseOptionalOperandBundles(BundleList, PFS))
8645 return true;
8646
8647 // If RetType is a non-function pointer type, then this is the short syntax
8648 // for the call, which means that RetType is just the return type. Infer the
8649 // rest of the function argument types from the arguments that are present.
8650 FunctionType *Ty;
8651 if (resolveFunctionType(RetType, ArgList, FuncTy&: Ty))
8652 return error(L: RetTypeLoc, Msg: "Invalid result type for LLVM function");
8653
8654 CalleeID.FTy = Ty;
8655
8656 // Look up the callee.
8657 Value *Callee;
8658 if (convertValIDToValue(Ty: PointerType::get(C&: Context, AddressSpace: CallAddrSpace), ID&: CalleeID,
8659 V&: Callee, PFS: &PFS))
8660 return true;
8661
8662 // Set up the Attribute for the function.
8663 SmallVector<AttributeSet, 8> Attrs;
8664
8665 SmallVector<Value*, 8> Args;
8666
8667 // Loop through FunctionType's arguments and ensure they are specified
8668 // correctly. Also, gather any parameter attributes.
8669 FunctionType::param_iterator I = Ty->param_begin();
8670 FunctionType::param_iterator E = Ty->param_end();
8671 for (const ParamInfo &Arg : ArgList) {
8672 Type *ExpectedTy = nullptr;
8673 if (I != E) {
8674 ExpectedTy = *I++;
8675 } else if (!Ty->isVarArg()) {
8676 return error(L: Arg.Loc, Msg: "too many arguments specified");
8677 }
8678
8679 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8680 return error(L: Arg.Loc, Msg: "argument is not of expected type '" +
8681 getTypeString(T: ExpectedTy) + "'");
8682 Args.push_back(Elt: Arg.V);
8683 Attrs.push_back(Elt: Arg.Attrs);
8684 }
8685
8686 if (I != E)
8687 return error(L: CallLoc, Msg: "not enough parameters specified for call");
8688
8689 // Finish off the Attribute and check them
8690 AttributeList PAL =
8691 AttributeList::get(C&: Context, FnAttrs: AttributeSet::get(C&: Context, B: FnAttrs),
8692 RetAttrs: AttributeSet::get(C&: Context, B: RetAttrs), ArgAttrs: Attrs);
8693
8694 CallInst *CI = CallInst::Create(Ty, Func: Callee, Args, Bundles: BundleList);
8695 CI->setTailCallKind(TCK);
8696 CI->setCallingConv(CC);
8697 if (FMF.any()) {
8698 if (!isa<FPMathOperator>(Val: CI)) {
8699 CI->deleteValue();
8700 return error(L: CallLoc, Msg: "fast-math-flags specified for call without "
8701 "floating-point scalar or vector return type");
8702 }
8703 CI->setFastMathFlags(FMF);
8704 }
8705
8706 if (CalleeID.Kind == ValID::t_GlobalName &&
8707 isOldDbgFormatIntrinsic(Name: CalleeID.StrVal)) {
8708 if (SeenNewDbgInfoFormat) {
8709 CI->deleteValue();
8710 return error(L: CallLoc, Msg: "llvm.dbg intrinsic should not appear in a module "
8711 "using non-intrinsic debug info");
8712 }
8713 SeenOldDbgInfoFormat = true;
8714 }
8715 CI->setAttributes(PAL);
8716 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8717 Inst = CI;
8718 return false;
8719}
8720
8721//===----------------------------------------------------------------------===//
8722// Memory Instructions.
8723//===----------------------------------------------------------------------===//
8724
8725/// parseAlloc
8726/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8727/// (',' 'align' i32)? (',', 'addrspace(n))?
8728int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8729 Value *Size = nullptr;
8730 LocTy SizeLoc, TyLoc, ASLoc;
8731 MaybeAlign Alignment;
8732 unsigned AddrSpace = 0;
8733 Type *Ty = nullptr;
8734
8735 bool IsInAlloca = EatIfPresent(T: lltok::kw_inalloca);
8736 bool IsSwiftError = EatIfPresent(T: lltok::kw_swifterror);
8737
8738 if (parseType(Result&: Ty, Loc&: TyLoc))
8739 return true;
8740
8741 if (Ty->isFunctionTy() || !PointerType::isValidElementType(ElemTy: Ty))
8742 return error(L: TyLoc, Msg: "invalid type for alloca");
8743
8744 bool AteExtraComma = false;
8745 if (EatIfPresent(T: lltok::comma)) {
8746 if (Lex.getKind() == lltok::kw_align) {
8747 if (parseOptionalAlignment(Alignment))
8748 return true;
8749 if (parseOptionalCommaAddrSpace(AddrSpace, Loc&: ASLoc, AteExtraComma))
8750 return true;
8751 } else if (Lex.getKind() == lltok::kw_addrspace) {
8752 ASLoc = Lex.getLoc();
8753 if (parseOptionalAddrSpace(AddrSpace))
8754 return true;
8755 } else if (Lex.getKind() == lltok::MetadataVar) {
8756 AteExtraComma = true;
8757 } else {
8758 if (parseTypeAndValue(V&: Size, Loc&: SizeLoc, PFS))
8759 return true;
8760 if (EatIfPresent(T: lltok::comma)) {
8761 if (Lex.getKind() == lltok::kw_align) {
8762 if (parseOptionalAlignment(Alignment))
8763 return true;
8764 if (parseOptionalCommaAddrSpace(AddrSpace, Loc&: ASLoc, AteExtraComma))
8765 return true;
8766 } else if (Lex.getKind() == lltok::kw_addrspace) {
8767 ASLoc = Lex.getLoc();
8768 if (parseOptionalAddrSpace(AddrSpace))
8769 return true;
8770 } else if (Lex.getKind() == lltok::MetadataVar) {
8771 AteExtraComma = true;
8772 }
8773 }
8774 }
8775 }
8776
8777 if (Size && !Size->getType()->isIntegerTy())
8778 return error(L: SizeLoc, Msg: "element count must have integer type");
8779
8780 SmallPtrSet<Type *, 4> Visited;
8781 if (!Alignment && !Ty->isSized(Visited: &Visited))
8782 return error(L: TyLoc, Msg: "Cannot allocate unsized type");
8783 if (!Alignment)
8784 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8785 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8786 AI->setUsedWithInAlloca(IsInAlloca);
8787 AI->setSwiftError(IsSwiftError);
8788 Inst = AI;
8789 return AteExtraComma ? InstExtraComma : InstNormal;
8790}
8791
8792/// parseLoad
8793/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8794/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8795/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8796int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8797 Value *Val; LocTy Loc;
8798 MaybeAlign Alignment;
8799 bool AteExtraComma = false;
8800 bool isAtomic = false;
8801 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
8802 SyncScope::ID SSID = SyncScope::System;
8803
8804 if (Lex.getKind() == lltok::kw_atomic) {
8805 isAtomic = true;
8806 Lex.Lex();
8807 }
8808
8809 bool isVolatile = false;
8810 if (Lex.getKind() == lltok::kw_volatile) {
8811 isVolatile = true;
8812 Lex.Lex();
8813 }
8814
8815 Type *Ty;
8816 LocTy ExplicitTypeLoc = Lex.getLoc();
8817 if (parseType(Result&: Ty) ||
8818 parseToken(T: lltok::comma, ErrMsg: "expected comma after load's type") ||
8819 parseTypeAndValue(V&: Val, Loc, PFS) ||
8820 parseScopeAndOrdering(IsAtomic: isAtomic, SSID, Ordering) ||
8821 parseOptionalCommaAlign(Alignment, AteExtraComma))
8822 return true;
8823
8824 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8825 return error(L: Loc, Msg: "load operand must be a pointer to a first class type");
8826 if (isAtomic && !Alignment)
8827 return error(L: Loc, Msg: "atomic load must have explicit non-zero alignment");
8828 if (Ordering == AtomicOrdering::Release ||
8829 Ordering == AtomicOrdering::AcquireRelease)
8830 return error(L: Loc, Msg: "atomic load cannot use Release ordering");
8831
8832 SmallPtrSet<Type *, 4> Visited;
8833 if (!Alignment && !Ty->isSized(Visited: &Visited))
8834 return error(L: ExplicitTypeLoc, Msg: "loading unsized types is not allowed");
8835 if (!Alignment)
8836 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8837 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8838 return AteExtraComma ? InstExtraComma : InstNormal;
8839}
8840
8841/// parseStore
8842
8843/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8844/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8845/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8846int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8847 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8848 MaybeAlign Alignment;
8849 bool AteExtraComma = false;
8850 bool isAtomic = false;
8851 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
8852 SyncScope::ID SSID = SyncScope::System;
8853
8854 if (Lex.getKind() == lltok::kw_atomic) {
8855 isAtomic = true;
8856 Lex.Lex();
8857 }
8858
8859 bool isVolatile = false;
8860 if (Lex.getKind() == lltok::kw_volatile) {
8861 isVolatile = true;
8862 Lex.Lex();
8863 }
8864
8865 if (parseTypeAndValue(V&: Val, Loc, PFS) ||
8866 parseToken(T: lltok::comma, ErrMsg: "expected ',' after store operand") ||
8867 parseTypeAndValue(V&: Ptr, Loc&: PtrLoc, PFS) ||
8868 parseScopeAndOrdering(IsAtomic: isAtomic, SSID, Ordering) ||
8869 parseOptionalCommaAlign(Alignment, AteExtraComma))
8870 return true;
8871
8872 if (!Ptr->getType()->isPointerTy())
8873 return error(L: PtrLoc, Msg: "store operand must be a pointer");
8874 if (!Val->getType()->isFirstClassType())
8875 return error(L: Loc, Msg: "store operand must be a first class value");
8876 if (isAtomic && !Alignment)
8877 return error(L: Loc, Msg: "atomic store must have explicit non-zero alignment");
8878 if (Ordering == AtomicOrdering::Acquire ||
8879 Ordering == AtomicOrdering::AcquireRelease)
8880 return error(L: Loc, Msg: "atomic store cannot use Acquire ordering");
8881 SmallPtrSet<Type *, 4> Visited;
8882 if (!Alignment && !Val->getType()->isSized(Visited: &Visited))
8883 return error(L: Loc, Msg: "storing unsized types is not allowed");
8884 if (!Alignment)
8885 Alignment = M->getDataLayout().getABITypeAlign(Ty: Val->getType());
8886
8887 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8888 return AteExtraComma ? InstExtraComma : InstNormal;
8889}
8890
8891/// parseCmpXchg
8892/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8893/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8894/// 'Align'?
8895int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8896 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8897 bool AteExtraComma = false;
8898 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8899 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8900 SyncScope::ID SSID = SyncScope::System;
8901 bool isVolatile = false;
8902 bool isWeak = false;
8903 MaybeAlign Alignment;
8904
8905 if (EatIfPresent(T: lltok::kw_weak))
8906 isWeak = true;
8907
8908 if (EatIfPresent(T: lltok::kw_volatile))
8909 isVolatile = true;
8910
8911 if (parseTypeAndValue(V&: Ptr, Loc&: PtrLoc, PFS) ||
8912 parseToken(T: lltok::comma, ErrMsg: "expected ',' after cmpxchg address") ||
8913 parseTypeAndValue(V&: Cmp, Loc&: CmpLoc, PFS) ||
8914 parseToken(T: lltok::comma, ErrMsg: "expected ',' after cmpxchg cmp operand") ||
8915 parseTypeAndValue(V&: New, Loc&: NewLoc, PFS) ||
8916 parseScopeAndOrdering(IsAtomic: true /*Always atomic*/, SSID, Ordering&: SuccessOrdering) ||
8917 parseOrdering(Ordering&: FailureOrdering) ||
8918 parseOptionalCommaAlign(Alignment, AteExtraComma))
8919 return true;
8920
8921 if (!AtomicCmpXchgInst::isValidSuccessOrdering(Ordering: SuccessOrdering))
8922 return tokError(Msg: "invalid cmpxchg success ordering");
8923 if (!AtomicCmpXchgInst::isValidFailureOrdering(Ordering: FailureOrdering))
8924 return tokError(Msg: "invalid cmpxchg failure ordering");
8925 if (!Ptr->getType()->isPointerTy())
8926 return error(L: PtrLoc, Msg: "cmpxchg operand must be a pointer");
8927 if (Cmp->getType() != New->getType())
8928 return error(L: NewLoc, Msg: "compare value and new value type do not match");
8929 if (!New->getType()->isFirstClassType())
8930 return error(L: NewLoc, Msg: "cmpxchg operand must be a first class value");
8931
8932 const Align DefaultAlignment(
8933 PFS.getFunction().getDataLayout().getTypeStoreSize(
8934 Ty: Cmp->getType()));
8935
8936 AtomicCmpXchgInst *CXI =
8937 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(u: DefaultAlignment),
8938 SuccessOrdering, FailureOrdering, SSID);
8939 CXI->setVolatile(isVolatile);
8940 CXI->setWeak(isWeak);
8941
8942 Inst = CXI;
8943 return AteExtraComma ? InstExtraComma : InstNormal;
8944}
8945
8946/// parseAtomicRMW
8947/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8948/// 'singlethread'? AtomicOrdering
8949int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8950 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8951 bool AteExtraComma = false;
8952 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
8953 SyncScope::ID SSID = SyncScope::System;
8954 bool isVolatile = false;
8955 bool IsFP = false;
8956 AtomicRMWInst::BinOp Operation;
8957 MaybeAlign Alignment;
8958
8959 if (EatIfPresent(T: lltok::kw_volatile))
8960 isVolatile = true;
8961
8962 switch (Lex.getKind()) {
8963 default:
8964 return tokError(Msg: "expected binary operation in atomicrmw");
8965 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
8966 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
8967 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
8968 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
8969 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
8970 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
8971 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
8972 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
8973 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
8974 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
8975 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
8976 case lltok::kw_uinc_wrap:
8977 Operation = AtomicRMWInst::UIncWrap;
8978 break;
8979 case lltok::kw_udec_wrap:
8980 Operation = AtomicRMWInst::UDecWrap;
8981 break;
8982 case lltok::kw_usub_cond:
8983 Operation = AtomicRMWInst::USubCond;
8984 break;
8985 case lltok::kw_usub_sat:
8986 Operation = AtomicRMWInst::USubSat;
8987 break;
8988 case lltok::kw_fadd:
8989 Operation = AtomicRMWInst::FAdd;
8990 IsFP = true;
8991 break;
8992 case lltok::kw_fsub:
8993 Operation = AtomicRMWInst::FSub;
8994 IsFP = true;
8995 break;
8996 case lltok::kw_fmax:
8997 Operation = AtomicRMWInst::FMax;
8998 IsFP = true;
8999 break;
9000 case lltok::kw_fmin:
9001 Operation = AtomicRMWInst::FMin;
9002 IsFP = true;
9003 break;
9004 case lltok::kw_fmaximum:
9005 Operation = AtomicRMWInst::FMaximum;
9006 IsFP = true;
9007 break;
9008 case lltok::kw_fminimum:
9009 Operation = AtomicRMWInst::FMinimum;
9010 IsFP = true;
9011 break;
9012 }
9013 Lex.Lex(); // Eat the operation.
9014
9015 if (parseTypeAndValue(V&: Ptr, Loc&: PtrLoc, PFS) ||
9016 parseToken(T: lltok::comma, ErrMsg: "expected ',' after atomicrmw address") ||
9017 parseTypeAndValue(V&: Val, Loc&: ValLoc, PFS) ||
9018 parseScopeAndOrdering(IsAtomic: true /*Always atomic*/, SSID, Ordering) ||
9019 parseOptionalCommaAlign(Alignment, AteExtraComma))
9020 return true;
9021
9022 if (Ordering == AtomicOrdering::Unordered)
9023 return tokError(Msg: "atomicrmw cannot be unordered");
9024 if (!Ptr->getType()->isPointerTy())
9025 return error(L: PtrLoc, Msg: "atomicrmw operand must be a pointer");
9026 if (Val->getType()->isScalableTy())
9027 return error(L: ValLoc, Msg: "atomicrmw operand may not be scalable");
9028
9029 if (Operation == AtomicRMWInst::Xchg) {
9030 if (!Val->getType()->isIntegerTy() &&
9031 !Val->getType()->isFloatingPointTy() &&
9032 !Val->getType()->isPointerTy()) {
9033 return error(
9034 L: ValLoc,
9035 Msg: "atomicrmw " + AtomicRMWInst::getOperationName(Op: Operation) +
9036 " operand must be an integer, floating point, or pointer type");
9037 }
9038 } else if (IsFP) {
9039 if (!Val->getType()->isFPOrFPVectorTy()) {
9040 return error(L: ValLoc, Msg: "atomicrmw " +
9041 AtomicRMWInst::getOperationName(Op: Operation) +
9042 " operand must be a floating point type");
9043 }
9044 } else {
9045 if (!Val->getType()->isIntegerTy()) {
9046 return error(L: ValLoc, Msg: "atomicrmw " +
9047 AtomicRMWInst::getOperationName(Op: Operation) +
9048 " operand must be an integer");
9049 }
9050 }
9051
9052 unsigned Size =
9053 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
9054 Ty: Val->getType());
9055 if (Size < 8 || (Size & (Size - 1)))
9056 return error(L: ValLoc, Msg: "atomicrmw operand must be power-of-two byte-sized"
9057 " integer");
9058 const Align DefaultAlignment(
9059 PFS.getFunction().getDataLayout().getTypeStoreSize(
9060 Ty: Val->getType()));
9061 AtomicRMWInst *RMWI =
9062 new AtomicRMWInst(Operation, Ptr, Val,
9063 Alignment.value_or(u: DefaultAlignment), Ordering, SSID);
9064 RMWI->setVolatile(isVolatile);
9065 Inst = RMWI;
9066 return AteExtraComma ? InstExtraComma : InstNormal;
9067}
9068
9069/// parseFence
9070/// ::= 'fence' 'singlethread'? AtomicOrdering
9071int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9072 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
9073 SyncScope::ID SSID = SyncScope::System;
9074 if (parseScopeAndOrdering(IsAtomic: true /*Always atomic*/, SSID, Ordering))
9075 return true;
9076
9077 if (Ordering == AtomicOrdering::Unordered)
9078 return tokError(Msg: "fence cannot be unordered");
9079 if (Ordering == AtomicOrdering::Monotonic)
9080 return tokError(Msg: "fence cannot be monotonic");
9081
9082 Inst = new FenceInst(Context, Ordering, SSID);
9083 return InstNormal;
9084}
9085
9086/// parseGetElementPtr
9087/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9088int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9089 Value *Ptr = nullptr;
9090 Value *Val = nullptr;
9091 LocTy Loc, EltLoc;
9092 GEPNoWrapFlags NW;
9093
9094 while (true) {
9095 if (EatIfPresent(T: lltok::kw_inbounds))
9096 NW |= GEPNoWrapFlags::inBounds();
9097 else if (EatIfPresent(T: lltok::kw_nusw))
9098 NW |= GEPNoWrapFlags::noUnsignedSignedWrap();
9099 else if (EatIfPresent(T: lltok::kw_nuw))
9100 NW |= GEPNoWrapFlags::noUnsignedWrap();
9101 else
9102 break;
9103 }
9104
9105 Type *Ty = nullptr;
9106 if (parseType(Result&: Ty) ||
9107 parseToken(T: lltok::comma, ErrMsg: "expected comma after getelementptr's type") ||
9108 parseTypeAndValue(V&: Ptr, Loc, PFS))
9109 return true;
9110
9111 Type *BaseType = Ptr->getType();
9112 PointerType *BasePointerType = dyn_cast<PointerType>(Val: BaseType->getScalarType());
9113 if (!BasePointerType)
9114 return error(L: Loc, Msg: "base of getelementptr must be a pointer");
9115
9116 SmallVector<Value*, 16> Indices;
9117 bool AteExtraComma = false;
9118 // GEP returns a vector of pointers if at least one of parameters is a vector.
9119 // All vector parameters should have the same vector width.
9120 ElementCount GEPWidth = BaseType->isVectorTy()
9121 ? cast<VectorType>(Val: BaseType)->getElementCount()
9122 : ElementCount::getFixed(MinVal: 0);
9123
9124 while (EatIfPresent(T: lltok::comma)) {
9125 if (Lex.getKind() == lltok::MetadataVar) {
9126 AteExtraComma = true;
9127 break;
9128 }
9129 if (parseTypeAndValue(V&: Val, Loc&: EltLoc, PFS))
9130 return true;
9131 if (!Val->getType()->isIntOrIntVectorTy())
9132 return error(L: EltLoc, Msg: "getelementptr index must be an integer");
9133
9134 if (auto *ValVTy = dyn_cast<VectorType>(Val: Val->getType())) {
9135 ElementCount ValNumEl = ValVTy->getElementCount();
9136 if (GEPWidth != ElementCount::getFixed(MinVal: 0) && GEPWidth != ValNumEl)
9137 return error(
9138 L: EltLoc,
9139 Msg: "getelementptr vector index has a wrong number of elements");
9140 GEPWidth = ValNumEl;
9141 }
9142 Indices.push_back(Elt: Val);
9143 }
9144
9145 SmallPtrSet<Type*, 4> Visited;
9146 if (!Indices.empty() && !Ty->isSized(Visited: &Visited))
9147 return error(L: Loc, Msg: "base element of getelementptr must be sized");
9148
9149 auto *STy = dyn_cast<StructType>(Val: Ty);
9150 if (STy && STy->isScalableTy())
9151 return error(L: Loc, Msg: "getelementptr cannot target structure that contains "
9152 "scalable vector type");
9153
9154 if (!GetElementPtrInst::getIndexedType(Ty, IdxList: Indices))
9155 return error(L: Loc, Msg: "invalid getelementptr indices");
9156 GetElementPtrInst *GEP = GetElementPtrInst::Create(PointeeType: Ty, Ptr, IdxList: Indices);
9157 Inst = GEP;
9158 GEP->setNoWrapFlags(NW);
9159 return AteExtraComma ? InstExtraComma : InstNormal;
9160}
9161
9162/// parseExtractValue
9163/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9164int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9165 Value *Val; LocTy Loc;
9166 SmallVector<unsigned, 4> Indices;
9167 bool AteExtraComma;
9168 if (parseTypeAndValue(V&: Val, Loc, PFS) ||
9169 parseIndexList(Indices, AteExtraComma))
9170 return true;
9171
9172 if (!Val->getType()->isAggregateType())
9173 return error(L: Loc, Msg: "extractvalue operand must be aggregate type");
9174
9175 if (!ExtractValueInst::getIndexedType(Agg: Val->getType(), Idxs: Indices))
9176 return error(L: Loc, Msg: "invalid indices for extractvalue");
9177 Inst = ExtractValueInst::Create(Agg: Val, Idxs: Indices);
9178 return AteExtraComma ? InstExtraComma : InstNormal;
9179}
9180
9181/// parseInsertValue
9182/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9183int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9184 Value *Val0, *Val1; LocTy Loc0, Loc1;
9185 SmallVector<unsigned, 4> Indices;
9186 bool AteExtraComma;
9187 if (parseTypeAndValue(V&: Val0, Loc&: Loc0, PFS) ||
9188 parseToken(T: lltok::comma, ErrMsg: "expected comma after insertvalue operand") ||
9189 parseTypeAndValue(V&: Val1, Loc&: Loc1, PFS) ||
9190 parseIndexList(Indices, AteExtraComma))
9191 return true;
9192
9193 if (!Val0->getType()->isAggregateType())
9194 return error(L: Loc0, Msg: "insertvalue operand must be aggregate type");
9195
9196 Type *IndexedType = ExtractValueInst::getIndexedType(Agg: Val0->getType(), Idxs: Indices);
9197 if (!IndexedType)
9198 return error(L: Loc0, Msg: "invalid indices for insertvalue");
9199 if (IndexedType != Val1->getType())
9200 return error(L: Loc1, Msg: "insertvalue operand and field disagree in type: '" +
9201 getTypeString(T: Val1->getType()) + "' instead of '" +
9202 getTypeString(T: IndexedType) + "'");
9203 Inst = InsertValueInst::Create(Agg: Val0, Val: Val1, Idxs: Indices);
9204 return AteExtraComma ? InstExtraComma : InstNormal;
9205}
9206
9207//===----------------------------------------------------------------------===//
9208// Embedded metadata.
9209//===----------------------------------------------------------------------===//
9210
9211/// parseMDNodeVector
9212/// ::= { Element (',' Element)* }
9213/// Element
9214/// ::= 'null' | Metadata
9215bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9216 if (parseToken(T: lltok::lbrace, ErrMsg: "expected '{' here"))
9217 return true;
9218
9219 // Check for an empty list.
9220 if (EatIfPresent(T: lltok::rbrace))
9221 return false;
9222
9223 do {
9224 if (EatIfPresent(T: lltok::kw_null)) {
9225 Elts.push_back(Elt: nullptr);
9226 continue;
9227 }
9228
9229 Metadata *MD;
9230 if (parseMetadata(MD, PFS: nullptr))
9231 return true;
9232 Elts.push_back(Elt: MD);
9233 } while (EatIfPresent(T: lltok::comma));
9234
9235 return parseToken(T: lltok::rbrace, ErrMsg: "expected end of metadata node");
9236}
9237
9238//===----------------------------------------------------------------------===//
9239// Use-list order directives.
9240//===----------------------------------------------------------------------===//
9241bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9242 SMLoc Loc) {
9243 if (!V->hasUseList())
9244 return false;
9245 if (V->use_empty())
9246 return error(L: Loc, Msg: "value has no uses");
9247
9248 unsigned NumUses = 0;
9249 SmallDenseMap<const Use *, unsigned, 16> Order;
9250 for (const Use &U : V->uses()) {
9251 if (++NumUses > Indexes.size())
9252 break;
9253 Order[&U] = Indexes[NumUses - 1];
9254 }
9255 if (NumUses < 2)
9256 return error(L: Loc, Msg: "value only has one use");
9257 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9258 return error(L: Loc,
9259 Msg: "wrong number of indexes, expected " + Twine(V->getNumUses()));
9260
9261 V->sortUseList(Cmp: [&](const Use &L, const Use &R) {
9262 return Order.lookup(Val: &L) < Order.lookup(Val: &R);
9263 });
9264 return false;
9265}
9266
9267/// parseUseListOrderIndexes
9268/// ::= '{' uint32 (',' uint32)+ '}'
9269bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9270 SMLoc Loc = Lex.getLoc();
9271 if (parseToken(T: lltok::lbrace, ErrMsg: "expected '{' here"))
9272 return true;
9273 if (Lex.getKind() == lltok::rbrace)
9274 return tokError(Msg: "expected non-empty list of uselistorder indexes");
9275
9276 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9277 // indexes should be distinct numbers in the range [0, size-1], and should
9278 // not be in order.
9279 unsigned Offset = 0;
9280 unsigned Max = 0;
9281 bool IsOrdered = true;
9282 assert(Indexes.empty() && "Expected empty order vector");
9283 do {
9284 unsigned Index;
9285 if (parseUInt32(Val&: Index))
9286 return true;
9287
9288 // Update consistency checks.
9289 Offset += Index - Indexes.size();
9290 Max = std::max(a: Max, b: Index);
9291 IsOrdered &= Index == Indexes.size();
9292
9293 Indexes.push_back(Elt: Index);
9294 } while (EatIfPresent(T: lltok::comma));
9295
9296 if (parseToken(T: lltok::rbrace, ErrMsg: "expected '}' here"))
9297 return true;
9298
9299 if (Indexes.size() < 2)
9300 return error(L: Loc, Msg: "expected >= 2 uselistorder indexes");
9301 if (Offset != 0 || Max >= Indexes.size())
9302 return error(L: Loc,
9303 Msg: "expected distinct uselistorder indexes in range [0, size)");
9304 if (IsOrdered)
9305 return error(L: Loc, Msg: "expected uselistorder indexes to change the order");
9306
9307 return false;
9308}
9309
9310/// parseUseListOrder
9311/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9312bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9313 SMLoc Loc = Lex.getLoc();
9314 if (parseToken(T: lltok::kw_uselistorder, ErrMsg: "expected uselistorder directive"))
9315 return true;
9316
9317 Value *V;
9318 SmallVector<unsigned, 16> Indexes;
9319 if (parseTypeAndValue(V, PFS) ||
9320 parseToken(T: lltok::comma, ErrMsg: "expected comma in uselistorder directive") ||
9321 parseUseListOrderIndexes(Indexes))
9322 return true;
9323
9324 return sortUseListOrder(V, Indexes, Loc);
9325}
9326
9327/// parseUseListOrderBB
9328/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
9329bool LLParser::parseUseListOrderBB() {
9330 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
9331 SMLoc Loc = Lex.getLoc();
9332 Lex.Lex();
9333
9334 ValID Fn, Label;
9335 SmallVector<unsigned, 16> Indexes;
9336 if (parseValID(ID&: Fn, /*PFS=*/nullptr) ||
9337 parseToken(T: lltok::comma, ErrMsg: "expected comma in uselistorder_bb directive") ||
9338 parseValID(ID&: Label, /*PFS=*/nullptr) ||
9339 parseToken(T: lltok::comma, ErrMsg: "expected comma in uselistorder_bb directive") ||
9340 parseUseListOrderIndexes(Indexes))
9341 return true;
9342
9343 // Check the function.
9344 GlobalValue *GV;
9345 if (Fn.Kind == ValID::t_GlobalName)
9346 GV = M->getNamedValue(Name: Fn.StrVal);
9347 else if (Fn.Kind == ValID::t_GlobalID)
9348 GV = NumberedVals.get(ID: Fn.UIntVal);
9349 else
9350 return error(L: Fn.Loc, Msg: "expected function name in uselistorder_bb");
9351 if (!GV)
9352 return error(L: Fn.Loc,
9353 Msg: "invalid function forward reference in uselistorder_bb");
9354 auto *F = dyn_cast<Function>(Val: GV);
9355 if (!F)
9356 return error(L: Fn.Loc, Msg: "expected function name in uselistorder_bb");
9357 if (F->isDeclaration())
9358 return error(L: Fn.Loc, Msg: "invalid declaration in uselistorder_bb");
9359
9360 // Check the basic block.
9361 if (Label.Kind == ValID::t_LocalID)
9362 return error(L: Label.Loc, Msg: "invalid numeric label in uselistorder_bb");
9363 if (Label.Kind != ValID::t_LocalName)
9364 return error(L: Label.Loc, Msg: "expected basic block name in uselistorder_bb");
9365 Value *V = F->getValueSymbolTable()->lookup(Name: Label.StrVal);
9366 if (!V)
9367 return error(L: Label.Loc, Msg: "invalid basic block in uselistorder_bb");
9368 if (!isa<BasicBlock>(Val: V))
9369 return error(L: Label.Loc, Msg: "expected basic block in uselistorder_bb");
9370
9371 return sortUseListOrder(V, Indexes, Loc);
9372}
9373
9374/// ModuleEntry
9375/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9376/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9377bool LLParser::parseModuleEntry(unsigned ID) {
9378 assert(Lex.getKind() == lltok::kw_module);
9379 Lex.Lex();
9380
9381 std::string Path;
9382 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9383 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
9384 parseToken(T: lltok::kw_path, ErrMsg: "expected 'path' here") ||
9385 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9386 parseStringConstant(Result&: Path) ||
9387 parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
9388 parseToken(T: lltok::kw_hash, ErrMsg: "expected 'hash' here") ||
9389 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9390 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
9391 return true;
9392
9393 ModuleHash Hash;
9394 if (parseUInt32(Val&: Hash[0]) || parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
9395 parseUInt32(Val&: Hash[1]) || parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
9396 parseUInt32(Val&: Hash[2]) || parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
9397 parseUInt32(Val&: Hash[3]) || parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
9398 parseUInt32(Val&: Hash[4]))
9399 return true;
9400
9401 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here") ||
9402 parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
9403 return true;
9404
9405 auto ModuleEntry = Index->addModule(ModPath: Path, Hash);
9406 ModuleIdMap[ID] = ModuleEntry->first();
9407
9408 return false;
9409}
9410
9411/// TypeIdEntry
9412/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9413bool LLParser::parseTypeIdEntry(unsigned ID) {
9414 assert(Lex.getKind() == lltok::kw_typeid);
9415 Lex.Lex();
9416
9417 std::string Name;
9418 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9419 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
9420 parseToken(T: lltok::kw_name, ErrMsg: "expected 'name' here") ||
9421 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9422 parseStringConstant(Result&: Name))
9423 return true;
9424
9425 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(TypeId: Name);
9426 if (parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
9427 parseTypeIdSummary(TIS) || parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
9428 return true;
9429
9430 // Check if this ID was forward referenced, and if so, update the
9431 // corresponding GUIDs.
9432 auto FwdRefTIDs = ForwardRefTypeIds.find(x: ID);
9433 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9434 for (auto TIDRef : FwdRefTIDs->second) {
9435 assert(!*TIDRef.first &&
9436 "Forward referenced type id GUID expected to be 0");
9437 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: Name);
9438 }
9439 ForwardRefTypeIds.erase(position: FwdRefTIDs);
9440 }
9441
9442 return false;
9443}
9444
9445/// TypeIdSummary
9446/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9447bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9448 if (parseToken(T: lltok::kw_summary, ErrMsg: "expected 'summary' here") ||
9449 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9450 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
9451 parseTypeTestResolution(TTRes&: TIS.TTRes))
9452 return true;
9453
9454 if (EatIfPresent(T: lltok::comma)) {
9455 // Expect optional wpdResolutions field
9456 if (parseOptionalWpdResolutions(WPDResMap&: TIS.WPDRes))
9457 return true;
9458 }
9459
9460 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
9461 return true;
9462
9463 return false;
9464}
9465
9466static ValueInfo EmptyVI =
9467 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9468
9469/// TypeIdCompatibleVtableEntry
9470/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9471/// TypeIdCompatibleVtableInfo
9472/// ')'
9473bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9474 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
9475 Lex.Lex();
9476
9477 std::string Name;
9478 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9479 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
9480 parseToken(T: lltok::kw_name, ErrMsg: "expected 'name' here") ||
9481 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9482 parseStringConstant(Result&: Name))
9483 return true;
9484
9485 TypeIdCompatibleVtableInfo &TI =
9486 Index->getOrInsertTypeIdCompatibleVtableSummary(TypeId: Name);
9487 if (parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
9488 parseToken(T: lltok::kw_summary, ErrMsg: "expected 'summary' here") ||
9489 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9490 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
9491 return true;
9492
9493 IdToIndexMapType IdToIndexMap;
9494 // parse each call edge
9495 do {
9496 uint64_t Offset;
9497 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
9498 parseToken(T: lltok::kw_offset, ErrMsg: "expected 'offset' here") ||
9499 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") || parseUInt64(Val&: Offset) ||
9500 parseToken(T: lltok::comma, ErrMsg: "expected ',' here"))
9501 return true;
9502
9503 LocTy Loc = Lex.getLoc();
9504 unsigned GVId;
9505 ValueInfo VI;
9506 if (parseGVReference(VI, GVId))
9507 return true;
9508
9509 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9510 // forward reference. We will save the location of the ValueInfo needing an
9511 // update, but can only do so once the std::vector is finalized.
9512 if (VI == EmptyVI)
9513 IdToIndexMap[GVId].push_back(x: std::make_pair(x: TI.size(), y&: Loc));
9514 TI.push_back(x: {Offset, VI});
9515
9516 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in call"))
9517 return true;
9518 } while (EatIfPresent(T: lltok::comma));
9519
9520 // Now that the TI vector is finalized, it is safe to save the locations
9521 // of any forward GV references that need updating later.
9522 for (auto I : IdToIndexMap) {
9523 auto &Infos = ForwardRefValueInfos[I.first];
9524 for (auto P : I.second) {
9525 assert(TI[P.first].VTableVI == EmptyVI &&
9526 "Forward referenced ValueInfo expected to be empty");
9527 Infos.emplace_back(args: &TI[P.first].VTableVI, args&: P.second);
9528 }
9529 }
9530
9531 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here") ||
9532 parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
9533 return true;
9534
9535 // Check if this ID was forward referenced, and if so, update the
9536 // corresponding GUIDs.
9537 auto FwdRefTIDs = ForwardRefTypeIds.find(x: ID);
9538 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9539 for (auto TIDRef : FwdRefTIDs->second) {
9540 assert(!*TIDRef.first &&
9541 "Forward referenced type id GUID expected to be 0");
9542 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(GlobalName: Name);
9543 }
9544 ForwardRefTypeIds.erase(position: FwdRefTIDs);
9545 }
9546
9547 return false;
9548}
9549
9550/// TypeTestResolution
9551/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9552/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9553/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9554/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9555/// [',' 'inlinesBits' ':' UInt64]? ')'
9556bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9557 if (parseToken(T: lltok::kw_typeTestRes, ErrMsg: "expected 'typeTestRes' here") ||
9558 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9559 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
9560 parseToken(T: lltok::kw_kind, ErrMsg: "expected 'kind' here") ||
9561 parseToken(T: lltok::colon, ErrMsg: "expected ':' here"))
9562 return true;
9563
9564 switch (Lex.getKind()) {
9565 case lltok::kw_unknown:
9566 TTRes.TheKind = TypeTestResolution::Unknown;
9567 break;
9568 case lltok::kw_unsat:
9569 TTRes.TheKind = TypeTestResolution::Unsat;
9570 break;
9571 case lltok::kw_byteArray:
9572 TTRes.TheKind = TypeTestResolution::ByteArray;
9573 break;
9574 case lltok::kw_inline:
9575 TTRes.TheKind = TypeTestResolution::Inline;
9576 break;
9577 case lltok::kw_single:
9578 TTRes.TheKind = TypeTestResolution::Single;
9579 break;
9580 case lltok::kw_allOnes:
9581 TTRes.TheKind = TypeTestResolution::AllOnes;
9582 break;
9583 default:
9584 return error(L: Lex.getLoc(), Msg: "unexpected TypeTestResolution kind");
9585 }
9586 Lex.Lex();
9587
9588 if (parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
9589 parseToken(T: lltok::kw_sizeM1BitWidth, ErrMsg: "expected 'sizeM1BitWidth' here") ||
9590 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9591 parseUInt32(Val&: TTRes.SizeM1BitWidth))
9592 return true;
9593
9594 // parse optional fields
9595 while (EatIfPresent(T: lltok::comma)) {
9596 switch (Lex.getKind()) {
9597 case lltok::kw_alignLog2:
9598 Lex.Lex();
9599 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") ||
9600 parseUInt64(Val&: TTRes.AlignLog2))
9601 return true;
9602 break;
9603 case lltok::kw_sizeM1:
9604 Lex.Lex();
9605 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseUInt64(Val&: TTRes.SizeM1))
9606 return true;
9607 break;
9608 case lltok::kw_bitMask: {
9609 unsigned Val;
9610 Lex.Lex();
9611 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseUInt32(Val))
9612 return true;
9613 assert(Val <= 0xff);
9614 TTRes.BitMask = (uint8_t)Val;
9615 break;
9616 }
9617 case lltok::kw_inlineBits:
9618 Lex.Lex();
9619 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") ||
9620 parseUInt64(Val&: TTRes.InlineBits))
9621 return true;
9622 break;
9623 default:
9624 return error(L: Lex.getLoc(), Msg: "expected optional TypeTestResolution field");
9625 }
9626 }
9627
9628 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
9629 return true;
9630
9631 return false;
9632}
9633
9634/// OptionalWpdResolutions
9635/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9636/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9637bool LLParser::parseOptionalWpdResolutions(
9638 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9639 if (parseToken(T: lltok::kw_wpdResolutions, ErrMsg: "expected 'wpdResolutions' here") ||
9640 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9641 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
9642 return true;
9643
9644 do {
9645 uint64_t Offset;
9646 WholeProgramDevirtResolution WPDRes;
9647 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
9648 parseToken(T: lltok::kw_offset, ErrMsg: "expected 'offset' here") ||
9649 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") || parseUInt64(Val&: Offset) ||
9650 parseToken(T: lltok::comma, ErrMsg: "expected ',' here") || parseWpdRes(WPDRes) ||
9651 parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
9652 return true;
9653 WPDResMap[Offset] = WPDRes;
9654 } while (EatIfPresent(T: lltok::comma));
9655
9656 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
9657 return true;
9658
9659 return false;
9660}
9661
9662/// WpdRes
9663/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9664/// [',' OptionalResByArg]? ')'
9665/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9666/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9667/// [',' OptionalResByArg]? ')'
9668/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9669/// [',' OptionalResByArg]? ')'
9670bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9671 if (parseToken(T: lltok::kw_wpdRes, ErrMsg: "expected 'wpdRes' here") ||
9672 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9673 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
9674 parseToken(T: lltok::kw_kind, ErrMsg: "expected 'kind' here") ||
9675 parseToken(T: lltok::colon, ErrMsg: "expected ':' here"))
9676 return true;
9677
9678 switch (Lex.getKind()) {
9679 case lltok::kw_indir:
9680 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
9681 break;
9682 case lltok::kw_singleImpl:
9683 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
9684 break;
9685 case lltok::kw_branchFunnel:
9686 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
9687 break;
9688 default:
9689 return error(L: Lex.getLoc(), Msg: "unexpected WholeProgramDevirtResolution kind");
9690 }
9691 Lex.Lex();
9692
9693 // parse optional fields
9694 while (EatIfPresent(T: lltok::comma)) {
9695 switch (Lex.getKind()) {
9696 case lltok::kw_singleImplName:
9697 Lex.Lex();
9698 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9699 parseStringConstant(Result&: WPDRes.SingleImplName))
9700 return true;
9701 break;
9702 case lltok::kw_resByArg:
9703 if (parseOptionalResByArg(ResByArg&: WPDRes.ResByArg))
9704 return true;
9705 break;
9706 default:
9707 return error(L: Lex.getLoc(),
9708 Msg: "expected optional WholeProgramDevirtResolution field");
9709 }
9710 }
9711
9712 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
9713 return true;
9714
9715 return false;
9716}
9717
9718/// OptionalResByArg
9719/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9720/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9721/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9722/// 'virtualConstProp' )
9723/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9724/// [',' 'bit' ':' UInt32]? ')'
9725bool LLParser::parseOptionalResByArg(
9726 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9727 &ResByArg) {
9728 if (parseToken(T: lltok::kw_resByArg, ErrMsg: "expected 'resByArg' here") ||
9729 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9730 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
9731 return true;
9732
9733 do {
9734 std::vector<uint64_t> Args;
9735 if (parseArgs(Args) || parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
9736 parseToken(T: lltok::kw_byArg, ErrMsg: "expected 'byArg here") ||
9737 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9738 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
9739 parseToken(T: lltok::kw_kind, ErrMsg: "expected 'kind' here") ||
9740 parseToken(T: lltok::colon, ErrMsg: "expected ':' here"))
9741 return true;
9742
9743 WholeProgramDevirtResolution::ByArg ByArg;
9744 switch (Lex.getKind()) {
9745 case lltok::kw_indir:
9746 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
9747 break;
9748 case lltok::kw_uniformRetVal:
9749 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
9750 break;
9751 case lltok::kw_uniqueRetVal:
9752 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
9753 break;
9754 case lltok::kw_virtualConstProp:
9755 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
9756 break;
9757 default:
9758 return error(L: Lex.getLoc(),
9759 Msg: "unexpected WholeProgramDevirtResolution::ByArg kind");
9760 }
9761 Lex.Lex();
9762
9763 // parse optional fields
9764 while (EatIfPresent(T: lltok::comma)) {
9765 switch (Lex.getKind()) {
9766 case lltok::kw_info:
9767 Lex.Lex();
9768 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9769 parseUInt64(Val&: ByArg.Info))
9770 return true;
9771 break;
9772 case lltok::kw_byte:
9773 Lex.Lex();
9774 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9775 parseUInt32(Val&: ByArg.Byte))
9776 return true;
9777 break;
9778 case lltok::kw_bit:
9779 Lex.Lex();
9780 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9781 parseUInt32(Val&: ByArg.Bit))
9782 return true;
9783 break;
9784 default:
9785 return error(L: Lex.getLoc(),
9786 Msg: "expected optional whole program devirt field");
9787 }
9788 }
9789
9790 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
9791 return true;
9792
9793 ResByArg[Args] = ByArg;
9794 } while (EatIfPresent(T: lltok::comma));
9795
9796 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
9797 return true;
9798
9799 return false;
9800}
9801
9802/// OptionalResByArg
9803/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9804bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9805 if (parseToken(T: lltok::kw_args, ErrMsg: "expected 'args' here") ||
9806 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9807 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
9808 return true;
9809
9810 do {
9811 uint64_t Val;
9812 if (parseUInt64(Val))
9813 return true;
9814 Args.push_back(x: Val);
9815 } while (EatIfPresent(T: lltok::comma));
9816
9817 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
9818 return true;
9819
9820 return false;
9821}
9822
9823static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9824
9825static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9826 bool ReadOnly = Fwd->isReadOnly();
9827 bool WriteOnly = Fwd->isWriteOnly();
9828 assert(!(ReadOnly && WriteOnly));
9829 *Fwd = Resolved;
9830 if (ReadOnly)
9831 Fwd->setReadOnly();
9832 if (WriteOnly)
9833 Fwd->setWriteOnly();
9834}
9835
9836/// Stores the given Name/GUID and associated summary into the Index.
9837/// Also updates any forward references to the associated entry ID.
9838bool LLParser::addGlobalValueToIndex(
9839 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9840 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9841 // First create the ValueInfo utilizing the Name or GUID.
9842 ValueInfo VI;
9843 if (GUID != 0) {
9844 assert(Name.empty());
9845 VI = Index->getOrInsertValueInfo(GUID);
9846 } else {
9847 assert(!Name.empty());
9848 if (M) {
9849 auto *GV = M->getNamedValue(Name);
9850 if (!GV)
9851 return error(L: Loc, Msg: "Reference to undefined global \"" + Name + "\"");
9852
9853 VI = Index->getOrInsertValueInfo(GV);
9854 } else {
9855 assert(
9856 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9857 "Need a source_filename to compute GUID for local");
9858 GUID = GlobalValue::getGUIDAssumingExternalLinkage(
9859 GlobalName: GlobalValue::getGlobalIdentifier(Name, Linkage, FileName: SourceFileName));
9860 VI = Index->getOrInsertValueInfo(GUID, Name: Index->saveString(String: Name));
9861 }
9862 }
9863
9864 // Resolve forward references from calls/refs
9865 auto FwdRefVIs = ForwardRefValueInfos.find(x: ID);
9866 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9867 for (auto VIRef : FwdRefVIs->second) {
9868 assert(VIRef.first->getRef() == FwdVIRef &&
9869 "Forward referenced ValueInfo expected to be empty");
9870 resolveFwdRef(Fwd: VIRef.first, Resolved&: VI);
9871 }
9872 ForwardRefValueInfos.erase(position: FwdRefVIs);
9873 }
9874
9875 // Resolve forward references from aliases
9876 auto FwdRefAliasees = ForwardRefAliasees.find(x: ID);
9877 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9878 for (auto AliaseeRef : FwdRefAliasees->second) {
9879 assert(!AliaseeRef.first->hasAliasee() &&
9880 "Forward referencing alias already has aliasee");
9881 assert(Summary && "Aliasee must be a definition");
9882 AliaseeRef.first->setAliasee(AliaseeVI&: VI, Aliasee: Summary.get());
9883 }
9884 ForwardRefAliasees.erase(position: FwdRefAliasees);
9885 }
9886
9887 // Add the summary if one was provided.
9888 if (Summary)
9889 Index->addGlobalValueSummary(VI, Summary: std::move(Summary));
9890
9891 // Save the associated ValueInfo for use in later references by ID.
9892 if (ID == NumberedValueInfos.size())
9893 NumberedValueInfos.push_back(x: VI);
9894 else {
9895 // Handle non-continuous numbers (to make test simplification easier).
9896 if (ID > NumberedValueInfos.size())
9897 NumberedValueInfos.resize(new_size: ID + 1);
9898 NumberedValueInfos[ID] = VI;
9899 }
9900
9901 return false;
9902}
9903
9904/// parseSummaryIndexFlags
9905/// ::= 'flags' ':' UInt64
9906bool LLParser::parseSummaryIndexFlags() {
9907 assert(Lex.getKind() == lltok::kw_flags);
9908 Lex.Lex();
9909
9910 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here"))
9911 return true;
9912 uint64_t Flags;
9913 if (parseUInt64(Val&: Flags))
9914 return true;
9915 if (Index)
9916 Index->setFlags(Flags);
9917 return false;
9918}
9919
9920/// parseBlockCount
9921/// ::= 'blockcount' ':' UInt64
9922bool LLParser::parseBlockCount() {
9923 assert(Lex.getKind() == lltok::kw_blockcount);
9924 Lex.Lex();
9925
9926 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here"))
9927 return true;
9928 uint64_t BlockCount;
9929 if (parseUInt64(Val&: BlockCount))
9930 return true;
9931 if (Index)
9932 Index->setBlockCount(BlockCount);
9933 return false;
9934}
9935
9936/// parseGVEntry
9937/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9938/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9939/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9940bool LLParser::parseGVEntry(unsigned ID) {
9941 assert(Lex.getKind() == lltok::kw_gv);
9942 Lex.Lex();
9943
9944 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9945 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
9946 return true;
9947
9948 LocTy Loc = Lex.getLoc();
9949 std::string Name;
9950 GlobalValue::GUID GUID = 0;
9951 switch (Lex.getKind()) {
9952 case lltok::kw_name:
9953 Lex.Lex();
9954 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9955 parseStringConstant(Result&: Name))
9956 return true;
9957 // Can't create GUID/ValueInfo until we have the linkage.
9958 break;
9959 case lltok::kw_guid:
9960 Lex.Lex();
9961 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") || parseUInt64(Val&: GUID))
9962 return true;
9963 break;
9964 default:
9965 return error(L: Lex.getLoc(), Msg: "expected name or guid tag");
9966 }
9967
9968 if (!EatIfPresent(T: lltok::comma)) {
9969 // No summaries. Wrap up.
9970 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
9971 return true;
9972 // This was created for a call to an external or indirect target.
9973 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
9974 // created for indirect calls with VP. A Name with no GUID came from
9975 // an external definition. We pass ExternalLinkage since that is only
9976 // used when the GUID must be computed from Name, and in that case
9977 // the symbol must have external linkage.
9978 return addGlobalValueToIndex(Name, GUID, Linkage: GlobalValue::ExternalLinkage, ID,
9979 Summary: nullptr, Loc);
9980 }
9981
9982 // Have a list of summaries
9983 if (parseToken(T: lltok::kw_summaries, ErrMsg: "expected 'summaries' here") ||
9984 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
9985 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
9986 return true;
9987 do {
9988 switch (Lex.getKind()) {
9989 case lltok::kw_function:
9990 if (parseFunctionSummary(Name, GUID, ID))
9991 return true;
9992 break;
9993 case lltok::kw_variable:
9994 if (parseVariableSummary(Name, GUID, ID))
9995 return true;
9996 break;
9997 case lltok::kw_alias:
9998 if (parseAliasSummary(Name, GUID, ID))
9999 return true;
10000 break;
10001 default:
10002 return error(L: Lex.getLoc(), Msg: "expected summary type");
10003 }
10004 } while (EatIfPresent(T: lltok::comma));
10005
10006 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here") ||
10007 parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10008 return true;
10009
10010 return false;
10011}
10012
10013/// FunctionSummary
10014/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10015/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10016/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10017/// [',' OptionalRefs]? ')'
10018bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10019 unsigned ID) {
10020 LocTy Loc = Lex.getLoc();
10021 assert(Lex.getKind() == lltok::kw_function);
10022 Lex.Lex();
10023
10024 StringRef ModulePath;
10025 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10026 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
10027 /*NotEligibleToImport=*/false,
10028 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10029 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10030 unsigned InstCount;
10031 SmallVector<FunctionSummary::EdgeTy, 0> Calls;
10032 FunctionSummary::TypeIdInfo TypeIdInfo;
10033 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10034 SmallVector<ValueInfo, 0> Refs;
10035 std::vector<CallsiteInfo> Callsites;
10036 std::vector<AllocInfo> Allocs;
10037 // Default is all-zeros (conservative values).
10038 FunctionSummary::FFlags FFlags = {};
10039 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10040 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
10041 parseModuleReference(ModulePath) ||
10042 parseToken(T: lltok::comma, ErrMsg: "expected ',' here") || parseGVFlags(GVFlags) ||
10043 parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
10044 parseToken(T: lltok::kw_insts, ErrMsg: "expected 'insts' here") ||
10045 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") || parseUInt32(Val&: InstCount))
10046 return true;
10047
10048 // parse optional fields
10049 while (EatIfPresent(T: lltok::comma)) {
10050 switch (Lex.getKind()) {
10051 case lltok::kw_funcFlags:
10052 if (parseOptionalFFlags(FFlags))
10053 return true;
10054 break;
10055 case lltok::kw_calls:
10056 if (parseOptionalCalls(Calls))
10057 return true;
10058 break;
10059 case lltok::kw_typeIdInfo:
10060 if (parseOptionalTypeIdInfo(TypeIdInfo))
10061 return true;
10062 break;
10063 case lltok::kw_refs:
10064 if (parseOptionalRefs(Refs))
10065 return true;
10066 break;
10067 case lltok::kw_params:
10068 if (parseOptionalParamAccesses(Params&: ParamAccesses))
10069 return true;
10070 break;
10071 case lltok::kw_allocs:
10072 if (parseOptionalAllocs(Allocs))
10073 return true;
10074 break;
10075 case lltok::kw_callsites:
10076 if (parseOptionalCallsites(Callsites))
10077 return true;
10078 break;
10079 default:
10080 return error(L: Lex.getLoc(), Msg: "expected optional function summary field");
10081 }
10082 }
10083
10084 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10085 return true;
10086
10087 auto FS = std::make_unique<FunctionSummary>(
10088 args&: GVFlags, args&: InstCount, args&: FFlags, args: std::move(Refs), args: std::move(Calls),
10089 args: std::move(TypeIdInfo.TypeTests),
10090 args: std::move(TypeIdInfo.TypeTestAssumeVCalls),
10091 args: std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10092 args: std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10093 args: std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10094 args: std::move(ParamAccesses), args: std::move(Callsites), args: std::move(Allocs));
10095
10096 FS->setModulePath(ModulePath);
10097
10098 return addGlobalValueToIndex(Name, GUID,
10099 Linkage: (GlobalValue::LinkageTypes)GVFlags.Linkage, ID,
10100 Summary: std::move(FS), Loc);
10101}
10102
10103/// VariableSummary
10104/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10105/// [',' OptionalRefs]? ')'
10106bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10107 unsigned ID) {
10108 LocTy Loc = Lex.getLoc();
10109 assert(Lex.getKind() == lltok::kw_variable);
10110 Lex.Lex();
10111
10112 StringRef ModulePath;
10113 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10114 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
10115 /*NotEligibleToImport=*/false,
10116 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10117 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10118 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10119 /* WriteOnly */ false,
10120 /* Constant */ false,
10121 GlobalObject::VCallVisibilityPublic);
10122 SmallVector<ValueInfo, 0> Refs;
10123 VTableFuncList VTableFuncs;
10124 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10125 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
10126 parseModuleReference(ModulePath) ||
10127 parseToken(T: lltok::comma, ErrMsg: "expected ',' here") || parseGVFlags(GVFlags) ||
10128 parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
10129 parseGVarFlags(GVarFlags))
10130 return true;
10131
10132 // parse optional fields
10133 while (EatIfPresent(T: lltok::comma)) {
10134 switch (Lex.getKind()) {
10135 case lltok::kw_vTableFuncs:
10136 if (parseOptionalVTableFuncs(VTableFuncs))
10137 return true;
10138 break;
10139 case lltok::kw_refs:
10140 if (parseOptionalRefs(Refs))
10141 return true;
10142 break;
10143 default:
10144 return error(L: Lex.getLoc(), Msg: "expected optional variable summary field");
10145 }
10146 }
10147
10148 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10149 return true;
10150
10151 auto GS =
10152 std::make_unique<GlobalVarSummary>(args&: GVFlags, args&: GVarFlags, args: std::move(Refs));
10153
10154 GS->setModulePath(ModulePath);
10155 GS->setVTableFuncs(std::move(VTableFuncs));
10156
10157 return addGlobalValueToIndex(Name, GUID,
10158 Linkage: (GlobalValue::LinkageTypes)GVFlags.Linkage, ID,
10159 Summary: std::move(GS), Loc);
10160}
10161
10162/// AliasSummary
10163/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10164/// 'aliasee' ':' GVReference ')'
10165bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10166 unsigned ID) {
10167 assert(Lex.getKind() == lltok::kw_alias);
10168 LocTy Loc = Lex.getLoc();
10169 Lex.Lex();
10170
10171 StringRef ModulePath;
10172 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10173 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
10174 /*NotEligibleToImport=*/false,
10175 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10176 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10177 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10178 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
10179 parseModuleReference(ModulePath) ||
10180 parseToken(T: lltok::comma, ErrMsg: "expected ',' here") || parseGVFlags(GVFlags) ||
10181 parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
10182 parseToken(T: lltok::kw_aliasee, ErrMsg: "expected 'aliasee' here") ||
10183 parseToken(T: lltok::colon, ErrMsg: "expected ':' here"))
10184 return true;
10185
10186 ValueInfo AliaseeVI;
10187 unsigned GVId;
10188 auto AS = std::make_unique<AliasSummary>(args&: GVFlags);
10189 AS->setModulePath(ModulePath);
10190
10191 if (!EatIfPresent(T: lltok::kw_null)) {
10192 if (parseGVReference(VI&: AliaseeVI, GVId))
10193 return true;
10194
10195 // Record forward reference if the aliasee is not parsed yet.
10196 if (AliaseeVI.getRef() == FwdVIRef) {
10197 ForwardRefAliasees[GVId].emplace_back(args: AS.get(), args&: Loc);
10198 } else {
10199 auto Summary = Index->findSummaryInModule(VI: AliaseeVI, ModuleId: ModulePath);
10200 assert(Summary && "Aliasee must be a definition");
10201 AS->setAliasee(AliaseeVI, Aliasee: Summary);
10202 }
10203 }
10204
10205 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10206 return true;
10207
10208 return addGlobalValueToIndex(Name, GUID,
10209 Linkage: (GlobalValue::LinkageTypes)GVFlags.Linkage, ID,
10210 Summary: std::move(AS), Loc);
10211}
10212
10213/// Flag
10214/// ::= [0|1]
10215bool LLParser::parseFlag(unsigned &Val) {
10216 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10217 return tokError(Msg: "expected integer");
10218 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10219 Lex.Lex();
10220 return false;
10221}
10222
10223/// OptionalFFlags
10224/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10225/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10226/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10227/// [',' 'noInline' ':' Flag]? ')'
10228/// [',' 'alwaysInline' ':' Flag]? ')'
10229/// [',' 'noUnwind' ':' Flag]? ')'
10230/// [',' 'mayThrow' ':' Flag]? ')'
10231/// [',' 'hasUnknownCall' ':' Flag]? ')'
10232/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10233
10234bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10235 assert(Lex.getKind() == lltok::kw_funcFlags);
10236 Lex.Lex();
10237
10238 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in funcFlags") ||
10239 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in funcFlags"))
10240 return true;
10241
10242 do {
10243 unsigned Val = 0;
10244 switch (Lex.getKind()) {
10245 case lltok::kw_readNone:
10246 Lex.Lex();
10247 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val))
10248 return true;
10249 FFlags.ReadNone = Val;
10250 break;
10251 case lltok::kw_readOnly:
10252 Lex.Lex();
10253 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val))
10254 return true;
10255 FFlags.ReadOnly = Val;
10256 break;
10257 case lltok::kw_noRecurse:
10258 Lex.Lex();
10259 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val))
10260 return true;
10261 FFlags.NoRecurse = Val;
10262 break;
10263 case lltok::kw_returnDoesNotAlias:
10264 Lex.Lex();
10265 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val))
10266 return true;
10267 FFlags.ReturnDoesNotAlias = Val;
10268 break;
10269 case lltok::kw_noInline:
10270 Lex.Lex();
10271 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val))
10272 return true;
10273 FFlags.NoInline = Val;
10274 break;
10275 case lltok::kw_alwaysInline:
10276 Lex.Lex();
10277 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val))
10278 return true;
10279 FFlags.AlwaysInline = Val;
10280 break;
10281 case lltok::kw_noUnwind:
10282 Lex.Lex();
10283 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val))
10284 return true;
10285 FFlags.NoUnwind = Val;
10286 break;
10287 case lltok::kw_mayThrow:
10288 Lex.Lex();
10289 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val))
10290 return true;
10291 FFlags.MayThrow = Val;
10292 break;
10293 case lltok::kw_hasUnknownCall:
10294 Lex.Lex();
10295 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val))
10296 return true;
10297 FFlags.HasUnknownCall = Val;
10298 break;
10299 case lltok::kw_mustBeUnreachable:
10300 Lex.Lex();
10301 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val))
10302 return true;
10303 FFlags.MustBeUnreachable = Val;
10304 break;
10305 default:
10306 return error(L: Lex.getLoc(), Msg: "expected function flag type");
10307 }
10308 } while (EatIfPresent(T: lltok::comma));
10309
10310 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in funcFlags"))
10311 return true;
10312
10313 return false;
10314}
10315
10316/// OptionalCalls
10317/// := 'calls' ':' '(' Call [',' Call]* ')'
10318/// Call ::= '(' 'callee' ':' GVReference
10319/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10320/// [ ',' 'tail' ]? ')'
10321bool LLParser::parseOptionalCalls(
10322 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10323 assert(Lex.getKind() == lltok::kw_calls);
10324 Lex.Lex();
10325
10326 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in calls") ||
10327 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in calls"))
10328 return true;
10329
10330 IdToIndexMapType IdToIndexMap;
10331 // parse each call edge
10332 do {
10333 ValueInfo VI;
10334 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in call") ||
10335 parseToken(T: lltok::kw_callee, ErrMsg: "expected 'callee' in call") ||
10336 parseToken(T: lltok::colon, ErrMsg: "expected ':'"))
10337 return true;
10338
10339 LocTy Loc = Lex.getLoc();
10340 unsigned GVId;
10341 if (parseGVReference(VI, GVId))
10342 return true;
10343
10344 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
10345 unsigned RelBF = 0;
10346 unsigned HasTailCall = false;
10347
10348 // parse optional fields
10349 while (EatIfPresent(T: lltok::comma)) {
10350 switch (Lex.getKind()) {
10351 case lltok::kw_hotness:
10352 Lex.Lex();
10353 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseHotness(Hotness))
10354 return true;
10355 break;
10356 // Deprecated, keep in order to support old files.
10357 case lltok::kw_relbf:
10358 Lex.Lex();
10359 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseUInt32(Val&: RelBF))
10360 return true;
10361 break;
10362 case lltok::kw_tail:
10363 Lex.Lex();
10364 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val&: HasTailCall))
10365 return true;
10366 break;
10367 default:
10368 return error(L: Lex.getLoc(), Msg: "expected hotness, relbf, or tail");
10369 }
10370 }
10371 // Keep track of the Call array index needing a forward reference.
10372 // We will save the location of the ValueInfo needing an update, but
10373 // can only do so once the std::vector is finalized.
10374 if (VI.getRef() == FwdVIRef)
10375 IdToIndexMap[GVId].push_back(x: std::make_pair(x: Calls.size(), y&: Loc));
10376 Calls.push_back(
10377 Elt: FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall)});
10378
10379 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in call"))
10380 return true;
10381 } while (EatIfPresent(T: lltok::comma));
10382
10383 // Now that the Calls vector is finalized, it is safe to save the locations
10384 // of any forward GV references that need updating later.
10385 for (auto I : IdToIndexMap) {
10386 auto &Infos = ForwardRefValueInfos[I.first];
10387 for (auto P : I.second) {
10388 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10389 "Forward referenced ValueInfo expected to be empty");
10390 Infos.emplace_back(args: &Calls[P.first].first, args&: P.second);
10391 }
10392 }
10393
10394 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in calls"))
10395 return true;
10396
10397 return false;
10398}
10399
10400/// Hotness
10401/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10402bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10403 switch (Lex.getKind()) {
10404 case lltok::kw_unknown:
10405 Hotness = CalleeInfo::HotnessType::Unknown;
10406 break;
10407 case lltok::kw_cold:
10408 Hotness = CalleeInfo::HotnessType::Cold;
10409 break;
10410 case lltok::kw_none:
10411 Hotness = CalleeInfo::HotnessType::None;
10412 break;
10413 case lltok::kw_hot:
10414 Hotness = CalleeInfo::HotnessType::Hot;
10415 break;
10416 case lltok::kw_critical:
10417 Hotness = CalleeInfo::HotnessType::Critical;
10418 break;
10419 default:
10420 return error(L: Lex.getLoc(), Msg: "invalid call edge hotness");
10421 }
10422 Lex.Lex();
10423 return false;
10424}
10425
10426/// OptionalVTableFuncs
10427/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10428/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10429bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10430 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10431 Lex.Lex();
10432
10433 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in vTableFuncs") ||
10434 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in vTableFuncs"))
10435 return true;
10436
10437 IdToIndexMapType IdToIndexMap;
10438 // parse each virtual function pair
10439 do {
10440 ValueInfo VI;
10441 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in vTableFunc") ||
10442 parseToken(T: lltok::kw_virtFunc, ErrMsg: "expected 'callee' in vTableFunc") ||
10443 parseToken(T: lltok::colon, ErrMsg: "expected ':'"))
10444 return true;
10445
10446 LocTy Loc = Lex.getLoc();
10447 unsigned GVId;
10448 if (parseGVReference(VI, GVId))
10449 return true;
10450
10451 uint64_t Offset;
10452 if (parseToken(T: lltok::comma, ErrMsg: "expected comma") ||
10453 parseToken(T: lltok::kw_offset, ErrMsg: "expected offset") ||
10454 parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseUInt64(Val&: Offset))
10455 return true;
10456
10457 // Keep track of the VTableFuncs array index needing a forward reference.
10458 // We will save the location of the ValueInfo needing an update, but
10459 // can only do so once the std::vector is finalized.
10460 if (VI == EmptyVI)
10461 IdToIndexMap[GVId].push_back(x: std::make_pair(x: VTableFuncs.size(), y&: Loc));
10462 VTableFuncs.push_back(x: {VI, Offset});
10463
10464 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in vTableFunc"))
10465 return true;
10466 } while (EatIfPresent(T: lltok::comma));
10467
10468 // Now that the VTableFuncs vector is finalized, it is safe to save the
10469 // locations of any forward GV references that need updating later.
10470 for (auto I : IdToIndexMap) {
10471 auto &Infos = ForwardRefValueInfos[I.first];
10472 for (auto P : I.second) {
10473 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10474 "Forward referenced ValueInfo expected to be empty");
10475 Infos.emplace_back(args: &VTableFuncs[P.first].FuncVI, args&: P.second);
10476 }
10477 }
10478
10479 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in vTableFuncs"))
10480 return true;
10481
10482 return false;
10483}
10484
10485/// ParamNo := 'param' ':' UInt64
10486bool LLParser::parseParamNo(uint64_t &ParamNo) {
10487 if (parseToken(T: lltok::kw_param, ErrMsg: "expected 'param' here") ||
10488 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") || parseUInt64(Val&: ParamNo))
10489 return true;
10490 return false;
10491}
10492
10493/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10494bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10495 APSInt Lower;
10496 APSInt Upper;
10497 auto ParseAPSInt = [&](APSInt &Val) {
10498 if (Lex.getKind() != lltok::APSInt)
10499 return tokError(Msg: "expected integer");
10500 Val = Lex.getAPSIntVal();
10501 Val = Val.extOrTrunc(width: FunctionSummary::ParamAccess::RangeWidth);
10502 Val.setIsSigned(true);
10503 Lex.Lex();
10504 return false;
10505 };
10506 if (parseToken(T: lltok::kw_offset, ErrMsg: "expected 'offset' here") ||
10507 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10508 parseToken(T: lltok::lsquare, ErrMsg: "expected '[' here") || ParseAPSInt(Lower) ||
10509 parseToken(T: lltok::comma, ErrMsg: "expected ',' here") || ParseAPSInt(Upper) ||
10510 parseToken(T: lltok::rsquare, ErrMsg: "expected ']' here"))
10511 return true;
10512
10513 ++Upper;
10514 Range =
10515 (Lower == Upper && !Lower.isMaxValue())
10516 ? ConstantRange::getEmpty(BitWidth: FunctionSummary::ParamAccess::RangeWidth)
10517 : ConstantRange(Lower, Upper);
10518
10519 return false;
10520}
10521
10522/// ParamAccessCall
10523/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10524bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10525 IdLocListType &IdLocList) {
10526 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
10527 parseToken(T: lltok::kw_callee, ErrMsg: "expected 'callee' here") ||
10528 parseToken(T: lltok::colon, ErrMsg: "expected ':' here"))
10529 return true;
10530
10531 unsigned GVId;
10532 ValueInfo VI;
10533 LocTy Loc = Lex.getLoc();
10534 if (parseGVReference(VI, GVId))
10535 return true;
10536
10537 Call.Callee = VI;
10538 IdLocList.emplace_back(args&: GVId, args&: Loc);
10539
10540 if (parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
10541 parseParamNo(ParamNo&: Call.ParamNo) ||
10542 parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
10543 parseParamAccessOffset(Range&: Call.Offsets))
10544 return true;
10545
10546 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10547 return true;
10548
10549 return false;
10550}
10551
10552/// ParamAccess
10553/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10554/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10555bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10556 IdLocListType &IdLocList) {
10557 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
10558 parseParamNo(ParamNo&: Param.ParamNo) ||
10559 parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
10560 parseParamAccessOffset(Range&: Param.Use))
10561 return true;
10562
10563 if (EatIfPresent(T: lltok::comma)) {
10564 if (parseToken(T: lltok::kw_calls, ErrMsg: "expected 'calls' here") ||
10565 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10566 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
10567 return true;
10568 do {
10569 FunctionSummary::ParamAccess::Call Call;
10570 if (parseParamAccessCall(Call, IdLocList))
10571 return true;
10572 Param.Calls.push_back(x: Call);
10573 } while (EatIfPresent(T: lltok::comma));
10574
10575 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10576 return true;
10577 }
10578
10579 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10580 return true;
10581
10582 return false;
10583}
10584
10585/// OptionalParamAccesses
10586/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10587bool LLParser::parseOptionalParamAccesses(
10588 std::vector<FunctionSummary::ParamAccess> &Params) {
10589 assert(Lex.getKind() == lltok::kw_params);
10590 Lex.Lex();
10591
10592 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10593 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
10594 return true;
10595
10596 IdLocListType VContexts;
10597 size_t CallsNum = 0;
10598 do {
10599 FunctionSummary::ParamAccess ParamAccess;
10600 if (parseParamAccess(Param&: ParamAccess, IdLocList&: VContexts))
10601 return true;
10602 CallsNum += ParamAccess.Calls.size();
10603 assert(VContexts.size() == CallsNum);
10604 (void)CallsNum;
10605 Params.emplace_back(args: std::move(ParamAccess));
10606 } while (EatIfPresent(T: lltok::comma));
10607
10608 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10609 return true;
10610
10611 // Now that the Params is finalized, it is safe to save the locations
10612 // of any forward GV references that need updating later.
10613 IdLocListType::const_iterator ItContext = VContexts.begin();
10614 for (auto &PA : Params) {
10615 for (auto &C : PA.Calls) {
10616 if (C.Callee.getRef() == FwdVIRef)
10617 ForwardRefValueInfos[ItContext->first].emplace_back(args: &C.Callee,
10618 args: ItContext->second);
10619 ++ItContext;
10620 }
10621 }
10622 assert(ItContext == VContexts.end());
10623
10624 return false;
10625}
10626
10627/// OptionalRefs
10628/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10629bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10630 assert(Lex.getKind() == lltok::kw_refs);
10631 Lex.Lex();
10632
10633 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in refs") ||
10634 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in refs"))
10635 return true;
10636
10637 struct ValueContext {
10638 ValueInfo VI;
10639 unsigned GVId;
10640 LocTy Loc;
10641 };
10642 std::vector<ValueContext> VContexts;
10643 // parse each ref edge
10644 do {
10645 ValueContext VC;
10646 VC.Loc = Lex.getLoc();
10647 if (parseGVReference(VI&: VC.VI, GVId&: VC.GVId))
10648 return true;
10649 VContexts.push_back(x: VC);
10650 } while (EatIfPresent(T: lltok::comma));
10651
10652 // Sort value contexts so that ones with writeonly
10653 // and readonly ValueInfo are at the end of VContexts vector.
10654 // See FunctionSummary::specialRefCounts()
10655 llvm::sort(C&: VContexts, Comp: [](const ValueContext &VC1, const ValueContext &VC2) {
10656 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10657 });
10658
10659 IdToIndexMapType IdToIndexMap;
10660 for (auto &VC : VContexts) {
10661 // Keep track of the Refs array index needing a forward reference.
10662 // We will save the location of the ValueInfo needing an update, but
10663 // can only do so once the std::vector is finalized.
10664 if (VC.VI.getRef() == FwdVIRef)
10665 IdToIndexMap[VC.GVId].push_back(x: std::make_pair(x: Refs.size(), y&: VC.Loc));
10666 Refs.push_back(Elt: VC.VI);
10667 }
10668
10669 // Now that the Refs vector is finalized, it is safe to save the locations
10670 // of any forward GV references that need updating later.
10671 for (auto I : IdToIndexMap) {
10672 auto &Infos = ForwardRefValueInfos[I.first];
10673 for (auto P : I.second) {
10674 assert(Refs[P.first].getRef() == FwdVIRef &&
10675 "Forward referenced ValueInfo expected to be empty");
10676 Infos.emplace_back(args: &Refs[P.first], args&: P.second);
10677 }
10678 }
10679
10680 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in refs"))
10681 return true;
10682
10683 return false;
10684}
10685
10686/// OptionalTypeIdInfo
10687/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10688/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10689/// [',' TypeCheckedLoadConstVCalls]? ')'
10690bool LLParser::parseOptionalTypeIdInfo(
10691 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10692 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10693 Lex.Lex();
10694
10695 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10696 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in typeIdInfo"))
10697 return true;
10698
10699 do {
10700 switch (Lex.getKind()) {
10701 case lltok::kw_typeTests:
10702 if (parseTypeTests(TypeTests&: TypeIdInfo.TypeTests))
10703 return true;
10704 break;
10705 case lltok::kw_typeTestAssumeVCalls:
10706 if (parseVFuncIdList(Kind: lltok::kw_typeTestAssumeVCalls,
10707 VFuncIdList&: TypeIdInfo.TypeTestAssumeVCalls))
10708 return true;
10709 break;
10710 case lltok::kw_typeCheckedLoadVCalls:
10711 if (parseVFuncIdList(Kind: lltok::kw_typeCheckedLoadVCalls,
10712 VFuncIdList&: TypeIdInfo.TypeCheckedLoadVCalls))
10713 return true;
10714 break;
10715 case lltok::kw_typeTestAssumeConstVCalls:
10716 if (parseConstVCallList(Kind: lltok::kw_typeTestAssumeConstVCalls,
10717 ConstVCallList&: TypeIdInfo.TypeTestAssumeConstVCalls))
10718 return true;
10719 break;
10720 case lltok::kw_typeCheckedLoadConstVCalls:
10721 if (parseConstVCallList(Kind: lltok::kw_typeCheckedLoadConstVCalls,
10722 ConstVCallList&: TypeIdInfo.TypeCheckedLoadConstVCalls))
10723 return true;
10724 break;
10725 default:
10726 return error(L: Lex.getLoc(), Msg: "invalid typeIdInfo list type");
10727 }
10728 } while (EatIfPresent(T: lltok::comma));
10729
10730 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in typeIdInfo"))
10731 return true;
10732
10733 return false;
10734}
10735
10736/// TypeTests
10737/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10738/// [',' (SummaryID | UInt64)]* ')'
10739bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10740 assert(Lex.getKind() == lltok::kw_typeTests);
10741 Lex.Lex();
10742
10743 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10744 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in typeIdInfo"))
10745 return true;
10746
10747 IdToIndexMapType IdToIndexMap;
10748 do {
10749 GlobalValue::GUID GUID = 0;
10750 if (Lex.getKind() == lltok::SummaryID) {
10751 unsigned ID = Lex.getUIntVal();
10752 LocTy Loc = Lex.getLoc();
10753 // Keep track of the TypeTests array index needing a forward reference.
10754 // We will save the location of the GUID needing an update, but
10755 // can only do so once the std::vector is finalized.
10756 IdToIndexMap[ID].push_back(x: std::make_pair(x: TypeTests.size(), y&: Loc));
10757 Lex.Lex();
10758 } else if (parseUInt64(Val&: GUID))
10759 return true;
10760 TypeTests.push_back(x: GUID);
10761 } while (EatIfPresent(T: lltok::comma));
10762
10763 // Now that the TypeTests vector is finalized, it is safe to save the
10764 // locations of any forward GV references that need updating later.
10765 for (auto I : IdToIndexMap) {
10766 auto &Ids = ForwardRefTypeIds[I.first];
10767 for (auto P : I.second) {
10768 assert(TypeTests[P.first] == 0 &&
10769 "Forward referenced type id GUID expected to be 0");
10770 Ids.emplace_back(args: &TypeTests[P.first], args&: P.second);
10771 }
10772 }
10773
10774 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in typeIdInfo"))
10775 return true;
10776
10777 return false;
10778}
10779
10780/// VFuncIdList
10781/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10782bool LLParser::parseVFuncIdList(
10783 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10784 assert(Lex.getKind() == Kind);
10785 Lex.Lex();
10786
10787 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10788 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
10789 return true;
10790
10791 IdToIndexMapType IdToIndexMap;
10792 do {
10793 FunctionSummary::VFuncId VFuncId;
10794 if (parseVFuncId(VFuncId, IdToIndexMap, Index: VFuncIdList.size()))
10795 return true;
10796 VFuncIdList.push_back(x: VFuncId);
10797 } while (EatIfPresent(T: lltok::comma));
10798
10799 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10800 return true;
10801
10802 // Now that the VFuncIdList vector is finalized, it is safe to save the
10803 // locations of any forward GV references that need updating later.
10804 for (auto I : IdToIndexMap) {
10805 auto &Ids = ForwardRefTypeIds[I.first];
10806 for (auto P : I.second) {
10807 assert(VFuncIdList[P.first].GUID == 0 &&
10808 "Forward referenced type id GUID expected to be 0");
10809 Ids.emplace_back(args: &VFuncIdList[P.first].GUID, args&: P.second);
10810 }
10811 }
10812
10813 return false;
10814}
10815
10816/// ConstVCallList
10817/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10818bool LLParser::parseConstVCallList(
10819 lltok::Kind Kind,
10820 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10821 assert(Lex.getKind() == Kind);
10822 Lex.Lex();
10823
10824 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10825 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
10826 return true;
10827
10828 IdToIndexMapType IdToIndexMap;
10829 do {
10830 FunctionSummary::ConstVCall ConstVCall;
10831 if (parseConstVCall(ConstVCall, IdToIndexMap, Index: ConstVCallList.size()))
10832 return true;
10833 ConstVCallList.push_back(x: ConstVCall);
10834 } while (EatIfPresent(T: lltok::comma));
10835
10836 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10837 return true;
10838
10839 // Now that the ConstVCallList vector is finalized, it is safe to save the
10840 // locations of any forward GV references that need updating later.
10841 for (auto I : IdToIndexMap) {
10842 auto &Ids = ForwardRefTypeIds[I.first];
10843 for (auto P : I.second) {
10844 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10845 "Forward referenced type id GUID expected to be 0");
10846 Ids.emplace_back(args: &ConstVCallList[P.first].VFunc.GUID, args&: P.second);
10847 }
10848 }
10849
10850 return false;
10851}
10852
10853/// ConstVCall
10854/// ::= '(' VFuncId ',' Args ')'
10855bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10856 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10857 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' here") ||
10858 parseVFuncId(VFuncId&: ConstVCall.VFunc, IdToIndexMap, Index))
10859 return true;
10860
10861 if (EatIfPresent(T: lltok::comma))
10862 if (parseArgs(Args&: ConstVCall.Args))
10863 return true;
10864
10865 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10866 return true;
10867
10868 return false;
10869}
10870
10871/// VFuncId
10872/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10873/// 'offset' ':' UInt64 ')'
10874bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10875 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10876 assert(Lex.getKind() == lltok::kw_vFuncId);
10877 Lex.Lex();
10878
10879 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10880 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
10881 return true;
10882
10883 if (Lex.getKind() == lltok::SummaryID) {
10884 VFuncId.GUID = 0;
10885 unsigned ID = Lex.getUIntVal();
10886 LocTy Loc = Lex.getLoc();
10887 // Keep track of the array index needing a forward reference.
10888 // We will save the location of the GUID needing an update, but
10889 // can only do so once the caller's std::vector is finalized.
10890 IdToIndexMap[ID].push_back(x: std::make_pair(x&: Index, y&: Loc));
10891 Lex.Lex();
10892 } else if (parseToken(T: lltok::kw_guid, ErrMsg: "expected 'guid' here") ||
10893 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10894 parseUInt64(Val&: VFuncId.GUID))
10895 return true;
10896
10897 if (parseToken(T: lltok::comma, ErrMsg: "expected ',' here") ||
10898 parseToken(T: lltok::kw_offset, ErrMsg: "expected 'offset' here") ||
10899 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10900 parseUInt64(Val&: VFuncId.Offset) ||
10901 parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10902 return true;
10903
10904 return false;
10905}
10906
10907/// GVFlags
10908/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10909/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10910/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10911/// 'canAutoHide' ':' Flag ',' ')'
10912bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10913 assert(Lex.getKind() == lltok::kw_flags);
10914 Lex.Lex();
10915
10916 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10917 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
10918 return true;
10919
10920 do {
10921 unsigned Flag = 0;
10922 switch (Lex.getKind()) {
10923 case lltok::kw_linkage:
10924 Lex.Lex();
10925 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'"))
10926 return true;
10927 bool HasLinkage;
10928 GVFlags.Linkage = parseOptionalLinkageAux(Kind: Lex.getKind(), HasLinkage);
10929 assert(HasLinkage && "Linkage not optional in summary entry");
10930 Lex.Lex();
10931 break;
10932 case lltok::kw_visibility:
10933 Lex.Lex();
10934 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'"))
10935 return true;
10936 parseOptionalVisibility(Res&: Flag);
10937 GVFlags.Visibility = Flag;
10938 break;
10939 case lltok::kw_notEligibleToImport:
10940 Lex.Lex();
10941 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val&: Flag))
10942 return true;
10943 GVFlags.NotEligibleToImport = Flag;
10944 break;
10945 case lltok::kw_live:
10946 Lex.Lex();
10947 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val&: Flag))
10948 return true;
10949 GVFlags.Live = Flag;
10950 break;
10951 case lltok::kw_dsoLocal:
10952 Lex.Lex();
10953 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val&: Flag))
10954 return true;
10955 GVFlags.DSOLocal = Flag;
10956 break;
10957 case lltok::kw_canAutoHide:
10958 Lex.Lex();
10959 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val&: Flag))
10960 return true;
10961 GVFlags.CanAutoHide = Flag;
10962 break;
10963 case lltok::kw_importType:
10964 Lex.Lex();
10965 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'"))
10966 return true;
10967 GlobalValueSummary::ImportKind IK;
10968 if (parseOptionalImportType(Kind: Lex.getKind(), Res&: IK))
10969 return true;
10970 GVFlags.ImportType = static_cast<unsigned>(IK);
10971 Lex.Lex();
10972 break;
10973 case lltok::kw_noRenameOnPromotion:
10974 Lex.Lex();
10975 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'") || parseFlag(Val&: Flag))
10976 return true;
10977 GVFlags.NoRenameOnPromotion = Flag;
10978 break;
10979 default:
10980 return error(L: Lex.getLoc(), Msg: "expected gv flag type");
10981 }
10982 } while (EatIfPresent(T: lltok::comma));
10983
10984 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' here"))
10985 return true;
10986
10987 return false;
10988}
10989
10990/// GVarFlags
10991/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
10992/// ',' 'writeonly' ':' Flag
10993/// ',' 'constant' ':' Flag ')'
10994bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10995 assert(Lex.getKind() == lltok::kw_varFlags);
10996 Lex.Lex();
10997
10998 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
10999 parseToken(T: lltok::lparen, ErrMsg: "expected '(' here"))
11000 return true;
11001
11002 auto ParseRest = [this](unsigned int &Val) {
11003 Lex.Lex();
11004 if (parseToken(T: lltok::colon, ErrMsg: "expected ':'"))
11005 return true;
11006 return parseFlag(Val);
11007 };
11008
11009 do {
11010 unsigned Flag = 0;
11011 switch (Lex.getKind()) {
11012 case lltok::kw_readonly:
11013 if (ParseRest(Flag))
11014 return true;
11015 GVarFlags.MaybeReadOnly = Flag;
11016 break;
11017 case lltok::kw_writeonly:
11018 if (ParseRest(Flag))
11019 return true;
11020 GVarFlags.MaybeWriteOnly = Flag;
11021 break;
11022 case lltok::kw_constant:
11023 if (ParseRest(Flag))
11024 return true;
11025 GVarFlags.Constant = Flag;
11026 break;
11027 case lltok::kw_vcall_visibility:
11028 if (ParseRest(Flag))
11029 return true;
11030 GVarFlags.VCallVisibility = Flag;
11031 break;
11032 default:
11033 return error(L: Lex.getLoc(), Msg: "expected gvar flag type");
11034 }
11035 } while (EatIfPresent(T: lltok::comma));
11036 return parseToken(T: lltok::rparen, ErrMsg: "expected ')' here");
11037}
11038
11039/// ModuleReference
11040/// ::= 'module' ':' UInt
11041bool LLParser::parseModuleReference(StringRef &ModulePath) {
11042 // parse module id.
11043 if (parseToken(T: lltok::kw_module, ErrMsg: "expected 'module' here") ||
11044 parseToken(T: lltok::colon, ErrMsg: "expected ':' here") ||
11045 parseToken(T: lltok::SummaryID, ErrMsg: "expected module ID"))
11046 return true;
11047
11048 unsigned ModuleID = Lex.getUIntVal();
11049 auto I = ModuleIdMap.find(x: ModuleID);
11050 // We should have already parsed all module IDs
11051 assert(I != ModuleIdMap.end());
11052 ModulePath = I->second;
11053 return false;
11054}
11055
11056/// GVReference
11057/// ::= SummaryID
11058bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11059 bool WriteOnly = false, ReadOnly = EatIfPresent(T: lltok::kw_readonly);
11060 if (!ReadOnly)
11061 WriteOnly = EatIfPresent(T: lltok::kw_writeonly);
11062 if (parseToken(T: lltok::SummaryID, ErrMsg: "expected GV ID"))
11063 return true;
11064
11065 GVId = Lex.getUIntVal();
11066 // Check if we already have a VI for this GV
11067 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11068 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11069 VI = NumberedValueInfos[GVId];
11070 } else
11071 // We will create a forward reference to the stored location.
11072 VI = ValueInfo(false, FwdVIRef);
11073
11074 if (ReadOnly)
11075 VI.setReadOnly();
11076 if (WriteOnly)
11077 VI.setWriteOnly();
11078 return false;
11079}
11080
11081/// OptionalAllocs
11082/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11083/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11084/// ',' MemProfs ')'
11085/// Version ::= UInt32
11086bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11087 assert(Lex.getKind() == lltok::kw_allocs);
11088 Lex.Lex();
11089
11090 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in allocs") ||
11091 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in allocs"))
11092 return true;
11093
11094 // parse each alloc
11095 do {
11096 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in alloc") ||
11097 parseToken(T: lltok::kw_versions, ErrMsg: "expected 'versions' in alloc") ||
11098 parseToken(T: lltok::colon, ErrMsg: "expected ':'") ||
11099 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in versions"))
11100 return true;
11101
11102 SmallVector<uint8_t> Versions;
11103 do {
11104 uint8_t V = 0;
11105 if (parseAllocType(AllocType&: V))
11106 return true;
11107 Versions.push_back(Elt: V);
11108 } while (EatIfPresent(T: lltok::comma));
11109
11110 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in versions") ||
11111 parseToken(T: lltok::comma, ErrMsg: "expected ',' in alloc"))
11112 return true;
11113
11114 std::vector<MIBInfo> MIBs;
11115 if (parseMemProfs(MIBs))
11116 return true;
11117
11118 Allocs.push_back(x: {Versions, MIBs});
11119
11120 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in alloc"))
11121 return true;
11122 } while (EatIfPresent(T: lltok::comma));
11123
11124 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in allocs"))
11125 return true;
11126
11127 return false;
11128}
11129
11130/// MemProfs
11131/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11132/// MemProf ::= '(' 'type' ':' AllocType
11133/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11134/// StackId ::= UInt64
11135bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11136 assert(Lex.getKind() == lltok::kw_memProf);
11137 Lex.Lex();
11138
11139 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in memprof") ||
11140 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in memprof"))
11141 return true;
11142
11143 // parse each MIB
11144 do {
11145 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in memprof") ||
11146 parseToken(T: lltok::kw_type, ErrMsg: "expected 'type' in memprof") ||
11147 parseToken(T: lltok::colon, ErrMsg: "expected ':'"))
11148 return true;
11149
11150 uint8_t AllocType;
11151 if (parseAllocType(AllocType))
11152 return true;
11153
11154 if (parseToken(T: lltok::comma, ErrMsg: "expected ',' in memprof") ||
11155 parseToken(T: lltok::kw_stackIds, ErrMsg: "expected 'stackIds' in memprof") ||
11156 parseToken(T: lltok::colon, ErrMsg: "expected ':'") ||
11157 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in stackIds"))
11158 return true;
11159
11160 SmallVector<unsigned> StackIdIndices;
11161 // Combined index alloc records may not have a stack id list.
11162 if (Lex.getKind() != lltok::rparen) {
11163 do {
11164 uint64_t StackId = 0;
11165 if (parseUInt64(Val&: StackId))
11166 return true;
11167 StackIdIndices.push_back(Elt: Index->addOrGetStackIdIndex(StackId));
11168 } while (EatIfPresent(T: lltok::comma));
11169 }
11170
11171 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in stackIds"))
11172 return true;
11173
11174 MIBs.push_back(x: {(AllocationType)AllocType, StackIdIndices});
11175
11176 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in memprof"))
11177 return true;
11178 } while (EatIfPresent(T: lltok::comma));
11179
11180 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in memprof"))
11181 return true;
11182
11183 return false;
11184}
11185
11186/// AllocType
11187/// := ('none'|'notcold'|'cold'|'hot')
11188bool LLParser::parseAllocType(uint8_t &AllocType) {
11189 switch (Lex.getKind()) {
11190 case lltok::kw_none:
11191 AllocType = (uint8_t)AllocationType::None;
11192 break;
11193 case lltok::kw_notcold:
11194 AllocType = (uint8_t)AllocationType::NotCold;
11195 break;
11196 case lltok::kw_cold:
11197 AllocType = (uint8_t)AllocationType::Cold;
11198 break;
11199 case lltok::kw_hot:
11200 AllocType = (uint8_t)AllocationType::Hot;
11201 break;
11202 default:
11203 return error(L: Lex.getLoc(), Msg: "invalid alloc type");
11204 }
11205 Lex.Lex();
11206 return false;
11207}
11208
11209/// OptionalCallsites
11210/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11211/// Callsite ::= '(' 'callee' ':' GVReference
11212/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11213/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11214/// Version ::= UInt32
11215/// StackId ::= UInt64
11216bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11217 assert(Lex.getKind() == lltok::kw_callsites);
11218 Lex.Lex();
11219
11220 if (parseToken(T: lltok::colon, ErrMsg: "expected ':' in callsites") ||
11221 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in callsites"))
11222 return true;
11223
11224 IdToIndexMapType IdToIndexMap;
11225 // parse each callsite
11226 do {
11227 if (parseToken(T: lltok::lparen, ErrMsg: "expected '(' in callsite") ||
11228 parseToken(T: lltok::kw_callee, ErrMsg: "expected 'callee' in callsite") ||
11229 parseToken(T: lltok::colon, ErrMsg: "expected ':'"))
11230 return true;
11231
11232 ValueInfo VI;
11233 unsigned GVId = 0;
11234 LocTy Loc = Lex.getLoc();
11235 if (!EatIfPresent(T: lltok::kw_null)) {
11236 if (parseGVReference(VI, GVId))
11237 return true;
11238 }
11239
11240 if (parseToken(T: lltok::comma, ErrMsg: "expected ',' in callsite") ||
11241 parseToken(T: lltok::kw_clones, ErrMsg: "expected 'clones' in callsite") ||
11242 parseToken(T: lltok::colon, ErrMsg: "expected ':'") ||
11243 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in clones"))
11244 return true;
11245
11246 SmallVector<unsigned> Clones;
11247 do {
11248 unsigned V = 0;
11249 if (parseUInt32(Val&: V))
11250 return true;
11251 Clones.push_back(Elt: V);
11252 } while (EatIfPresent(T: lltok::comma));
11253
11254 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in clones") ||
11255 parseToken(T: lltok::comma, ErrMsg: "expected ',' in callsite") ||
11256 parseToken(T: lltok::kw_stackIds, ErrMsg: "expected 'stackIds' in callsite") ||
11257 parseToken(T: lltok::colon, ErrMsg: "expected ':'") ||
11258 parseToken(T: lltok::lparen, ErrMsg: "expected '(' in stackIds"))
11259 return true;
11260
11261 SmallVector<unsigned> StackIdIndices;
11262 // Synthesized callsite records will not have a stack id list.
11263 if (Lex.getKind() != lltok::rparen) {
11264 do {
11265 uint64_t StackId = 0;
11266 if (parseUInt64(Val&: StackId))
11267 return true;
11268 StackIdIndices.push_back(Elt: Index->addOrGetStackIdIndex(StackId));
11269 } while (EatIfPresent(T: lltok::comma));
11270 }
11271
11272 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in stackIds"))
11273 return true;
11274
11275 // Keep track of the Callsites array index needing a forward reference.
11276 // We will save the location of the ValueInfo needing an update, but
11277 // can only do so once the SmallVector is finalized.
11278 if (VI.getRef() == FwdVIRef)
11279 IdToIndexMap[GVId].push_back(x: std::make_pair(x: Callsites.size(), y&: Loc));
11280 Callsites.push_back(x: {VI, Clones, StackIdIndices});
11281
11282 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in callsite"))
11283 return true;
11284 } while (EatIfPresent(T: lltok::comma));
11285
11286 // Now that the Callsites vector is finalized, it is safe to save the
11287 // locations of any forward GV references that need updating later.
11288 for (auto I : IdToIndexMap) {
11289 auto &Infos = ForwardRefValueInfos[I.first];
11290 for (auto P : I.second) {
11291 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11292 "Forward referenced ValueInfo expected to be empty");
11293 Infos.emplace_back(args: &Callsites[P.first].Callee, args&: P.second);
11294 }
11295 }
11296
11297 if (parseToken(T: lltok::rparen, ErrMsg: "expected ')' in callsites"))
11298 return true;
11299
11300 return false;
11301}
11302