LLVM 24.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/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"
30#include "llvm/IR/Constants.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/GlobalIFunc.h"
36#include "llvm/IR/InlineAsm.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"
51#include "llvm/Support/ModRef.h"
54#include <algorithm>
55#include <cassert>
56#include <cstring>
57#include <optional>
58#include <vector>
59
60using namespace llvm;
61
63 "allow-incomplete-ir", cl::init(false), cl::Hidden,
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 Lex.getLoc(),
84 "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
96 const SlotMapping *Slots) {
97 restoreParsingState(Slots);
98 Lex.Lex();
99
100 Type *Ty = nullptr;
101 if (parseType(Ty) || parseConstantValue(Ty, C))
102 return true;
103 if (Lex.getKind() != lltok::Eof)
104 return error(Lex.getLoc(), "expected end of string");
105 return false;
106}
107
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(Ty))
117 return true;
118 SMLoc End = Lex.getLoc();
119 Read = End.getPointer() - Start.getPointer();
120
121 return false;
122}
123
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 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
147 for (const auto &I : Slots->Types)
148 NumberedTypes.insert(
149 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
150}
151
153 // White-list intrinsics that are safe to drop.
155 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
156 return;
157
159 for (Value *V : II->args())
160 if (auto *MV = dyn_cast<MetadataAsValue>(V))
161 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
162 if (MD->isTemporary())
163 MVs.push_back(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(instructions(F))) {
181 I.eraseMetadataIf(Pred);
182
183 if (auto *II = dyn_cast<IntrinsicInst>(&I))
185 }
186 }
187
188 for (GlobalVariable &GV : M->globals())
189 GV.eraseMetadataIf(Pred);
190
191 llvm::erase_if(PendingDbgRecords,
192 [](const auto &E) { return std::get<2>(E)->isTemporary(); });
193 llvm::erase_if(PendingDbgInsts,
194 [](const auto &E) { return std::get<2>(E)->isTemporary(); });
195
196 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
197 // Check whether there is only a single use left, which would be in our
198 // own NumberedMetadata.
199 if (Info.first->getNumTemporaryUses() == 1) {
200 NumberedMetadata.erase(ID);
201 ForwardRefMDNodes.erase(ID);
202 }
203 }
204}
205
206/// validateEndOfModule - Do final validity and basic correctness checks at the
207/// end of the module.
208bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
209 if (!M)
210 return false;
211
212 // We should have already returned an error if we observed both intrinsics and
213 // records in this IR.
214 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
215 "Mixed debug intrinsics/records seen without a parsing error?");
216
217 // Handle any function attribute group forward references.
218 for (const auto &RAG : ForwardRefAttrGroups) {
219 Value *V = RAG.first;
220 const std::vector<unsigned> &Attrs = RAG.second;
221 AttrBuilder B(Context);
222
223 for (const auto &Attr : Attrs) {
224 auto R = NumberedAttrBuilders.find(Attr);
225 if (R != NumberedAttrBuilders.end())
226 B.merge(R->second);
227 }
228
229 if (Function *Fn = dyn_cast<Function>(V)) {
230 AttributeList AS = Fn->getAttributes();
231 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
232 AS = AS.removeFnAttributes(Context);
233
234 FnAttrs.merge(B);
235
236 // If the alignment was parsed as an attribute, move to the alignment
237 // field.
238 if (MaybeAlign A = FnAttrs.getAlignment()) {
239 Fn->setAlignment(*A);
240 FnAttrs.removeAttribute(Attribute::Alignment);
241 }
242
243 AS = AS.addFnAttributes(Context, FnAttrs);
244 Fn->setAttributes(AS);
245 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
246 AttributeList AS = CI->getAttributes();
247 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
248 AS = AS.removeFnAttributes(Context);
249 FnAttrs.merge(B);
250 AS = AS.addFnAttributes(Context, FnAttrs);
251 CI->setAttributes(AS);
252 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
253 AttributeList AS = II->getAttributes();
254 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
255 AS = AS.removeFnAttributes(Context);
256 FnAttrs.merge(B);
257 AS = AS.addFnAttributes(Context, FnAttrs);
258 II->setAttributes(AS);
259 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
260 AttributeList AS = CBI->getAttributes();
261 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
262 AS = AS.removeFnAttributes(Context);
263 FnAttrs.merge(B);
264 AS = AS.addFnAttributes(Context, FnAttrs);
265 CBI->setAttributes(AS);
266 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
267 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
268 Attrs.merge(B);
269 GV->setAttributes(AttributeSet::get(Context,Attrs));
270 } else {
271 llvm_unreachable("invalid object with forward attribute group reference");
272 }
273 }
274
275 // If there are entries in ForwardRefBlockAddresses at this point, the
276 // function was never defined.
277 if (!ForwardRefBlockAddresses.empty())
278 return error(ForwardRefBlockAddresses.begin()->first.Loc,
279 "expected function name in blockaddress");
280
281 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
282 GlobalValue *FwdRef) {
283 GlobalValue *GV = nullptr;
284 if (GVRef.Kind == ValID::t_GlobalName) {
285 GV = M->getNamedValue(GVRef.StrVal);
286 } else {
287 GV = NumberedVals.get(GVRef.UIntVal);
288 }
289
290 if (!GV)
291 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
292 "' referenced by dso_local_equivalent");
293
294 if (!GV->getValueType()->isFunctionTy())
295 return error(GVRef.Loc,
296 "expected a function, alias to function, or ifunc "
297 "in dso_local_equivalent");
298
299 auto *Equiv = DSOLocalEquivalent::get(GV);
300 FwdRef->replaceAllUsesWith(Equiv);
301 FwdRef->eraseFromParent();
302 return false;
303 };
304
305 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
306 // point, they are references after the function was defined. Resolve those
307 // now.
308 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
309 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
310 return true;
311 }
312 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
313 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
314 return true;
315 }
316 ForwardRefDSOLocalEquivalentIDs.clear();
317 ForwardRefDSOLocalEquivalentNames.clear();
318
319 for (const auto &NT : NumberedTypes)
320 if (NT.second.second.isValid())
321 return error(NT.second.second,
322 "use of undefined type '%" + Twine(NT.first) + "'");
323
324 for (const auto &[Name, TypeInfo] : NamedTypes)
325 if (TypeInfo.second.isValid())
326 return error(TypeInfo.second,
327 "use of undefined type named '" + Name + "'");
328
329 if (!ForwardRefComdats.empty())
330 return error(ForwardRefComdats.begin()->second,
331 "use of undefined comdat '$" +
332 ForwardRefComdats.begin()->first + "'");
333
334 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
335 dropUnknownMetadataReferences();
336
337 if (!ForwardRefMDNodes.empty())
338 return error(ForwardRefMDNodes.begin()->second.second,
339 "use of undefined metadata '!" +
340 Twine(ForwardRefMDNodes.begin()->first) + "'");
341
342 // Set debug locations.
343 for (auto [Loc, DR, MD] : PendingDbgRecords) {
344 if (auto *DI = dyn_cast<DILocation>(MD))
345 DR->setDebugLoc(DebugLoc(DI));
346 else
347 return error(Loc, "invalid debug location");
348 }
349 PendingDbgRecords.clear();
350 for (auto [Loc, I, MD] : PendingDbgInsts) {
351 if (auto *DI = dyn_cast<DILocation>(MD))
352 I->setDebugLoc(DebugLoc(DI));
353 else
354 return error(Loc, "invalid !dbg metadata");
355 }
356 PendingDbgInsts.clear();
357
358 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
359 if (StringRef(Name).starts_with("llvm.")) {
361 // Automatically create declarations for intrinsics. Intrinsics can only
362 // be called directly, so the call function type directly determines the
363 // declaration function type.
364 //
365 // Additionally, automatically add the required mangling suffix to the
366 // intrinsic name. This means that we may replace a single forward
367 // declaration with multiple functions here.
368 for (Use &U : make_early_inc_range(Info.first->uses())) {
369 auto *CB = dyn_cast<CallBase>(U.getUser());
370 if (!CB || !CB->isCallee(&U))
371 return error(Info.second, "intrinsic can only be used as callee");
372
373 std::string ErrorMsg;
374 raw_string_ostream ErrorOS(ErrorMsg);
375
376 SmallVector<Type *> OverloadTys;
377 if (IID != Intrinsic::not_intrinsic &&
378 Intrinsic::isSignatureValid(IID, CB->getFunctionType(), OverloadTys,
379 ErrorOS)) {
380 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
381 } else {
382 // Try to upgrade the intrinsic.
383 Function *TmpF = Function::Create(CB->getFunctionType(),
385 Function *NewF = nullptr;
386 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
387 if (IID == Intrinsic::not_intrinsic)
388 return error(Info.second, "unknown intrinsic '" + Name + "'");
389 return error(Info.second, ErrorMsg);
390 }
391
392 U.set(TmpF);
393 UpgradeIntrinsicCall(CB, NewF);
394 if (TmpF->use_empty())
395 TmpF->eraseFromParent();
396 }
397 }
398
399 Info.first->eraseFromParent();
400 ForwardRefVals.erase(Name);
401 continue;
402 }
403
404 // If incomplete IR is allowed, also add declarations for
405 // non-intrinsics.
407 continue;
408
409 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
410 FunctionType *FTy = nullptr;
411 for (Use &U : V->uses()) {
412 auto *CB = dyn_cast<CallBase>(U.getUser());
413 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
414 return nullptr;
415 FTy = CB->getFunctionType();
416 }
417 return FTy;
418 };
419
420 // First check whether this global is only used in calls with the same
421 // type, in which case we'll insert a function. Otherwise, fall back to
422 // using a dummy i8 type.
423 Type *Ty = GetCommonFunctionType(Info.first);
424 if (!Ty)
425 Ty = Type::getInt8Ty(Context);
426
427 GlobalValue *GV;
428 if (auto *FTy = dyn_cast<FunctionType>(Ty))
430 else
431 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
433 /*Initializer*/ nullptr, Name);
434 Info.first->replaceAllUsesWith(GV);
435 Info.first->eraseFromParent();
436 ForwardRefVals.erase(Name);
437 }
438
439 if (!ForwardRefVals.empty())
440 return error(ForwardRefVals.begin()->second.second,
441 "use of undefined value '@" + ForwardRefVals.begin()->first +
442 "'");
443
444 if (!ForwardRefValIDs.empty())
445 return error(ForwardRefValIDs.begin()->second.second,
446 "use of undefined value '@" +
447 Twine(ForwardRefValIDs.begin()->first) + "'");
448
449 // Resolve metadata cycles.
450 for (auto &N : NumberedMetadata) {
451 if (N.second && !N.second->isResolved())
452 N.second->resolveCycles();
453 }
454
456 NewDistinctSPs.clear();
457
458 for (auto *Inst : InstsWithTBAATag) {
459 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
460 // With incomplete IR, the tbaa metadata may have been dropped.
462 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
463 if (MD) {
464 auto *UpgradedMD = UpgradeTBAANode(*MD);
465 if (MD != UpgradedMD)
466 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
467 }
468 }
469
470 // Look for intrinsic functions and CallInst that need to be upgraded. We use
471 // make_early_inc_range here because we may remove some functions.
474
475 if (UpgradeDebugInfo)
477
483
484 if (!Slots)
485 return false;
486 // Initialize the slot mapping.
487 // Because by this point we've parsed and validated everything, we can "steal"
488 // the mapping from LLParser as it doesn't need it anymore.
489 Slots->GlobalValues = std::move(NumberedVals);
490 Slots->MetadataNodes = std::move(NumberedMetadata);
491 for (const auto &I : NamedTypes)
492 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
493 for (const auto &I : NumberedTypes)
494 Slots->Types.insert(std::make_pair(I.first, I.second.first));
495
496 return false;
497}
498
499/// Do final validity and basic correctness checks at the end of the index.
500bool LLParser::validateEndOfIndex() {
501 if (!Index)
502 return false;
503
504 if (!ForwardRefValueInfos.empty())
505 return error(ForwardRefValueInfos.begin()->second.front().second,
506 "use of undefined summary '^" +
507 Twine(ForwardRefValueInfos.begin()->first) + "'");
508
509 if (!ForwardRefAliasees.empty())
510 return error(ForwardRefAliasees.begin()->second.front().second,
511 "use of undefined summary '^" +
512 Twine(ForwardRefAliasees.begin()->first) + "'");
513
514 if (!ForwardRefTypeIds.empty())
515 return error(ForwardRefTypeIds.begin()->second.front().second,
516 "use of undefined type id summary '^" +
517 Twine(ForwardRefTypeIds.begin()->first) + "'");
518
519 return false;
520}
521
522//===----------------------------------------------------------------------===//
523// Top-Level Entities
524//===----------------------------------------------------------------------===//
525
526bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
527 // Delay parsing of the data layout string until the target triple is known.
528 // Then, pass both the the target triple and the tentative data layout string
529 // to DataLayoutCallback, allowing to override the DL string.
530 // This enables importing modules with invalid DL strings.
531 std::string TentativeDLStr = M->getDataLayoutStr();
532 LocTy DLStrLoc;
533
534 bool Done = false;
535 while (!Done) {
536 switch (Lex.getKind()) {
537 case lltok::kw_target:
538 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
539 return true;
540 break;
542 if (parseSourceFileName())
543 return true;
544 break;
545 default:
546 Done = true;
547 }
548 }
549 // Run the override callback to potentially change the data layout string, and
550 // parse the data layout string.
551 if (auto LayoutOverride =
552 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
553 TentativeDLStr = *LayoutOverride;
554 DLStrLoc = {};
555 }
556 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
557 if (!MaybeDL)
558 return error(DLStrLoc, toString(MaybeDL.takeError()));
559 M->setDataLayout(MaybeDL.get());
560 return false;
561}
562
563bool LLParser::parseTopLevelEntities() {
564 // If there is no Module, then parse just the summary index entries.
565 if (!M) {
566 while (true) {
567 switch (Lex.getKind()) {
568 case lltok::Eof:
569 return false;
570 case lltok::SummaryID:
571 if (parseSummaryEntry())
572 return true;
573 break;
575 if (parseSourceFileName())
576 return true;
577 break;
578 default:
579 // Skip everything else
580 Lex.Lex();
581 }
582 }
583 }
584 while (true) {
585 switch (Lex.getKind()) {
586 default:
587 return tokError("expected top-level entity");
588 case lltok::Eof: return false;
590 if (parseDeclare())
591 return true;
592 break;
593 case lltok::kw_define:
594 if (parseDefine())
595 return true;
596 break;
597 case lltok::kw_module:
598 if (parseModuleAsm())
599 return true;
600 break;
602 if (parseUnnamedType())
603 return true;
604 break;
605 case lltok::LocalVar:
606 if (parseNamedType())
607 return true;
608 break;
609 case lltok::GlobalID:
610 if (parseUnnamedGlobal())
611 return true;
612 break;
613 case lltok::GlobalVar:
614 if (parseNamedGlobal())
615 return true;
616 break;
617 case lltok::ComdatVar: if (parseComdat()) return true; break;
618 case lltok::exclaim:
619 if (parseStandaloneMetadata())
620 return true;
621 break;
622 case lltok::SummaryID:
623 if (parseSummaryEntry())
624 return true;
625 break;
627 if (parseNamedMetadata())
628 return true;
629 break;
631 if (parseUnnamedAttrGrp())
632 return true;
633 break;
635 if (parseUseListOrder())
636 return true;
637 break;
638 }
639 }
640}
641
642/// toplevelentity
643/// ::= 'module' 'asm' STRINGCONSTANT
644/// ::= 'module' 'asm' '(' 'property_name1:' STRINGCONSTANT ','
645/// 'property_name2:' STRINGCONSTANT ')'
646/// STRINGCONSTANT
647bool LLParser::parseModuleAsm() {
648 assert(Lex.getKind() == lltok::kw_module);
649 Lex.Lex();
650
651 std::string AsmStr;
652 if (parseToken(lltok::kw_asm, "expected 'module asm'"))
653 return true;
654
655 Module::GlobalAsmProperties Props;
656 if (EatIfPresent(lltok::lparen)) {
657 while (true) {
658 std::string Key, Value;
659 SMLoc Loc = Lex.getLoc();
660 if (Lex.getKind() != lltok::LabelStr)
661 return error(Loc, "expected property name followed by ':'");
662
663 Key = Lex.getStrVal();
664 Lex.Lex();
665
666 if (parseStringConstant(Value))
667 return true;
668
669 if (!Props.set(Key, Value))
670 return error(Loc, "unknown property name");
671
672 if (EatIfPresent(lltok::rparen))
673 break;
674 if (parseToken(lltok::comma, "expected ',' or ')'"))
675 return true;
676 }
677 }
678
679 do {
680 std::string AsmStrPart;
681 if (parseStringConstant(AsmStrPart))
682 return true;
683 AsmStr += AsmStrPart + "\n";
684 } while (Lex.getKind() == lltok::StringConstant);
685
686 M->appendModuleInlineAsm({AsmStr, Props});
687 return false;
688}
689
690/// toplevelentity
691/// ::= 'target' 'triple' '=' STRINGCONSTANT
692/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
693bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
694 LocTy &DLStrLoc) {
695 assert(Lex.getKind() == lltok::kw_target);
696 std::string Str;
697 switch (Lex.Lex()) {
698 default:
699 return tokError("unknown target property");
700 case lltok::kw_triple:
701 Lex.Lex();
702 if (parseToken(lltok::equal, "expected '=' after target triple") ||
703 parseStringConstant(Str))
704 return true;
705 M->setTargetTriple(Triple(std::move(Str)));
706 return false;
708 Lex.Lex();
709 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
710 return true;
711 DLStrLoc = Lex.getLoc();
712 if (parseStringConstant(TentativeDLStr))
713 return true;
714 return false;
715 }
716}
717
718/// toplevelentity
719/// ::= 'source_filename' '=' STRINGCONSTANT
720bool LLParser::parseSourceFileName() {
721 assert(Lex.getKind() == lltok::kw_source_filename);
722 Lex.Lex();
723 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
724 parseStringConstant(SourceFileName))
725 return true;
726 if (M)
727 M->setSourceFileName(SourceFileName);
728 return false;
729}
730
731/// parseUnnamedType:
732/// ::= LocalVarID '=' 'type' type
733bool LLParser::parseUnnamedType() {
734 LocTy TypeLoc = Lex.getLoc();
735 unsigned TypeID = Lex.getUIntVal();
736 Lex.Lex(); // eat LocalVarID;
737
738 if (parseToken(lltok::equal, "expected '=' after name") ||
739 parseToken(lltok::kw_type, "expected 'type' after '='"))
740 return true;
741
742 Type *Result = nullptr;
743 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
744 return true;
745
746 if (!isa<StructType>(Result)) {
747 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
748 if (Entry.first)
749 return error(TypeLoc, "non-struct types may not be recursive");
750 Entry.first = Result;
751 Entry.second = SMLoc();
752 }
753
754 return false;
755}
756
757/// toplevelentity
758/// ::= LocalVar '=' 'type' type
759bool LLParser::parseNamedType() {
760 std::string Name = Lex.getStrVal();
761 LocTy NameLoc = Lex.getLoc();
762 Lex.Lex(); // eat LocalVar.
763
764 if (parseToken(lltok::equal, "expected '=' after name") ||
765 parseToken(lltok::kw_type, "expected 'type' after name"))
766 return true;
767
768 Type *Result = nullptr;
769 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
770 return true;
771
772 if (!isa<StructType>(Result)) {
773 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
774 if (Entry.first)
775 return error(NameLoc, "non-struct types may not be recursive");
776 Entry.first = Result;
777 Entry.second = SMLoc();
778 }
779
780 return false;
781}
782
783/// toplevelentity
784/// ::= 'declare' FunctionHeader
785bool LLParser::parseDeclare() {
786 assert(Lex.getKind() == lltok::kw_declare);
787 Lex.Lex();
788
789 std::vector<std::pair<unsigned, MDNode *>> MDs;
790 while (Lex.getKind() == lltok::MetadataVar) {
791 unsigned MDK;
792 MDNode *N;
793 if (parseMetadataAttachment(MDK, N))
794 return true;
795 MDs.push_back({MDK, N});
796 }
797
798 Function *F;
799 unsigned FunctionNumber = -1;
800 SmallVector<unsigned> UnnamedArgNums;
801 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
802 return true;
803 for (auto &MD : MDs)
804 F->addMetadata(MD.first, *MD.second);
805 return false;
806}
807
808/// toplevelentity
809/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
810bool LLParser::parseDefine() {
811 assert(Lex.getKind() == lltok::kw_define);
812
813 FileLoc FunctionStart = getTokLineColumnPos();
814 Lex.Lex();
815
816 Function *F;
817 unsigned FunctionNumber = -1;
818 SmallVector<unsigned> UnnamedArgNums;
819 bool RetValue =
820 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
821 parseOptionalFunctionMetadata(*F) ||
822 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
823 if (ParserContext)
824 ParserContext->addFunctionLocation(
825 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
826
827 return RetValue;
828}
829
830/// parseGlobalType
831/// ::= 'constant'
832/// ::= 'global'
833bool LLParser::parseGlobalType(bool &IsConstant) {
834 if (Lex.getKind() == lltok::kw_constant)
835 IsConstant = true;
836 else if (Lex.getKind() == lltok::kw_global)
837 IsConstant = false;
838 else {
839 IsConstant = false;
840 return tokError("expected 'global' or 'constant'");
841 }
842 Lex.Lex();
843 return false;
844}
845
846bool LLParser::parseOptionalUnnamedAddr(
847 GlobalVariable::UnnamedAddr &UnnamedAddr) {
848 if (EatIfPresent(lltok::kw_unnamed_addr))
850 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
852 else
853 UnnamedAddr = GlobalValue::UnnamedAddr::None;
854 return false;
855}
856
857/// parseUnnamedGlobal:
858/// OptionalVisibility (ALIAS | IFUNC) ...
859/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
860/// OptionalDLLStorageClass
861/// ... -> global variable
862/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
863/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
864/// OptionalVisibility
865/// OptionalDLLStorageClass
866/// ... -> global variable
867bool LLParser::parseUnnamedGlobal() {
868 unsigned VarID;
869 std::string Name;
870 LocTy NameLoc = Lex.getLoc();
871
872 // Handle the GlobalID form.
873 if (Lex.getKind() == lltok::GlobalID) {
874 VarID = Lex.getUIntVal();
875 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
876 return true;
877
878 Lex.Lex(); // eat GlobalID;
879 if (parseToken(lltok::equal, "expected '=' after name"))
880 return true;
881 } else {
882 VarID = NumberedVals.getNext();
883 }
884
885 bool HasLinkage;
886 unsigned Linkage, Visibility, DLLStorageClass;
887 bool DSOLocal;
889 GlobalVariable::UnnamedAddr UnnamedAddr;
890 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
891 DSOLocal) ||
892 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
893 return true;
894
895 switch (Lex.getKind()) {
896 default:
897 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
898 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
899 case lltok::kw_alias:
900 case lltok::kw_ifunc:
901 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
902 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
903 }
904}
905
906/// parseNamedGlobal:
907/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
908/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
909/// OptionalVisibility OptionalDLLStorageClass
910/// ... -> global variable
911bool LLParser::parseNamedGlobal() {
912 assert(Lex.getKind() == lltok::GlobalVar);
913 LocTy NameLoc = Lex.getLoc();
914 std::string Name = Lex.getStrVal();
915 Lex.Lex();
916
917 bool HasLinkage;
918 unsigned Linkage, Visibility, DLLStorageClass;
919 bool DSOLocal;
921 GlobalVariable::UnnamedAddr UnnamedAddr;
922 if (parseToken(lltok::equal, "expected '=' in global variable") ||
923 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
924 DSOLocal) ||
925 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
926 return true;
927
928 switch (Lex.getKind()) {
929 default:
930 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
931 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
932 case lltok::kw_alias:
933 case lltok::kw_ifunc:
934 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
935 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
936 }
937}
938
939bool LLParser::parseComdat() {
940 assert(Lex.getKind() == lltok::ComdatVar);
941 std::string Name = Lex.getStrVal();
942 LocTy NameLoc = Lex.getLoc();
943 Lex.Lex();
944
945 if (parseToken(lltok::equal, "expected '=' here"))
946 return true;
947
948 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
949 return tokError("expected comdat type");
950
952 switch (Lex.getKind()) {
953 default:
954 return tokError("unknown selection kind");
955 case lltok::kw_any:
956 SK = Comdat::Any;
957 break;
960 break;
962 SK = Comdat::Largest;
963 break;
966 break;
968 SK = Comdat::SameSize;
969 break;
970 }
971 Lex.Lex();
972
973 // See if the comdat was forward referenced, if so, use the comdat.
974 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
975 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
976 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
977 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
978
979 Comdat *C;
980 if (I != ComdatSymTab.end())
981 C = &I->second;
982 else
983 C = M->getOrInsertComdat(Name);
984 C->setSelectionKind(SK);
985
986 return false;
987}
988
989// MDString:
990// ::= '!' STRINGCONSTANT
991bool LLParser::parseMDString(MDString *&Result) {
992 std::string Str;
993 if (parseStringConstant(Str))
994 return true;
995 Result = MDString::get(Context, Str);
996 return false;
997}
998
999// MDNode:
1000// ::= '!' MDNodeNumber
1001bool LLParser::parseMDNodeID(MDNode *&Result) {
1002 // !{ ..., !42, ... }
1003 LocTy IDLoc = Lex.getLoc();
1004 unsigned MID = 0;
1005 if (parseUInt32(MID))
1006 return true;
1007
1008 // If not a forward reference, just return it now.
1009 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
1010 if (!Inserted) {
1011 Result = It->second;
1012 return false;
1013 }
1014
1015 // Otherwise, create MDNode forward reference.
1016 auto &FwdRef = ForwardRefMDNodes[MID];
1017 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
1018
1019 Result = FwdRef.first.get();
1020 It->second.reset(Result);
1021 return false;
1022}
1023
1024/// parseNamedMetadata:
1025/// !foo = !{ !1, !2 }
1026bool LLParser::parseNamedMetadata() {
1027 assert(Lex.getKind() == lltok::MetadataVar);
1028 std::string Name = Lex.getStrVal();
1029 Lex.Lex();
1030
1031 if (parseToken(lltok::equal, "expected '=' here") ||
1032 parseToken(lltok::exclaim, "Expected '!' here") ||
1033 parseToken(lltok::lbrace, "Expected '{' here"))
1034 return true;
1035
1036 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1037 if (Lex.getKind() != lltok::rbrace)
1038 do {
1039 MDNode *N = nullptr;
1040 // parse DIExpressions inline as a special case. They are still MDNodes,
1041 // so they can still appear in named metadata. Remove this logic if they
1042 // become plain Metadata.
1043 if (Lex.getKind() == lltok::MetadataVar &&
1044 Lex.getStrVal() == "DIExpression") {
1045 if (parseDIExpression(N, /*IsDistinct=*/false))
1046 return true;
1047 // DIArgLists should only appear inline in a function, as they may
1048 // contain LocalAsMetadata arguments which require a function context.
1049 } else if (Lex.getKind() == lltok::MetadataVar &&
1050 Lex.getStrVal() == "DIArgList") {
1051 return tokError("found DIArgList outside of function");
1052 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1053 parseMDNodeID(N)) {
1054 return true;
1055 }
1056 NMD->addOperand(N);
1057 } while (EatIfPresent(lltok::comma));
1058
1059 return parseToken(lltok::rbrace, "expected end of metadata node");
1060}
1061
1062/// parseStandaloneMetadata:
1063/// !42 = !{...}
1064bool LLParser::parseStandaloneMetadata() {
1065 assert(Lex.getKind() == lltok::exclaim);
1066 Lex.Lex();
1067 unsigned MetadataID = 0;
1068
1069 MDNode *Init;
1070 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1071 return true;
1072
1073 // Detect common error, from old metadata syntax.
1074 if (Lex.getKind() == lltok::Type)
1075 return tokError("unexpected type in metadata definition");
1076
1077 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1078 if (Lex.getKind() == lltok::MetadataVar) {
1079 if (parseSpecializedMDNode(Init, IsDistinct))
1080 return true;
1081 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1082 parseMDTuple(Init, IsDistinct))
1083 return true;
1084
1085 // See if this was forward referenced, if so, handle it.
1086 auto FI = ForwardRefMDNodes.find(MetadataID);
1087 if (FI != ForwardRefMDNodes.end()) {
1088 auto *ToReplace = FI->second.first.get();
1089 // DIAssignID has its own special forward-reference "replacement" for
1090 // attachments (the temporary attachments are never actually attached).
1091 if (isa<DIAssignID>(Init)) {
1092 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1093 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1094 "Inst unexpectedly already has DIAssignID attachment");
1095 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1096 }
1097 }
1098
1099 ToReplace->replaceAllUsesWith(Init);
1100 ForwardRefMDNodes.erase(FI);
1101
1102 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1103 } else {
1104 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1105 if (!Inserted)
1106 return tokError("Metadata id is already used");
1107 It->second.reset(Init);
1108 }
1109
1110 return false;
1111}
1112
1113// Skips a single module summary entry.
1114bool LLParser::skipModuleSummaryEntry() {
1115 // Each module summary entry consists of a tag for the entry
1116 // type, followed by a colon, then the fields which may be surrounded by
1117 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1118 // support is in place we will look for the tokens corresponding to the
1119 // expected tags.
1120 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1121 Lex.getKind() != lltok::kw_typeid &&
1122 Lex.getKind() != lltok::kw_typeidCompatibleVTable &&
1123 Lex.getKind() != lltok::kw_flags && Lex.getKind() != lltok::kw_blockcount)
1124 return tokError("Expected 'gv', 'module', 'typeid', "
1125 "'typeidCompatibleVTable', 'flags' or 'blockcount' at the "
1126 "start of summary entry");
1127 if (Lex.getKind() == lltok::kw_flags)
1128 return parseSummaryIndexFlags();
1129 if (Lex.getKind() == lltok::kw_blockcount)
1130 return parseBlockCount();
1131 Lex.Lex();
1132 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1133 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1134 return true;
1135 // Now walk through the parenthesized entry, until the number of open
1136 // parentheses goes back down to 0 (the first '(' was parsed above).
1137 unsigned NumOpenParen = 1;
1138 do {
1139 switch (Lex.getKind()) {
1140 case lltok::lparen:
1141 NumOpenParen++;
1142 break;
1143 case lltok::rparen:
1144 NumOpenParen--;
1145 break;
1146 case lltok::Eof:
1147 return tokError("found end of file while parsing summary entry");
1148 default:
1149 // Skip everything in between parentheses.
1150 break;
1151 }
1152 Lex.Lex();
1153 } while (NumOpenParen > 0);
1154 return false;
1155}
1156
1157/// SummaryEntry
1158/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1159bool LLParser::parseSummaryEntry() {
1160 assert(Lex.getKind() == lltok::SummaryID);
1161 unsigned SummaryID = Lex.getUIntVal();
1162
1163 // For summary entries, colons should be treated as distinct tokens,
1164 // not an indication of the end of a label token.
1165 Lex.setIgnoreColonInIdentifiers(true);
1166
1167 Lex.Lex();
1168 if (parseToken(lltok::equal, "expected '=' here"))
1169 return true;
1170
1171 // If we don't have an index object, skip the summary entry.
1172 if (!Index)
1173 return skipModuleSummaryEntry();
1174
1175 bool result = false;
1176 switch (Lex.getKind()) {
1177 case lltok::kw_gv:
1178 result = parseGVEntry(SummaryID);
1179 break;
1180 case lltok::kw_module:
1181 result = parseModuleEntry(SummaryID);
1182 break;
1183 case lltok::kw_typeid:
1184 result = parseTypeIdEntry(SummaryID);
1185 break;
1187 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1188 break;
1189 case lltok::kw_flags:
1190 result = parseSummaryIndexFlags();
1191 break;
1193 result = parseBlockCount();
1194 break;
1195 default:
1196 result = error(Lex.getLoc(), "unexpected summary kind");
1197 break;
1198 }
1199 Lex.setIgnoreColonInIdentifiers(false);
1200 return result;
1201}
1202
1211
1212// If there was an explicit dso_local, update GV. In the absence of an explicit
1213// dso_local we keep the default value.
1214static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1215 if (DSOLocal)
1216 GV.setDSOLocal(true);
1217}
1218
1219/// parseAliasOrIFunc:
1220/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1221/// OptionalVisibility OptionalDLLStorageClass
1222/// OptionalThreadLocal OptionalUnnamedAddr
1223/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1224///
1225/// AliaseeOrResolver
1226/// ::= TypeAndValue
1227///
1228/// SymbolAttrs
1229/// ::= ',' 'partition' StringConstant
1230///
1231/// Everything through OptionalUnnamedAddr has already been parsed.
1232///
1233bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1234 LocTy NameLoc, unsigned L, unsigned Visibility,
1235 unsigned DLLStorageClass, bool DSOLocal,
1237 GlobalVariable::UnnamedAddr UnnamedAddr) {
1238 bool IsAlias;
1239 if (Lex.getKind() == lltok::kw_alias)
1240 IsAlias = true;
1241 else if (Lex.getKind() == lltok::kw_ifunc)
1242 IsAlias = false;
1243 else
1244 llvm_unreachable("Not an alias or ifunc!");
1245 Lex.Lex();
1246
1248
1249 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1250 return error(NameLoc, "invalid linkage type for alias");
1251
1252 if (!isValidVisibilityForLinkage(Visibility, L))
1253 return error(NameLoc,
1254 "symbol with local linkage must have default visibility");
1255
1256 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1257 return error(NameLoc,
1258 "symbol with local linkage cannot have a DLL storage class");
1259
1260 Type *Ty;
1261 LocTy ExplicitTypeLoc = Lex.getLoc();
1262 if (parseType(Ty) ||
1263 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1264 return true;
1265
1266 Constant *Aliasee;
1267 LocTy AliaseeLoc = Lex.getLoc();
1268 if (Lex.getKind() != lltok::kw_bitcast &&
1269 Lex.getKind() != lltok::kw_getelementptr &&
1270 Lex.getKind() != lltok::kw_addrspacecast &&
1271 Lex.getKind() != lltok::kw_inttoptr) {
1272 if (parseGlobalTypeAndValue(Aliasee))
1273 return true;
1274 } else {
1275 // The bitcast dest type is not present, it is implied by the dest type.
1276 ValID ID;
1277 if (parseValID(ID, /*PFS=*/nullptr))
1278 return true;
1279 if (ID.Kind != ValID::t_Constant)
1280 return error(AliaseeLoc, "invalid aliasee");
1281 Aliasee = ID.ConstantVal;
1282 }
1283
1284 Type *AliaseeType = Aliasee->getType();
1285 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1286 if (!PTy)
1287 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1288 unsigned AddrSpace = PTy->getAddressSpace();
1289
1290 GlobalValue *GVal = nullptr;
1291
1292 // See if the alias was forward referenced, if so, prepare to replace the
1293 // forward reference.
1294 if (!Name.empty()) {
1295 auto I = ForwardRefVals.find(Name);
1296 if (I != ForwardRefVals.end()) {
1297 GVal = I->second.first;
1298 ForwardRefVals.erase(Name);
1299 } else if (M->getNamedValue(Name)) {
1300 return error(NameLoc, "redefinition of global '@" + Name + "'");
1301 }
1302 } else {
1303 auto I = ForwardRefValIDs.find(NameID);
1304 if (I != ForwardRefValIDs.end()) {
1305 GVal = I->second.first;
1306 ForwardRefValIDs.erase(I);
1307 }
1308 }
1309
1310 // Okay, create the alias/ifunc but do not insert it into the module yet.
1311 std::unique_ptr<GlobalAlias> GA;
1312 std::unique_ptr<GlobalIFunc> GI;
1313 GlobalValue *GV;
1314 if (IsAlias) {
1315 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1316 /*Parent=*/nullptr));
1317 GV = GA.get();
1318 } else {
1319 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1320 /*Parent=*/nullptr));
1321 GV = GI.get();
1322 }
1323 GV->setThreadLocalMode(TLM);
1326 GV->setUnnamedAddr(UnnamedAddr);
1327 maybeSetDSOLocal(DSOLocal, *GV);
1328
1329 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1330 // Now parse them if there are any.
1331 while (Lex.getKind() == lltok::comma) {
1332 Lex.Lex();
1333
1334 if (Lex.getKind() == lltok::kw_partition) {
1335 Lex.Lex();
1336 GV->setPartition(Lex.getStrVal());
1337 if (parseToken(lltok::StringConstant, "expected partition string"))
1338 return true;
1339 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1340 if (parseGlobalObjectMetadataAttachment(*GI))
1341 return true;
1342 } else {
1343 return tokError("unknown alias or ifunc property!");
1344 }
1345 }
1346
1347 if (Name.empty())
1348 NumberedVals.add(NameID, GV);
1349
1350 if (GVal) {
1351 // Verify that types agree.
1352 if (GVal->getType() != GV->getType())
1353 return error(
1354 ExplicitTypeLoc,
1355 "forward reference and definition of alias have different types");
1356
1357 // If they agree, just RAUW the old value with the alias and remove the
1358 // forward ref info.
1359 GVal->replaceAllUsesWith(GV);
1360 GVal->eraseFromParent();
1361 }
1362
1363 // Insert into the module, we know its name won't collide now.
1364 if (IsAlias)
1365 M->insertAlias(GA.release());
1366 else
1367 M->insertIFunc(GI.release());
1368 assert(GV->getName() == Name && "Should not be a name conflict!");
1369
1370 return false;
1371}
1372
1373static bool isSanitizer(lltok::Kind Kind) {
1374 switch (Kind) {
1377 case lltok::kw_sanitize_memtag:
1379 return true;
1380 default:
1381 return false;
1382 }
1383}
1384
1385bool LLParser::parseSanitizer(GlobalVariable *GV) {
1386 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1388 if (GV->hasSanitizerMetadata())
1389 Meta = GV->getSanitizerMetadata();
1390
1391 switch (Lex.getKind()) {
1393 Meta.NoAddress = true;
1394 break;
1396 Meta.NoHWAddress = true;
1397 break;
1398 case lltok::kw_sanitize_memtag:
1399 Meta.Memtag = true;
1400 break;
1402 Meta.IsDynInit = true;
1403 break;
1404 default:
1405 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1406 }
1407 GV->setSanitizerMetadata(Meta);
1408 Lex.Lex();
1409 return false;
1410}
1411
1412/// parseGlobal
1413/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1414/// OptionalVisibility OptionalDLLStorageClass
1415/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1416/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1417/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1418/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1419/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1420/// Const OptionalAttrs
1421///
1422/// Everything up to and including OptionalUnnamedAddr has been parsed
1423/// already.
1424///
1425bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1426 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1427 unsigned Visibility, unsigned DLLStorageClass,
1428 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1429 GlobalVariable::UnnamedAddr UnnamedAddr) {
1430 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1431 return error(NameLoc,
1432 "symbol with local linkage must have default visibility");
1433
1434 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1435 return error(NameLoc,
1436 "symbol with local linkage cannot have a DLL storage class");
1437
1438 unsigned AddrSpace;
1439 bool IsConstant, IsExternallyInitialized;
1440 LocTy IsExternallyInitializedLoc;
1441 LocTy TyLoc;
1442
1443 Type *Ty = nullptr;
1444 if (parseOptionalAddrSpace(AddrSpace) ||
1445 parseOptionalToken(lltok::kw_externally_initialized,
1446 IsExternallyInitialized,
1447 &IsExternallyInitializedLoc) ||
1448 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1449 return true;
1450
1451 // If the linkage is specified and is external, then no initializer is
1452 // present.
1453 Constant *Init = nullptr;
1454 if (!HasLinkage ||
1457 if (parseGlobalValue(Ty, Init))
1458 return true;
1459 }
1460
1462 return error(TyLoc, "invalid type for global variable");
1463
1464 GlobalValue *GVal = nullptr;
1465
1466 // See if the global was forward referenced, if so, use the global.
1467 if (!Name.empty()) {
1468 auto I = ForwardRefVals.find(Name);
1469 if (I != ForwardRefVals.end()) {
1470 GVal = I->second.first;
1471 ForwardRefVals.erase(I);
1472 } else if (M->getNamedValue(Name)) {
1473 return error(NameLoc, "redefinition of global '@" + Name + "'");
1474 }
1475 } else {
1476 // Handle @"", where a name is syntactically specified, but semantically
1477 // missing.
1478 if (NameID == (unsigned)-1)
1479 NameID = NumberedVals.getNext();
1480
1481 auto I = ForwardRefValIDs.find(NameID);
1482 if (I != ForwardRefValIDs.end()) {
1483 GVal = I->second.first;
1484 ForwardRefValIDs.erase(I);
1485 }
1486 }
1487
1488 GlobalVariable *GV = new GlobalVariable(
1489 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1491
1492 if (Name.empty())
1493 NumberedVals.add(NameID, GV);
1494
1495 // Set the parsed properties on the global.
1496 if (Init)
1497 GV->setInitializer(Init);
1498 GV->setConstant(IsConstant);
1500 maybeSetDSOLocal(DSOLocal, *GV);
1503 GV->setExternallyInitialized(IsExternallyInitialized);
1504 GV->setThreadLocalMode(TLM);
1505 GV->setUnnamedAddr(UnnamedAddr);
1506
1507 if (GVal) {
1508 if (GVal->getAddressSpace() != AddrSpace)
1509 return error(
1510 TyLoc,
1511 "forward reference and definition of global have different types");
1512
1513 GVal->replaceAllUsesWith(GV);
1514 GVal->eraseFromParent();
1515 }
1516
1517 // parse attributes on the global.
1518 while (Lex.getKind() == lltok::comma) {
1519 Lex.Lex();
1520
1521 if (Lex.getKind() == lltok::kw_section) {
1522 Lex.Lex();
1523 GV->setSection(Lex.getStrVal());
1524 if (parseToken(lltok::StringConstant, "expected global section string"))
1525 return true;
1526 } else if (Lex.getKind() == lltok::kw_partition) {
1527 Lex.Lex();
1528 GV->setPartition(Lex.getStrVal());
1529 if (parseToken(lltok::StringConstant, "expected partition string"))
1530 return true;
1531 } else if (Lex.getKind() == lltok::kw_align) {
1532 MaybeAlign Alignment;
1533 if (parseOptionalAlignment(Alignment))
1534 return true;
1535 if (Alignment)
1536 GV->setAlignment(*Alignment);
1537 } else if (Lex.getKind() == lltok::kw_code_model) {
1539 if (parseOptionalCodeModel(CodeModel))
1540 return true;
1541 GV->setCodeModel(CodeModel);
1542 } else if (Lex.getKind() == lltok::MetadataVar) {
1543 if (parseGlobalObjectMetadataAttachment(*GV))
1544 return true;
1545 } else if (isSanitizer(Lex.getKind())) {
1546 if (parseSanitizer(GV))
1547 return true;
1548 } else {
1549 Comdat *C;
1550 if (parseOptionalComdat(Name, C))
1551 return true;
1552 if (C)
1553 GV->setComdat(C);
1554 else
1555 return tokError("unknown global variable property!");
1556 }
1557 }
1558
1559 AttrBuilder Attrs(M->getContext());
1560 LocTy BuiltinLoc;
1561 std::vector<unsigned> FwdRefAttrGrps;
1562 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1563 return true;
1564 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1565 GV->setAttributes(AttributeSet::get(Context, Attrs));
1566 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1567 }
1568
1569 return false;
1570}
1571
1572/// parseUnnamedAttrGrp
1573/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1574bool LLParser::parseUnnamedAttrGrp() {
1575 assert(Lex.getKind() == lltok::kw_attributes);
1576 LocTy AttrGrpLoc = Lex.getLoc();
1577 Lex.Lex();
1578
1579 if (Lex.getKind() != lltok::AttrGrpID)
1580 return tokError("expected attribute group id");
1581
1582 unsigned VarID = Lex.getUIntVal();
1583 std::vector<unsigned> unused;
1584 LocTy BuiltinLoc;
1585 Lex.Lex();
1586
1587 if (parseToken(lltok::equal, "expected '=' here") ||
1588 parseToken(lltok::lbrace, "expected '{' here"))
1589 return true;
1590
1591 auto R = NumberedAttrBuilders.find(VarID);
1592 if (R == NumberedAttrBuilders.end())
1593 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1594
1595 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1596 parseToken(lltok::rbrace, "expected end of attribute group"))
1597 return true;
1598
1599 if (!R->second.hasAttributes())
1600 return error(AttrGrpLoc, "attribute group has no attributes");
1601
1602 return false;
1603}
1604
1606 switch (Kind) {
1607#define GET_ATTR_NAMES
1608#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1609 case lltok::kw_##DISPLAY_NAME: \
1610 return Attribute::ENUM_NAME;
1611#include "llvm/IR/Attributes.inc"
1612 default:
1613 return Attribute::None;
1614 }
1615}
1616
1617bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1618 bool InAttrGroup) {
1619 if (Attribute::isTypeAttrKind(Attr))
1620 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1621
1622 switch (Attr) {
1623 case Attribute::Alignment: {
1624 MaybeAlign Alignment;
1625 if (InAttrGroup) {
1626 uint32_t Value = 0;
1627 Lex.Lex();
1628 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1629 return true;
1631 } else {
1632 if (parseOptionalAlignment(Alignment, true))
1633 return true;
1634 }
1635 B.addAlignmentAttr(Alignment);
1636 return false;
1637 }
1638 case Attribute::StackAlignment: {
1639 unsigned Alignment;
1640 if (InAttrGroup) {
1641 Lex.Lex();
1642 if (parseToken(lltok::equal, "expected '=' here") ||
1643 parseUInt32(Alignment))
1644 return true;
1645 } else {
1646 if (parseOptionalStackAlignment(Alignment))
1647 return true;
1648 }
1649 B.addStackAlignmentAttr(Alignment);
1650 return false;
1651 }
1652 case Attribute::AllocSize: {
1653 unsigned ElemSizeArg;
1654 std::optional<unsigned> NumElemsArg;
1655 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1656 return true;
1657 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1658 return false;
1659 }
1660 case Attribute::VScaleRange: {
1661 unsigned MinValue, MaxValue;
1662 if (parseVScaleRangeArguments(MinValue, MaxValue))
1663 return true;
1664 B.addVScaleRangeAttr(MinValue,
1665 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1666 return false;
1667 }
1668 case Attribute::Dereferenceable: {
1669 std::optional<uint64_t> Bytes;
1670 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1671 return true;
1672 assert(Bytes.has_value());
1673 B.addDereferenceableAttr(Bytes.value());
1674 return false;
1675 }
1676 case Attribute::DeadOnReturn: {
1677 std::optional<uint64_t> Bytes;
1678 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1679 /*ErrorNoBytes=*/false))
1680 return true;
1681 if (Bytes.has_value()) {
1682 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1683 } else {
1684 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1685 }
1686 return false;
1687 }
1688 case Attribute::DereferenceableOrNull: {
1689 std::optional<uint64_t> Bytes;
1690 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1691 return true;
1692 assert(Bytes.has_value());
1693 B.addDereferenceableOrNullAttr(Bytes.value());
1694 return false;
1695 }
1696 case Attribute::UWTable: {
1698 if (parseOptionalUWTableKind(Kind))
1699 return true;
1700 B.addUWTableAttr(Kind);
1701 return false;
1702 }
1703 case Attribute::AllocKind: {
1705 if (parseAllocKind(Kind))
1706 return true;
1707 B.addAllocKindAttr(Kind);
1708 return false;
1709 }
1710 case Attribute::Memory: {
1711 std::optional<MemoryEffects> ME = parseMemoryAttr();
1712 if (!ME)
1713 return true;
1714 B.addMemoryAttr(*ME);
1715 return false;
1716 }
1717 case Attribute::DenormalFPEnv: {
1718 std::optional<DenormalFPEnv> Mode = parseDenormalFPEnvAttr();
1719 if (!Mode)
1720 return true;
1721
1722 B.addDenormalFPEnvAttr(*Mode);
1723 return false;
1724 }
1725 case Attribute::NoFPClass: {
1726 if (FPClassTest NoFPClass =
1727 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1728 B.addNoFPClassAttr(NoFPClass);
1729 return false;
1730 }
1731
1732 return true;
1733 }
1734 case Attribute::Range:
1735 return parseRangeAttr(B);
1736 case Attribute::Initializes:
1737 return parseInitializesAttr(B);
1738 case Attribute::Captures:
1739 return parseCapturesAttr(B);
1740 default:
1741 B.addAttribute(Attr);
1742 Lex.Lex();
1743 return false;
1744 }
1745}
1746
1748 switch (Kind) {
1749 case lltok::kw_readnone:
1750 ME &= MemoryEffects::none();
1751 return true;
1752 case lltok::kw_readonly:
1754 return true;
1755 case lltok::kw_writeonly:
1757 return true;
1760 return true;
1763 return true;
1766 return true;
1767 default:
1768 return false;
1769 }
1770}
1771
1772/// parseFnAttributeValuePairs
1773/// ::= <attr> | <attr> '=' <value>
1774bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1775 std::vector<unsigned> &FwdRefAttrGrps,
1776 bool InAttrGrp, LocTy &BuiltinLoc) {
1777 bool HaveError = false;
1778
1779 B.clear();
1780
1782 while (true) {
1783 lltok::Kind Token = Lex.getKind();
1784 if (Token == lltok::rbrace)
1785 break; // Finished.
1786
1787 if (Token == lltok::StringConstant) {
1788 if (parseStringAttribute(B))
1789 return true;
1790 continue;
1791 }
1792
1793 if (Token == lltok::AttrGrpID) {
1794 // Allow a function to reference an attribute group:
1795 //
1796 // define void @foo() #1 { ... }
1797 if (InAttrGrp) {
1798 HaveError |= error(
1799 Lex.getLoc(),
1800 "cannot have an attribute group reference in an attribute group");
1801 } else {
1802 // Save the reference to the attribute group. We'll fill it in later.
1803 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1804 }
1805 Lex.Lex();
1806 continue;
1807 }
1808
1809 SMLoc Loc = Lex.getLoc();
1810 if (Token == lltok::kw_builtin)
1811 BuiltinLoc = Loc;
1812
1813 if (upgradeMemoryAttr(ME, Token)) {
1814 Lex.Lex();
1815 continue;
1816 }
1817
1819 if (Attr == Attribute::None) {
1820 if (!InAttrGrp)
1821 break;
1822 return error(Lex.getLoc(), "unterminated attribute group");
1823 }
1824
1825 if (parseEnumAttribute(Attr, B, InAttrGrp))
1826 return true;
1827
1828 // As a hack, we allow function alignment to be initially parsed as an
1829 // attribute on a function declaration/definition or added to an attribute
1830 // group and later moved to the alignment field.
1831 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1832 HaveError |= error(Loc, "this attribute does not apply to functions");
1833 }
1834
1835 if (ME != MemoryEffects::unknown())
1836 B.addMemoryAttr(ME);
1837 return HaveError;
1838}
1839
1840//===----------------------------------------------------------------------===//
1841// GlobalValue Reference/Resolution Routines.
1842//===----------------------------------------------------------------------===//
1843
1845 // The used global type does not matter. We will later RAUW it with a
1846 // global/function of the correct type.
1847 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1850 PTy->getAddressSpace());
1851}
1852
1853Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1854 Value *Val) {
1855 Type *ValTy = Val->getType();
1856 if (ValTy == Ty)
1857 return Val;
1858 if (Ty->isLabelTy())
1859 error(Loc, "'" + Name + "' is not a basic block");
1860 else
1861 error(Loc, "'" + Name + "' defined with type '" +
1862 getTypeString(Val->getType()) + "' but expected '" +
1863 getTypeString(Ty) + "'");
1864 return nullptr;
1865}
1866
1867/// getGlobalVal - Get a value with the specified name or ID, creating a
1868/// forward reference record if needed. This can return null if the value
1869/// exists but does not have the right type.
1870GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1871 LocTy Loc) {
1873 if (!PTy) {
1874 error(Loc, "global variable reference must have pointer type");
1875 return nullptr;
1876 }
1877
1878 // Look this name up in the normal function symbol table.
1879 GlobalValue *Val =
1880 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1881
1882 // If this is a forward reference for the value, see if we already created a
1883 // forward ref record.
1884 if (!Val) {
1885 auto I = ForwardRefVals.find(Name);
1886 if (I != ForwardRefVals.end())
1887 Val = I->second.first;
1888 }
1889
1890 // If we have the value in the symbol table or fwd-ref table, return it.
1891 if (Val)
1893 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1894
1895 // Otherwise, create a new forward reference for this value and remember it.
1896 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1897 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1898 return FwdVal;
1899}
1900
1901GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1903 if (!PTy) {
1904 error(Loc, "global variable reference must have pointer type");
1905 return nullptr;
1906 }
1907
1908 GlobalValue *Val = NumberedVals.get(ID);
1909
1910 // If this is a forward reference for the value, see if we already created a
1911 // forward ref record.
1912 if (!Val) {
1913 auto I = ForwardRefValIDs.find(ID);
1914 if (I != ForwardRefValIDs.end())
1915 Val = I->second.first;
1916 }
1917
1918 // If we have the value in the symbol table or fwd-ref table, return it.
1919 if (Val)
1921 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1922
1923 // Otherwise, create a new forward reference for this value and remember it.
1924 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1925 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1926 return FwdVal;
1927}
1928
1929//===----------------------------------------------------------------------===//
1930// Comdat Reference/Resolution Routines.
1931//===----------------------------------------------------------------------===//
1932
1933Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1934 // Look this name up in the comdat symbol table.
1935 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1936 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1937 if (I != ComdatSymTab.end())
1938 return &I->second;
1939
1940 // Otherwise, create a new forward reference for this value and remember it.
1941 Comdat *C = M->getOrInsertComdat(Name);
1942 ForwardRefComdats[Name] = Loc;
1943 return C;
1944}
1945
1946//===----------------------------------------------------------------------===//
1947// Helper Routines.
1948//===----------------------------------------------------------------------===//
1949
1950/// parseToken - If the current token has the specified kind, eat it and return
1951/// success. Otherwise, emit the specified error and return failure.
1952bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1953 if (Lex.getKind() != T)
1954 return tokError(ErrMsg);
1955 Lex.Lex();
1956 return false;
1957}
1958
1959/// parseStringConstant
1960/// ::= StringConstant
1961bool LLParser::parseStringConstant(std::string &Result) {
1962 if (Lex.getKind() != lltok::StringConstant)
1963 return tokError("expected string constant");
1964 Result = Lex.getStrVal();
1965 Lex.Lex();
1966 return false;
1967}
1968
1969/// parseUInt32
1970/// ::= uint32
1971bool LLParser::parseUInt32(uint32_t &Val) {
1972 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1973 return tokError("expected integer");
1974 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1975 if (Val64 != unsigned(Val64))
1976 return tokError("expected 32-bit integer (too large)");
1977 Val = Val64;
1978 Lex.Lex();
1979 return false;
1980}
1981
1982/// parseUInt64
1983/// ::= uint64
1984bool LLParser::parseUInt64(uint64_t &Val) {
1985 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1986 return tokError("expected integer");
1987 Val = Lex.getAPSIntVal().getLimitedValue();
1988 Lex.Lex();
1989 return false;
1990}
1991
1992/// parseTLSModel
1993/// := 'localdynamic'
1994/// := 'initialexec'
1995/// := 'localexec'
1996bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1997 switch (Lex.getKind()) {
1998 default:
1999 return tokError("expected localdynamic, initialexec or localexec");
2002 break;
2005 break;
2008 break;
2009 }
2010
2011 Lex.Lex();
2012 return false;
2013}
2014
2015/// parseOptionalThreadLocal
2016/// := /*empty*/
2017/// := 'thread_local'
2018/// := 'thread_local' '(' tlsmodel ')'
2019bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
2021 if (!EatIfPresent(lltok::kw_thread_local))
2022 return false;
2023
2025 if (Lex.getKind() == lltok::lparen) {
2026 Lex.Lex();
2027 return parseTLSModel(TLM) ||
2028 parseToken(lltok::rparen, "expected ')' after thread local model");
2029 }
2030 return false;
2031}
2032
2033/// parseOptionalAddrSpace
2034/// := /*empty*/
2035/// := 'addrspace' '(' uint32 ')'
2036bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
2037 AddrSpace = DefaultAS;
2038 if (!EatIfPresent(lltok::kw_addrspace))
2039 return false;
2040
2041 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
2042 if (Lex.getKind() == lltok::StringConstant) {
2043 const std::string &AddrSpaceStr = Lex.getStrVal();
2044 if (AddrSpaceStr == "A") {
2045 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2046 } else if (AddrSpaceStr == "G") {
2047 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2048 } else if (AddrSpaceStr == "P") {
2049 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2050 } else if (std::optional<unsigned> AS =
2051 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2052 AddrSpace = *AS;
2053 } else {
2054 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
2055 }
2056 Lex.Lex();
2057 return false;
2058 }
2059 if (Lex.getKind() != lltok::APSInt)
2060 return tokError("expected integer or string constant");
2061 SMLoc Loc = Lex.getLoc();
2062 if (parseUInt32(AddrSpace))
2063 return true;
2064 if (!isUInt<24>(AddrSpace))
2065 return error(Loc, "invalid address space, must be a 24-bit integer");
2066 return false;
2067 };
2068
2069 return parseToken(lltok::lparen, "expected '(' in address space") ||
2070 ParseAddrspaceValue(AddrSpace) ||
2071 parseToken(lltok::rparen, "expected ')' in address space");
2072}
2073
2074/// parseStringAttribute
2075/// := StringConstant
2076/// := StringConstant '=' StringConstant
2077bool LLParser::parseStringAttribute(AttrBuilder &B) {
2078 std::string Attr = Lex.getStrVal();
2079 Lex.Lex();
2080 std::string Val;
2081 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
2082 return true;
2083 B.addAttribute(Attr, Val);
2084 return false;
2085}
2086
2087/// Parse a potentially empty list of parameter or return attributes.
2088bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2089 bool HaveError = false;
2090
2091 B.clear();
2092
2093 while (true) {
2094 lltok::Kind Token = Lex.getKind();
2095 if (Token == lltok::StringConstant) {
2096 if (parseStringAttribute(B))
2097 return true;
2098 continue;
2099 }
2100
2101 if (Token == lltok::kw_nocapture) {
2102 Lex.Lex();
2103 B.addCapturesAttr(CaptureInfo::none());
2104 continue;
2105 }
2106
2107 SMLoc Loc = Lex.getLoc();
2109 if (Attr == Attribute::None)
2110 return HaveError;
2111
2112 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2113 return true;
2114
2115 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2116 HaveError |= error(Loc, "this attribute does not apply to parameters");
2117 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2118 HaveError |= error(Loc, "this attribute does not apply to return values");
2119 }
2120}
2121
2122static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2123 HasLinkage = true;
2124 switch (Kind) {
2125 default:
2126 HasLinkage = false;
2128 case lltok::kw_private:
2130 case lltok::kw_internal:
2132 case lltok::kw_weak:
2134 case lltok::kw_weak_odr:
2136 case lltok::kw_linkonce:
2144 case lltok::kw_common:
2148 case lltok::kw_external:
2150 }
2151}
2152
2153/// parseOptionalLinkage
2154/// ::= /*empty*/
2155/// ::= 'private'
2156/// ::= 'internal'
2157/// ::= 'weak'
2158/// ::= 'weak_odr'
2159/// ::= 'linkonce'
2160/// ::= 'linkonce_odr'
2161/// ::= 'available_externally'
2162/// ::= 'appending'
2163/// ::= 'common'
2164/// ::= 'extern_weak'
2165/// ::= 'external'
2166bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2167 unsigned &Visibility,
2168 unsigned &DLLStorageClass, bool &DSOLocal) {
2169 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2170 if (HasLinkage)
2171 Lex.Lex();
2172 parseOptionalDSOLocal(DSOLocal);
2173 parseOptionalVisibility(Visibility);
2174 parseOptionalDLLStorageClass(DLLStorageClass);
2175
2176 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2177 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2178 }
2179
2180 return false;
2181}
2182
2183void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2184 switch (Lex.getKind()) {
2185 default:
2186 DSOLocal = false;
2187 break;
2189 DSOLocal = true;
2190 Lex.Lex();
2191 break;
2193 DSOLocal = false;
2194 Lex.Lex();
2195 break;
2196 }
2197}
2198
2199/// parseOptionalVisibility
2200/// ::= /*empty*/
2201/// ::= 'default'
2202/// ::= 'hidden'
2203/// ::= 'protected'
2204///
2205void LLParser::parseOptionalVisibility(unsigned &Res) {
2206 switch (Lex.getKind()) {
2207 default:
2209 return;
2210 case lltok::kw_default:
2212 break;
2213 case lltok::kw_hidden:
2215 break;
2218 break;
2219 }
2220 Lex.Lex();
2221}
2222
2223bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2225 switch (Kind) {
2226 default:
2227 return tokError("unknown import kind. Expect definition or declaration.");
2230 return false;
2233 return false;
2234 }
2235}
2236
2237/// parseOptionalDLLStorageClass
2238/// ::= /*empty*/
2239/// ::= 'dllimport'
2240/// ::= 'dllexport'
2241///
2242void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2243 switch (Lex.getKind()) {
2244 default:
2246 return;
2249 break;
2252 break;
2253 }
2254 Lex.Lex();
2255}
2256
2257/// parseOptionalCallingConv
2258/// ::= /*empty*/
2259/// ::= 'ccc'
2260/// ::= 'fastcc'
2261/// ::= 'intel_ocl_bicc'
2262/// ::= 'coldcc'
2263/// ::= 'cfguard_checkcc'
2264/// ::= 'x86_stdcallcc'
2265/// ::= 'x86_fastcallcc'
2266/// ::= 'x86_thiscallcc'
2267/// ::= 'x86_vectorcallcc'
2268/// ::= 'arm_apcscc'
2269/// ::= 'arm_aapcscc'
2270/// ::= 'arm_aapcs_vfpcc'
2271/// ::= 'aarch64_vector_pcs'
2272/// ::= 'aarch64_sve_vector_pcs'
2273/// ::= 'aarch64_sme_preservemost_from_x0'
2274/// ::= 'aarch64_sme_preservemost_from_x1'
2275/// ::= 'aarch64_sme_preservemost_from_x2'
2276/// ::= 'msp430_intrcc'
2277/// ::= 'avr_intrcc'
2278/// ::= 'avr_signalcc'
2279/// ::= 'ptx_kernel'
2280/// ::= 'ptx_device'
2281/// ::= 'spir_func'
2282/// ::= 'spir_kernel'
2283/// ::= 'x86_64_sysvcc'
2284/// ::= 'win64cc'
2285/// ::= 'anyregcc'
2286/// ::= 'preserve_mostcc'
2287/// ::= 'preserve_allcc'
2288/// ::= 'preserve_nonecc'
2289/// ::= 'ghccc'
2290/// ::= 'swiftcc'
2291/// ::= 'swifttailcc'
2292/// ::= 'x86_intrcc'
2293/// ::= 'hhvmcc'
2294/// ::= 'hhvm_ccc'
2295/// ::= 'cxx_fast_tlscc'
2296/// ::= 'amdgpu_vs'
2297/// ::= 'amdgpu_ls'
2298/// ::= 'amdgpu_hs'
2299/// ::= 'amdgpu_es'
2300/// ::= 'amdgpu_gs'
2301/// ::= 'amdgpu_ps'
2302/// ::= 'amdgpu_cs'
2303/// ::= 'amdgpu_cs_chain'
2304/// ::= 'amdgpu_cs_chain_preserve'
2305/// ::= 'amdgpu_kernel'
2306/// ::= 'tailcc'
2307/// ::= 'm68k_rtdcc'
2308/// ::= 'graalcc'
2309/// ::= 'riscv_vector_cc'
2310/// ::= 'riscv_vls_cc'
2311/// ::= 'cc' UINT
2312///
2313bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2314 switch (Lex.getKind()) {
2315 default: CC = CallingConv::C; return false;
2316 case lltok::kw_ccc: CC = CallingConv::C; break;
2317 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2318 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2331 break;
2334 break;
2337 break;
2340 break;
2350 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2351 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2355 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2356 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2359 case lltok::kw_hhvmcc:
2361 break;
2362 case lltok::kw_hhvm_ccc:
2364 break;
2376 break;
2379 break;
2383 break;
2384 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2386 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2389 break;
2391 // Default ABI_VLEN
2393 Lex.Lex();
2394 if (!EatIfPresent(lltok::lparen))
2395 break;
2396 uint32_t ABIVlen;
2397 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2398 return true;
2399 switch (ABIVlen) {
2400 default:
2401 return tokError("unknown RISC-V ABI VLEN");
2402#define CC_VLS_CASE(ABIVlen) \
2403 case ABIVlen: \
2404 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2405 break;
2406 CC_VLS_CASE(32)
2407 CC_VLS_CASE(64)
2408 CC_VLS_CASE(128)
2409 CC_VLS_CASE(256)
2410 CC_VLS_CASE(512)
2411 CC_VLS_CASE(1024)
2412 CC_VLS_CASE(2048)
2413 CC_VLS_CASE(4096)
2414 CC_VLS_CASE(8192)
2415 CC_VLS_CASE(16384)
2416 CC_VLS_CASE(32768)
2417 CC_VLS_CASE(65536)
2418#undef CC_VLS_CASE
2419 }
2420 return false;
2423 break;
2426 break;
2429 break;
2430 case lltok::kw_cc: {
2431 Lex.Lex();
2432 return parseUInt32(CC);
2433 }
2434 }
2435
2436 Lex.Lex();
2437 return false;
2438}
2439
2440/// parseMetadataAttachment
2441/// ::= !dbg !42
2442bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2443 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2444
2445 std::string Name = Lex.getStrVal();
2446 Kind = M->getMDKindID(Name);
2447 Lex.Lex();
2448
2449 return parseMDNode(MD);
2450}
2451
2452/// parseInstructionMetadata
2453/// ::= !dbg !42 (',' !dbg !57)*
2454bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2455 do {
2456 if (Lex.getKind() != lltok::MetadataVar)
2457 return tokError("expected metadata after comma");
2458
2459 unsigned MDK;
2460 MDNode *N;
2461 auto Loc = Lex.getLoc();
2462 if (parseMetadataAttachment(MDK, N))
2463 return true;
2464
2465 if (MDK == LLVMContext::MD_DIAssignID)
2466 TempDIAssignIDAttachments[N].push_back(&Inst);
2467 else if (MDK == LLVMContext::MD_dbg)
2468 PendingDbgInsts.emplace_back(Loc, &Inst, N);
2469 else
2470 Inst.setMetadata(MDK, N);
2471
2472 if (MDK == LLVMContext::MD_tbaa)
2473 InstsWithTBAATag.push_back(&Inst);
2474
2475 // If this is the end of the list, we're done.
2476 } while (EatIfPresent(lltok::comma));
2477 return false;
2478}
2479
2480/// parseGlobalObjectMetadataAttachment
2481/// ::= !dbg !57
2482bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2483 unsigned MDK;
2484 MDNode *N;
2485 if (parseMetadataAttachment(MDK, N))
2486 return true;
2487
2488 GO.addMetadata(MDK, *N);
2489 return false;
2490}
2491
2492/// parseOptionalFunctionMetadata
2493/// ::= (!dbg !57)*
2494bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2495 while (Lex.getKind() == lltok::MetadataVar)
2496 if (parseGlobalObjectMetadataAttachment(F))
2497 return true;
2498 return false;
2499}
2500
2501/// parseOptionalAlignment
2502/// ::= /* empty */
2503/// ::= 'align' 4
2504bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2505 Alignment = std::nullopt;
2506 if (!EatIfPresent(lltok::kw_align))
2507 return false;
2508 LocTy AlignLoc = Lex.getLoc();
2509 uint64_t Value = 0;
2510
2511 LocTy ParenLoc = Lex.getLoc();
2512 bool HaveParens = false;
2513 if (AllowParens) {
2514 if (EatIfPresent(lltok::lparen))
2515 HaveParens = true;
2516 }
2517
2518 if (parseUInt64(Value))
2519 return true;
2520
2521 if (HaveParens && !EatIfPresent(lltok::rparen))
2522 return error(ParenLoc, "expected ')'");
2523
2524 if (!isPowerOf2_64(Value))
2525 return error(AlignLoc, "alignment is not a power of two");
2527 return error(AlignLoc, "huge alignments are not supported yet");
2529 return false;
2530}
2531
2532/// parseOptionalPrefAlignment
2533/// ::= /* empty */
2534/// ::= 'prefalign' '(' 4 ')'
2535bool LLParser::parseOptionalPrefAlignment(MaybeAlign &Alignment) {
2536 Alignment = std::nullopt;
2537 if (!EatIfPresent(lltok::kw_prefalign))
2538 return false;
2539 LocTy AlignLoc = Lex.getLoc();
2540 uint64_t Value = 0;
2541
2542 LocTy ParenLoc = Lex.getLoc();
2543 if (!EatIfPresent(lltok::lparen))
2544 return error(ParenLoc, "expected '('");
2545
2546 if (parseUInt64(Value))
2547 return true;
2548
2549 ParenLoc = Lex.getLoc();
2550 if (!EatIfPresent(lltok::rparen))
2551 return error(ParenLoc, "expected ')'");
2552
2553 if (!isPowerOf2_64(Value))
2554 return error(AlignLoc, "alignment is not a power of two");
2556 return error(AlignLoc, "huge alignments are not supported yet");
2558 return false;
2559}
2560
2561/// parseOptionalCodeModel
2562/// ::= /* empty */
2563/// ::= 'code_model' "large"
2564bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2565 Lex.Lex();
2566 auto StrVal = Lex.getStrVal();
2567 auto ErrMsg = "expected global code model string";
2568 if (StrVal == "tiny")
2569 model = CodeModel::Tiny;
2570 else if (StrVal == "small")
2571 model = CodeModel::Small;
2572 else if (StrVal == "kernel")
2573 model = CodeModel::Kernel;
2574 else if (StrVal == "medium")
2575 model = CodeModel::Medium;
2576 else if (StrVal == "large")
2577 model = CodeModel::Large;
2578 else
2579 return tokError(ErrMsg);
2580 if (parseToken(lltok::StringConstant, ErrMsg))
2581 return true;
2582 return false;
2583}
2584
2585/// parseOptionalAttrBytes
2586/// ::= /* empty */
2587/// ::= AttrKind '(' 4 ')'
2588///
2589/// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or
2590/// 'dead_on_return'
2591bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind,
2592 std::optional<uint64_t> &Bytes,
2593 bool ErrorNoBytes) {
2594 assert((AttrKind == lltok::kw_dereferenceable ||
2595 AttrKind == lltok::kw_dereferenceable_or_null ||
2596 AttrKind == lltok::kw_dead_on_return) &&
2597 "contract!");
2598
2599 Bytes = 0;
2600 if (!EatIfPresent(AttrKind))
2601 return false;
2602 LocTy ParenLoc = Lex.getLoc();
2603 if (!EatIfPresent(lltok::lparen)) {
2604 if (ErrorNoBytes)
2605 return error(ParenLoc, "expected '('");
2606 Bytes = std::nullopt;
2607 return false;
2608 }
2609 LocTy DerefLoc = Lex.getLoc();
2610 if (parseUInt64(Bytes.value()))
2611 return true;
2612 ParenLoc = Lex.getLoc();
2613 if (!EatIfPresent(lltok::rparen))
2614 return error(ParenLoc, "expected ')'");
2615 if (!Bytes.value())
2616 return error(DerefLoc, "byte count specified must be non-zero");
2617 return false;
2618}
2619
2620bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2621 Lex.Lex();
2623 if (!EatIfPresent(lltok::lparen))
2624 return false;
2625 LocTy KindLoc = Lex.getLoc();
2626 if (Lex.getKind() == lltok::kw_sync)
2628 else if (Lex.getKind() == lltok::kw_async)
2630 else
2631 return error(KindLoc, "expected unwind table kind");
2632 Lex.Lex();
2633 return parseToken(lltok::rparen, "expected ')'");
2634}
2635
2636bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2637 Lex.Lex();
2638 LocTy ParenLoc = Lex.getLoc();
2639 if (!EatIfPresent(lltok::lparen))
2640 return error(ParenLoc, "expected '('");
2641 LocTy KindLoc = Lex.getLoc();
2642 std::string Arg;
2643 if (parseStringConstant(Arg))
2644 return error(KindLoc, "expected allockind value");
2645 for (StringRef A : llvm::split(Arg, ",")) {
2646 if (A == "alloc") {
2648 } else if (A == "realloc") {
2650 } else if (A == "free") {
2652 } else if (A == "uninitialized") {
2654 } else if (A == "zeroed") {
2656 } else if (A == "aligned") {
2658 } else {
2659 return error(KindLoc, Twine("unknown allockind ") + A);
2660 }
2661 }
2662 ParenLoc = Lex.getLoc();
2663 if (!EatIfPresent(lltok::rparen))
2664 return error(ParenLoc, "expected ')'");
2665 if (Kind == AllocFnKind::Unknown)
2666 return error(KindLoc, "expected allockind value");
2667 return false;
2668}
2669
2671 using Loc = IRMemLocation;
2672
2673 switch (Tok) {
2674 case lltok::kw_argmem:
2675 return {Loc::ArgMem};
2677 return {Loc::InaccessibleMem};
2678 case lltok::kw_errnomem:
2679 return {Loc::ErrnoMem};
2681 return {Loc::TargetMem0};
2683 return {Loc::TargetMem1};
2684 case lltok::kw_target_mem: {
2687 Targets.push_back(Loc);
2688 return Targets;
2689 }
2690 default:
2691 return {};
2692 }
2693}
2694
2695static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2696 switch (Tok) {
2697 case lltok::kw_none:
2698 return ModRefInfo::NoModRef;
2699 case lltok::kw_read:
2700 return ModRefInfo::Ref;
2701 case lltok::kw_write:
2702 return ModRefInfo::Mod;
2704 return ModRefInfo::ModRef;
2705 default:
2706 return std::nullopt;
2707 }
2708}
2709
2710static std::optional<DenormalMode::DenormalModeKind>
2712 switch (Tok) {
2713 case lltok::kw_ieee:
2714 return DenormalMode::IEEE;
2719 case lltok::kw_dynamic:
2720 return DenormalMode::Dynamic;
2721 default:
2722 return std::nullopt;
2723 }
2724}
2725
2726std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2728
2729 // We use syntax like memory(argmem: read), so the colon should not be
2730 // interpreted as a label terminator.
2731 Lex.setIgnoreColonInIdentifiers(true);
2732 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2733
2734 Lex.Lex();
2735 if (!EatIfPresent(lltok::lparen)) {
2736 tokError("expected '('");
2737 return std::nullopt;
2738 }
2739
2740 bool SeenLoc = false;
2741 bool SeenTargetLoc = false;
2742 do {
2743 SmallVector<IRMemLocation, 2> Locs = keywordToLoc(Lex.getKind());
2744 if (!Locs.empty()) {
2745 Lex.Lex();
2746 if (!EatIfPresent(lltok::colon)) {
2747 tokError("expected ':' after location");
2748 return std::nullopt;
2749 }
2750 }
2751
2752 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2753 if (!MR) {
2754 if (Locs.empty())
2755 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2756 "or access kind (none, read, write, readwrite)");
2757 else
2758 tokError("expected access kind (none, read, write, readwrite)");
2759 return std::nullopt;
2760 }
2761
2762 Lex.Lex();
2763 if (!Locs.empty()) {
2764 SeenLoc = true;
2765 for (IRMemLocation Loc : Locs) {
2766 ME = ME.getWithModRef(Loc, *MR);
2767 if (ME.isTargetMemLoc(Loc) && Locs.size() == 1)
2768 SeenTargetLoc = true;
2769 }
2770 if (Locs.size() > 1 && SeenTargetLoc) {
2771 tokError("target memory default access kind must be specified first");
2772 return std::nullopt;
2773 }
2774
2775 } else {
2776 if (SeenLoc) {
2777 tokError("default access kind must be specified first");
2778 return std::nullopt;
2779 }
2780 ME = MemoryEffects(*MR);
2781 }
2782
2783 if (EatIfPresent(lltok::rparen))
2784 return ME;
2785 } while (EatIfPresent(lltok::comma));
2786
2787 tokError("unterminated memory attribute");
2788 return std::nullopt;
2789}
2790
2791std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2792 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2793 keywordToDenormalModeKind(Lex.getKind());
2794 if (!OutputMode) {
2795 tokError("expected denormal behavior kind (ieee, preservesign, "
2796 "positivezero, dynamic)");
2797 return {};
2798 }
2799
2800 Lex.Lex();
2801
2802 std::optional<DenormalMode::DenormalModeKind> InputMode;
2803 if (EatIfPresent(lltok::bar)) {
2804 InputMode = keywordToDenormalModeKind(Lex.getKind());
2805 if (!InputMode) {
2806 tokError("expected denormal behavior kind (ieee, preservesign, "
2807 "positivezero, dynamic)");
2808 return {};
2809 }
2810
2811 Lex.Lex();
2812 } else {
2813 // Single item, input == output mode
2814 InputMode = OutputMode;
2815 }
2816
2817 return DenormalMode(*OutputMode, *InputMode);
2818}
2819
2820std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2821 // We use syntax like denormal_fpenv(float: preservesign), so the colon should
2822 // not be interpreted as a label terminator.
2823 Lex.setIgnoreColonInIdentifiers(true);
2824 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2825
2826 Lex.Lex();
2827
2828 if (parseToken(lltok::lparen, "expected '('"))
2829 return {};
2830
2831 DenormalMode DefaultMode = DenormalMode::getIEEE();
2832 DenormalMode F32Mode = DenormalMode::getInvalid();
2833
2834 bool HasDefaultSection = false;
2835 if (Lex.getKind() != lltok::Type) {
2836 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2837 if (!ParsedDefaultMode)
2838 return {};
2839 DefaultMode = *ParsedDefaultMode;
2840 HasDefaultSection = true;
2841 }
2842
2843 bool HasComma = EatIfPresent(lltok::comma);
2844 if (Lex.getKind() == lltok::Type) {
2845 if (HasDefaultSection && !HasComma) {
2846 tokError("expected ',' before float:");
2847 return {};
2848 }
2849
2850 Type *Ty = nullptr;
2851 if (parseType(Ty) || !Ty->isFloatTy()) {
2852 tokError("expected float:");
2853 return {};
2854 }
2855
2856 if (parseToken(lltok::colon, "expected ':' before float denormal_fpenv"))
2857 return {};
2858
2859 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2860 if (!ParsedF32Mode)
2861 return {};
2862
2863 F32Mode = *ParsedF32Mode;
2864 }
2865
2866 if (parseToken(lltok::rparen, "unterminated denormal_fpenv"))
2867 return {};
2868
2869 return DenormalFPEnv(DefaultMode, F32Mode);
2870}
2871
2872static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2873 switch (Tok) {
2874 case lltok::kw_all:
2875 return fcAllFlags;
2876 case lltok::kw_nan:
2877 return fcNan;
2878 case lltok::kw_snan:
2879 return fcSNan;
2880 case lltok::kw_qnan:
2881 return fcQNan;
2882 case lltok::kw_inf:
2883 return fcInf;
2884 case lltok::kw_ninf:
2885 return fcNegInf;
2886 case lltok::kw_pinf:
2887 return fcPosInf;
2888 case lltok::kw_norm:
2889 return fcNormal;
2890 case lltok::kw_nnorm:
2891 return fcNegNormal;
2892 case lltok::kw_pnorm:
2893 return fcPosNormal;
2894 case lltok::kw_sub:
2895 return fcSubnormal;
2896 case lltok::kw_nsub:
2897 return fcNegSubnormal;
2898 case lltok::kw_psub:
2899 return fcPosSubnormal;
2900 case lltok::kw_zero:
2901 return fcZero;
2902 case lltok::kw_nzero:
2903 return fcNegZero;
2904 case lltok::kw_pzero:
2905 return fcPosZero;
2906 default:
2907 return 0;
2908 }
2909}
2910
2911unsigned LLParser::parseNoFPClassAttr() {
2912 unsigned Mask = fcNone;
2913
2914 Lex.Lex();
2915 if (!EatIfPresent(lltok::lparen)) {
2916 tokError("expected '('");
2917 return 0;
2918 }
2919
2920 do {
2921 uint64_t Value = 0;
2922 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2923 if (TestMask != 0) {
2924 Mask |= TestMask;
2925 // TODO: Disallow overlapping masks to avoid copy paste errors
2926 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2927 !parseUInt64(Value)) {
2928 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2929 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2930 return 0;
2931 }
2932
2933 if (!EatIfPresent(lltok::rparen)) {
2934 error(Lex.getLoc(), "expected ')'");
2935 return 0;
2936 }
2937
2938 return Value;
2939 } else {
2940 error(Lex.getLoc(), "expected nofpclass test mask");
2941 return 0;
2942 }
2943
2944 Lex.Lex();
2945 if (EatIfPresent(lltok::rparen))
2946 return Mask;
2947 } while (1);
2948
2949 llvm_unreachable("unterminated nofpclass attribute");
2950}
2951
2952/// parseOptionalCommaAlign
2953/// ::=
2954/// ::= ',' align 4
2955///
2956/// This returns with AteExtraComma set to true if it ate an excess comma at the
2957/// end.
2958bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2959 bool &AteExtraComma) {
2960 AteExtraComma = false;
2961 while (EatIfPresent(lltok::comma)) {
2962 // Metadata at the end is an early exit.
2963 if (Lex.getKind() == lltok::MetadataVar) {
2964 AteExtraComma = true;
2965 return false;
2966 }
2967
2968 if (Lex.getKind() != lltok::kw_align)
2969 return error(Lex.getLoc(), "expected metadata or 'align'");
2970
2971 if (parseOptionalAlignment(Alignment))
2972 return true;
2973 }
2974
2975 return false;
2976}
2977
2978/// parseOptionalCommaAddrSpace
2979/// ::=
2980/// ::= ',' addrspace(1)
2981///
2982/// This returns with AteExtraComma set to true if it ate an excess comma at the
2983/// end.
2984bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2985 bool &AteExtraComma) {
2986 AteExtraComma = false;
2987 while (EatIfPresent(lltok::comma)) {
2988 // Metadata at the end is an early exit.
2989 if (Lex.getKind() == lltok::MetadataVar) {
2990 AteExtraComma = true;
2991 return false;
2992 }
2993
2994 Loc = Lex.getLoc();
2995 if (Lex.getKind() != lltok::kw_addrspace)
2996 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2997
2998 if (parseOptionalAddrSpace(AddrSpace))
2999 return true;
3000 }
3001
3002 return false;
3003}
3004
3005bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
3006 std::optional<unsigned> &HowManyArg) {
3007 Lex.Lex();
3008
3009 auto StartParen = Lex.getLoc();
3010 if (!EatIfPresent(lltok::lparen))
3011 return error(StartParen, "expected '('");
3012
3013 if (parseUInt32(BaseSizeArg))
3014 return true;
3015
3016 if (EatIfPresent(lltok::comma)) {
3017 auto HowManyAt = Lex.getLoc();
3018 unsigned HowMany;
3019 if (parseUInt32(HowMany))
3020 return true;
3021 if (HowMany == BaseSizeArg)
3022 return error(HowManyAt,
3023 "'allocsize' indices can't refer to the same parameter");
3024 HowManyArg = HowMany;
3025 } else
3026 HowManyArg = std::nullopt;
3027
3028 auto EndParen = Lex.getLoc();
3029 if (!EatIfPresent(lltok::rparen))
3030 return error(EndParen, "expected ')'");
3031 return false;
3032}
3033
3034bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
3035 unsigned &MaxValue) {
3036 Lex.Lex();
3037
3038 auto StartParen = Lex.getLoc();
3039 if (!EatIfPresent(lltok::lparen))
3040 return error(StartParen, "expected '('");
3041
3042 if (parseUInt32(MinValue))
3043 return true;
3044
3045 if (EatIfPresent(lltok::comma)) {
3046 if (parseUInt32(MaxValue))
3047 return true;
3048 } else
3049 MaxValue = MinValue;
3050
3051 auto EndParen = Lex.getLoc();
3052 if (!EatIfPresent(lltok::rparen))
3053 return error(EndParen, "expected ')'");
3054 return false;
3055}
3056
3057/// parseScopeAndOrdering
3058/// if isAtomic: ::= SyncScope? AtomicOrdering
3059/// else: ::=
3060///
3061/// This sets Scope and Ordering to the parsed values.
3062bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
3063 AtomicOrdering &Ordering) {
3064 if (!IsAtomic)
3065 return false;
3066
3067 return parseScope(SSID) || parseOrdering(Ordering);
3068}
3069
3070/// parseScope
3071/// ::= syncscope("singlethread" | "<target scope>")?
3072///
3073/// This sets synchronization scope ID to the ID of the parsed value.
3074bool LLParser::parseScope(SyncScope::ID &SSID) {
3075 SSID = SyncScope::System;
3076 if (EatIfPresent(lltok::kw_syncscope)) {
3077 auto StartParenAt = Lex.getLoc();
3078 if (!EatIfPresent(lltok::lparen))
3079 return error(StartParenAt, "Expected '(' in syncscope");
3080
3081 std::string SSN;
3082 auto SSNAt = Lex.getLoc();
3083 if (parseStringConstant(SSN))
3084 return error(SSNAt, "Expected synchronization scope name");
3085
3086 auto EndParenAt = Lex.getLoc();
3087 if (!EatIfPresent(lltok::rparen))
3088 return error(EndParenAt, "Expected ')' in syncscope");
3089
3090 SSID = Context.getOrInsertSyncScopeID(SSN);
3091 }
3092
3093 return false;
3094}
3095
3096/// parseOrdering
3097/// ::= AtomicOrdering
3098///
3099/// This sets Ordering to the parsed value.
3100bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
3101 switch (Lex.getKind()) {
3102 default:
3103 return tokError("Expected ordering on atomic instruction");
3106 // Not specified yet:
3107 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
3111 case lltok::kw_seq_cst:
3113 break;
3114 }
3115 Lex.Lex();
3116 return false;
3117}
3118
3119/// parseOptionalStackAlignment
3120/// ::= /* empty */
3121/// ::= 'alignstack' '(' 4 ')'
3122bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
3123 Alignment = 0;
3124 if (!EatIfPresent(lltok::kw_alignstack))
3125 return false;
3126 LocTy ParenLoc = Lex.getLoc();
3127 if (!EatIfPresent(lltok::lparen))
3128 return error(ParenLoc, "expected '('");
3129 LocTy AlignLoc = Lex.getLoc();
3130 if (parseUInt32(Alignment))
3131 return true;
3132 ParenLoc = Lex.getLoc();
3133 if (!EatIfPresent(lltok::rparen))
3134 return error(ParenLoc, "expected ')'");
3135 if (!isPowerOf2_32(Alignment))
3136 return error(AlignLoc, "stack alignment is not a power of two");
3137 return false;
3138}
3139
3140/// parseIndexList - This parses the index list for an insert/extractvalue
3141/// instruction. This sets AteExtraComma in the case where we eat an extra
3142/// comma at the end of the line and find that it is followed by metadata.
3143/// Clients that don't allow metadata can call the version of this function that
3144/// only takes one argument.
3145///
3146/// parseIndexList
3147/// ::= (',' uint32)+
3148///
3149bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
3150 bool &AteExtraComma) {
3151 AteExtraComma = false;
3152
3153 if (Lex.getKind() != lltok::comma)
3154 return tokError("expected ',' as start of index list");
3155
3156 while (EatIfPresent(lltok::comma)) {
3157 if (Lex.getKind() == lltok::MetadataVar) {
3158 if (Indices.empty())
3159 return tokError("expected index");
3160 AteExtraComma = true;
3161 return false;
3162 }
3163 unsigned Idx = 0;
3164 if (parseUInt32(Idx))
3165 return true;
3166 Indices.push_back(Idx);
3167 }
3168
3169 return false;
3170}
3171
3172//===----------------------------------------------------------------------===//
3173// Type Parsing.
3174//===----------------------------------------------------------------------===//
3175
3176/// parseType - parse a type.
3177bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
3178 SMLoc TypeLoc = Lex.getLoc();
3179 switch (Lex.getKind()) {
3180 default:
3181 return tokError(Msg);
3182 case lltok::Type:
3183 // Type ::= 'float' | 'void' (etc)
3184 Result = Lex.getTyVal();
3185 Lex.Lex();
3186
3187 // Handle "ptr" opaque pointer type.
3188 //
3189 // Type ::= ptr ('addrspace' '(' uint32 ')')?
3190 if (Result->isPointerTy()) {
3191 unsigned AddrSpace;
3192 if (parseOptionalAddrSpace(AddrSpace))
3193 return true;
3194 Result = PointerType::get(getContext(), AddrSpace);
3195
3196 // Give a nice error for 'ptr*'.
3197 if (Lex.getKind() == lltok::star)
3198 return tokError("ptr* is invalid - use ptr instead");
3199
3200 // Fall through to parsing the type suffixes only if this 'ptr' is a
3201 // function return. Otherwise, return success, implicitly rejecting other
3202 // suffixes.
3203 if (Lex.getKind() != lltok::lparen)
3204 return false;
3205 }
3206 break;
3207 case lltok::kw_target: {
3208 // Type ::= TargetExtType
3209 if (parseTargetExtType(Result))
3210 return true;
3211 break;
3212 }
3213 case lltok::lbrace:
3214 // Type ::= StructType
3215 if (parseAnonStructType(Result, false))
3216 return true;
3217 break;
3218 case lltok::lsquare:
3219 // Type ::= '[' ... ']'
3220 Lex.Lex(); // eat the lsquare.
3221 if (parseArrayVectorType(Result, false))
3222 return true;
3223 break;
3224 case lltok::less: // Either vector or packed struct.
3225 // Type ::= '<' ... '>'
3226 Lex.Lex();
3227 if (Lex.getKind() == lltok::lbrace) {
3228 if (parseAnonStructType(Result, true) ||
3229 parseToken(lltok::greater, "expected '>' at end of packed struct"))
3230 return true;
3231 } else if (parseArrayVectorType(Result, true))
3232 return true;
3233 break;
3234 case lltok::LocalVar: {
3235 // Type ::= %foo
3236 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3237
3238 // If the type hasn't been defined yet, create a forward definition and
3239 // remember where that forward def'n was seen (in case it never is defined).
3240 if (!Entry.first) {
3241 Entry.first = StructType::create(Context, Lex.getStrVal());
3242 Entry.second = Lex.getLoc();
3243 }
3244 Result = Entry.first;
3245 Lex.Lex();
3246 break;
3247 }
3248
3249 case lltok::LocalVarID: {
3250 // Type ::= %4
3251 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3252
3253 // If the type hasn't been defined yet, create a forward definition and
3254 // remember where that forward def'n was seen (in case it never is defined).
3255 if (!Entry.first) {
3256 Entry.first = StructType::create(Context);
3257 Entry.second = Lex.getLoc();
3258 }
3259 Result = Entry.first;
3260 Lex.Lex();
3261 break;
3262 }
3263 }
3264
3265 // parse the type suffixes.
3266 while (true) {
3267 switch (Lex.getKind()) {
3268 // End of type.
3269 default:
3270 if (!AllowVoid && Result->isVoidTy())
3271 return error(TypeLoc, "void type only allowed for function results");
3272 return false;
3273
3274 // Type ::= Type '*'
3275 case lltok::star:
3276 if (Result->isLabelTy())
3277 return tokError("basic block pointers are invalid");
3278 if (Result->isVoidTy())
3279 return tokError("pointers to void are invalid - use i8* instead");
3281 return tokError("pointer to this type is invalid");
3282 Result = PointerType::getUnqual(Context);
3283 Lex.Lex();
3284 break;
3285
3286 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3287 case lltok::kw_addrspace: {
3288 if (Result->isLabelTy())
3289 return tokError("basic block pointers are invalid");
3290 if (Result->isVoidTy())
3291 return tokError("pointers to void are invalid; use i8* instead");
3293 return tokError("pointer to this type is invalid");
3294 unsigned AddrSpace;
3295 if (parseOptionalAddrSpace(AddrSpace) ||
3296 parseToken(lltok::star, "expected '*' in address space"))
3297 return true;
3298
3299 Result = PointerType::get(Context, AddrSpace);
3300 break;
3301 }
3302
3303 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3304 case lltok::lparen:
3305 if (parseFunctionType(Result))
3306 return true;
3307 break;
3308 }
3309 }
3310}
3311
3312/// parseParameterList
3313/// ::= '(' ')'
3314/// ::= '(' Arg (',' Arg)* ')'
3315/// Arg
3316/// ::= Type OptionalAttributes Value OptionalAttributes
3317bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3318 PerFunctionState &PFS, bool IsMustTailCall,
3319 bool InVarArgsFunc) {
3320 if (parseToken(lltok::lparen, "expected '(' in call"))
3321 return true;
3322
3323 while (Lex.getKind() != lltok::rparen) {
3324 // If this isn't the first argument, we need a comma.
3325 if (!ArgList.empty() &&
3326 parseToken(lltok::comma, "expected ',' in argument list"))
3327 return true;
3328
3329 // parse an ellipsis if this is a musttail call in a variadic function.
3330 if (Lex.getKind() == lltok::dotdotdot) {
3331 const char *Msg = "unexpected ellipsis in argument list for ";
3332 if (!IsMustTailCall)
3333 return tokError(Twine(Msg) + "non-musttail call");
3334 if (!InVarArgsFunc)
3335 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3336 Lex.Lex(); // Lex the '...', it is purely for readability.
3337 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3338 }
3339
3340 // parse the argument.
3341 LocTy ArgLoc;
3342 Type *ArgTy = nullptr;
3343 Value *V;
3344 if (parseType(ArgTy, ArgLoc))
3345 return true;
3347 return error(ArgLoc, "invalid type for function argument");
3348
3349 AttrBuilder ArgAttrs(M->getContext());
3350
3351 if (ArgTy->isMetadataTy()) {
3352 if (parseMetadataAsValue(V, PFS))
3353 return true;
3354 } else {
3355 // Otherwise, handle normal operands.
3356 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3357 return true;
3358 }
3359 ArgList.push_back(ParamInfo(
3360 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3361 }
3362
3363 if (IsMustTailCall && InVarArgsFunc)
3364 return tokError("expected '...' at end of argument list for musttail call "
3365 "in varargs function");
3366
3367 Lex.Lex(); // Lex the ')'.
3368 return false;
3369}
3370
3371/// parseRequiredTypeAttr
3372/// ::= attrname(<ty>)
3373bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3374 Attribute::AttrKind AttrKind) {
3375 Type *Ty = nullptr;
3376 if (!EatIfPresent(AttrToken))
3377 return true;
3378 if (!EatIfPresent(lltok::lparen))
3379 return error(Lex.getLoc(), "expected '('");
3380 if (parseType(Ty))
3381 return true;
3382 if (!EatIfPresent(lltok::rparen))
3383 return error(Lex.getLoc(), "expected ')'");
3384
3385 B.addTypeAttr(AttrKind, Ty);
3386 return false;
3387}
3388
3389/// parseRangeAttr
3390/// ::= range(<ty> <n>,<n>)
3391bool LLParser::parseRangeAttr(AttrBuilder &B) {
3392 Lex.Lex();
3393
3394 APInt Lower;
3395 APInt Upper;
3396 Type *Ty = nullptr;
3397 LocTy TyLoc;
3398
3399 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3400 if (Lex.getKind() != lltok::APSInt)
3401 return tokError("expected integer");
3402 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3403 return tokError(
3404 "integer is too large for the bit width of specified type");
3405 Val = Lex.getAPSIntVal().extend(BitWidth);
3406 Lex.Lex();
3407 return false;
3408 };
3409
3410 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3411 return true;
3412 if (!Ty->isIntegerTy())
3413 return error(TyLoc, "the range must have integer type!");
3414
3415 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3416
3417 if (ParseAPSInt(BitWidth, Lower) ||
3418 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3419 return true;
3420 if (Lower == Upper && !Lower.isZero())
3421 return tokError("the range represent the empty set but limits aren't 0!");
3422
3423 if (parseToken(lltok::rparen, "expected ')'"))
3424 return true;
3425
3426 B.addRangeAttr(ConstantRange(Lower, Upper));
3427 return false;
3428}
3429
3430/// parseInitializesAttr
3431/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3432bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3433 Lex.Lex();
3434
3435 auto ParseAPSInt = [&](APInt &Val) {
3436 if (Lex.getKind() != lltok::APSInt)
3437 return tokError("expected integer");
3438 Val = Lex.getAPSIntVal().extend(64);
3439 Lex.Lex();
3440 return false;
3441 };
3442
3443 if (parseToken(lltok::lparen, "expected '('"))
3444 return true;
3445
3447 // Parse each constant range.
3448 do {
3449 APInt Lower, Upper;
3450 if (parseToken(lltok::lparen, "expected '('"))
3451 return true;
3452
3453 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3454 ParseAPSInt(Upper))
3455 return true;
3456
3457 if (Lower == Upper)
3458 return tokError("the range should not represent the full or empty set!");
3459
3460 if (parseToken(lltok::rparen, "expected ')'"))
3461 return true;
3462
3463 RangeList.push_back(ConstantRange(Lower, Upper));
3464 } while (EatIfPresent(lltok::comma));
3465
3466 if (parseToken(lltok::rparen, "expected ')'"))
3467 return true;
3468
3469 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3470 if (!CRLOrNull.has_value())
3471 return tokError("Invalid (unordered or overlapping) range list");
3472 B.addInitializesAttr(*CRLOrNull);
3473 return false;
3474}
3475
3476bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3478 std::optional<CaptureComponents> Ret;
3479
3480 // We use syntax like captures(ret: address, provenance), so the colon
3481 // should not be interpreted as a label terminator.
3482 Lex.setIgnoreColonInIdentifiers(true);
3483 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
3484
3485 Lex.Lex();
3486 if (parseToken(lltok::lparen, "expected '('"))
3487 return true;
3488
3489 CaptureComponents *Current = &Other;
3490 bool SeenComponent = false;
3491 while (true) {
3492 if (EatIfPresent(lltok::kw_ret)) {
3493 if (parseToken(lltok::colon, "expected ':'"))
3494 return true;
3495 if (Ret)
3496 return tokError("duplicate 'ret' location");
3498 Current = &*Ret;
3499 SeenComponent = false;
3500 }
3501
3502 if (EatIfPresent(lltok::kw_none)) {
3503 if (SeenComponent)
3504 return tokError("cannot use 'none' with other component");
3505 *Current = CaptureComponents::None;
3506 } else {
3507 if (SeenComponent && capturesNothing(*Current))
3508 return tokError("cannot use 'none' with other component");
3509
3510 if (EatIfPresent(lltok::kw_address_is_null))
3512 else if (EatIfPresent(lltok::kw_address))
3513 *Current |= CaptureComponents::Address;
3514 else if (EatIfPresent(lltok::kw_provenance))
3516 else if (EatIfPresent(lltok::kw_read_provenance))
3518 else
3519 return tokError("expected one of 'none', 'address', 'address_is_null', "
3520 "'provenance' or 'read_provenance'");
3521 }
3522
3523 SeenComponent = true;
3524 if (EatIfPresent(lltok::rparen))
3525 break;
3526
3527 if (parseToken(lltok::comma, "expected ',' or ')'"))
3528 return true;
3529 }
3530
3531 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3532 return false;
3533}
3534
3535/// parseOptionalOperandBundles
3536/// ::= /*empty*/
3537/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3538///
3539/// OperandBundle
3540/// ::= bundle-tag '(' ')'
3541/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3542///
3543/// bundle-tag ::= String Constant
3544bool LLParser::parseOptionalOperandBundles(
3545 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3546 LocTy BeginLoc = Lex.getLoc();
3547 if (!EatIfPresent(lltok::lsquare))
3548 return false;
3549
3550 while (Lex.getKind() != lltok::rsquare) {
3551 // If this isn't the first operand bundle, we need a comma.
3552 if (!BundleList.empty() &&
3553 parseToken(lltok::comma, "expected ',' in input list"))
3554 return true;
3555
3556 std::string Tag;
3557 if (parseStringConstant(Tag))
3558 return true;
3559
3560 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3561 return true;
3562
3563 std::vector<Value *> Inputs;
3564 while (Lex.getKind() != lltok::rparen) {
3565 // If this isn't the first input, we need a comma.
3566 if (!Inputs.empty() &&
3567 parseToken(lltok::comma, "expected ',' in input list"))
3568 return true;
3569
3570 Type *Ty = nullptr;
3571 Value *Input = nullptr;
3572 if (parseType(Ty))
3573 return true;
3574 if (Ty->isMetadataTy()) {
3575 if (parseMetadataAsValue(Input, PFS))
3576 return true;
3577 } else if (parseValue(Ty, Input, PFS)) {
3578 return true;
3579 }
3580 Inputs.push_back(Input);
3581 }
3582
3583 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3584
3585 Lex.Lex(); // Lex the ')'.
3586 }
3587
3588 if (BundleList.empty())
3589 return error(BeginLoc, "operand bundle set must not be empty");
3590
3591 Lex.Lex(); // Lex the ']'.
3592 return false;
3593}
3594
3595bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3596 unsigned NextID, unsigned ID) {
3597 if (ID < NextID)
3598 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3599 Twine(NextID) + "' or greater");
3600
3601 return false;
3602}
3603
3604/// parseArgumentList - parse the argument list for a function type or function
3605/// prototype.
3606/// ::= '(' ArgTypeListI ')'
3607/// ArgTypeListI
3608/// ::= /*empty*/
3609/// ::= '...'
3610/// ::= ArgTypeList ',' '...'
3611/// ::= ArgType (',' ArgType)*
3612///
3613bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3614 SmallVectorImpl<unsigned> &UnnamedArgNums,
3615 bool &IsVarArg) {
3616 unsigned CurValID = 0;
3617 IsVarArg = false;
3618 assert(Lex.getKind() == lltok::lparen);
3619 Lex.Lex(); // eat the (.
3620
3621 if (Lex.getKind() != lltok::rparen) {
3622 do {
3623 // Handle ... at end of arg list.
3624 if (EatIfPresent(lltok::dotdotdot)) {
3625 IsVarArg = true;
3626 break;
3627 }
3628
3629 // Otherwise must be an argument type.
3630 LocTy TypeLoc = Lex.getLoc();
3631 Type *ArgTy = nullptr;
3632 AttrBuilder Attrs(M->getContext());
3633 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3634 return true;
3635
3636 if (ArgTy->isVoidTy())
3637 return error(TypeLoc, "argument can not have void type");
3638
3639 std::string Name;
3640 FileLoc IdentStart;
3641 FileLoc IdentEnd;
3642 bool Unnamed = false;
3643 if (Lex.getKind() == lltok::LocalVar) {
3644 Name = Lex.getStrVal();
3645 IdentStart = getTokLineColumnPos();
3646 Lex.Lex();
3647 IdentEnd = getPrevTokEndLineColumnPos();
3648 } else {
3649 unsigned ArgID;
3650 if (Lex.getKind() == lltok::LocalVarID) {
3651 ArgID = Lex.getUIntVal();
3652 IdentStart = getTokLineColumnPos();
3653 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3654 return true;
3655 Lex.Lex();
3656 IdentEnd = getPrevTokEndLineColumnPos();
3657 } else {
3658 ArgID = CurValID;
3659 Unnamed = true;
3660 }
3661 UnnamedArgNums.push_back(ArgID);
3662 CurValID = ArgID + 1;
3663 }
3664
3666 return error(TypeLoc, "invalid type for function argument");
3667
3668 ArgList.emplace_back(
3669 TypeLoc, ArgTy,
3670 Unnamed ? std::nullopt
3671 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3672 AttributeSet::get(ArgTy->getContext(), Attrs), std::move(Name));
3673 } while (EatIfPresent(lltok::comma));
3674 }
3675
3676 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3677}
3678
3679/// parseFunctionType
3680/// ::= Type ArgumentList OptionalAttrs
3681bool LLParser::parseFunctionType(Type *&Result) {
3682 assert(Lex.getKind() == lltok::lparen);
3683
3685 return tokError("invalid function return type");
3686
3688 bool IsVarArg;
3689 SmallVector<unsigned> UnnamedArgNums;
3690 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3691 return true;
3692
3693 // Reject names on the arguments lists.
3694 for (const ArgInfo &Arg : ArgList) {
3695 if (!Arg.Name.empty())
3696 return error(Arg.Loc, "argument name invalid in function type");
3697 if (Arg.Attrs.hasAttributes())
3698 return error(Arg.Loc, "argument attributes invalid in function type");
3699 }
3700
3701 SmallVector<Type*, 16> ArgListTy;
3702 for (const ArgInfo &Arg : ArgList)
3703 ArgListTy.push_back(Arg.Ty);
3704
3705 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3706 return false;
3707}
3708
3709/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3710/// other structs.
3711bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3713 if (parseStructBody(Elts))
3714 return true;
3715
3716 Result = StructType::get(Context, Elts, Packed);
3717 return false;
3718}
3719
3720/// parseStructDefinition - parse a struct in a 'type' definition.
3721bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3722 std::pair<Type *, LocTy> &Entry,
3723 Type *&ResultTy) {
3724 // If the type was already defined, diagnose the redefinition.
3725 if (Entry.first && !Entry.second.isValid())
3726 return error(TypeLoc, "redefinition of type");
3727
3728 // If we have opaque, just return without filling in the definition for the
3729 // struct. This counts as a definition as far as the .ll file goes.
3730 if (EatIfPresent(lltok::kw_opaque)) {
3731 // This type is being defined, so clear the location to indicate this.
3732 Entry.second = SMLoc();
3733
3734 // If this type number has never been uttered, create it.
3735 if (!Entry.first)
3736 Entry.first = StructType::create(Context, Name);
3737 ResultTy = Entry.first;
3738 return false;
3739 }
3740
3741 // If the type starts with '<', then it is either a packed struct or a vector.
3742 bool isPacked = EatIfPresent(lltok::less);
3743
3744 // If we don't have a struct, then we have a random type alias, which we
3745 // accept for compatibility with old files. These types are not allowed to be
3746 // forward referenced and not allowed to be recursive.
3747 if (Lex.getKind() != lltok::lbrace) {
3748 if (Entry.first)
3749 return error(TypeLoc, "forward references to non-struct type");
3750
3751 ResultTy = nullptr;
3752 if (isPacked)
3753 return parseArrayVectorType(ResultTy, true);
3754 return parseType(ResultTy);
3755 }
3756
3757 // This type is being defined, so clear the location to indicate this.
3758 Entry.second = SMLoc();
3759
3760 // If this type number has never been uttered, create it.
3761 if (!Entry.first)
3762 Entry.first = StructType::create(Context, Name);
3763
3764 StructType *STy = cast<StructType>(Entry.first);
3765
3767 if (parseStructBody(Body) ||
3768 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3769 return true;
3770
3771 if (auto E = STy->setBodyOrError(Body, isPacked))
3772 return tokError(toString(std::move(E)));
3773
3774 ResultTy = STy;
3775 return false;
3776}
3777
3778/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3779/// StructType
3780/// ::= '{' '}'
3781/// ::= '{' Type (',' Type)* '}'
3782/// ::= '<' '{' '}' '>'
3783/// ::= '<' '{' Type (',' Type)* '}' '>'
3784bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3785 assert(Lex.getKind() == lltok::lbrace);
3786 Lex.Lex(); // Consume the '{'
3787
3788 // Handle the empty struct.
3789 if (EatIfPresent(lltok::rbrace))
3790 return false;
3791
3792 LocTy EltTyLoc = Lex.getLoc();
3793 Type *Ty = nullptr;
3794 if (parseType(Ty))
3795 return true;
3796 Body.push_back(Ty);
3797
3799 return error(EltTyLoc, "invalid element type for struct");
3800
3801 while (EatIfPresent(lltok::comma)) {
3802 EltTyLoc = Lex.getLoc();
3803 if (parseType(Ty))
3804 return true;
3805
3807 return error(EltTyLoc, "invalid element type for struct");
3808
3809 Body.push_back(Ty);
3810 }
3811
3812 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3813}
3814
3815/// parseArrayVectorType - parse an array or vector type, assuming the first
3816/// token has already been consumed.
3817/// Type
3818/// ::= '[' APSINTVAL 'x' Types ']'
3819/// ::= '<' APSINTVAL 'x' Types '>'
3820/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3821bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3822 bool Scalable = false;
3823
3824 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3825 Lex.Lex(); // consume the 'vscale'
3826 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3827 return true;
3828
3829 Scalable = true;
3830 }
3831
3832 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3833 Lex.getAPSIntVal().getBitWidth() > 64)
3834 return tokError("expected number in address space");
3835
3836 LocTy SizeLoc = Lex.getLoc();
3837 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3838 Lex.Lex();
3839
3840 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3841 return true;
3842
3843 LocTy TypeLoc = Lex.getLoc();
3844 Type *EltTy = nullptr;
3845 if (parseType(EltTy))
3846 return true;
3847
3848 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3849 "expected end of sequential type"))
3850 return true;
3851
3852 if (IsVector) {
3853 if (Size == 0)
3854 return error(SizeLoc, "zero element vector is illegal");
3855 if ((unsigned)Size != Size)
3856 return error(SizeLoc, "size too large for vector");
3858 return error(TypeLoc, "invalid vector element type");
3859 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3860 } else {
3862 return error(TypeLoc, "invalid array element type");
3863 Result = ArrayType::get(EltTy, Size);
3864 }
3865 return false;
3866}
3867
3868/// parseTargetExtType - handle target extension type syntax
3869/// TargetExtType
3870/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3871///
3872/// TargetExtTypeParams
3873/// ::= /*empty*/
3874/// ::= ',' Type TargetExtTypeParams
3875///
3876/// TargetExtIntParams
3877/// ::= /*empty*/
3878/// ::= ',' uint32 TargetExtIntParams
3879bool LLParser::parseTargetExtType(Type *&Result) {
3880 Lex.Lex(); // Eat the 'target' keyword.
3881
3882 // Get the mandatory type name.
3883 std::string TypeName;
3884 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3885 parseStringConstant(TypeName))
3886 return true;
3887
3888 // Parse all of the integer and type parameters at the same time; the use of
3889 // SeenInt will allow us to catch cases where type parameters follow integer
3890 // parameters.
3891 SmallVector<Type *> TypeParams;
3892 SmallVector<unsigned> IntParams;
3893 bool SeenInt = false;
3894 while (Lex.getKind() == lltok::comma) {
3895 Lex.Lex(); // Eat the comma.
3896
3897 if (Lex.getKind() == lltok::APSInt) {
3898 SeenInt = true;
3899 unsigned IntVal;
3900 if (parseUInt32(IntVal))
3901 return true;
3902 IntParams.push_back(IntVal);
3903 } else if (SeenInt) {
3904 // The only other kind of parameter we support is type parameters, which
3905 // must precede the integer parameters. This is therefore an error.
3906 return tokError("expected uint32 param");
3907 } else {
3908 Type *TypeParam;
3909 if (parseType(TypeParam, /*AllowVoid=*/true))
3910 return true;
3911 TypeParams.push_back(TypeParam);
3912 }
3913 }
3914
3915 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3916 return true;
3917
3918 auto TTy =
3919 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3920 if (auto E = TTy.takeError())
3921 return tokError(toString(std::move(E)));
3922
3923 Result = *TTy;
3924 return false;
3925}
3926
3927//===----------------------------------------------------------------------===//
3928// Function Semantic Analysis.
3929//===----------------------------------------------------------------------===//
3930
3931LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3932 int functionNumber,
3933 ArrayRef<unsigned> UnnamedArgNums)
3934 : P(p), F(f), FunctionNumber(functionNumber) {
3935
3936 // Insert unnamed arguments into the NumberedVals list.
3937 auto It = UnnamedArgNums.begin();
3938 for (Argument &A : F.args()) {
3939 if (!A.hasName()) {
3940 unsigned ArgNum = *It++;
3941 NumberedVals.add(ArgNum, &A);
3942 }
3943 }
3944}
3945
3946LLParser::PerFunctionState::~PerFunctionState() {
3947 // If there were any forward referenced non-basicblock values, delete them.
3948
3949 for (const auto &P : ForwardRefVals) {
3950 if (isa<BasicBlock>(P.second.first))
3951 continue;
3952 P.second.first->replaceAllUsesWith(
3953 PoisonValue::get(P.second.first->getType()));
3954 P.second.first->deleteValue();
3955 }
3956
3957 for (const auto &P : ForwardRefValIDs) {
3958 if (isa<BasicBlock>(P.second.first))
3959 continue;
3960 P.second.first->replaceAllUsesWith(
3961 PoisonValue::get(P.second.first->getType()));
3962 P.second.first->deleteValue();
3963 }
3964}
3965
3966bool LLParser::PerFunctionState::finishFunction() {
3967 if (!ForwardRefVals.empty())
3968 return P.error(ForwardRefVals.begin()->second.second,
3969 "use of undefined value '%" + ForwardRefVals.begin()->first +
3970 "'");
3971 if (!ForwardRefValIDs.empty())
3972 return P.error(ForwardRefValIDs.begin()->second.second,
3973 "use of undefined value '%" +
3974 Twine(ForwardRefValIDs.begin()->first) + "'");
3975 return false;
3976}
3977
3978/// getVal - Get a value with the specified name or ID, creating a
3979/// forward reference record if needed. This can return null if the value
3980/// exists but does not have the right type.
3981Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3982 LocTy Loc) {
3983 // Look this name up in the normal function symbol table.
3984 Value *Val = F.getValueSymbolTable()->lookup(Name);
3985
3986 // If this is a forward reference for the value, see if we already created a
3987 // forward ref record.
3988 if (!Val) {
3989 auto I = ForwardRefVals.find(Name);
3990 if (I != ForwardRefVals.end())
3991 Val = I->second.first;
3992 }
3993
3994 // If we have the value in the symbol table or fwd-ref table, return it.
3995 if (Val)
3996 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3997
3998 // Don't make placeholders with invalid type.
3999 if (!Ty->isFirstClassType()) {
4000 P.error(Loc, "invalid use of a non-first-class type");
4001 return nullptr;
4002 }
4003
4004 // Otherwise, create a new forward reference for this value and remember it.
4005 Value *FwdVal;
4006 if (Ty->isLabelTy()) {
4007 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
4008 } else {
4009 FwdVal = new Argument(Ty, Name);
4010 }
4011 if (FwdVal->getName() != Name) {
4012 P.error(Loc, "name is too long which can result in name collisions, "
4013 "consider making the name shorter or "
4014 "increasing -non-global-value-max-name-size");
4015 return nullptr;
4016 }
4017
4018 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
4019 return FwdVal;
4020}
4021
4022Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
4023 // Look this name up in the normal function symbol table.
4024 Value *Val = NumberedVals.get(ID);
4025
4026 // If this is a forward reference for the value, see if we already created a
4027 // forward ref record.
4028 if (!Val) {
4029 auto I = ForwardRefValIDs.find(ID);
4030 if (I != ForwardRefValIDs.end())
4031 Val = I->second.first;
4032 }
4033
4034 // If we have the value in the symbol table or fwd-ref table, return it.
4035 if (Val)
4036 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
4037
4038 if (!Ty->isFirstClassType()) {
4039 P.error(Loc, "invalid use of a non-first-class type");
4040 return nullptr;
4041 }
4042
4043 // Otherwise, create a new forward reference for this value and remember it.
4044 Value *FwdVal;
4045 if (Ty->isLabelTy()) {
4046 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
4047 } else {
4048 FwdVal = new Argument(Ty);
4049 }
4050
4051 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
4052 return FwdVal;
4053}
4054
4055/// setInstName - After an instruction is parsed and inserted into its
4056/// basic block, this installs its name.
4057bool LLParser::PerFunctionState::setInstName(int NameID,
4058 const std::string &NameStr,
4059 LocTy NameLoc, Instruction *Inst) {
4060 // If this instruction has void type, it cannot have a name or ID specified.
4061 if (Inst->getType()->isVoidTy()) {
4062 if (NameID != -1 || !NameStr.empty())
4063 return P.error(NameLoc, "instructions returning void cannot have a name");
4064 return false;
4065 }
4066
4067 // If this was a numbered instruction, verify that the instruction is the
4068 // expected value and resolve any forward references.
4069 if (NameStr.empty()) {
4070 // If neither a name nor an ID was specified, just use the next ID.
4071 if (NameID == -1)
4072 NameID = NumberedVals.getNext();
4073
4074 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
4075 NameID))
4076 return true;
4077
4078 auto FI = ForwardRefValIDs.find(NameID);
4079 if (FI != ForwardRefValIDs.end()) {
4080 Value *Sentinel = FI->second.first;
4081 if (Sentinel->getType() != Inst->getType())
4082 return P.error(NameLoc, "instruction forward referenced with type '" +
4083 getTypeString(FI->second.first->getType()) +
4084 "'");
4085
4086 Sentinel->replaceAllUsesWith(Inst);
4087 Sentinel->deleteValue();
4088 ForwardRefValIDs.erase(FI);
4089 }
4090
4091 NumberedVals.add(NameID, Inst);
4092 return false;
4093 }
4094
4095 // Otherwise, the instruction had a name. Resolve forward refs and set it.
4096 auto FI = ForwardRefVals.find(NameStr);
4097 if (FI != ForwardRefVals.end()) {
4098 Value *Sentinel = FI->second.first;
4099 if (Sentinel->getType() != Inst->getType())
4100 return P.error(NameLoc, "instruction forward referenced with type '" +
4101 getTypeString(FI->second.first->getType()) +
4102 "'");
4103
4104 Sentinel->replaceAllUsesWith(Inst);
4105 Sentinel->deleteValue();
4106 ForwardRefVals.erase(FI);
4107 }
4108
4109 // Set the name on the instruction.
4110 Inst->setName(NameStr);
4111
4112 if (Inst->getName() != NameStr)
4113 return P.error(NameLoc, "multiple definition of local value named '" +
4114 NameStr + "'");
4115 return false;
4116}
4117
4118/// getBB - Get a basic block with the specified name or ID, creating a
4119/// forward reference record if needed.
4120BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
4121 LocTy Loc) {
4123 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
4124}
4125
4126BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
4128 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
4129}
4130
4131/// defineBB - Define the specified basic block, which is either named or
4132/// unnamed. If there is an error, this returns null otherwise it returns
4133/// the block being defined.
4134BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
4135 int NameID, LocTy Loc) {
4136 BasicBlock *BB;
4137 if (Name.empty()) {
4138 if (NameID != -1) {
4139 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
4140 return nullptr;
4141 } else {
4142 NameID = NumberedVals.getNext();
4143 }
4144 BB = getBB(NameID, Loc);
4145 if (!BB) {
4146 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
4147 return nullptr;
4148 }
4149 } else {
4150 BB = getBB(Name, Loc);
4151 if (!BB) {
4152 P.error(Loc, "unable to create block named '" + Name + "'");
4153 return nullptr;
4154 }
4155 }
4156
4157 // Move the block to the end of the function. Forward ref'd blocks are
4158 // inserted wherever they happen to be referenced.
4159 F.splice(F.end(), &F, BB->getIterator());
4160
4161 // Remove the block from forward ref sets.
4162 if (Name.empty()) {
4163 ForwardRefValIDs.erase(NameID);
4164 NumberedVals.add(NameID, BB);
4165 } else {
4166 // BB forward references are already in the function symbol table.
4167 ForwardRefVals.erase(Name);
4168 }
4169
4170 return BB;
4171}
4172
4173//===----------------------------------------------------------------------===//
4174// Constants.
4175//===----------------------------------------------------------------------===//
4176
4177/// parseValID - parse an abstract value that doesn't necessarily have a
4178/// type implied. For example, if we parse "4" we don't know what integer type
4179/// it has. The value will later be combined with its type and checked for
4180/// basic correctness. PFS is used to convert function-local operands of
4181/// metadata (since metadata operands are not just parsed here but also
4182/// converted to values). PFS can be null when we are not parsing metadata
4183/// values inside a function.
4184bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
4185 ID.Loc = Lex.getLoc();
4186 switch (Lex.getKind()) {
4187 default:
4188 return tokError("expected value token");
4189 case lltok::GlobalID: // @42
4190 ID.UIntVal = Lex.getUIntVal();
4191 ID.Kind = ValID::t_GlobalID;
4192 break;
4193 case lltok::GlobalVar: // @foo
4194 ID.StrVal = Lex.getStrVal();
4195 ID.Kind = ValID::t_GlobalName;
4196 break;
4197 case lltok::LocalVarID: // %42
4198 ID.UIntVal = Lex.getUIntVal();
4199 ID.Kind = ValID::t_LocalID;
4200 break;
4201 case lltok::LocalVar: // %foo
4202 ID.StrVal = Lex.getStrVal();
4203 ID.Kind = ValID::t_LocalName;
4204 break;
4205 case lltok::APSInt:
4206 ID.APSIntVal = Lex.getAPSIntVal();
4207 ID.Kind = ValID::t_APSInt;
4208 break;
4209 case lltok::APFloat: {
4210 ID.APFloatVal = Lex.getAPFloatVal();
4211 ID.Kind = ValID::t_APFloat;
4212 break;
4213 }
4214 case lltok::FloatLiteral: {
4215 if (!ExpectedTy)
4216 return error(ID.Loc, "unexpected floating-point literal");
4217 if (!ExpectedTy->isFloatingPointTy())
4218 return error(ID.Loc, "floating-point constant invalid for type");
4219 ID.APFloatVal = APFloat(ExpectedTy->getFltSemantics());
4220 APFloat::opStatus Except =
4221 cantFail(ID.APFloatVal.convertFromString(
4222 Lex.getStrVal(), RoundingMode::NearestTiesToEven),
4223 "Invalid float strings should be caught by the lexer");
4224 // Forbid overflowing and underflowing literals, but permit inexact
4225 // literals. Underflow is thrown when the result is denormal, so to allow
4226 // denormals, only reject underflowing literals that resulted in a zero.
4227 if (Except & APFloat::opOverflow)
4228 return error(ID.Loc, "floating-point constant overflowed type");
4229 if ((Except & APFloat::opUnderflow) && ID.APFloatVal.isZero())
4230 return error(ID.Loc, "floating-point constant underflowed type");
4231 ID.Kind = ValID::t_APFloat;
4232 break;
4233 }
4235 if (!ExpectedTy)
4236 return error(ID.Loc, "unexpected floating-point literal");
4237 const auto &Semantics = ExpectedTy->getFltSemantics();
4238 const APInt &Bits = Lex.getAPSIntVal();
4239 if (APFloat::getSizeInBits(Semantics) != Bits.getBitWidth())
4240 return error(ID.Loc, "float hex literal has incorrect number of bits");
4241 ID.APFloatVal = APFloat(Semantics, Bits);
4242 ID.Kind = ValID::t_APFloat;
4243 break;
4244 }
4245 case lltok::kw_true:
4246 ID.ConstantVal = ConstantInt::getTrue(Context);
4247 ID.Kind = ValID::t_Constant;
4248 break;
4249 case lltok::kw_false:
4250 ID.ConstantVal = ConstantInt::getFalse(Context);
4251 ID.Kind = ValID::t_Constant;
4252 break;
4253 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
4254 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
4255 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
4256 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
4257 case lltok::kw_none: ID.Kind = ValID::t_None; break;
4258
4259 case lltok::lbrace: {
4260 // ValID ::= '{' ConstVector '}'
4261 Lex.Lex();
4263 if (parseGlobalValueVector(Elts) ||
4264 parseToken(lltok::rbrace, "expected end of struct constant"))
4265 return true;
4266
4267 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4268 ID.UIntVal = Elts.size();
4269 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4270 Elts.size() * sizeof(Elts[0]));
4272 return false;
4273 }
4274 case lltok::less: {
4275 // ValID ::= '<' ConstVector '>' --> Vector.
4276 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
4277 Lex.Lex();
4278 bool isPackedStruct = EatIfPresent(lltok::lbrace);
4279
4281 LocTy FirstEltLoc = Lex.getLoc();
4282 if (parseGlobalValueVector(Elts) ||
4283 (isPackedStruct &&
4284 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4285 parseToken(lltok::greater, "expected end of constant"))
4286 return true;
4287
4288 if (isPackedStruct) {
4289 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4290 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4291 Elts.size() * sizeof(Elts[0]));
4292 ID.UIntVal = Elts.size();
4294 return false;
4295 }
4296
4297 if (Elts.empty())
4298 return error(ID.Loc, "constant vector must not be empty");
4299
4300 if (!Elts[0]->getType()->isIntegerTy() && !Elts[0]->getType()->isByteTy() &&
4301 !Elts[0]->getType()->isFloatingPointTy() &&
4302 !Elts[0]->getType()->isPointerTy())
4303 return error(
4304 FirstEltLoc,
4305 "vector elements must have integer, byte, pointer or floating point "
4306 "type");
4307
4308 // Verify that all the vector elements have the same type.
4309 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4310 if (Elts[i]->getType() != Elts[0]->getType())
4311 return error(FirstEltLoc, "vector element #" + Twine(i) +
4312 " is not of type '" +
4313 getTypeString(Elts[0]->getType()));
4314
4315 ID.ConstantVal = ConstantVector::get(Elts);
4316 ID.Kind = ValID::t_Constant;
4317 return false;
4318 }
4319 case lltok::lsquare: { // Array Constant
4320 Lex.Lex();
4322 LocTy FirstEltLoc = Lex.getLoc();
4323 if (parseGlobalValueVector(Elts) ||
4324 parseToken(lltok::rsquare, "expected end of array constant"))
4325 return true;
4326
4327 // Handle empty element.
4328 if (Elts.empty()) {
4329 // Use undef instead of an array because it's inconvenient to determine
4330 // the element type at this point, there being no elements to examine.
4331 ID.Kind = ValID::t_EmptyArray;
4332 return false;
4333 }
4334
4335 if (!Elts[0]->getType()->isFirstClassType())
4336 return error(FirstEltLoc, "invalid array element type: " +
4337 getTypeString(Elts[0]->getType()));
4338
4339 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4340
4341 // Verify all elements are correct type!
4342 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4343 if (Elts[i]->getType() != Elts[0]->getType())
4344 return error(FirstEltLoc, "array element #" + Twine(i) +
4345 " is not of type '" +
4346 getTypeString(Elts[0]->getType()));
4347 }
4348
4349 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4350 ID.Kind = ValID::t_Constant;
4351 return false;
4352 }
4353 case lltok::kw_c: { // c "foo"
4354 Lex.Lex();
4355 ArrayType *ATy = cast<ArrayType>(ExpectedTy);
4356 ID.ConstantVal = ConstantDataArray::getString(
4357 Context, Lex.getStrVal(), false, ATy->getElementType()->isByteTy());
4358 if (parseToken(lltok::StringConstant, "expected string"))
4359 return true;
4360 ID.Kind = ValID::t_Constant;
4361 return false;
4362 }
4363 case lltok::kw_asm: {
4364 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4365 // STRINGCONSTANT
4366 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4367 Lex.Lex();
4368 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4369 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4370 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4371 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4372 parseStringConstant(ID.StrVal) ||
4373 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4374 parseToken(lltok::StringConstant, "expected constraint string"))
4375 return true;
4376 ID.StrVal2 = Lex.getStrVal();
4377 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4378 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4379 ID.Kind = ValID::t_InlineAsm;
4380 return false;
4381 }
4382
4384 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4385 Lex.Lex();
4386
4387 ValID Fn, Label;
4388
4389 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4390 parseValID(Fn, PFS) ||
4391 parseToken(lltok::comma,
4392 "expected comma in block address expression") ||
4393 parseValID(Label, PFS) ||
4394 parseToken(lltok::rparen, "expected ')' in block address expression"))
4395 return true;
4396
4398 return error(Fn.Loc, "expected function name in blockaddress");
4399 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4400 return error(Label.Loc, "expected basic block name in blockaddress");
4401
4402 // Try to find the function (but skip it if it's forward-referenced).
4403 GlobalValue *GV = nullptr;
4404 if (Fn.Kind == ValID::t_GlobalID) {
4405 GV = NumberedVals.get(Fn.UIntVal);
4406 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4407 GV = M->getNamedValue(Fn.StrVal);
4408 }
4409 Function *F = nullptr;
4410 if (GV) {
4411 // Confirm that it's actually a function with a definition.
4412 if (!isa<Function>(GV))
4413 return error(Fn.Loc, "expected function name in blockaddress");
4414 F = cast<Function>(GV);
4415 if (F->isDeclaration())
4416 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4417 }
4418
4419 if (!F) {
4420 // Make a global variable as a placeholder for this reference.
4421 GlobalValue *&FwdRef =
4422 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4423 if (!FwdRef) {
4424 unsigned FwdDeclAS;
4425 if (ExpectedTy) {
4426 // If we know the type that the blockaddress is being assigned to,
4427 // we can use the address space of that type.
4428 if (!ExpectedTy->isPointerTy())
4429 return error(ID.Loc,
4430 "type of blockaddress must be a pointer and not '" +
4431 getTypeString(ExpectedTy) + "'");
4432 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4433 } else if (PFS) {
4434 // Otherwise, we default the address space of the current function.
4435 FwdDeclAS = PFS->getFunction().getAddressSpace();
4436 } else {
4437 llvm_unreachable("Unknown address space for blockaddress");
4438 }
4439 FwdRef = new GlobalVariable(
4440 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4441 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4442 }
4443
4444 ID.ConstantVal = FwdRef;
4445 ID.Kind = ValID::t_Constant;
4446 return false;
4447 }
4448
4449 // We found the function; now find the basic block. Don't use PFS, since we
4450 // might be inside a constant expression.
4451 BasicBlock *BB;
4452 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4453 if (Label.Kind == ValID::t_LocalID)
4454 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4455 else
4456 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4457 if (!BB)
4458 return error(Label.Loc, "referenced value is not a basic block");
4459 } else {
4460 if (Label.Kind == ValID::t_LocalID)
4461 return error(Label.Loc, "cannot take address of numeric label after "
4462 "the function is defined");
4464 F->getValueSymbolTable()->lookup(Label.StrVal));
4465 if (!BB)
4466 return error(Label.Loc, "referenced value is not a basic block");
4467 }
4468
4469 ID.ConstantVal = BlockAddress::get(F, BB);
4470 ID.Kind = ValID::t_Constant;
4471 return false;
4472 }
4473
4475 // ValID ::= 'dso_local_equivalent' @foo
4476 Lex.Lex();
4477
4478 ValID Fn;
4479
4480 if (parseValID(Fn, PFS))
4481 return true;
4482
4484 return error(Fn.Loc,
4485 "expected global value name in dso_local_equivalent");
4486
4487 // Try to find the function (but skip it if it's forward-referenced).
4488 GlobalValue *GV = nullptr;
4489 if (Fn.Kind == ValID::t_GlobalID) {
4490 GV = NumberedVals.get(Fn.UIntVal);
4491 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4492 GV = M->getNamedValue(Fn.StrVal);
4493 }
4494
4495 if (!GV) {
4496 // Make a placeholder global variable as a placeholder for this reference.
4497 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4498 ? ForwardRefDSOLocalEquivalentIDs
4499 : ForwardRefDSOLocalEquivalentNames;
4500 GlobalValue *&FwdRef = FwdRefMap[Fn];
4501 if (!FwdRef) {
4502 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4503 GlobalValue::InternalLinkage, nullptr, "",
4505 }
4506
4507 ID.ConstantVal = FwdRef;
4508 ID.Kind = ValID::t_Constant;
4509 return false;
4510 }
4511
4512 if (!GV->getValueType()->isFunctionTy())
4513 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4514 "in dso_local_equivalent");
4515
4516 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4517 ID.Kind = ValID::t_Constant;
4518 return false;
4519 }
4520
4521 case lltok::kw_no_cfi: {
4522 // ValID ::= 'no_cfi' @foo
4523 Lex.Lex();
4524
4525 if (parseValID(ID, PFS))
4526 return true;
4527
4528 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4529 return error(ID.Loc, "expected global value name in no_cfi");
4530
4531 ID.NoCFI = true;
4532 return false;
4533 }
4534 case lltok::kw_ptrauth: {
4535 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4536 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4537 // )? )? ')'
4538 Lex.Lex();
4539
4540 Constant *Ptr, *Key;
4541 Constant *Disc = nullptr, *AddrDisc = nullptr,
4542 *DeactivationSymbol = nullptr;
4543
4544 if (parseToken(lltok::lparen,
4545 "expected '(' in constant ptrauth expression") ||
4546 parseGlobalTypeAndValue(Ptr) ||
4547 parseToken(lltok::comma,
4548 "expected comma in constant ptrauth expression") ||
4549 parseGlobalTypeAndValue(Key))
4550 return true;
4551 // If present, parse the optional disc/addrdisc/ds.
4552 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(Disc))
4553 return true;
4554 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4555 return true;
4556 if (EatIfPresent(lltok::comma) &&
4557 parseGlobalTypeAndValue(DeactivationSymbol))
4558 return true;
4559 if (parseToken(lltok::rparen,
4560 "expected ')' in constant ptrauth expression"))
4561 return true;
4562
4563 if (!Ptr->getType()->isPointerTy())
4564 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4565
4566 auto *KeyC = dyn_cast<ConstantInt>(Key);
4567 if (!KeyC || KeyC->getBitWidth() != 32)
4568 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4569
4570 ConstantInt *DiscC = nullptr;
4571 if (Disc) {
4572 DiscC = dyn_cast<ConstantInt>(Disc);
4573 if (!DiscC || DiscC->getBitWidth() != 64)
4574 return error(
4575 ID.Loc,
4576 "constant ptrauth integer discriminator must be i64 constant");
4577 } else {
4578 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4579 }
4580
4581 if (AddrDisc) {
4582 if (!AddrDisc->getType()->isPointerTy())
4583 return error(
4584 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4585 } else {
4586 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4587 }
4588
4589 if (!DeactivationSymbol)
4590 DeactivationSymbol =
4592 if (!DeactivationSymbol->getType()->isPointerTy())
4593 return error(ID.Loc,
4594 "constant ptrauth deactivation symbol must be a pointer");
4595
4596 ID.ConstantVal =
4597 ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc, DeactivationSymbol);
4598 ID.Kind = ValID::t_Constant;
4599 return false;
4600 }
4601
4602 case lltok::kw_trunc:
4603 case lltok::kw_bitcast:
4605 case lltok::kw_inttoptr:
4607 case lltok::kw_ptrtoint: {
4608 unsigned Opc = Lex.getUIntVal();
4609 Type *DestTy = nullptr;
4610 Constant *SrcVal;
4611 Lex.Lex();
4612 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4613 parseGlobalTypeAndValue(SrcVal) ||
4614 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4615 parseType(DestTy) ||
4616 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4617 return true;
4618 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4619 return error(ID.Loc, "invalid cast opcode for cast from '" +
4620 getTypeString(SrcVal->getType()) + "' to '" +
4621 getTypeString(DestTy) + "'");
4623 SrcVal, DestTy);
4624 ID.Kind = ValID::t_Constant;
4625 return false;
4626 }
4628 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4630 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4631 case lltok::kw_udiv:
4632 return error(ID.Loc, "udiv constexprs are no longer supported");
4633 case lltok::kw_sdiv:
4634 return error(ID.Loc, "sdiv constexprs are no longer supported");
4635 case lltok::kw_urem:
4636 return error(ID.Loc, "urem constexprs are no longer supported");
4637 case lltok::kw_srem:
4638 return error(ID.Loc, "srem constexprs are no longer supported");
4639 case lltok::kw_fadd:
4640 return error(ID.Loc, "fadd constexprs are no longer supported");
4641 case lltok::kw_fsub:
4642 return error(ID.Loc, "fsub constexprs are no longer supported");
4643 case lltok::kw_fmul:
4644 return error(ID.Loc, "fmul constexprs are no longer supported");
4645 case lltok::kw_fdiv:
4646 return error(ID.Loc, "fdiv constexprs are no longer supported");
4647 case lltok::kw_frem:
4648 return error(ID.Loc, "frem constexprs are no longer supported");
4649 case lltok::kw_and:
4650 return error(ID.Loc, "and constexprs are no longer supported");
4651 case lltok::kw_or:
4652 return error(ID.Loc, "or constexprs are no longer supported");
4653 case lltok::kw_lshr:
4654 return error(ID.Loc, "lshr constexprs are no longer supported");
4655 case lltok::kw_ashr:
4656 return error(ID.Loc, "ashr constexprs are no longer supported");
4657 case lltok::kw_shl:
4658 return error(ID.Loc, "shl constexprs are no longer supported");
4659 case lltok::kw_mul:
4660 return error(ID.Loc, "mul constexprs are no longer supported");
4661 case lltok::kw_fneg:
4662 return error(ID.Loc, "fneg constexprs are no longer supported");
4663 case lltok::kw_select:
4664 return error(ID.Loc, "select constexprs are no longer supported");
4665 case lltok::kw_zext:
4666 return error(ID.Loc, "zext constexprs are no longer supported");
4667 case lltok::kw_sext:
4668 return error(ID.Loc, "sext constexprs are no longer supported");
4669 case lltok::kw_fptrunc:
4670 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4671 case lltok::kw_fpext:
4672 return error(ID.Loc, "fpext constexprs are no longer supported");
4673 case lltok::kw_uitofp:
4674 return error(ID.Loc, "uitofp constexprs are no longer supported");
4675 case lltok::kw_sitofp:
4676 return error(ID.Loc, "sitofp constexprs are no longer supported");
4677 case lltok::kw_fptoui:
4678 return error(ID.Loc, "fptoui constexprs are no longer supported");
4679 case lltok::kw_fptosi:
4680 return error(ID.Loc, "fptosi constexprs are no longer supported");
4681 case lltok::kw_icmp:
4682 return error(ID.Loc, "icmp constexprs are no longer supported");
4683 case lltok::kw_fcmp:
4684 return error(ID.Loc, "fcmp constexprs are no longer supported");
4685
4686 // Binary Operators.
4687 case lltok::kw_add:
4688 case lltok::kw_sub:
4689 case lltok::kw_xor: {
4690 bool NUW = false;
4691 bool NSW = false;
4692 unsigned Opc = Lex.getUIntVal();
4693 Constant *Val0, *Val1;
4694 Lex.Lex();
4695 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4696 Opc == Instruction::Mul) {
4697 if (EatIfPresent(lltok::kw_nuw))
4698 NUW = true;
4699 if (EatIfPresent(lltok::kw_nsw)) {
4700 NSW = true;
4701 if (EatIfPresent(lltok::kw_nuw))
4702 NUW = true;
4703 }
4704 }
4705 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4706 parseGlobalTypeAndValue(Val0) ||
4707 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4708 parseGlobalTypeAndValue(Val1) ||
4709 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4710 return true;
4711 if (Val0->getType() != Val1->getType())
4712 return error(ID.Loc, "operands of constexpr must have same type");
4713 // Check that the type is valid for the operator.
4714 if (!Val0->getType()->isIntOrIntVectorTy())
4715 return error(ID.Loc,
4716 "constexpr requires integer or integer vector operands");
4717 unsigned Flags = 0;
4720 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4721 ID.Kind = ValID::t_Constant;
4722 return false;
4723 }
4724
4725 case lltok::kw_splat: {
4726 Lex.Lex();
4727 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4728 return true;
4729 Constant *C;
4730 if (parseGlobalTypeAndValue(C))
4731 return true;
4732 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4733 return true;
4734
4735 ID.ConstantVal = C;
4737 return false;
4738 }
4739
4744 unsigned Opc = Lex.getUIntVal();
4746 GEPNoWrapFlags NW;
4747 bool HasInRange = false;
4748 APSInt InRangeStart;
4749 APSInt InRangeEnd;
4750 Type *Ty;
4751 Lex.Lex();
4752
4753 if (Opc == Instruction::GetElementPtr) {
4754 while (true) {
4755 if (EatIfPresent(lltok::kw_inbounds))
4757 else if (EatIfPresent(lltok::kw_nusw))
4759 else if (EatIfPresent(lltok::kw_nuw))
4761 else
4762 break;
4763 }
4764
4765 if (EatIfPresent(lltok::kw_inrange)) {
4766 if (parseToken(lltok::lparen, "expected '('"))
4767 return true;
4768 if (Lex.getKind() != lltok::APSInt)
4769 return tokError("expected integer");
4770 InRangeStart = Lex.getAPSIntVal();
4771 Lex.Lex();
4772 if (parseToken(lltok::comma, "expected ','"))
4773 return true;
4774 if (Lex.getKind() != lltok::APSInt)
4775 return tokError("expected integer");
4776 InRangeEnd = Lex.getAPSIntVal();
4777 Lex.Lex();
4778 if (parseToken(lltok::rparen, "expected ')'"))
4779 return true;
4780 HasInRange = true;
4781 }
4782 }
4783
4784 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4785 return true;
4786
4787 if (Opc == Instruction::GetElementPtr) {
4788 if (parseType(Ty) ||
4789 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4790 return true;
4791 }
4792
4793 if (parseGlobalValueVector(Elts) ||
4794 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4795 return true;
4796
4797 if (Opc == Instruction::GetElementPtr) {
4798 if (Elts.size() == 0 ||
4799 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4800 return error(ID.Loc, "base of getelementptr must be a pointer");
4801
4802 Type *BaseType = Elts[0]->getType();
4803 std::optional<ConstantRange> InRange;
4804 if (HasInRange) {
4805 unsigned IndexWidth =
4806 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4807 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4808 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4809 if (InRangeStart.sge(InRangeEnd))
4810 return error(ID.Loc, "expected end to be larger than start");
4811 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4812 }
4813
4814 unsigned GEPWidth =
4815 BaseType->isVectorTy()
4816 ? cast<FixedVectorType>(BaseType)->getNumElements()
4817 : 0;
4818
4819 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4820 for (Constant *Val : Indices) {
4821 Type *ValTy = Val->getType();
4822 if (!ValTy->isIntOrIntVectorTy())
4823 return error(ID.Loc, "getelementptr index must be an integer");
4824 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4825 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4826 if (GEPWidth && (ValNumEl != GEPWidth))
4827 return error(
4828 ID.Loc,
4829 "getelementptr vector index has a wrong number of elements");
4830 // GEPWidth may have been unknown because the base is a scalar,
4831 // but it is known now.
4832 GEPWidth = ValNumEl;
4833 }
4834 }
4835
4836 SmallPtrSet<Type*, 4> Visited;
4837 if (!Indices.empty() && !Ty->isSized(&Visited))
4838 return error(ID.Loc, "base element of getelementptr must be sized");
4839
4841 return error(ID.Loc, "invalid base element for constant getelementptr");
4842
4843 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4844 return error(ID.Loc, "invalid getelementptr indices");
4845
4846 ID.ConstantVal =
4847 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4848 } else if (Opc == Instruction::ShuffleVector) {
4849 if (Elts.size() != 3)
4850 return error(ID.Loc, "expected three operands to shufflevector");
4851 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4852 return error(ID.Loc, "invalid operands to shufflevector");
4853 SmallVector<int, 16> Mask;
4855 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4856 } else if (Opc == Instruction::ExtractElement) {
4857 if (Elts.size() != 2)
4858 return error(ID.Loc, "expected two operands to extractelement");
4859 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4860 return error(ID.Loc, "invalid extractelement operands");
4861 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4862 } else {
4863 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4864 if (Elts.size() != 3)
4865 return error(ID.Loc, "expected three operands to insertelement");
4866 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4867 return error(ID.Loc, "invalid insertelement operands");
4868 ID.ConstantVal =
4869 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4870 }
4871
4872 ID.Kind = ValID::t_Constant;
4873 return false;
4874 }
4875 }
4876
4877 Lex.Lex();
4878 return false;
4879}
4880
4881/// parseGlobalValue - parse a global value with the specified type.
4882bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4883 C = nullptr;
4884 ValID ID;
4885 Value *V = nullptr;
4886 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4887 convertValIDToValue(Ty, ID, V, nullptr);
4888 if (V && !(C = dyn_cast<Constant>(V)))
4889 return error(ID.Loc, "global values must be constants");
4890 return Parsed;
4891}
4892
4893bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4894 Type *Ty = nullptr;
4895 return parseType(Ty) || parseGlobalValue(Ty, V);
4896}
4897
4898bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4899 C = nullptr;
4900
4901 LocTy KwLoc = Lex.getLoc();
4902 if (!EatIfPresent(lltok::kw_comdat))
4903 return false;
4904
4905 if (EatIfPresent(lltok::lparen)) {
4906 if (Lex.getKind() != lltok::ComdatVar)
4907 return tokError("expected comdat variable");
4908 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4909 Lex.Lex();
4910 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4911 return true;
4912 } else {
4913 if (GlobalName.empty())
4914 return tokError("comdat cannot be unnamed");
4915 C = getComdat(std::string(GlobalName), KwLoc);
4916 }
4917
4918 return false;
4919}
4920
4921/// parseGlobalValueVector
4922/// ::= /*empty*/
4923/// ::= TypeAndValue (',' TypeAndValue)*
4924bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4925 // Empty list.
4926 if (Lex.getKind() == lltok::rbrace ||
4927 Lex.getKind() == lltok::rsquare ||
4928 Lex.getKind() == lltok::greater ||
4929 Lex.getKind() == lltok::rparen)
4930 return false;
4931
4932 do {
4933 // Let the caller deal with inrange.
4934 if (Lex.getKind() == lltok::kw_inrange)
4935 return false;
4936
4937 Constant *C;
4938 if (parseGlobalTypeAndValue(C))
4939 return true;
4940 Elts.push_back(C);
4941 } while (EatIfPresent(lltok::comma));
4942
4943 return false;
4944}
4945
4946bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4948 if (parseMDNodeVector(Elts))
4949 return true;
4950
4951 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4952 return false;
4953}
4954
4955/// MDNode:
4956/// ::= !{ ... }
4957/// ::= !7
4958/// ::= !DILocation(...)
4959bool LLParser::parseMDNode(MDNode *&N) {
4960 if (Lex.getKind() == lltok::MetadataVar)
4961 return parseSpecializedMDNode(N);
4962
4963 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4964}
4965
4966bool LLParser::parseMDNodeTail(MDNode *&N) {
4967 // !{ ... }
4968 if (Lex.getKind() == lltok::lbrace)
4969 return parseMDTuple(N);
4970
4971 // !42
4972 return parseMDNodeID(N);
4973}
4974
4975namespace {
4976
4977/// Structure to represent an optional metadata field.
4978template <class FieldTy> struct MDFieldImpl {
4979 typedef MDFieldImpl ImplTy;
4980 FieldTy Val;
4981 bool Seen;
4982
4983 void assign(FieldTy Val) {
4984 Seen = true;
4985 this->Val = std::move(Val);
4986 }
4987
4988 explicit MDFieldImpl(FieldTy Default)
4989 : Val(std::move(Default)), Seen(false) {}
4990};
4991
4992/// Structure to represent an optional metadata field that
4993/// can be of either type (A or B) and encapsulates the
4994/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4995/// to reimplement the specifics for representing each Field.
4996template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4997 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4998 FieldTypeA A;
4999 FieldTypeB B;
5000 bool Seen;
5001
5002 enum {
5003 IsInvalid = 0,
5004 IsTypeA = 1,
5005 IsTypeB = 2
5006 } WhatIs;
5007
5008 void assign(FieldTypeA A) {
5009 Seen = true;
5010 this->A = std::move(A);
5011 WhatIs = IsTypeA;
5012 }
5013
5014 void assign(FieldTypeB B) {
5015 Seen = true;
5016 this->B = std::move(B);
5017 WhatIs = IsTypeB;
5018 }
5019
5020 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5021 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
5022 WhatIs(IsInvalid) {}
5023};
5024
5025struct MDUnsignedField : public MDFieldImpl<uint64_t> {
5026 uint64_t Max;
5027
5028 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
5029 : ImplTy(Default), Max(Max) {}
5030};
5031
5032struct LineField : public MDUnsignedField {
5033 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5034};
5035
5036struct ColumnField : public MDUnsignedField {
5037 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5038};
5039
5040struct DwarfTagField : public MDUnsignedField {
5041 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
5042 DwarfTagField(dwarf::Tag DefaultTag)
5043 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
5044};
5045
5046struct DwarfMacinfoTypeField : public MDUnsignedField {
5047 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
5048 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
5049 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
5050};
5051
5052struct DwarfAttEncodingField : public MDUnsignedField {
5053 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
5054};
5055
5056struct DwarfVirtualityField : public MDUnsignedField {
5057 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
5058};
5059
5060struct DwarfLangField : public MDUnsignedField {
5061 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
5062};
5063
5064struct DwarfSourceLangNameField : public MDUnsignedField {
5065 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5066};
5067
5068struct DwarfLangDialectField : public MDUnsignedField {
5069 DwarfLangDialectField()
5070 : MDUnsignedField(0, dwarf::DW_LLVM_LANG_DIALECT_max) {}
5071};
5072
5073struct DwarfCCField : public MDUnsignedField {
5074 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
5075};
5076
5077struct DwarfEnumKindField : public MDUnsignedField {
5078 DwarfEnumKindField()
5079 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
5080 dwarf::DW_APPLE_ENUM_KIND_max) {}
5081};
5082
5083struct EmissionKindField : public MDUnsignedField {
5084 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5085};
5086
5087struct FixedPointKindField : public MDUnsignedField {
5088 FixedPointKindField()
5089 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5090};
5091
5092struct NameTableKindField : public MDUnsignedField {
5093 NameTableKindField()
5094 : MDUnsignedField(
5095 0, (unsigned)
5096 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5097};
5098
5099struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
5100 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5101};
5102
5103struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
5104 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5105};
5106
5107struct MDAPSIntField : public MDFieldImpl<APSInt> {
5108 MDAPSIntField() : ImplTy(APSInt()) {}
5109};
5110
5111struct MDSignedField : public MDFieldImpl<int64_t> {
5112 int64_t Min = INT64_MIN;
5113 int64_t Max = INT64_MAX;
5114
5115 MDSignedField(int64_t Default = 0)
5116 : ImplTy(Default) {}
5117 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
5118 : ImplTy(Default), Min(Min), Max(Max) {}
5119};
5120
5121struct MDBoolField : public MDFieldImpl<bool> {
5122 MDBoolField(bool Default = false) : ImplTy(Default) {}
5123};
5124
5125struct MDField : public MDFieldImpl<Metadata *> {
5126 bool AllowNull;
5127
5128 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5129};
5130
5131struct MDStringField : public MDFieldImpl<MDString *> {
5132 enum class EmptyIs {
5133 Null, //< Allow empty input string, map to nullptr
5134 Empty, //< Allow empty input string, map to an empty MDString
5135 Error, //< Disallow empty string, map to an error
5136 } EmptyIs;
5137 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
5138 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5139};
5140
5141struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
5142 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
5143};
5144
5145struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
5146 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
5147};
5148
5149struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5150 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
5151 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
5152
5153 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
5154 bool AllowNull = true)
5155 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
5156
5157 bool isMDSignedField() const { return WhatIs == IsTypeA; }
5158 bool isMDField() const { return WhatIs == IsTypeB; }
5159 int64_t getMDSignedValue() const {
5160 assert(isMDSignedField() && "Wrong field type");
5161 return A.Val;
5162 }
5163 Metadata *getMDFieldValue() const {
5164 assert(isMDField() && "Wrong field type");
5165 return B.Val;
5166 }
5167};
5168
5169struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5170 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
5171 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
5172
5173 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
5174 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
5175
5176 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
5177 bool isMDField() const { return WhatIs == IsTypeB; }
5178 uint64_t getMDUnsignedValue() const {
5179 assert(isMDUnsignedField() && "Wrong field type");
5180 return A.Val;
5181 }
5182 Metadata *getMDFieldValue() const {
5183 assert(isMDField() && "Wrong field type");
5184 return B.Val;
5185 }
5186
5187 Metadata *getValueAsMetadata(LLVMContext &Context) const {
5188 if (isMDUnsignedField())
5190 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
5191 if (isMDField())
5192 return getMDFieldValue();
5193 return nullptr;
5194 }
5195};
5196
5197} // end anonymous namespace
5198
5199namespace llvm {
5200
5201template <>
5202bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
5203 if (Lex.getKind() != lltok::APSInt)
5204 return tokError("expected integer");
5205
5206 Result.assign(Lex.getAPSIntVal());
5207 Lex.Lex();
5208 return false;
5209}
5210
5211template <>
5212bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5213 MDUnsignedField &Result) {
5214 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5215 return tokError("expected unsigned integer");
5216
5217 auto &U = Lex.getAPSIntVal();
5218 if (U.ugt(Result.Max))
5219 return tokError("value for '" + Name + "' too large, limit is " +
5220 Twine(Result.Max));
5221 Result.assign(U.getZExtValue());
5222 assert(Result.Val <= Result.Max && "Expected value in range");
5223 Lex.Lex();
5224 return false;
5225}
5226
5227template <>
5228bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
5229 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5230}
5231template <>
5232bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
5233 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5234}
5235
5236template <>
5237bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
5238 if (Lex.getKind() == lltok::APSInt)
5239 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5240
5241 if (Lex.getKind() != lltok::DwarfTag)
5242 return tokError("expected DWARF tag");
5243
5244 unsigned Tag = dwarf::getTag(Lex.getStrVal());
5246 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
5247 assert(Tag <= Result.Max && "Expected valid DWARF tag");
5248
5249 Result.assign(Tag);
5250 Lex.Lex();
5251 return false;
5252}
5253
5254template <>
5255bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5256 DwarfMacinfoTypeField &Result) {
5257 if (Lex.getKind() == lltok::APSInt)
5258 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5259
5260 if (Lex.getKind() != lltok::DwarfMacinfo)
5261 return tokError("expected DWARF macinfo type");
5262
5263 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
5264 if (Macinfo == dwarf::DW_MACINFO_invalid)
5265 return tokError("invalid DWARF macinfo type" + Twine(" '") +
5266 Lex.getStrVal() + "'");
5267 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
5268
5269 Result.assign(Macinfo);
5270 Lex.Lex();
5271 return false;
5272}
5273
5274template <>
5275bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5276 DwarfVirtualityField &Result) {
5277 if (Lex.getKind() == lltok::APSInt)
5278 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5279
5280 if (Lex.getKind() != lltok::DwarfVirtuality)
5281 return tokError("expected DWARF virtuality code");
5282
5283 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
5284 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5285 return tokError("invalid DWARF virtuality code" + Twine(" '") +
5286 Lex.getStrVal() + "'");
5287 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5288 Result.assign(Virtuality);
5289 Lex.Lex();
5290 return false;
5291}
5292
5293template <>
5294bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5295 DwarfEnumKindField &Result) {
5296 if (Lex.getKind() == lltok::APSInt)
5297 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5298
5299 if (Lex.getKind() != lltok::DwarfEnumKind)
5300 return tokError("expected DWARF enum kind code");
5301
5302 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5303 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5304 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5305 Lex.getStrVal() + "'");
5306 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5307 Result.assign(EnumKind);
5308 Lex.Lex();
5309 return false;
5310}
5311
5312template <>
5313bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5314 if (Lex.getKind() == lltok::APSInt)
5315 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5316
5317 if (Lex.getKind() != lltok::DwarfLang)
5318 return tokError("expected DWARF language");
5319
5320 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5321 if (!Lang)
5322 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5323 "'");
5324 assert(Lang <= Result.Max && "Expected valid DWARF language");
5325 Result.assign(Lang);
5326 Lex.Lex();
5327 return false;
5328}
5329
5330template <>
5331bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5332 DwarfSourceLangNameField &Result) {
5333 if (Lex.getKind() == lltok::APSInt)
5334 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5335
5336 if (Lex.getKind() != lltok::DwarfSourceLangName)
5337 return tokError("expected DWARF source language name");
5338
5339 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5340 if (!Lang)
5341 return tokError("invalid DWARF source language name" + Twine(" '") +
5342 Lex.getStrVal() + "'");
5343 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5344 Result.assign(Lang);
5345 Lex.Lex();
5346 return false;
5347}
5348
5349template <>
5350bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5351 DwarfLangDialectField &Result) {
5352 // Specifying the dialect field requires a recognized dialect: simt or
5353 // tile (numerically 1 or 2). Omitting the field is the only way to
5354 // express "no dialect specified".
5355 if (Lex.getKind() == lltok::APSInt) {
5356 if (Lex.getAPSIntVal() == 0)
5357 return tokError("value for 'dialect' must be a known DWARF language "
5358 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5359 "DW_LLVM_LANG_DIALECT_tile)");
5360 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5361 }
5362
5363 if (Lex.getKind() != lltok::DwarfLangDialect)
5364 return tokError("expected DWARF language dialect");
5365
5366 StringRef DialectString = Lex.getStrVal();
5367 // getLanguageDialect returns a sentinel above Result.Max for unknown
5368 // spellings; only simt and tile are registered, so any unrecognized
5369 // DW_LLVM_LANG_DIALECT_* token is rejected here.
5370 unsigned Dialect = dwarf::getLanguageDialect(DialectString);
5371 if (Dialect > Result.Max)
5372 return tokError("invalid DWARF language dialect" + Twine(" '") +
5373 DialectString + "'");
5374 Result.assign(Dialect);
5375 Lex.Lex();
5376 return false;
5377}
5378
5379template <>
5380bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5381 if (Lex.getKind() == lltok::APSInt)
5382 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5383
5384 if (Lex.getKind() != lltok::DwarfCC)
5385 return tokError("expected DWARF calling convention");
5386
5387 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5388 if (!CC)
5389 return tokError("invalid DWARF calling convention" + Twine(" '") +
5390 Lex.getStrVal() + "'");
5391 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5392 Result.assign(CC);
5393 Lex.Lex();
5394 return false;
5395}
5396
5397template <>
5398bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5399 EmissionKindField &Result) {
5400 if (Lex.getKind() == lltok::APSInt)
5401 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5402
5403 if (Lex.getKind() != lltok::EmissionKind)
5404 return tokError("expected emission kind");
5405
5406 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5407 if (!Kind)
5408 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5409 "'");
5410 assert(*Kind <= Result.Max && "Expected valid emission kind");
5411 Result.assign(*Kind);
5412 Lex.Lex();
5413 return false;
5414}
5415
5416template <>
5417bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5418 FixedPointKindField &Result) {
5419 if (Lex.getKind() == lltok::APSInt)
5420 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5421
5422 if (Lex.getKind() != lltok::FixedPointKind)
5423 return tokError("expected fixed-point kind");
5424
5425 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5426 if (!Kind)
5427 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5428 "'");
5429 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5430 Result.assign(*Kind);
5431 Lex.Lex();
5432 return false;
5433}
5434
5435template <>
5436bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5437 NameTableKindField &Result) {
5438 if (Lex.getKind() == lltok::APSInt)
5439 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5440
5441 if (Lex.getKind() != lltok::NameTableKind)
5442 return tokError("expected nameTable kind");
5443
5444 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5445 if (!Kind)
5446 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5447 "'");
5448 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5449 Result.assign((unsigned)*Kind);
5450 Lex.Lex();
5451 return false;
5452}
5453
5454template <>
5455bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5456 DwarfAttEncodingField &Result) {
5457 if (Lex.getKind() == lltok::APSInt)
5458 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5459
5460 if (Lex.getKind() != lltok::DwarfAttEncoding)
5461 return tokError("expected DWARF type attribute encoding");
5462
5463 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5464 if (!Encoding)
5465 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5466 Lex.getStrVal() + "'");
5467 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5468 Result.assign(Encoding);
5469 Lex.Lex();
5470 return false;
5471}
5472
5473/// DIFlagField
5474/// ::= uint32
5475/// ::= DIFlagVector
5476/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5477template <>
5478bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5479
5480 // parser for a single flag.
5481 auto parseFlag = [&](DINode::DIFlags &Val) {
5482 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5483 uint32_t TempVal = static_cast<uint32_t>(Val);
5484 bool Res = parseUInt32(TempVal);
5485 Val = static_cast<DINode::DIFlags>(TempVal);
5486 return Res;
5487 }
5488
5489 if (Lex.getKind() != lltok::DIFlag)
5490 return tokError("expected debug info flag");
5491
5492 Val = DINode::getFlag(Lex.getStrVal());
5493 if (!Val)
5494 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5495 "'");
5496 Lex.Lex();
5497 return false;
5498 };
5499
5500 // parse the flags and combine them together.
5501 DINode::DIFlags Combined = DINode::FlagZero;
5502 do {
5503 DINode::DIFlags Val;
5504 if (parseFlag(Val))
5505 return true;
5506 Combined |= Val;
5507 } while (EatIfPresent(lltok::bar));
5508
5509 Result.assign(Combined);
5510 return false;
5511}
5512
5513/// DISPFlagField
5514/// ::= uint32
5515/// ::= DISPFlagVector
5516/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5517template <>
5518bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5519
5520 // parser for a single flag.
5521 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5522 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5523 uint32_t TempVal = static_cast<uint32_t>(Val);
5524 bool Res = parseUInt32(TempVal);
5525 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5526 return Res;
5527 }
5528
5529 if (Lex.getKind() != lltok::DISPFlag)
5530 return tokError("expected debug info flag");
5531
5532 Val = DISubprogram::getFlag(Lex.getStrVal());
5533 if (!Val)
5534 return tokError(Twine("invalid subprogram debug info flag '") +
5535 Lex.getStrVal() + "'");
5536 Lex.Lex();
5537 return false;
5538 };
5539
5540 // parse the flags and combine them together.
5541 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5542 do {
5544 if (parseFlag(Val))
5545 return true;
5546 Combined |= Val;
5547 } while (EatIfPresent(lltok::bar));
5548
5549 Result.assign(Combined);
5550 return false;
5551}
5552
5553template <>
5554bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5555 if (Lex.getKind() != lltok::APSInt)
5556 return tokError("expected signed integer");
5557
5558 auto &S = Lex.getAPSIntVal();
5559 if (S < Result.Min)
5560 return tokError("value for '" + Name + "' too small, limit is " +
5561 Twine(Result.Min));
5562 if (S > Result.Max)
5563 return tokError("value for '" + Name + "' too large, limit is " +
5564 Twine(Result.Max));
5565 Result.assign(S.getExtValue());
5566 assert(Result.Val >= Result.Min && "Expected value in range");
5567 assert(Result.Val <= Result.Max && "Expected value in range");
5568 Lex.Lex();
5569 return false;
5570}
5571
5572template <>
5573bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5574 switch (Lex.getKind()) {
5575 default:
5576 return tokError("expected 'true' or 'false'");
5577 case lltok::kw_true:
5578 Result.assign(true);
5579 break;
5580 case lltok::kw_false:
5581 Result.assign(false);
5582 break;
5583 }
5584 Lex.Lex();
5585 return false;
5586}
5587
5588template <>
5589bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5590 if (Lex.getKind() == lltok::kw_null) {
5591 if (!Result.AllowNull)
5592 return tokError("'" + Name + "' cannot be null");
5593 Lex.Lex();
5594 Result.assign(nullptr);
5595 return false;
5596 }
5597
5598 Metadata *MD;
5599 if (parseMetadata(MD, nullptr))
5600 return true;
5601
5602 Result.assign(MD);
5603 return false;
5604}
5605
5606template <>
5607bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5608 MDSignedOrMDField &Result) {
5609 // Try to parse a signed int.
5610 if (Lex.getKind() == lltok::APSInt) {
5611 MDSignedField Res = Result.A;
5612 if (!parseMDField(Loc, Name, Res)) {
5613 Result.assign(Res);
5614 return false;
5615 }
5616 return true;
5617 }
5618
5619 // Otherwise, try to parse as an MDField.
5620 MDField Res = Result.B;
5621 if (!parseMDField(Loc, Name, Res)) {
5622 Result.assign(Res);
5623 return false;
5624 }
5625
5626 return true;
5627}
5628
5629template <>
5630bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5631 MDUnsignedOrMDField &Result) {
5632 // Try to parse an unsigned int.
5633 if (Lex.getKind() == lltok::APSInt) {
5634 MDUnsignedField Res = Result.A;
5635 if (!parseMDField(Loc, Name, Res)) {
5636 Result.assign(Res);
5637 return false;
5638 }
5639 return true;
5640 }
5641
5642 // Otherwise, try to parse as an MDField.
5643 MDField Res = Result.B;
5644 if (!parseMDField(Loc, Name, Res)) {
5645 Result.assign(Res);
5646 return false;
5647 }
5648
5649 return true;
5650}
5651
5652template <>
5653bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5654 LocTy ValueLoc = Lex.getLoc();
5655 std::string S;
5656 if (parseStringConstant(S))
5657 return true;
5658
5659 if (S.empty()) {
5660 switch (Result.EmptyIs) {
5661 case MDStringField::EmptyIs::Null:
5662 Result.assign(nullptr);
5663 return false;
5664 case MDStringField::EmptyIs::Empty:
5665 break;
5666 case MDStringField::EmptyIs::Error:
5667 return error(ValueLoc, "'" + Name + "' cannot be empty");
5668 }
5669 }
5670
5671 Result.assign(MDString::get(Context, S));
5672 return false;
5673}
5674
5675template <>
5676bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5678 if (parseMDNodeVector(MDs))
5679 return true;
5680
5681 Result.assign(std::move(MDs));
5682 return false;
5683}
5684
5685template <>
5686bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5687 ChecksumKindField &Result) {
5688 std::optional<DIFile::ChecksumKind> CSKind =
5689 DIFile::getChecksumKind(Lex.getStrVal());
5690
5691 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5692 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5693 "'");
5694
5695 Result.assign(*CSKind);
5696 Lex.Lex();
5697 return false;
5698}
5699
5700} // end namespace llvm
5701
5702template <class ParserTy>
5703bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5704 do {
5705 if (Lex.getKind() != lltok::LabelStr)
5706 return tokError("expected field label here");
5707
5708 if (ParseField())
5709 return true;
5710 } while (EatIfPresent(lltok::comma));
5711
5712 return false;
5713}
5714
5715template <class ParserTy>
5716bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5717 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5718 Lex.Lex();
5719
5720 if (parseToken(lltok::lparen, "expected '(' here"))
5721 return true;
5722 if (Lex.getKind() != lltok::rparen)
5723 if (parseMDFieldsImplBody(ParseField))
5724 return true;
5725
5726 ClosingLoc = Lex.getLoc();
5727 return parseToken(lltok::rparen, "expected ')' here");
5728}
5729
5730template <class FieldTy>
5731bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5732 if (Result.Seen)
5733 return tokError("field '" + Name + "' cannot be specified more than once");
5734
5735 LocTy Loc = Lex.getLoc();
5736 Lex.Lex();
5737 return parseMDField(Loc, Name, Result);
5738}
5739
5740bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5741 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5742
5743#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5744 if (Lex.getStrVal() == #CLASS) \
5745 return parse##CLASS(N, IsDistinct);
5746#include "llvm/IR/Metadata.def"
5747
5748 return tokError("expected metadata type");
5749}
5750
5751#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5752#define NOP_FIELD(NAME, TYPE, INIT)
5753#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5754 if (!NAME.Seen) \
5755 return error(ClosingLoc, "missing required field '" #NAME "'");
5756#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5757 if (Lex.getStrVal() == #NAME) \
5758 return parseMDField(#NAME, NAME);
5759#define PARSE_MD_FIELDS() \
5760 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5761 do { \
5762 LocTy ClosingLoc; \
5763 if (parseMDFieldsImpl( \
5764 [&]() -> bool { \
5765 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5766 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5767 "'"); \
5768 }, \
5769 ClosingLoc)) \
5770 return true; \
5771 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5772 } while (false)
5773#define GET_OR_DISTINCT(CLASS, ARGS) \
5774 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5775
5776/// parseDILocationFields:
5777/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5778/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5779bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5780#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5781 OPTIONAL(line, LineField, ); \
5782 OPTIONAL(column, ColumnField, ); \
5783 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5784 OPTIONAL(inlinedAt, MDField, ); \
5785 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5786 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5787 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5789#undef VISIT_MD_FIELDS
5790
5791 Result = GET_OR_DISTINCT(
5792 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5793 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5794 return false;
5795}
5796
5797/// parseDIAssignID:
5798/// ::= distinct !DIAssignID()
5799bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5800 if (!IsDistinct)
5801 return tokError("missing 'distinct', required for !DIAssignID()");
5802
5803 Lex.Lex();
5804
5805 // Now eat the parens.
5806 if (parseToken(lltok::lparen, "expected '(' here"))
5807 return true;
5808 if (parseToken(lltok::rparen, "expected ')' here"))
5809 return true;
5810
5812 return false;
5813}
5814
5815/// parseGenericDINode:
5816/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5817bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5818#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5819 REQUIRED(tag, DwarfTagField, ); \
5820 OPTIONAL(header, MDStringField, ); \
5821 OPTIONAL(operands, MDFieldList, );
5823#undef VISIT_MD_FIELDS
5824
5825 Result = GET_OR_DISTINCT(GenericDINode,
5826 (Context, tag.Val, header.Val, operands.Val));
5827 return false;
5828}
5829
5830/// parseDISubrangeType:
5831/// ::= !DISubrangeType(name: "whatever", file: !0,
5832/// line: 7, scope: !1, baseType: !2, size: 32,
5833/// align: 32, flags: 0, lowerBound: !3
5834/// upperBound: !4, stride: !5, bias: !6)
5835bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5836#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5837 OPTIONAL(name, MDStringField, ); \
5838 OPTIONAL(file, MDField, ); \
5839 OPTIONAL(line, LineField, ); \
5840 OPTIONAL(scope, MDField, ); \
5841 OPTIONAL(baseType, MDField, ); \
5842 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5843 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5844 OPTIONAL(flags, DIFlagField, ); \
5845 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5846 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5847 OPTIONAL(stride, MDSignedOrMDField, ); \
5848 OPTIONAL(bias, MDSignedOrMDField, );
5850#undef VISIT_MD_FIELDS
5851
5852 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5853 if (Bound.isMDSignedField())
5855 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5856 if (Bound.isMDField())
5857 return Bound.getMDFieldValue();
5858 return nullptr;
5859 };
5860
5861 Metadata *LowerBound = convToMetadata(lowerBound);
5862 Metadata *UpperBound = convToMetadata(upperBound);
5863 Metadata *Stride = convToMetadata(stride);
5864 Metadata *Bias = convToMetadata(bias);
5865
5867 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5868 size.getValueAsMetadata(Context), align.Val, flags.Val,
5869 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5870
5871 return false;
5872}
5873
5874/// parseDISubrange:
5875/// ::= !DISubrange(count: 30, lowerBound: 2)
5876/// ::= !DISubrange(count: !node, lowerBound: 2)
5877/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5878bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5879#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5880 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5881 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5882 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5883 OPTIONAL(stride, MDSignedOrMDField, );
5885#undef VISIT_MD_FIELDS
5886
5887 Metadata *Count = nullptr;
5888 Metadata *LowerBound = nullptr;
5889 Metadata *UpperBound = nullptr;
5890 Metadata *Stride = nullptr;
5891
5892 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5893 if (Bound.isMDSignedField())
5895 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5896 if (Bound.isMDField())
5897 return Bound.getMDFieldValue();
5898 return nullptr;
5899 };
5900
5901 Count = convToMetadata(count);
5902 LowerBound = convToMetadata(lowerBound);
5903 UpperBound = convToMetadata(upperBound);
5904 Stride = convToMetadata(stride);
5905
5906 Result = GET_OR_DISTINCT(DISubrange,
5907 (Context, Count, LowerBound, UpperBound, Stride));
5908
5909 return false;
5910}
5911
5912/// parseDIGenericSubrange:
5913/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5914/// !node3)
5915bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5916#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5917 OPTIONAL(count, MDSignedOrMDField, ); \
5918 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5919 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5920 OPTIONAL(stride, MDSignedOrMDField, );
5922#undef VISIT_MD_FIELDS
5923
5924 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5925 if (Bound.isMDSignedField())
5926 return DIExpression::get(
5927 Context, {dwarf::DW_OP_consts,
5928 static_cast<uint64_t>(Bound.getMDSignedValue())});
5929 if (Bound.isMDField())
5930 return Bound.getMDFieldValue();
5931 return nullptr;
5932 };
5933
5934 Metadata *Count = ConvToMetadata(count);
5935 Metadata *LowerBound = ConvToMetadata(lowerBound);
5936 Metadata *UpperBound = ConvToMetadata(upperBound);
5937 Metadata *Stride = ConvToMetadata(stride);
5938
5939 Result = GET_OR_DISTINCT(DIGenericSubrange,
5940 (Context, Count, LowerBound, UpperBound, Stride));
5941
5942 return false;
5943}
5944
5945/// parseDIEnumerator:
5946/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5947bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5948#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5949 REQUIRED(name, MDStringField, ); \
5950 REQUIRED(value, MDAPSIntField, ); \
5951 OPTIONAL(isUnsigned, MDBoolField, (false));
5953#undef VISIT_MD_FIELDS
5954
5955 if (isUnsigned.Val && value.Val.isNegative())
5956 return tokError("unsigned enumerator with negative value");
5957
5958 APSInt Value(value.Val);
5959 // Add a leading zero so that unsigned values with the msb set are not
5960 // mistaken for negative values when used for signed enumerators.
5961 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5962 Value = Value.zext(Value.getBitWidth() + 1);
5963
5964 Result =
5965 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5966
5967 return false;
5968}
5969
5970/// parseDIBasicType:
5971/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5972/// encoding: DW_ATE_encoding, flags: 0)
5973bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5974#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5975 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5976 OPTIONAL(name, MDStringField, ); \
5977 OPTIONAL(file, MDField, ); \
5978 OPTIONAL(line, LineField, ); \
5979 OPTIONAL(scope, MDField, ); \
5980 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5981 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5982 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5983 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5984 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5985 OPTIONAL(flags, DIFlagField, );
5987#undef VISIT_MD_FIELDS
5988
5990 DIBasicType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5991 size.getValueAsMetadata(Context), align.Val, encoding.Val,
5992 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5993 return false;
5994}
5995
5996/// parseDIFixedPointType:
5997/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5998/// align: 32, encoding: DW_ATE_signed_fixed,
5999/// flags: 0, kind: Rational, factor: 3, numerator: 1,
6000/// denominator: 8)
6001bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
6002#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6003 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6004 OPTIONAL(name, MDStringField, ); \
6005 OPTIONAL(file, MDField, ); \
6006 OPTIONAL(line, LineField, ); \
6007 OPTIONAL(scope, MDField, ); \
6008 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6009 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6010 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6011 OPTIONAL(flags, DIFlagField, ); \
6012 OPTIONAL(kind, FixedPointKindField, ); \
6013 OPTIONAL(factor, MDSignedField, ); \
6014 OPTIONAL(numerator, MDAPSIntField, ); \
6015 OPTIONAL(denominator, MDAPSIntField, );
6017#undef VISIT_MD_FIELDS
6018
6019 Result = GET_OR_DISTINCT(DIFixedPointType,
6020 (Context, tag.Val, name.Val, file.Val, line.Val,
6021 scope.Val, size.getValueAsMetadata(Context),
6022 align.Val, encoding.Val, flags.Val, kind.Val,
6023 factor.Val, numerator.Val, denominator.Val));
6024 return false;
6025}
6026
6027/// parseDIStringType:
6028/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
6029bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
6030#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6031 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6032 OPTIONAL(name, MDStringField, ); \
6033 OPTIONAL(stringLength, MDField, ); \
6034 OPTIONAL(stringLengthExpression, MDField, ); \
6035 OPTIONAL(stringLocationExpression, MDField, ); \
6036 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6037 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6038 OPTIONAL(encoding, DwarfAttEncodingField, );
6040#undef VISIT_MD_FIELDS
6041
6043 DIStringType,
6044 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
6045 stringLocationExpression.Val, size.getValueAsMetadata(Context),
6046 align.Val, encoding.Val));
6047 return false;
6048}
6049
6050/// parseDIDerivedType:
6051/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
6052/// line: 7, scope: !1, baseType: !2, size: 32,
6053/// align: 32, offset: 0, flags: 0, extraData: !3,
6054/// dwarfAddressSpace: 3, ptrAuthKey: 1,
6055/// ptrAuthIsAddressDiscriminated: true,
6056/// ptrAuthExtraDiscriminator: 0x1234,
6057/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
6058/// )
6059bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
6060#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6061 REQUIRED(tag, DwarfTagField, ); \
6062 OPTIONAL(name, MDStringField, ); \
6063 OPTIONAL(file, MDField, ); \
6064 OPTIONAL(line, LineField, ); \
6065 OPTIONAL(scope, MDField, ); \
6066 REQUIRED(baseType, MDField, ); \
6067 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6068 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6069 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6070 OPTIONAL(flags, DIFlagField, ); \
6071 OPTIONAL(extraData, MDField, ); \
6072 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6073 OPTIONAL(annotations, MDField, ); \
6074 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6075 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6076 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6077 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6078 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6080#undef VISIT_MD_FIELDS
6081
6082 std::optional<unsigned> DWARFAddressSpace;
6083 if (dwarfAddressSpace.Val != UINT32_MAX)
6084 DWARFAddressSpace = dwarfAddressSpace.Val;
6085 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6086 if (ptrAuthKey.Val)
6087 PtrAuthData.emplace(
6088 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6089 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6090 ptrAuthAuthenticatesNullValues.Val);
6091
6093 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6094 baseType.Val, size.getValueAsMetadata(Context), align.Val,
6095 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6096 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6097 return false;
6098}
6099
6100bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
6101#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6102 REQUIRED(tag, DwarfTagField, ); \
6103 OPTIONAL(name, MDStringField, ); \
6104 OPTIONAL(file, MDField, ); \
6105 OPTIONAL(line, LineField, ); \
6106 OPTIONAL(scope, MDField, ); \
6107 OPTIONAL(baseType, MDField, ); \
6108 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6109 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6110 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6111 OPTIONAL(flags, DIFlagField, ); \
6112 OPTIONAL(elements, MDField, ); \
6113 OPTIONAL(runtimeLang, DwarfLangField, ); \
6114 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6115 OPTIONAL(vtableHolder, MDField, ); \
6116 OPTIONAL(templateParams, MDField, ); \
6117 OPTIONAL(identifier, MDStringField, ); \
6118 OPTIONAL(discriminator, MDField, ); \
6119 OPTIONAL(dataLocation, MDField, ); \
6120 OPTIONAL(associated, MDField, ); \
6121 OPTIONAL(allocated, MDField, ); \
6122 OPTIONAL(rank, MDSignedOrMDField, ); \
6123 OPTIONAL(annotations, MDField, ); \
6124 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6125 OPTIONAL(specification, MDField, ); \
6126 OPTIONAL(bitStride, MDField, );
6128#undef VISIT_MD_FIELDS
6129
6130 Metadata *Rank = nullptr;
6131 if (rank.isMDSignedField())
6133 Type::getInt64Ty(Context), rank.getMDSignedValue()));
6134 else if (rank.isMDField())
6135 Rank = rank.getMDFieldValue();
6136
6137 std::optional<unsigned> EnumKind;
6138 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
6139 EnumKind = enumKind.Val;
6140
6141 // If this has an identifier try to build an ODR type.
6142 if (identifier.Val)
6143 if (auto *CT = DICompositeType::buildODRType(
6144 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
6145 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
6146 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6147 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6148 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6149 dataLocation.Val, associated.Val, allocated.Val, Rank,
6150 annotations.Val, bitStride.Val)) {
6151 Result = CT;
6152 return false;
6153 }
6154
6155 // Create a new node, and save it in the context if it belongs in the type
6156 // map.
6158 DICompositeType,
6159 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
6160 size.getValueAsMetadata(Context), align.Val,
6161 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6162 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6163 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6164 allocated.Val, Rank, annotations.Val, specification.Val,
6165 num_extra_inhabitants.Val, bitStride.Val));
6166 return false;
6167}
6168
6169bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
6170#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6171 OPTIONAL(flags, DIFlagField, ); \
6172 OPTIONAL(cc, DwarfCCField, ); \
6173 REQUIRED(types, MDField, );
6175#undef VISIT_MD_FIELDS
6176
6177 Result = GET_OR_DISTINCT(DISubroutineType,
6178 (Context, flags.Val, cc.Val, types.Val));
6179 return false;
6180}
6181
6182/// parseDIFileType:
6183/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
6184/// checksumkind: CSK_MD5,
6185/// checksum: "000102030405060708090a0b0c0d0e0f",
6186/// source: "source file contents")
6187bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
6188 // The default constructed value for checksumkind is required, but will never
6189 // be used, as the parser checks if the field was actually Seen before using
6190 // the Val.
6191#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6192 REQUIRED(filename, MDStringField, ); \
6193 REQUIRED(directory, MDStringField, ); \
6194 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6195 OPTIONAL(checksum, MDStringField, ); \
6196 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6198#undef VISIT_MD_FIELDS
6199
6200 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6201 if (checksumkind.Seen && checksum.Seen)
6202 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6203 else if (checksumkind.Seen || checksum.Seen)
6204 return tokError("'checksumkind' and 'checksum' must be provided together");
6205
6206 MDString *Source = nullptr;
6207 if (source.Seen)
6208 Source = source.Val;
6210 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
6211 return false;
6212}
6213
6214/// parseDICompileUnit:
6215/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
6216/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
6217/// splitDebugFilename: "abc.debug",
6218/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
6219/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
6220/// sysroot: "/", sdk: "MacOSX.sdk",
6221/// dialect: DW_LLVM_LANG_DIALECT_simt)
6222bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
6223 if (!IsDistinct)
6224 return tokError("missing 'distinct', required for !DICompileUnit");
6225
6226 LocTy Loc = Lex.getLoc();
6227
6228#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6229 REQUIRED(file, MDField, (/* AllowNull */ false)); \
6230 OPTIONAL(language, DwarfLangField, ); \
6231 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6232 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6233 OPTIONAL(producer, MDStringField, ); \
6234 OPTIONAL(isOptimized, MDBoolField, ); \
6235 OPTIONAL(flags, MDStringField, ); \
6236 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6237 OPTIONAL(splitDebugFilename, MDStringField, ); \
6238 OPTIONAL(emissionKind, EmissionKindField, ); \
6239 OPTIONAL(enums, MDField, ); \
6240 OPTIONAL(retainedTypes, MDField, ); \
6241 OPTIONAL(globals, MDField, ); \
6242 OPTIONAL(imports, MDField, ); \
6243 OPTIONAL(macros, MDField, ); \
6244 OPTIONAL(dwoId, MDUnsignedField, ); \
6245 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6246 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6247 OPTIONAL(nameTableKind, NameTableKindField, ); \
6248 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6249 OPTIONAL(sysroot, MDStringField, ); \
6250 OPTIONAL(sdk, MDStringField, ); \
6251 OPTIONAL(dialect, DwarfLangDialectField, );
6253#undef VISIT_MD_FIELDS
6254
6255 if (!language.Seen && !sourceLanguageName.Seen)
6256 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
6257 "required for !DICompileUnit");
6258
6259 if (language.Seen && sourceLanguageName.Seen)
6260 return error(Loc, "can only specify one of 'language' and "
6261 "'sourceLanguageName' on !DICompileUnit");
6262
6263 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6264 return error(Loc, "'sourceLanguageVersion' requires an associated "
6265 "'sourceLanguageName' on !DICompileUnit");
6266
6267 uint16_t Dialect = static_cast<uint16_t>(dialect.Val);
6268 DISourceLanguageName SourceLanguage =
6269 language.Seen
6270 ? DISourceLanguageName(static_cast<uint16_t>(language.Val), Dialect)
6271 : DISourceLanguageName(
6272 static_cast<uint16_t>(sourceLanguageName.Val),
6273 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6274
6276 Context, SourceLanguage, file.Val, producer.Val, isOptimized.Val,
6277 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6278 enums.Val, retainedTypes.Val, globals.Val, imports.Val, macros.Val,
6279 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6280 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6281 return false;
6282}
6283
6284/// parseDISubprogram:
6285/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
6286/// file: !1, line: 7, type: !2, isLocal: false,
6287/// isDefinition: true, scopeLine: 8, containingType: !3,
6288/// virtuality: DW_VIRTUALTIY_pure_virtual,
6289/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
6290/// spFlags: 10, isOptimized: false, templateParams: !4,
6291/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
6292/// annotations: !8)
6293bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
6294 auto Loc = Lex.getLoc();
6295#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6296 OPTIONAL(scope, MDField, ); \
6297 OPTIONAL(name, MDStringField, ); \
6298 OPTIONAL(linkageName, MDStringField, ); \
6299 OPTIONAL(file, MDField, ); \
6300 OPTIONAL(line, LineField, ); \
6301 REQUIRED(type, MDField, (/* AllowNull */ false)); \
6302 OPTIONAL(isLocal, MDBoolField, ); \
6303 OPTIONAL(isDefinition, MDBoolField, (true)); \
6304 OPTIONAL(scopeLine, LineField, ); \
6305 OPTIONAL(containingType, MDField, ); \
6306 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6307 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6308 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6309 OPTIONAL(flags, DIFlagField, ); \
6310 OPTIONAL(spFlags, DISPFlagField, ); \
6311 OPTIONAL(isOptimized, MDBoolField, ); \
6312 OPTIONAL(unit, MDField, ); \
6313 OPTIONAL(templateParams, MDField, ); \
6314 OPTIONAL(declaration, MDField, ); \
6315 OPTIONAL(retainedNodes, MDField, ); \
6316 OPTIONAL(thrownTypes, MDField, ); \
6317 OPTIONAL(annotations, MDField, ); \
6318 OPTIONAL(targetFuncName, MDStringField, ); \
6319 OPTIONAL(keyInstructions, MDBoolField, );
6321#undef VISIT_MD_FIELDS
6322
6323 // An explicit spFlags field takes precedence over individual fields in
6324 // older IR versions.
6325 DISubprogram::DISPFlags SPFlags =
6326 spFlags.Seen ? spFlags.Val
6327 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
6328 isOptimized.Val, virtuality.Val);
6329 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6330 return error(
6331 Loc,
6332 "missing 'distinct', required for !DISubprogram that is a Definition");
6334 DISubprogram,
6335 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6336 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6337 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6338 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6339 targetFuncName.Val, keyInstructions.Val));
6340
6341 if (IsDistinct)
6342 NewDistinctSPs.push_back(cast<DISubprogram>(Result));
6343
6344 return false;
6345}
6346
6347/// parseDILexicalBlock:
6348/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6349bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6350#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6351 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6352 OPTIONAL(file, MDField, ); \
6353 OPTIONAL(line, LineField, ); \
6354 OPTIONAL(column, ColumnField, );
6356#undef VISIT_MD_FIELDS
6357
6359 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6360 return false;
6361}
6362
6363/// parseDILexicalBlockFile:
6364/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6365bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6366#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6367 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6368 OPTIONAL(file, MDField, ); \
6369 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6371#undef VISIT_MD_FIELDS
6372
6373 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6374 (Context, scope.Val, file.Val, discriminator.Val));
6375 return false;
6376}
6377
6378/// parseDICommonBlock:
6379/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6380bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6381#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6382 REQUIRED(scope, MDField, ); \
6383 OPTIONAL(declaration, MDField, ); \
6384 OPTIONAL(name, MDStringField, ); \
6385 OPTIONAL(file, MDField, ); \
6386 OPTIONAL(line, LineField, );
6388#undef VISIT_MD_FIELDS
6389
6390 Result = GET_OR_DISTINCT(DICommonBlock,
6391 (Context, scope.Val, declaration.Val, name.Val,
6392 file.Val, line.Val));
6393 return false;
6394}
6395
6396/// parseDINamespace:
6397/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6398bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6399#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6400 REQUIRED(scope, MDField, ); \
6401 OPTIONAL(name, MDStringField, ); \
6402 OPTIONAL(exportSymbols, MDBoolField, );
6404#undef VISIT_MD_FIELDS
6405
6406 Result = GET_OR_DISTINCT(DINamespace,
6407 (Context, scope.Val, name.Val, exportSymbols.Val));
6408 return false;
6409}
6410
6411/// parseDIMacro:
6412/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6413/// "SomeValue")
6414bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6415#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6416 REQUIRED(type, DwarfMacinfoTypeField, ); \
6417 OPTIONAL(line, LineField, ); \
6418 REQUIRED(name, MDStringField, ); \
6419 OPTIONAL(value, MDStringField, );
6421#undef VISIT_MD_FIELDS
6422
6423 Result = GET_OR_DISTINCT(DIMacro,
6424 (Context, type.Val, line.Val, name.Val, value.Val));
6425 return false;
6426}
6427
6428/// parseDIMacroFile:
6429/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6430bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6431#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6432 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6433 OPTIONAL(line, LineField, ); \
6434 REQUIRED(file, MDField, ); \
6435 OPTIONAL(nodes, MDField, );
6437#undef VISIT_MD_FIELDS
6438
6439 Result = GET_OR_DISTINCT(DIMacroFile,
6440 (Context, type.Val, line.Val, file.Val, nodes.Val));
6441 return false;
6442}
6443
6444/// parseDIModule:
6445/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6446/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6447/// file: !1, line: 4, isDecl: false)
6448bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6449#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6450 REQUIRED(scope, MDField, ); \
6451 REQUIRED(name, MDStringField, ); \
6452 OPTIONAL(configMacros, MDStringField, ); \
6453 OPTIONAL(includePath, MDStringField, ); \
6454 OPTIONAL(apinotes, MDStringField, ); \
6455 OPTIONAL(file, MDField, ); \
6456 OPTIONAL(line, LineField, ); \
6457 OPTIONAL(isDecl, MDBoolField, );
6459#undef VISIT_MD_FIELDS
6460
6461 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6462 configMacros.Val, includePath.Val,
6463 apinotes.Val, line.Val, isDecl.Val));
6464 return false;
6465}
6466
6467/// parseDITemplateTypeParameter:
6468/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6469bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6470#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6471 OPTIONAL(name, MDStringField, ); \
6472 REQUIRED(type, MDField, ); \
6473 OPTIONAL(defaulted, MDBoolField, );
6475#undef VISIT_MD_FIELDS
6476
6477 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6478 (Context, name.Val, type.Val, defaulted.Val));
6479 return false;
6480}
6481
6482/// parseDITemplateValueParameter:
6483/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6484/// name: "V", type: !1, defaulted: false,
6485/// value: i32 7)
6486bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6487#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6488 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6489 OPTIONAL(name, MDStringField, ); \
6490 OPTIONAL(type, MDField, ); \
6491 OPTIONAL(defaulted, MDBoolField, ); \
6492 REQUIRED(value, MDField, );
6493
6495#undef VISIT_MD_FIELDS
6496
6498 DITemplateValueParameter,
6499 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6500 return false;
6501}
6502
6503/// parseDIGlobalVariable:
6504/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6505/// file: !1, line: 7, type: !2, isLocal: false,
6506/// isDefinition: true, templateParams: !3,
6507/// declaration: !4, align: 8)
6508bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6509#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6510 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6511 OPTIONAL(scope, MDField, ); \
6512 OPTIONAL(linkageName, MDStringField, ); \
6513 OPTIONAL(file, MDField, ); \
6514 OPTIONAL(line, LineField, ); \
6515 OPTIONAL(type, MDField, ); \
6516 OPTIONAL(isLocal, MDBoolField, ); \
6517 OPTIONAL(isDefinition, MDBoolField, (true)); \
6518 OPTIONAL(templateParams, MDField, ); \
6519 OPTIONAL(declaration, MDField, ); \
6520 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6521 OPTIONAL(annotations, MDField, );
6523#undef VISIT_MD_FIELDS
6524
6525 Result =
6526 GET_OR_DISTINCT(DIGlobalVariable,
6527 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6528 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6529 declaration.Val, templateParams.Val, align.Val,
6530 annotations.Val));
6531 return false;
6532}
6533
6534/// parseDILocalVariable:
6535/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6536/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6537/// align: 8)
6538/// ::= !DILocalVariable(scope: !0, name: "foo",
6539/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6540/// align: 8)
6541bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6542#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6543 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6544 OPTIONAL(name, MDStringField, ); \
6545 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6546 OPTIONAL(file, MDField, ); \
6547 OPTIONAL(line, LineField, ); \
6548 OPTIONAL(type, MDField, ); \
6549 OPTIONAL(flags, DIFlagField, ); \
6550 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6551 OPTIONAL(annotations, MDField, );
6553#undef VISIT_MD_FIELDS
6554
6555 Result = GET_OR_DISTINCT(DILocalVariable,
6556 (Context, scope.Val, name.Val, file.Val, line.Val,
6557 type.Val, arg.Val, flags.Val, align.Val,
6558 annotations.Val));
6559 return false;
6560}
6561
6562/// parseDILabel:
6563/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6564bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6565#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6566 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6567 REQUIRED(name, MDStringField, ); \
6568 REQUIRED(file, MDField, ); \
6569 REQUIRED(line, LineField, ); \
6570 OPTIONAL(column, ColumnField, ); \
6571 OPTIONAL(isArtificial, MDBoolField, ); \
6572 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6574#undef VISIT_MD_FIELDS
6575
6576 std::optional<unsigned> CoroSuspendIdx =
6577 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6578 : std::nullopt;
6579
6580 Result = GET_OR_DISTINCT(DILabel,
6581 (Context, scope.Val, name.Val, file.Val, line.Val,
6582 column.Val, isArtificial.Val, CoroSuspendIdx));
6583 return false;
6584}
6585
6586/// parseDIExpressionBody:
6587/// ::= (0, 7, -1)
6588bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6589 if (parseToken(lltok::lparen, "expected '(' here"))
6590 return true;
6591
6592 SmallVector<uint64_t, 8> Elements;
6593 if (Lex.getKind() != lltok::rparen)
6594 do {
6595 if (Lex.getKind() == lltok::DwarfOp) {
6596 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6597 Lex.Lex();
6598 Elements.push_back(Op);
6599 continue;
6600 }
6601 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6602 }
6603
6604 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6605 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6606 Lex.Lex();
6607 Elements.push_back(Op);
6608 continue;
6609 }
6610 return tokError(Twine("invalid DWARF attribute encoding '") +
6611 Lex.getStrVal() + "'");
6612 }
6613
6614 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6615 return tokError("expected unsigned integer");
6616
6617 auto &U = Lex.getAPSIntVal();
6618 if (U.ugt(UINT64_MAX))
6619 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6620 Elements.push_back(U.getZExtValue());
6621 Lex.Lex();
6622 } while (EatIfPresent(lltok::comma));
6623
6624 if (parseToken(lltok::rparen, "expected ')' here"))
6625 return true;
6626
6627 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6628 return false;
6629}
6630
6631/// parseDIExpression:
6632/// ::= !DIExpression(0, 7, -1)
6633bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6634 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6635 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6636 Lex.Lex();
6637
6638 return parseDIExpressionBody(Result, IsDistinct);
6639}
6640
6641/// ParseDIArgList:
6642/// ::= !DIArgList(i32 7, i64 %0)
6643bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6644 assert(PFS && "Expected valid function state");
6645 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6646 Lex.Lex();
6647
6648 if (parseToken(lltok::lparen, "expected '(' here"))
6649 return true;
6650
6652 if (Lex.getKind() != lltok::rparen)
6653 do {
6654 Metadata *MD;
6655 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6656 return true;
6657 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6658 } while (EatIfPresent(lltok::comma));
6659
6660 if (parseToken(lltok::rparen, "expected ')' here"))
6661 return true;
6662
6663 MD = DIArgList::get(Context, Args);
6664 return false;
6665}
6666
6667/// parseDIGlobalVariableExpression:
6668/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6669bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6670 bool IsDistinct) {
6671#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6672 REQUIRED(var, MDField, ); \
6673 REQUIRED(expr, MDField, );
6675#undef VISIT_MD_FIELDS
6676
6677 Result =
6678 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6679 return false;
6680}
6681
6682/// parseDIObjCProperty:
6683/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6684/// getter: "getFoo", attributes: 7, type: !2)
6685bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6686#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6687 OPTIONAL(name, MDStringField, ); \
6688 OPTIONAL(file, MDField, ); \
6689 OPTIONAL(line, LineField, ); \
6690 OPTIONAL(setter, MDStringField, ); \
6691 OPTIONAL(getter, MDStringField, ); \
6692 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6693 OPTIONAL(type, MDField, );
6695#undef VISIT_MD_FIELDS
6696
6697 Result = GET_OR_DISTINCT(DIObjCProperty,
6698 (Context, name.Val, file.Val, line.Val, getter.Val,
6699 setter.Val, attributes.Val, type.Val));
6700 return false;
6701}
6702
6703/// parseDIProperty:
6704/// ::= !DIProperty(name: "x", file: !1, line: 7, type: !2,
6705/// backing_storage: !3)
6706bool LLParser::parseDIProperty(MDNode *&Result, bool IsDistinct) {
6707#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6708 OPTIONAL(name, MDStringField, ); \
6709 OPTIONAL(file, MDField, ); \
6710 OPTIONAL(line, LineField, ); \
6711 OPTIONAL(type, MDField, ); \
6712 OPTIONAL(backing_storage, MDField, );
6714#undef VISIT_MD_FIELDS
6715
6716 Result = GET_OR_DISTINCT(DIProperty, (Context, name.Val, file.Val, line.Val,
6717 type.Val, backing_storage.Val));
6718 return false;
6719}
6720
6721/// parseDIImportedEntity:
6722/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6723/// line: 7, name: "foo", elements: !2)
6724bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6725#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6726 REQUIRED(tag, DwarfTagField, ); \
6727 REQUIRED(scope, MDField, ); \
6728 OPTIONAL(entity, MDField, ); \
6729 OPTIONAL(file, MDField, ); \
6730 OPTIONAL(line, LineField, ); \
6731 OPTIONAL(name, MDStringField, ); \
6732 OPTIONAL(elements, MDField, );
6734#undef VISIT_MD_FIELDS
6735
6736 Result = GET_OR_DISTINCT(DIImportedEntity,
6737 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6738 line.Val, name.Val, elements.Val));
6739 return false;
6740}
6741
6742#undef PARSE_MD_FIELD
6743#undef NOP_FIELD
6744#undef REQUIRE_FIELD
6745#undef DECLARE_FIELD
6746
6747/// parseMetadataAsValue
6748/// ::= metadata i32 %local
6749/// ::= metadata i32 @global
6750/// ::= metadata i32 7
6751/// ::= metadata !0
6752/// ::= metadata !{...}
6753/// ::= metadata !"string"
6754bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6755 // Note: the type 'metadata' has already been parsed.
6756 Metadata *MD;
6757 if (parseMetadata(MD, &PFS))
6758 return true;
6759
6760 V = MetadataAsValue::get(Context, MD);
6761 return false;
6762}
6763
6764/// parseValueAsMetadata
6765/// ::= i32 %local
6766/// ::= i32 @global
6767/// ::= i32 7
6768bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6769 PerFunctionState *PFS) {
6770 Type *Ty;
6771 LocTy Loc;
6772 if (parseType(Ty, TypeMsg, Loc))
6773 return true;
6774 if (Ty->isMetadataTy())
6775 return error(Loc, "invalid metadata-value-metadata roundtrip");
6776
6777 Value *V;
6778 if (parseValue(Ty, V, PFS))
6779 return true;
6780
6781 MD = ValueAsMetadata::get(V);
6782 return false;
6783}
6784
6785/// parseMetadata
6786/// ::= i32 %local
6787/// ::= i32 @global
6788/// ::= i32 7
6789/// ::= !42
6790/// ::= !{...}
6791/// ::= !"string"
6792/// ::= !DILocation(...)
6793bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6794 if (Lex.getKind() == lltok::MetadataVar) {
6795 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6796 // so parsing this requires a Function State.
6797 if (Lex.getStrVal() == "DIArgList") {
6798 Metadata *AL;
6799 if (parseDIArgList(AL, PFS))
6800 return true;
6801 MD = AL;
6802 return false;
6803 }
6804 MDNode *N;
6805 if (parseSpecializedMDNode(N)) {
6806 return true;
6807 }
6808 MD = N;
6809 return false;
6810 }
6811
6812 // ValueAsMetadata:
6813 // <type> <value>
6814 if (Lex.getKind() != lltok::exclaim)
6815 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6816
6817 // '!'.
6818 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6819 Lex.Lex();
6820
6821 // MDString:
6822 // ::= '!' STRINGCONSTANT
6823 if (Lex.getKind() == lltok::StringConstant) {
6824 MDString *S;
6825 if (parseMDString(S))
6826 return true;
6827 MD = S;
6828 return false;
6829 }
6830
6831 // MDNode:
6832 // !{ ... }
6833 // !7
6834 MDNode *N;
6835 if (parseMDNodeTail(N))
6836 return true;
6837 MD = N;
6838 return false;
6839}
6840
6841//===----------------------------------------------------------------------===//
6842// Function Parsing.
6843//===----------------------------------------------------------------------===//
6844
6845bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6846 PerFunctionState *PFS) {
6847 if (Ty->isFunctionTy())
6848 return error(ID.Loc, "functions are not values, refer to them as pointers");
6849
6850 switch (ID.Kind) {
6851 case ValID::t_LocalID:
6852 if (!PFS)
6853 return error(ID.Loc, "invalid use of function-local name");
6854 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6855 return V == nullptr;
6856 case ValID::t_LocalName:
6857 if (!PFS)
6858 return error(ID.Loc, "invalid use of function-local name");
6859 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6860 return V == nullptr;
6861 case ValID::t_InlineAsm: {
6862 if (!ID.FTy)
6863 return error(ID.Loc, "invalid type for inline asm constraint string");
6864 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6865 return error(ID.Loc, toString(std::move(Err)));
6866 V = InlineAsm::get(
6867 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6868 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6869 return false;
6870 }
6872 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6873 if (V && ID.NoCFI)
6875 return V == nullptr;
6876 case ValID::t_GlobalID:
6877 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6878 if (V && ID.NoCFI)
6880 return V == nullptr;
6881 case ValID::t_APSInt:
6882 if (!Ty->isIntegerTy() && !Ty->isByteTy())
6883 return error(ID.Loc, "integer/byte constant must have integer/byte type");
6884 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6885 Ty->isIntegerTy() ? V = ConstantInt::get(Context, ID.APSIntVal)
6886 : V = ConstantByte::get(Context, ID.APSIntVal);
6887 return false;
6888 case ValID::t_APFloat:
6889 if (!Ty->isFloatingPointTy() ||
6890 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6891 return error(ID.Loc, "floating point constant invalid for type");
6892
6893 // The lexer has no type info, so builds all half, bfloat, float, and double
6894 // FP constants as double. Fix this here. Long double does not need this.
6895 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6896 // Check for signaling before potentially converting and losing that info.
6897 bool IsSNAN = ID.APFloatVal.isSignaling();
6898 bool Ignored;
6899 if (Ty->isHalfTy())
6900 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6901 &Ignored);
6902 else if (Ty->isBFloatTy())
6903 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6904 &Ignored);
6905 else if (Ty->isFloatTy())
6906 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6907 &Ignored);
6908 if (IsSNAN) {
6909 // The convert call above may quiet an SNaN, so manufacture another
6910 // SNaN. The bitcast works because the payload (significand) parameter
6911 // is truncated to fit.
6912 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6913 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6914 ID.APFloatVal.isNegative(), &Payload);
6915 }
6916 }
6917 V = ConstantFP::get(Context, ID.APFloatVal);
6918
6919 if (V->getType() != Ty)
6920 return error(ID.Loc, "floating point constant does not have type '" +
6921 getTypeString(Ty) + "'");
6922
6923 return false;
6924 case ValID::t_Null:
6925 if (!Ty->isPointerTy())
6926 return error(ID.Loc, "null must be a pointer type");
6928 return false;
6929 case ValID::t_Undef:
6930 // FIXME: LabelTy should not be a first-class type.
6931 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6932 return error(ID.Loc, "invalid type for undef constant");
6933 V = UndefValue::get(Ty);
6934 return false;
6936 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6937 return error(ID.Loc, "invalid empty array initializer");
6938 V = PoisonValue::get(Ty);
6939 return false;
6940 case ValID::t_Zero:
6941 // FIXME: LabelTy should not be a first-class type.
6942 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6943 return error(ID.Loc, "invalid type for null constant");
6944 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6945 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6946 return error(ID.Loc, "invalid type for null constant");
6948 return false;
6949 case ValID::t_None:
6950 if (!Ty->isTokenTy())
6951 return error(ID.Loc, "invalid type for none constant");
6953 return false;
6954 case ValID::t_Poison:
6955 // FIXME: LabelTy should not be a first-class type.
6956 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6957 return error(ID.Loc, "invalid type for poison constant");
6958 V = PoisonValue::get(Ty);
6959 return false;
6960 case ValID::t_Constant:
6961 if (ID.ConstantVal->getType() != Ty)
6962 return error(ID.Loc, "constant expression type mismatch: got type '" +
6963 getTypeString(ID.ConstantVal->getType()) +
6964 "' but expected '" + getTypeString(Ty) + "'");
6965 V = ID.ConstantVal;
6966 return false;
6968 if (!Ty->isVectorTy())
6969 return error(ID.Loc, "vector constant must have vector type");
6970 if (ID.ConstantVal->getType() != Ty->getScalarType())
6971 return error(ID.Loc, "constant expression type mismatch: got type '" +
6972 getTypeString(ID.ConstantVal->getType()) +
6973 "' but expected '" +
6974 getTypeString(Ty->getScalarType()) + "'");
6975 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6976 ID.ConstantVal);
6977 return false;
6980 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6981 if (ST->getNumElements() != ID.UIntVal)
6982 return error(ID.Loc,
6983 "initializer with struct type has wrong # elements");
6984 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6985 return error(ID.Loc, "packed'ness of initializer and type don't match");
6986
6987 // Verify that the elements are compatible with the structtype.
6988 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6989 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6990 return error(
6991 ID.Loc,
6992 "element " + Twine(i) +
6993 " of struct initializer doesn't match struct element type");
6994
6996 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6997 } else
6998 return error(ID.Loc, "constant expression type mismatch");
6999 return false;
7000 }
7001 llvm_unreachable("Invalid ValID");
7002}
7003
7004bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
7005 C = nullptr;
7006 ValID ID;
7007 auto Loc = Lex.getLoc();
7008 if (parseValID(ID, /*PFS=*/nullptr, /*ExpectedTy=*/Ty))
7009 return true;
7010 switch (ID.Kind) {
7011 case ValID::t_APSInt:
7012 case ValID::t_APFloat:
7013 case ValID::t_Undef:
7014 case ValID::t_Poison:
7015 case ValID::t_Zero:
7016 case ValID::t_Constant:
7020 Value *V;
7021 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
7022 return true;
7023 assert(isa<Constant>(V) && "Expected a constant value");
7024 C = cast<Constant>(V);
7025 return false;
7026 }
7027 case ValID::t_Null:
7029 return false;
7030 default:
7031 return error(Loc, "expected a constant value");
7032 }
7033}
7034
7035bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
7036 V = nullptr;
7037 ValID ID;
7038
7039 FileLoc Start = getTokLineColumnPos();
7040 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
7041 if (!Ret && ParserContext) {
7042 FileLoc End = getPrevTokEndLineColumnPos();
7043 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
7044 }
7045 return Ret;
7046}
7047
7048bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
7049 Type *Ty = nullptr;
7050 return parseType(Ty) || parseValue(Ty, V, PFS);
7051}
7052
7053bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
7054 PerFunctionState &PFS) {
7055 Value *V;
7056 Loc = Lex.getLoc();
7057 if (parseTypeAndValue(V, PFS))
7058 return true;
7059 if (!isa<BasicBlock>(V))
7060 return error(Loc, "expected a basic block");
7061 BB = cast<BasicBlock>(V);
7062 return false;
7063}
7064
7066 // Exit early for the common (non-debug-intrinsic) case.
7067 // We can make this the only check when we begin supporting all "llvm.dbg"
7068 // intrinsics in the new debug info format.
7069 if (!Name.starts_with("llvm.dbg."))
7070 return false;
7072 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7073 FnID == Intrinsic::dbg_assign;
7074}
7075
7076/// FunctionHeader
7077/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
7078/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
7079/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
7080/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
7081bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
7082 unsigned &FunctionNumber,
7083 SmallVectorImpl<unsigned> &UnnamedArgNums) {
7084 // parse the linkage.
7085 LocTy LinkageLoc = Lex.getLoc();
7086 unsigned Linkage;
7087 unsigned Visibility;
7088 unsigned DLLStorageClass;
7089 bool DSOLocal;
7090 AttrBuilder RetAttrs(M->getContext());
7091 unsigned CC;
7092 bool HasLinkage;
7093 Type *RetType = nullptr;
7094 LocTy RetTypeLoc = Lex.getLoc();
7095 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
7096 DSOLocal) ||
7097 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7098 parseType(RetType, RetTypeLoc, true /*void allowed*/))
7099 return true;
7100
7101 // Verify that the linkage is ok.
7104 break; // always ok.
7106 if (IsDefine)
7107 return error(LinkageLoc, "invalid linkage for function definition");
7108 break;
7116 if (!IsDefine)
7117 return error(LinkageLoc, "invalid linkage for function declaration");
7118 break;
7121 return error(LinkageLoc, "invalid function linkage type");
7122 }
7123
7124 if (!isValidVisibilityForLinkage(Visibility, Linkage))
7125 return error(LinkageLoc,
7126 "symbol with local linkage must have default visibility");
7127
7128 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
7129 return error(LinkageLoc,
7130 "symbol with local linkage cannot have a DLL storage class");
7131
7132 if (!FunctionType::isValidReturnType(RetType))
7133 return error(RetTypeLoc, "invalid function return type");
7134
7135 LocTy NameLoc = Lex.getLoc();
7136
7137 std::string FunctionName;
7138 if (Lex.getKind() == lltok::GlobalVar) {
7139 FunctionName = Lex.getStrVal();
7140 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
7141 FunctionNumber = Lex.getUIntVal();
7142 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
7143 FunctionNumber))
7144 return true;
7145 } else {
7146 return tokError("expected function name");
7147 }
7148
7149 Lex.Lex();
7150
7151 if (Lex.getKind() != lltok::lparen)
7152 return tokError("expected '(' in function argument list");
7153
7155 bool IsVarArg;
7156 AttrBuilder FuncAttrs(M->getContext());
7157 std::vector<unsigned> FwdRefAttrGrps;
7158 LocTy BuiltinLoc;
7159 std::string Section;
7160 std::string Partition;
7161 MaybeAlign Alignment, PrefAlignment;
7162 std::string GC;
7164 unsigned AddrSpace = 0;
7165 Constant *Prefix = nullptr;
7166 Constant *Prologue = nullptr;
7167 Constant *PersonalityFn = nullptr;
7168 Comdat *C;
7169
7170 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7171 parseOptionalUnnamedAddr(UnnamedAddr) ||
7172 parseOptionalProgramAddrSpace(AddrSpace) ||
7173 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
7174 BuiltinLoc) ||
7175 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
7176 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
7177 parseOptionalComdat(FunctionName, C) ||
7178 parseOptionalAlignment(Alignment) ||
7179 parseOptionalPrefAlignment(PrefAlignment) ||
7180 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
7181 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
7182 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
7183 (EatIfPresent(lltok::kw_personality) &&
7184 parseGlobalTypeAndValue(PersonalityFn)))
7185 return true;
7186
7187 if (FuncAttrs.contains(Attribute::Builtin))
7188 return error(BuiltinLoc, "'builtin' attribute not valid on function");
7189
7190 // If the alignment was parsed as an attribute, move to the alignment field.
7191 if (MaybeAlign A = FuncAttrs.getAlignment()) {
7192 Alignment = A;
7193 FuncAttrs.removeAttribute(Attribute::Alignment);
7194 }
7195
7196 // Okay, if we got here, the function is syntactically valid. Convert types
7197 // and do semantic checks.
7198 std::vector<Type*> ParamTypeList;
7200
7201 for (const ArgInfo &Arg : ArgList) {
7202 ParamTypeList.push_back(Arg.Ty);
7203 Attrs.push_back(Arg.Attrs);
7204 }
7205
7206 AttributeList PAL =
7207 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
7208 AttributeSet::get(Context, RetAttrs), Attrs);
7209
7210 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
7211 return error(RetTypeLoc, "functions with 'sret' argument must return void");
7212
7213 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
7214 PointerType *PFT = PointerType::get(Context, AddrSpace);
7215
7216 Fn = nullptr;
7217 GlobalValue *FwdFn = nullptr;
7218 if (!FunctionName.empty()) {
7219 // If this was a definition of a forward reference, remove the definition
7220 // from the forward reference table and fill in the forward ref.
7221 auto FRVI = ForwardRefVals.find(FunctionName);
7222 if (FRVI != ForwardRefVals.end()) {
7223 FwdFn = FRVI->second.first;
7224 if (FwdFn->getType() != PFT)
7225 return error(FRVI->second.second,
7226 "invalid forward reference to "
7227 "function '" +
7228 FunctionName +
7229 "' with wrong type: "
7230 "expected '" +
7231 getTypeString(PFT) + "' but was '" +
7232 getTypeString(FwdFn->getType()) + "'");
7233 ForwardRefVals.erase(FRVI);
7234 } else if ((Fn = M->getFunction(FunctionName))) {
7235 // Reject redefinitions.
7236 return error(NameLoc,
7237 "invalid redefinition of function '" + FunctionName + "'");
7238 } else if (M->getNamedValue(FunctionName)) {
7239 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
7240 }
7241
7242 } else {
7243 // Handle @"", where a name is syntactically specified, but semantically
7244 // missing.
7245 if (FunctionNumber == (unsigned)-1)
7246 FunctionNumber = NumberedVals.getNext();
7247
7248 // If this is a definition of a forward referenced function, make sure the
7249 // types agree.
7250 auto I = ForwardRefValIDs.find(FunctionNumber);
7251 if (I != ForwardRefValIDs.end()) {
7252 FwdFn = I->second.first;
7253 if (FwdFn->getType() != PFT)
7254 return error(NameLoc, "type of definition and forward reference of '@" +
7255 Twine(FunctionNumber) +
7256 "' disagree: "
7257 "expected '" +
7258 getTypeString(PFT) + "' but was '" +
7259 getTypeString(FwdFn->getType()) + "'");
7260 ForwardRefValIDs.erase(I);
7261 }
7262 }
7263
7265 FunctionName, M);
7266
7267 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
7268
7269 if (FunctionName.empty())
7270 NumberedVals.add(FunctionNumber, Fn);
7271
7273 maybeSetDSOLocal(DSOLocal, *Fn);
7276 Fn->setCallingConv(CC);
7277 Fn->setAttributes(PAL);
7278 Fn->setUnnamedAddr(UnnamedAddr);
7279 if (Alignment)
7280 Fn->setAlignment(*Alignment);
7281 Fn->setPreferredAlignment(PrefAlignment);
7282 Fn->setSection(Section);
7283 Fn->setPartition(Partition);
7284 Fn->setComdat(C);
7285 Fn->setPersonalityFn(PersonalityFn);
7286 if (!GC.empty()) Fn->setGC(GC);
7287 Fn->setPrefixData(Prefix);
7288 Fn->setPrologueData(Prologue);
7289 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7290
7291 // Add all of the arguments we parsed to the function.
7292 Function::arg_iterator ArgIt = Fn->arg_begin();
7293 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7294 if (ParserContext && ArgList[i].IdentLoc)
7295 ParserContext->addInstructionOrArgumentLocation(
7296 &*ArgIt, ArgList[i].IdentLoc.value());
7297 // If the argument has a name, insert it into the argument symbol table.
7298 if (ArgList[i].Name.empty()) continue;
7299
7300 // Set the name, if it conflicted, it will be auto-renamed.
7301 ArgIt->setName(ArgList[i].Name);
7302
7303 if (ArgIt->getName() != ArgList[i].Name)
7304 return error(ArgList[i].Loc,
7305 "redefinition of argument '%" + ArgList[i].Name + "'");
7306 }
7307
7308 if (FwdFn) {
7309 FwdFn->replaceAllUsesWith(Fn);
7310 FwdFn->eraseFromParent();
7311 }
7312
7313 if (IsDefine)
7314 return false;
7315
7316 // Check the declaration has no block address forward references.
7317 ValID ID;
7318 if (FunctionName.empty()) {
7319 ID.Kind = ValID::t_GlobalID;
7320 ID.UIntVal = FunctionNumber;
7321 } else {
7322 ID.Kind = ValID::t_GlobalName;
7323 ID.StrVal = FunctionName;
7324 }
7325 auto Blocks = ForwardRefBlockAddresses.find(ID);
7326 if (Blocks != ForwardRefBlockAddresses.end())
7327 return error(Blocks->first.Loc,
7328 "cannot take blockaddress inside a declaration");
7329 return false;
7330}
7331
7332bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7333 ValID ID;
7334 if (FunctionNumber == -1) {
7335 ID.Kind = ValID::t_GlobalName;
7336 ID.StrVal = std::string(F.getName());
7337 } else {
7338 ID.Kind = ValID::t_GlobalID;
7339 ID.UIntVal = FunctionNumber;
7340 }
7341
7342 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7343 if (Blocks == P.ForwardRefBlockAddresses.end())
7344 return false;
7345
7346 for (const auto &I : Blocks->second) {
7347 const ValID &BBID = I.first;
7348 GlobalValue *GV = I.second;
7349
7350 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7351 "Expected local id or name");
7352 BasicBlock *BB;
7353 if (BBID.Kind == ValID::t_LocalName)
7354 BB = getBB(BBID.StrVal, BBID.Loc);
7355 else
7356 BB = getBB(BBID.UIntVal, BBID.Loc);
7357 if (!BB)
7358 return P.error(BBID.Loc, "referenced value is not a basic block");
7359
7360 Value *ResolvedVal = BlockAddress::get(&F, BB);
7361 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7362 ResolvedVal);
7363 if (!ResolvedVal)
7364 return true;
7365 GV->replaceAllUsesWith(ResolvedVal);
7366 GV->eraseFromParent();
7367 }
7368
7369 P.ForwardRefBlockAddresses.erase(Blocks);
7370 return false;
7371}
7372
7373/// parseFunctionBody
7374/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7375bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7376 ArrayRef<unsigned> UnnamedArgNums) {
7377 if (Lex.getKind() != lltok::lbrace)
7378 return tokError("expected '{' in function body");
7379 Lex.Lex(); // eat the {.
7380
7381 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7382
7383 // Resolve block addresses and allow basic blocks to be forward-declared
7384 // within this function.
7385 if (PFS.resolveForwardRefBlockAddresses())
7386 return true;
7387 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7388
7389 // We need at least one basic block.
7390 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7391 return tokError("function body requires at least one basic block");
7392
7393 while (Lex.getKind() != lltok::rbrace &&
7394 Lex.getKind() != lltok::kw_uselistorder)
7395 if (parseBasicBlock(PFS))
7396 return true;
7397
7398 while (Lex.getKind() != lltok::rbrace)
7399 if (parseUseListOrder(&PFS))
7400 return true;
7401
7402 // Eat the }.
7403 Lex.Lex();
7404
7405 // Verify function is ok.
7406 return PFS.finishFunction();
7407}
7408
7409/// parseBasicBlock
7410/// ::= (LabelStr|LabelID)? Instruction*
7411bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7412 FileLoc BBStart = getTokLineColumnPos();
7413
7414 // If this basic block starts out with a name, remember it.
7415 std::string Name;
7416 int NameID = -1;
7417 LocTy NameLoc = Lex.getLoc();
7418 if (Lex.getKind() == lltok::LabelStr) {
7419 Name = Lex.getStrVal();
7420 Lex.Lex();
7421 } else if (Lex.getKind() == lltok::LabelID) {
7422 NameID = Lex.getUIntVal();
7423 Lex.Lex();
7424 }
7425
7426 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7427 if (!BB)
7428 return true;
7429
7430 std::string NameStr;
7431
7432 // Parse the instructions and debug values in this block until we get a
7433 // terminator.
7434 Instruction *Inst;
7435 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7436 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7437 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7438 do {
7439 // Handle debug records first - there should always be an instruction
7440 // following the debug records, i.e. they cannot appear after the block
7441 // terminator.
7442 while (Lex.getKind() == lltok::hash) {
7443 if (SeenOldDbgInfoFormat)
7444 return error(Lex.getLoc(), "debug record should not appear in a module "
7445 "containing debug info intrinsics");
7446 SeenNewDbgInfoFormat = true;
7447 Lex.Lex();
7448
7449 DbgRecord *DR;
7450 if (parseDebugRecord(DR, PFS))
7451 return true;
7452 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7453 }
7454
7455 FileLoc InstStart = getTokLineColumnPos();
7456 // This instruction may have three possibilities for a name: a) none
7457 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7458 LocTy NameLoc = Lex.getLoc();
7459 int NameID = -1;
7460 NameStr = "";
7461
7462 if (Lex.getKind() == lltok::LocalVarID) {
7463 NameID = Lex.getUIntVal();
7464 Lex.Lex();
7465 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7466 return true;
7467 } else if (Lex.getKind() == lltok::LocalVar) {
7468 NameStr = Lex.getStrVal();
7469 Lex.Lex();
7470 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7471 return true;
7472 }
7473
7474 switch (parseInstruction(Inst, BB, PFS)) {
7475 default:
7476 llvm_unreachable("Unknown parseInstruction result!");
7477 case InstError: return true;
7478 case InstNormal:
7479 Inst->insertInto(BB, BB->end());
7480
7481 // With a normal result, we check to see if the instruction is followed by
7482 // a comma and metadata.
7483 if (EatIfPresent(lltok::comma))
7484 if (parseInstructionMetadata(*Inst))
7485 return true;
7486 break;
7487 case InstExtraComma:
7488 Inst->insertInto(BB, BB->end());
7489
7490 // If the instruction parser ate an extra comma at the end of it, it
7491 // *must* be followed by metadata.
7492 if (parseInstructionMetadata(*Inst))
7493 return true;
7494 break;
7495 }
7496
7497 // Set the name on the instruction.
7498 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7499 return true;
7500
7501 // Attach any preceding debug values to this instruction.
7502 for (DbgRecordPtr &DR : TrailingDbgRecord)
7503 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7504 TrailingDbgRecord.clear();
7505 if (ParserContext) {
7506 ParserContext->addInstructionOrArgumentLocation(
7507 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7508 }
7509 } while (!Inst->isTerminator());
7510
7511 if (ParserContext)
7512 ParserContext->addBlockLocation(
7513 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7514
7515 assert(TrailingDbgRecord.empty() &&
7516 "All debug values should have been attached to an instruction.");
7517
7518 return false;
7519}
7520
7521/// parseDebugRecord
7522/// ::= #dbg_label '(' MDNode ')'
7523/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7524/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7525bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7526 using RecordKind = DbgRecord::Kind;
7527 using LocType = DbgVariableRecord::LocationType;
7528 LocTy DVRLoc = Lex.getLoc();
7529 if (Lex.getKind() != lltok::DbgRecordType)
7530 return error(DVRLoc, "expected debug record type here");
7531 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7532 .Case("declare", RecordKind::ValueKind)
7533 .Case("value", RecordKind::ValueKind)
7534 .Case("assign", RecordKind::ValueKind)
7535 .Case("label", RecordKind::LabelKind)
7536 .Case("declare_value", RecordKind::ValueKind);
7537
7538 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7539 // full DbgVariableRecord processing stage.
7540 if (RecordType == RecordKind::LabelKind) {
7541 Lex.Lex();
7542 if (parseToken(lltok::lparen, "Expected '(' here"))
7543 return true;
7544 MDNode *Label;
7545 if (parseMDNode(Label))
7546 return true;
7547 if (parseToken(lltok::comma, "Expected ',' here"))
7548 return true;
7549 MDNode *DbgLoc;
7550 if (parseMDNode(DbgLoc))
7551 return true;
7552 if (parseToken(lltok::rparen, "Expected ')' here"))
7553 return true;
7555 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7556 return false;
7557 }
7558
7559 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7560 .Case("declare", LocType::Declare)
7561 .Case("value", LocType::Value)
7562 .Case("assign", LocType::Assign)
7563 .Case("declare_value", LocType::DeclareValue);
7564
7565 Lex.Lex();
7566 if (parseToken(lltok::lparen, "Expected '(' here"))
7567 return true;
7568
7569 // Parse Value field.
7570 Metadata *ValLocMD;
7571 if (parseMetadata(ValLocMD, &PFS))
7572 return true;
7573 if (parseToken(lltok::comma, "Expected ',' here"))
7574 return true;
7575
7576 // Parse Variable field.
7577 MDNode *Variable;
7578 if (parseMDNode(Variable))
7579 return true;
7580 if (parseToken(lltok::comma, "Expected ',' here"))
7581 return true;
7582
7583 // Parse Expression field.
7584 MDNode *Expression;
7585 if (parseMDNode(Expression))
7586 return true;
7587 if (parseToken(lltok::comma, "Expected ',' here"))
7588 return true;
7589
7590 // Parse additional fields for #dbg_assign.
7591 MDNode *AssignID = nullptr;
7592 Metadata *AddressLocation = nullptr;
7593 MDNode *AddressExpression = nullptr;
7594 if (ValueType == LocType::Assign) {
7595 // Parse DIAssignID.
7596 if (parseMDNode(AssignID))
7597 return true;
7598 if (parseToken(lltok::comma, "Expected ',' here"))
7599 return true;
7600
7601 // Parse address ValueAsMetadata.
7602 if (parseMetadata(AddressLocation, &PFS))
7603 return true;
7604 if (parseToken(lltok::comma, "Expected ',' here"))
7605 return true;
7606
7607 // Parse address DIExpression.
7608 if (parseMDNode(AddressExpression))
7609 return true;
7610 if (parseToken(lltok::comma, "Expected ',' here"))
7611 return true;
7612 }
7613
7614 /// Parse DILocation.
7615 MDNode *DebugLoc;
7616 if (parseMDNode(DebugLoc))
7617 return true;
7618
7619 if (parseToken(lltok::rparen, "Expected ')' here"))
7620 return true;
7622 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7623 AddressExpression);
7624 PendingDbgRecords.emplace_back(DVRLoc, DR, DebugLoc);
7625 return false;
7626}
7627//===----------------------------------------------------------------------===//
7628// Instruction Parsing.
7629//===----------------------------------------------------------------------===//
7630
7631/// parseInstruction - parse one of the many different instructions.
7632///
7633int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7634 PerFunctionState &PFS) {
7635 lltok::Kind Token = Lex.getKind();
7636 if (Token == lltok::Eof)
7637 return tokError("found end of file when expecting more instructions");
7638 LocTy Loc = Lex.getLoc();
7639 unsigned KeywordVal = Lex.getUIntVal();
7640 Lex.Lex(); // Eat the keyword.
7641
7642 switch (Token) {
7643 default:
7644 return error(Loc, "expected instruction opcode");
7645 // Terminator Instructions.
7646 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7647 case lltok::kw_ret:
7648 return parseRet(Inst, BB, PFS);
7649 case lltok::kw_br:
7650 return parseBr(Inst, PFS);
7651 case lltok::kw_switch:
7652 return parseSwitch(Inst, PFS);
7654 return parseIndirectBr(Inst, PFS);
7655 case lltok::kw_invoke:
7656 return parseInvoke(Inst, PFS);
7657 case lltok::kw_resume:
7658 return parseResume(Inst, PFS);
7660 return parseCleanupRet(Inst, PFS);
7661 case lltok::kw_catchret:
7662 return parseCatchRet(Inst, PFS);
7664 return parseCatchSwitch(Inst, PFS);
7665 case lltok::kw_catchpad:
7666 return parseCatchPad(Inst, PFS);
7668 return parseCleanupPad(Inst, PFS);
7669 case lltok::kw_callbr:
7670 return parseCallBr(Inst, PFS);
7671 // Unary Operators.
7672 case lltok::kw_fneg: {
7673 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7674 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7675 if (Res != 0)
7676 return Res;
7677 if (FMF.any())
7678 Inst->setFastMathFlags(FMF);
7679 return false;
7680 }
7681 // Binary Operators.
7682 case lltok::kw_add:
7683 case lltok::kw_sub:
7684 case lltok::kw_mul:
7685 case lltok::kw_shl: {
7686 bool NUW = EatIfPresent(lltok::kw_nuw);
7687 bool NSW = EatIfPresent(lltok::kw_nsw);
7688 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7689
7690 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7691 return true;
7692
7693 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7694 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7695 return false;
7696 }
7697 case lltok::kw_fadd:
7698 case lltok::kw_fsub:
7699 case lltok::kw_fmul:
7700 case lltok::kw_fdiv:
7701 case lltok::kw_frem: {
7702 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7703 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7704 if (Res != 0)
7705 return Res;
7706 if (FMF.any())
7707 Inst->setFastMathFlags(FMF);
7708 return 0;
7709 }
7710
7711 case lltok::kw_sdiv:
7712 case lltok::kw_udiv:
7713 case lltok::kw_lshr:
7714 case lltok::kw_ashr: {
7715 bool Exact = EatIfPresent(lltok::kw_exact);
7716
7717 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7718 return true;
7719 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7720 return false;
7721 }
7722
7723 case lltok::kw_urem:
7724 case lltok::kw_srem:
7725 return parseArithmetic(Inst, PFS, KeywordVal,
7726 /*IsFP*/ false);
7727 case lltok::kw_or: {
7728 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7729 if (parseLogical(Inst, PFS, KeywordVal))
7730 return true;
7731 if (Disjoint)
7732 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7733 return false;
7734 }
7735 case lltok::kw_and:
7736 case lltok::kw_xor:
7737 return parseLogical(Inst, PFS, KeywordVal);
7738 case lltok::kw_icmp: {
7739 bool SameSign = EatIfPresent(lltok::kw_samesign);
7740 if (parseCompare(Inst, PFS, KeywordVal))
7741 return true;
7742 if (SameSign)
7743 cast<ICmpInst>(Inst)->setSameSign();
7744 return false;
7745 }
7746 case lltok::kw_fcmp: {
7747 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7748 int Res = parseCompare(Inst, PFS, KeywordVal);
7749 if (Res != 0)
7750 return Res;
7751 if (FMF.any())
7752 Inst->setFastMathFlags(FMF);
7753 return 0;
7754 }
7755
7756 // Casts.
7757 case lltok::kw_uitofp: {
7758 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7759 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7760 bool Res = parseCast(Inst, PFS, KeywordVal);
7761 if (Res != 0)
7762 return Res;
7763 if (NonNeg)
7764 Inst->setNonNeg();
7765 Inst->setFastMathFlags(FMF);
7766 return 0;
7767 }
7768 case lltok::kw_zext: {
7769 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7770 bool Res = parseCast(Inst, PFS, KeywordVal);
7771 if (Res != 0)
7772 return Res;
7773 if (NonNeg)
7774 Inst->setNonNeg();
7775 return 0;
7776 }
7777 case lltok::kw_trunc: {
7778 bool NUW = EatIfPresent(lltok::kw_nuw);
7779 bool NSW = EatIfPresent(lltok::kw_nsw);
7780 if (!NUW)
7781 NUW = EatIfPresent(lltok::kw_nuw);
7782 if (parseCast(Inst, PFS, KeywordVal))
7783 return true;
7784 if (NUW)
7785 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7786 if (NSW)
7787 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7788 return false;
7789 }
7790 case lltok::kw_sext:
7791 case lltok::kw_bitcast:
7793 case lltok::kw_fptoui:
7794 case lltok::kw_fptosi:
7795 case lltok::kw_inttoptr:
7797 case lltok::kw_ptrtoint:
7798 return parseCast(Inst, PFS, KeywordVal);
7799 case lltok::kw_fptrunc:
7800 case lltok::kw_fpext:
7801 case lltok::kw_sitofp: {
7802 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7803 if (parseCast(Inst, PFS, KeywordVal))
7804 return true;
7805 if (FMF.any())
7806 Inst->setFastMathFlags(FMF);
7807 return false;
7808 }
7809
7810 // Other.
7811 case lltok::kw_select: {
7812 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7813 int Res = parseSelect(Inst, PFS);
7814 if (Res != 0)
7815 return Res;
7816 if (FMF.any()) {
7817 if (!isa<FPMathOperator>(Inst)) {
7818 Inst->deleteValue();
7819 return error(Loc, "fast-math-flags specified for select without "
7820 "floating-point scalar or vector return type");
7821 }
7822 Inst->setFastMathFlags(FMF);
7823 }
7824 return 0;
7825 }
7826 case lltok::kw_va_arg:
7827 return parseVAArg(Inst, PFS);
7829 return parseExtractElement(Inst, PFS);
7831 return parseInsertElement(Inst, PFS);
7833 return parseShuffleVector(Inst, PFS);
7834 case lltok::kw_phi: {
7835 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7836 int Res = parsePHI(Inst, PFS);
7837 if (Res != 0)
7838 return Res;
7839 if (FMF.any()) {
7840 if (!isa<FPMathOperator>(Inst)) {
7841 Inst->deleteValue();
7842 return error(Loc, "fast-math-flags specified for phi without "
7843 "floating-point scalar or vector return type");
7844 }
7845 Inst->setFastMathFlags(FMF);
7846 }
7847 return 0;
7848 }
7850 return parseLandingPad(Inst, PFS);
7851 case lltok::kw_freeze:
7852 return parseFreeze(Inst, PFS);
7853 // Call.
7854 case lltok::kw_call:
7855 return parseCall(Inst, PFS, CallInst::TCK_None);
7856 case lltok::kw_tail:
7857 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7858 case lltok::kw_musttail:
7859 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7860 case lltok::kw_notail:
7861 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7862 // Memory.
7863 case lltok::kw_alloca:
7864 return parseAlloc(Inst, PFS);
7865 case lltok::kw_load:
7866 return parseLoad(Inst, PFS);
7867 case lltok::kw_store:
7868 return parseStore(Inst, PFS);
7869 case lltok::kw_cmpxchg:
7870 return parseCmpXchg(Inst, PFS);
7872 return parseAtomicRMW(Inst, PFS);
7873 case lltok::kw_fence:
7874 return parseFence(Inst, PFS);
7876 return parseGetElementPtr(Inst, PFS);
7878 return parseExtractValue(Inst, PFS);
7880 return parseInsertValue(Inst, PFS);
7881 }
7882}
7883
7884/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7885bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7886 if (Opc == Instruction::FCmp) {
7887 switch (Lex.getKind()) {
7888 default:
7889 return tokError("expected fcmp predicate (e.g. 'oeq')");
7890 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7891 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7892 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7893 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7894 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7895 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7896 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7897 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7898 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7899 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7900 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7901 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7902 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7903 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7904 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7905 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7906 }
7907 } else {
7908 switch (Lex.getKind()) {
7909 default:
7910 return tokError("expected icmp predicate (e.g. 'eq')");
7911 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7912 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7913 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7914 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7915 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7916 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7917 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7918 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7919 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7920 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7921 }
7922 }
7923 Lex.Lex();
7924 return false;
7925}
7926
7927//===----------------------------------------------------------------------===//
7928// Terminator Instructions.
7929//===----------------------------------------------------------------------===//
7930
7931/// parseRet - parse a return instruction.
7932/// ::= 'ret' void (',' !dbg, !1)*
7933/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7934bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7935 PerFunctionState &PFS) {
7936 SMLoc TypeLoc = Lex.getLoc();
7937 Type *Ty = nullptr;
7938 if (parseType(Ty, true /*void allowed*/))
7939 return true;
7940
7941 Type *ResType = PFS.getFunction().getReturnType();
7942
7943 if (Ty->isVoidTy()) {
7944 if (!ResType->isVoidTy())
7945 return error(TypeLoc, "value doesn't match function result type '" +
7946 getTypeString(ResType) + "'");
7947
7948 Inst = ReturnInst::Create(Context);
7949 return false;
7950 }
7951
7952 Value *RV;
7953 if (parseValue(Ty, RV, PFS))
7954 return true;
7955
7956 if (ResType != RV->getType())
7957 return error(TypeLoc, "value doesn't match function result type '" +
7958 getTypeString(ResType) + "'");
7959
7960 Inst = ReturnInst::Create(Context, RV);
7961 return false;
7962}
7963
7964/// parseBr
7965/// ::= 'br' TypeAndValue
7966/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7967bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7968 LocTy Loc, Loc2;
7969 Value *Op0;
7970 BasicBlock *Op1, *Op2;
7971 if (parseTypeAndValue(Op0, Loc, PFS))
7972 return true;
7973
7974 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7975 Inst = UncondBrInst::Create(BB);
7976 return false;
7977 }
7978
7979 if (Op0->getType() != Type::getInt1Ty(Context))
7980 return error(Loc, "branch condition must have 'i1' type");
7981
7982 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7983 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7984 parseToken(lltok::comma, "expected ',' after true destination") ||
7985 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7986 return true;
7987
7988 Inst = CondBrInst::Create(Op0, Op1, Op2);
7989 return false;
7990}
7991
7992/// parseSwitch
7993/// Instruction
7994/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7995/// JumpTable
7996/// ::= (TypeAndValue ',' TypeAndValue)*
7997bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7998 LocTy CondLoc, BBLoc;
7999 Value *Cond;
8000 BasicBlock *DefaultBB;
8001 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
8002 parseToken(lltok::comma, "expected ',' after switch condition") ||
8003 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
8004 parseToken(lltok::lsquare, "expected '[' with switch table"))
8005 return true;
8006
8007 if (!Cond->getType()->isIntegerTy())
8008 return error(CondLoc, "switch condition must have integer type");
8009
8010 // parse the jump table pairs.
8011 SmallPtrSet<Value*, 32> SeenCases;
8013 while (Lex.getKind() != lltok::rsquare) {
8014 Value *Constant;
8015 BasicBlock *DestBB;
8016
8017 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8018 parseToken(lltok::comma, "expected ',' after case value") ||
8019 parseTypeAndBasicBlock(DestBB, PFS))
8020 return true;
8021
8022 if (!SeenCases.insert(Constant).second)
8023 return error(CondLoc, "duplicate case value in switch");
8024 if (!isa<ConstantInt>(Constant))
8025 return error(CondLoc, "case value is not a constant integer");
8026
8027 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
8028 }
8029
8030 Lex.Lex(); // Eat the ']'.
8031
8032 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
8033 for (const auto &[OnVal, Dest] : Table)
8034 SI->addCase(OnVal, Dest);
8035 Inst = SI;
8036 return false;
8037}
8038
8039/// parseIndirectBr
8040/// Instruction
8041/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
8042bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8043 LocTy AddrLoc;
8044 Value *Address;
8045 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
8046 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
8047 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
8048 return true;
8049
8050 if (!Address->getType()->isPointerTy())
8051 return error(AddrLoc, "indirectbr address must have pointer type");
8052
8053 // parse the destination list.
8054 SmallVector<BasicBlock*, 16> DestList;
8055
8056 if (Lex.getKind() != lltok::rsquare) {
8057 BasicBlock *DestBB;
8058 if (parseTypeAndBasicBlock(DestBB, PFS))
8059 return true;
8060 DestList.push_back(DestBB);
8061
8062 while (EatIfPresent(lltok::comma)) {
8063 if (parseTypeAndBasicBlock(DestBB, PFS))
8064 return true;
8065 DestList.push_back(DestBB);
8066 }
8067 }
8068
8069 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8070 return true;
8071
8072 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
8073 for (BasicBlock *Dest : DestList)
8074 IBI->addDestination(Dest);
8075 Inst = IBI;
8076 return false;
8077}
8078
8079// If RetType is a non-function pointer type, then this is the short syntax
8080// for the call, which means that RetType is just the return type. Infer the
8081// rest of the function argument types from the arguments that are present.
8082bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
8083 FunctionType *&FuncTy) {
8084 FuncTy = dyn_cast<FunctionType>(RetType);
8085 if (!FuncTy) {
8086 // Pull out the types of all of the arguments...
8087 SmallVector<Type *, 8> ParamTypes;
8088 ParamTypes.reserve(ArgList.size());
8089 for (const ParamInfo &Arg : ArgList)
8090 ParamTypes.push_back(Arg.V->getType());
8091
8092 if (!FunctionType::isValidReturnType(RetType))
8093 return true;
8094
8095 FuncTy = FunctionType::get(RetType, ParamTypes, false);
8096 }
8097 return false;
8098}
8099
8100/// parseInvoke
8101/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
8102/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
8103bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8104 LocTy CallLoc = Lex.getLoc();
8105 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8106 std::vector<unsigned> FwdRefAttrGrps;
8107 LocTy NoBuiltinLoc;
8108 unsigned CC;
8109 unsigned InvokeAddrSpace;
8110 Type *RetType = nullptr;
8111 LocTy RetTypeLoc;
8112 ValID CalleeID;
8115
8116 BasicBlock *NormalBB, *UnwindBB;
8117 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8118 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8119 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8120 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8121 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8122 NoBuiltinLoc) ||
8123 parseOptionalOperandBundles(BundleList, PFS) ||
8124 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
8125 parseTypeAndBasicBlock(NormalBB, PFS) ||
8126 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
8127 parseTypeAndBasicBlock(UnwindBB, PFS))
8128 return true;
8129
8130 // If RetType is a non-function pointer type, then this is the short syntax
8131 // for the call, which means that RetType is just the return type. Infer the
8132 // rest of the function argument types from the arguments that are present.
8133 FunctionType *Ty;
8134 if (resolveFunctionType(RetType, ArgList, Ty))
8135 return error(RetTypeLoc, "Invalid result type for LLVM function");
8136
8137 CalleeID.FTy = Ty;
8138
8139 // Look up the callee.
8140 Value *Callee;
8141 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
8142 Callee, &PFS))
8143 return true;
8144
8145 // Set up the Attribute for the function.
8146 SmallVector<Value *, 8> Args;
8148
8149 // Loop through FunctionType's arguments and ensure they are specified
8150 // correctly. Also, gather any parameter attributes.
8151 FunctionType::param_iterator I = Ty->param_begin();
8152 FunctionType::param_iterator E = Ty->param_end();
8153 for (const ParamInfo &Arg : ArgList) {
8154 Type *ExpectedTy = nullptr;
8155 if (I != E) {
8156 ExpectedTy = *I++;
8157 } else if (!Ty->isVarArg()) {
8158 return error(Arg.Loc, "too many arguments specified");
8159 }
8160
8161 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8162 return error(Arg.Loc, "argument is not of expected type '" +
8163 getTypeString(ExpectedTy) + "'");
8164 Args.push_back(Arg.V);
8165 ArgAttrs.push_back(Arg.Attrs);
8166 }
8167
8168 if (I != E)
8169 return error(CallLoc, "not enough parameters specified for call");
8170
8171 // Finish off the Attribute and check them
8172 AttributeList PAL =
8173 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8174 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8175
8176 InvokeInst *II =
8177 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
8178 II->setCallingConv(CC);
8179 II->setAttributes(PAL);
8180 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
8181 Inst = II;
8182 return false;
8183}
8184
8185/// parseResume
8186/// ::= 'resume' TypeAndValue
8187bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8188 Value *Exn; LocTy ExnLoc;
8189 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8190 return true;
8191
8192 ResumeInst *RI = ResumeInst::Create(Exn);
8193 Inst = RI;
8194 return false;
8195}
8196
8197bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8198 PerFunctionState &PFS) {
8199 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
8200 return true;
8201
8202 while (Lex.getKind() != lltok::rsquare) {
8203 // If this isn't the first argument, we need a comma.
8204 if (!Args.empty() &&
8205 parseToken(lltok::comma, "expected ',' in argument list"))
8206 return true;
8207
8208 // parse the argument.
8209 LocTy ArgLoc;
8210 Type *ArgTy = nullptr;
8211 if (parseType(ArgTy, ArgLoc))
8212 return true;
8213
8214 Value *V;
8215 if (ArgTy->isMetadataTy()) {
8216 if (parseMetadataAsValue(V, PFS))
8217 return true;
8218 } else {
8219 if (parseValue(ArgTy, V, PFS))
8220 return true;
8221 }
8222 Args.push_back(V);
8223 }
8224
8225 Lex.Lex(); // Lex the ']'.
8226 return false;
8227}
8228
8229/// parseCleanupRet
8230/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
8231bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8232 Value *CleanupPad = nullptr;
8233
8234 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
8235 return true;
8236
8237 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
8238 return true;
8239
8240 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
8241 return true;
8242
8243 BasicBlock *UnwindBB = nullptr;
8244 if (Lex.getKind() == lltok::kw_to) {
8245 Lex.Lex();
8246 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
8247 return true;
8248 } else {
8249 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8250 return true;
8251 }
8252 }
8253
8254 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
8255 return false;
8256}
8257
8258/// parseCatchRet
8259/// ::= 'catchret' from Parent Value 'to' TypeAndValue
8260bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8261 Value *CatchPad = nullptr;
8262
8263 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
8264 return true;
8265
8266 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
8267 return true;
8268
8269 BasicBlock *BB;
8270 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
8271 parseTypeAndBasicBlock(BB, PFS))
8272 return true;
8273
8274 Inst = CatchReturnInst::Create(CatchPad, BB);
8275 return false;
8276}
8277
8278/// parseCatchSwitch
8279/// ::= 'catchswitch' within Parent
8280bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8281 Value *ParentPad;
8282
8283 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
8284 return true;
8285
8286 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8287 Lex.getKind() != lltok::LocalVarID)
8288 return tokError("expected scope value for catchswitch");
8289
8290 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8291 return true;
8292
8293 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
8294 return true;
8295
8297 do {
8298 BasicBlock *DestBB;
8299 if (parseTypeAndBasicBlock(DestBB, PFS))
8300 return true;
8301 Table.push_back(DestBB);
8302 } while (EatIfPresent(lltok::comma));
8303
8304 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
8305 return true;
8306
8307 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
8308 return true;
8309
8310 BasicBlock *UnwindBB = nullptr;
8311 if (EatIfPresent(lltok::kw_to)) {
8312 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
8313 return true;
8314 } else {
8315 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8316 return true;
8317 }
8318
8319 auto *CatchSwitch =
8320 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
8321 for (BasicBlock *DestBB : Table)
8322 CatchSwitch->addHandler(DestBB);
8323 Inst = CatchSwitch;
8324 return false;
8325}
8326
8327/// parseCatchPad
8328/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
8329bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8330 Value *CatchSwitch = nullptr;
8331
8332 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
8333 return true;
8334
8335 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
8336 return tokError("expected scope value for catchpad");
8337
8338 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
8339 return true;
8340
8341 SmallVector<Value *, 8> Args;
8342 if (parseExceptionArgs(Args, PFS))
8343 return true;
8344
8345 Inst = CatchPadInst::Create(CatchSwitch, Args);
8346 return false;
8347}
8348
8349/// parseCleanupPad
8350/// ::= 'cleanuppad' within Parent ParamList
8351bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8352 Value *ParentPad = nullptr;
8353
8354 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
8355 return true;
8356
8357 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8358 Lex.getKind() != lltok::LocalVarID)
8359 return tokError("expected scope value for cleanuppad");
8360
8361 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8362 return true;
8363
8364 SmallVector<Value *, 8> Args;
8365 if (parseExceptionArgs(Args, PFS))
8366 return true;
8367
8368 Inst = CleanupPadInst::Create(ParentPad, Args);
8369 return false;
8370}
8371
8372//===----------------------------------------------------------------------===//
8373// Unary Operators.
8374//===----------------------------------------------------------------------===//
8375
8376/// parseUnaryOp
8377/// ::= UnaryOp TypeAndValue ',' Value
8378///
8379/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8380/// operand is allowed.
8381bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8382 unsigned Opc, bool IsFP) {
8383 LocTy Loc; Value *LHS;
8384 if (parseTypeAndValue(LHS, Loc, PFS))
8385 return true;
8386
8387 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8389
8390 if (!Valid)
8391 return error(Loc, "invalid operand type for instruction");
8392
8394 return false;
8395}
8396
8397/// parseCallBr
8398/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8399/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8400/// '[' LabelList ']'
8401bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8402 LocTy CallLoc = Lex.getLoc();
8403 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8404 std::vector<unsigned> FwdRefAttrGrps;
8405 LocTy NoBuiltinLoc;
8406 unsigned CC;
8407 Type *RetType = nullptr;
8408 LocTy RetTypeLoc;
8409 ValID CalleeID;
8412
8413 BasicBlock *DefaultDest;
8414 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8415 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8416 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8417 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8418 NoBuiltinLoc) ||
8419 parseOptionalOperandBundles(BundleList, PFS) ||
8420 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8421 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8422 parseToken(lltok::lsquare, "expected '[' in callbr"))
8423 return true;
8424
8425 // parse the destination list.
8426 SmallVector<BasicBlock *, 16> IndirectDests;
8427
8428 if (Lex.getKind() != lltok::rsquare) {
8429 BasicBlock *DestBB;
8430 if (parseTypeAndBasicBlock(DestBB, PFS))
8431 return true;
8432 IndirectDests.push_back(DestBB);
8433
8434 while (EatIfPresent(lltok::comma)) {
8435 if (parseTypeAndBasicBlock(DestBB, PFS))
8436 return true;
8437 IndirectDests.push_back(DestBB);
8438 }
8439 }
8440
8441 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8442 return true;
8443
8444 // If RetType is a non-function pointer type, then this is the short syntax
8445 // for the call, which means that RetType is just the return type. Infer the
8446 // rest of the function argument types from the arguments that are present.
8447 FunctionType *Ty;
8448 if (resolveFunctionType(RetType, ArgList, Ty))
8449 return error(RetTypeLoc, "Invalid result type for LLVM function");
8450
8451 CalleeID.FTy = Ty;
8452
8453 // Look up the callee.
8454 Value *Callee;
8455 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8456 &PFS))
8457 return true;
8458
8459 // Set up the Attribute for the function.
8460 SmallVector<Value *, 8> Args;
8462
8463 // Loop through FunctionType's arguments and ensure they are specified
8464 // correctly. Also, gather any parameter attributes.
8465 FunctionType::param_iterator I = Ty->param_begin();
8466 FunctionType::param_iterator E = Ty->param_end();
8467 for (const ParamInfo &Arg : ArgList) {
8468 Type *ExpectedTy = nullptr;
8469 if (I != E) {
8470 ExpectedTy = *I++;
8471 } else if (!Ty->isVarArg()) {
8472 return error(Arg.Loc, "too many arguments specified");
8473 }
8474
8475 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8476 return error(Arg.Loc, "argument is not of expected type '" +
8477 getTypeString(ExpectedTy) + "'");
8478 Args.push_back(Arg.V);
8479 ArgAttrs.push_back(Arg.Attrs);
8480 }
8481
8482 if (I != E)
8483 return error(CallLoc, "not enough parameters specified for call");
8484
8485 // Finish off the Attribute and check them
8486 AttributeList PAL =
8487 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8488 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8489
8490 CallBrInst *CBI =
8491 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8492 BundleList);
8493 CBI->setCallingConv(CC);
8494 CBI->setAttributes(PAL);
8495 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8496 Inst = CBI;
8497 return false;
8498}
8499
8500//===----------------------------------------------------------------------===//
8501// Binary Operators.
8502//===----------------------------------------------------------------------===//
8503
8504/// parseArithmetic
8505/// ::= ArithmeticOps TypeAndValue ',' Value
8506///
8507/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8508/// operand is allowed.
8509bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8510 unsigned Opc, bool IsFP) {
8511 LocTy Loc; Value *LHS, *RHS;
8512 if (parseTypeAndValue(LHS, Loc, PFS) ||
8513 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8514 parseValue(LHS->getType(), RHS, PFS))
8515 return true;
8516
8517 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8519
8520 if (!Valid)
8521 return error(Loc, "invalid operand type for instruction");
8522
8524 return false;
8525}
8526
8527/// parseLogical
8528/// ::= ArithmeticOps TypeAndValue ',' Value {
8529bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8530 unsigned Opc) {
8531 LocTy Loc; Value *LHS, *RHS;
8532 if (parseTypeAndValue(LHS, Loc, PFS) ||
8533 parseToken(lltok::comma, "expected ',' in logical operation") ||
8534 parseValue(LHS->getType(), RHS, PFS))
8535 return true;
8536
8537 if (!LHS->getType()->isIntOrIntVectorTy())
8538 return error(Loc,
8539 "instruction requires integer or integer vector operands");
8540
8542 return false;
8543}
8544
8545/// parseCompare
8546/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8547/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8548bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8549 unsigned Opc) {
8550 // parse the integer/fp comparison predicate.
8551 LocTy Loc;
8552 unsigned Pred;
8553 Value *LHS, *RHS;
8554 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8555 parseToken(lltok::comma, "expected ',' after compare value") ||
8556 parseValue(LHS->getType(), RHS, PFS))
8557 return true;
8558
8559 if (Opc == Instruction::FCmp) {
8560 if (!LHS->getType()->isFPOrFPVectorTy())
8561 return error(Loc, "fcmp requires floating point operands");
8562 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8563 } else {
8564 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8565 if (!LHS->getType()->isIntOrIntVectorTy() &&
8567 return error(Loc, "icmp requires integer operands");
8568 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8569 }
8570 return false;
8571}
8572
8573//===----------------------------------------------------------------------===//
8574// Other Instructions.
8575//===----------------------------------------------------------------------===//
8576
8577/// parseCast
8578/// ::= CastOpc TypeAndValue 'to' Type
8579bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8580 unsigned Opc) {
8581 LocTy Loc;
8582 Value *Op;
8583 Type *DestTy = nullptr;
8584 if (parseTypeAndValue(Op, Loc, PFS) ||
8585 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8586 parseType(DestTy))
8587 return true;
8588
8590 return error(Loc, "invalid cast opcode for cast from '" +
8591 getTypeString(Op->getType()) + "' to '" +
8592 getTypeString(DestTy) + "'");
8593 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8594 return false;
8595}
8596
8597/// parseSelect
8598/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8599bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8600 LocTy Loc;
8601 Value *Op0, *Op1, *Op2;
8602 if (parseTypeAndValue(Op0, Loc, PFS) ||
8603 parseToken(lltok::comma, "expected ',' after select condition") ||
8604 parseTypeAndValue(Op1, PFS) ||
8605 parseToken(lltok::comma, "expected ',' after select value") ||
8606 parseTypeAndValue(Op2, PFS))
8607 return true;
8608
8609 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8610 return error(Loc, Reason);
8611
8612 Inst = SelectInst::Create(Op0, Op1, Op2);
8613 return false;
8614}
8615
8616/// parseVAArg
8617/// ::= 'va_arg' TypeAndValue ',' Type
8618bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8619 Value *Op;
8620 Type *EltTy = nullptr;
8621 LocTy TypeLoc;
8622 if (parseTypeAndValue(Op, PFS) ||
8623 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8624 parseType(EltTy, TypeLoc))
8625 return true;
8626
8627 if (!EltTy->isFirstClassType())
8628 return error(TypeLoc, "va_arg requires operand with first class type");
8629
8630 Inst = new VAArgInst(Op, EltTy);
8631 return false;
8632}
8633
8634/// parseExtractElement
8635/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8636bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8637 LocTy Loc;
8638 Value *Op0, *Op1;
8639 if (parseTypeAndValue(Op0, Loc, PFS) ||
8640 parseToken(lltok::comma, "expected ',' after extract value") ||
8641 parseTypeAndValue(Op1, PFS))
8642 return true;
8643
8645 return error(Loc, "invalid extractelement operands");
8646
8647 Inst = ExtractElementInst::Create(Op0, Op1);
8648 return false;
8649}
8650
8651/// parseInsertElement
8652/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8653bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8654 LocTy Loc;
8655 Value *Op0, *Op1, *Op2;
8656 if (parseTypeAndValue(Op0, Loc, PFS) ||
8657 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8658 parseTypeAndValue(Op1, PFS) ||
8659 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8660 parseTypeAndValue(Op2, PFS))
8661 return true;
8662
8663 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8664 return error(Loc, "invalid insertelement operands");
8665
8666 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8667 return false;
8668}
8669
8670/// parseShuffleVector
8671/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8672bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8673 LocTy Loc;
8674 Value *Op0, *Op1, *Op2;
8675 if (parseTypeAndValue(Op0, Loc, PFS) ||
8676 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8677 parseTypeAndValue(Op1, PFS) ||
8678 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8679 parseTypeAndValue(Op2, PFS))
8680 return true;
8681
8682 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8683 return error(Loc, "invalid shufflevector operands");
8684
8685 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8686 return false;
8687}
8688
8689/// parsePHI
8690/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8691int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8692 Type *Ty = nullptr; LocTy TypeLoc;
8693 Value *Op0, *Op1;
8694
8695 if (parseType(Ty, TypeLoc))
8696 return true;
8697
8698 if (!Ty->isFirstClassType())
8699 return error(TypeLoc, "phi node must have first class type");
8700
8701 bool First = true;
8702 bool AteExtraComma = false;
8704
8705 while (true) {
8706 if (First) {
8707 if (Lex.getKind() != lltok::lsquare)
8708 break;
8709 First = false;
8710 } else if (!EatIfPresent(lltok::comma))
8711 break;
8712
8713 if (Lex.getKind() == lltok::MetadataVar) {
8714 AteExtraComma = true;
8715 break;
8716 }
8717
8718 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8719 parseValue(Ty, Op0, PFS) ||
8720 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8721 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8722 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8723 return true;
8724
8725 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8726 }
8727
8728 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8729 for (const auto &[Val, BB] : PHIVals)
8730 PN->addIncoming(Val, BB);
8731 Inst = PN;
8732 return AteExtraComma ? InstExtraComma : InstNormal;
8733}
8734
8735/// parseLandingPad
8736/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8737/// Clause
8738/// ::= 'catch' TypeAndValue
8739/// ::= 'filter'
8740/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8741bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8742 Type *Ty = nullptr; LocTy TyLoc;
8743
8744 if (parseType(Ty, TyLoc))
8745 return true;
8746
8747 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8748 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8749
8750 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8752 if (EatIfPresent(lltok::kw_catch))
8754 else if (EatIfPresent(lltok::kw_filter))
8756 else
8757 return tokError("expected 'catch' or 'filter' clause type");
8758
8759 Value *V;
8760 LocTy VLoc;
8761 if (parseTypeAndValue(V, VLoc, PFS))
8762 return true;
8763
8764 // A 'catch' type expects a non-array constant. A filter clause expects an
8765 // array constant.
8766 if (CT == LandingPadInst::Catch) {
8767 if (isa<ArrayType>(V->getType()))
8768 return error(VLoc, "'catch' clause has an invalid type");
8769 } else {
8770 if (!isa<ArrayType>(V->getType()))
8771 return error(VLoc, "'filter' clause has an invalid type");
8772 }
8773
8775 if (!CV)
8776 return error(VLoc, "clause argument must be a constant");
8777 LP->addClause(CV);
8778 }
8779
8780 Inst = LP.release();
8781 return false;
8782}
8783
8784/// parseFreeze
8785/// ::= 'freeze' Type Value
8786bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8787 LocTy Loc;
8788 Value *Op;
8789 if (parseTypeAndValue(Op, Loc, PFS))
8790 return true;
8791
8792 Inst = new FreezeInst(Op);
8793 return false;
8794}
8795
8796/// parseCall
8797/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8798/// OptionalAttrs Type Value ParameterList OptionalAttrs
8799/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8800/// OptionalAttrs Type Value ParameterList OptionalAttrs
8801/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8802/// OptionalAttrs Type Value ParameterList OptionalAttrs
8803/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8804/// OptionalAttrs Type Value ParameterList OptionalAttrs
8805bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8807 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8808 std::vector<unsigned> FwdRefAttrGrps;
8809 LocTy BuiltinLoc;
8810 unsigned CallAddrSpace;
8811 unsigned CC;
8812 Type *RetType = nullptr;
8813 LocTy RetTypeLoc;
8814 ValID CalleeID;
8817 LocTy CallLoc = Lex.getLoc();
8818
8819 if (TCK != CallInst::TCK_None &&
8820 parseToken(lltok::kw_call,
8821 "expected 'tail call', 'musttail call', or 'notail call'"))
8822 return true;
8823
8824 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8825
8826 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8827 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8828 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8829 parseValID(CalleeID, &PFS) ||
8830 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8831 PFS.getFunction().isVarArg()) ||
8832 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8833 parseOptionalOperandBundles(BundleList, PFS))
8834 return true;
8835
8836 // If RetType is a non-function pointer type, then this is the short syntax
8837 // for the call, which means that RetType is just the return type. Infer the
8838 // rest of the function argument types from the arguments that are present.
8839 FunctionType *Ty;
8840 if (resolveFunctionType(RetType, ArgList, Ty))
8841 return error(RetTypeLoc, "Invalid result type for LLVM function");
8842
8843 CalleeID.FTy = Ty;
8844
8845 // Look up the callee.
8846 Value *Callee;
8847 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8848 Callee, &PFS))
8849 return true;
8850
8851 // Set up the Attribute for the function.
8853
8854 SmallVector<Value*, 8> Args;
8855
8856 // Loop through FunctionType's arguments and ensure they are specified
8857 // correctly. Also, gather any parameter attributes.
8858 FunctionType::param_iterator I = Ty->param_begin();
8859 FunctionType::param_iterator E = Ty->param_end();
8860 for (const ParamInfo &Arg : ArgList) {
8861 Type *ExpectedTy = nullptr;
8862 if (I != E) {
8863 ExpectedTy = *I++;
8864 } else if (!Ty->isVarArg()) {
8865 return error(Arg.Loc, "too many arguments specified");
8866 }
8867
8868 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8869 return error(Arg.Loc, "argument is not of expected type '" +
8870 getTypeString(ExpectedTy) + "'");
8871 Args.push_back(Arg.V);
8872 Attrs.push_back(Arg.Attrs);
8873 }
8874
8875 if (I != E)
8876 return error(CallLoc, "not enough parameters specified for call");
8877
8878 // Finish off the Attribute and check them
8879 AttributeList PAL =
8880 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8881 AttributeSet::get(Context, RetAttrs), Attrs);
8882
8883 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8884 CI->setTailCallKind(TCK);
8885 CI->setCallingConv(CC);
8886 if (FMF.any()) {
8887 if (!isa<FPMathOperator>(CI)) {
8888 CI->deleteValue();
8889 return error(CallLoc, "fast-math-flags specified for call without "
8890 "floating-point scalar or vector return type");
8891 }
8892 CI->setFastMathFlags(FMF);
8893 }
8894
8895 if (CalleeID.Kind == ValID::t_GlobalName &&
8896 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8897 if (SeenNewDbgInfoFormat) {
8898 CI->deleteValue();
8899 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8900 "using non-intrinsic debug info");
8901 }
8902 SeenOldDbgInfoFormat = true;
8903 }
8904 CI->setAttributes(PAL);
8905 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8906 Inst = CI;
8907 return false;
8908}
8909
8910//===----------------------------------------------------------------------===//
8911// Memory Instructions.
8912//===----------------------------------------------------------------------===//
8913
8914/// parseAlloc
8915/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8916/// (',' 'align' i32)? (',', 'addrspace(n))?
8917int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8918 Value *Size = nullptr;
8919 LocTy SizeLoc, TyLoc, ASLoc;
8920 MaybeAlign Alignment;
8921 unsigned AddrSpace = 0;
8922 Type *Ty = nullptr;
8923
8924 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8925 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8926
8927 if (parseType(Ty, TyLoc))
8928 return true;
8929
8931 return error(TyLoc, "invalid type for alloca");
8932
8933 bool AteExtraComma = false;
8934 if (EatIfPresent(lltok::comma)) {
8935 if (Lex.getKind() == lltok::kw_align) {
8936 if (parseOptionalAlignment(Alignment))
8937 return true;
8938 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8939 return true;
8940 } else if (Lex.getKind() == lltok::kw_addrspace) {
8941 ASLoc = Lex.getLoc();
8942 if (parseOptionalAddrSpace(AddrSpace))
8943 return true;
8944 } else if (Lex.getKind() == lltok::MetadataVar) {
8945 AteExtraComma = true;
8946 } else {
8947 if (parseTypeAndValue(Size, SizeLoc, PFS))
8948 return true;
8949 if (EatIfPresent(lltok::comma)) {
8950 if (Lex.getKind() == lltok::kw_align) {
8951 if (parseOptionalAlignment(Alignment))
8952 return true;
8953 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8954 return true;
8955 } else if (Lex.getKind() == lltok::kw_addrspace) {
8956 ASLoc = Lex.getLoc();
8957 if (parseOptionalAddrSpace(AddrSpace))
8958 return true;
8959 } else if (Lex.getKind() == lltok::MetadataVar) {
8960 AteExtraComma = true;
8961 }
8962 }
8963 }
8964 }
8965
8966 if (Size && !Size->getType()->isIntegerTy())
8967 return error(SizeLoc, "element count must have integer type");
8968
8969 SmallPtrSet<Type *, 4> Visited;
8970 if (!Alignment && !Ty->isSized(&Visited))
8971 return error(TyLoc, "Cannot allocate unsized type");
8972 if (!Alignment)
8973 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8974 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8975 AI->setUsedWithInAlloca(IsInAlloca);
8976 AI->setSwiftError(IsSwiftError);
8977 Inst = AI;
8978 return AteExtraComma ? InstExtraComma : InstNormal;
8979}
8980
8981/// parseLoad
8982/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8983/// ::= 'load' 'atomic' 'volatile'? 'elementwise'? TypeAndValue
8984/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8985int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8986 Value *Val; LocTy Loc;
8987 MaybeAlign Alignment;
8988 bool AteExtraComma = false;
8989 bool isAtomic = false;
8992
8993 if (Lex.getKind() == lltok::kw_atomic) {
8994 isAtomic = true;
8995 Lex.Lex();
8996 }
8997
8998 bool isVolatile = false;
8999 if (Lex.getKind() == lltok::kw_volatile) {
9000 isVolatile = true;
9001 Lex.Lex();
9002 }
9003
9004 bool IsElementwise = false;
9005 if (Lex.getKind() == lltok::kw_elementwise) {
9006 IsElementwise = true;
9007 Lex.Lex();
9008 }
9009
9010 Type *Ty;
9011 LocTy ExplicitTypeLoc = Lex.getLoc();
9012 if (parseType(Ty) ||
9013 parseToken(lltok::comma, "expected comma after load's type") ||
9014 parseTypeAndValue(Val, Loc, PFS) ||
9015 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9016 parseOptionalCommaAlign(Alignment, AteExtraComma))
9017 return true;
9018
9019 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
9020 return error(Loc, "load operand must be a pointer to a first class type");
9021
9022 if (IsElementwise && !isAtomic)
9023 return error(Loc, "elementwise load must be atomic");
9024
9025 if (IsElementwise && !isa<FixedVectorType>(Ty))
9026 return error(ExplicitTypeLoc,
9027 "atomic elementwise load operand must have fixed vector type");
9028
9029 if (isAtomic && !Alignment)
9030 return error(Loc, "atomic load must have explicit non-zero alignment");
9031
9032 if (Ordering == AtomicOrdering::Release ||
9034 return error(Loc, "atomic load cannot use Release ordering");
9035 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9036 return error(Loc,
9037 "atomic elementwise load cannot be sequentially consistent");
9038
9039 SmallPtrSet<Type *, 4> Visited;
9040 if (!Alignment && !Ty->isSized(&Visited))
9041 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
9042 if (!Alignment)
9043 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9044 Inst = new LoadInst(Ty, Val, "",
9045 LoadStoreInstProperties{isVolatile, *Alignment, Ordering,
9046 SSID, IsElementwise},
9047 /*InsertBefore=*/nullptr);
9048 return AteExtraComma ? InstExtraComma : InstNormal;
9049}
9050
9051/// parseStore
9052
9053/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
9054/// ::= 'store' 'atomic' 'volatile'? 'elementwise'? TypeAndValue ','
9055/// TypeAndValue 'singlethread'? AtomicOrdering (',' 'align' i32)?
9056int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9057 Value *Val, *Ptr;
9058 LocTy Loc, PtrLoc;
9059 MaybeAlign Alignment;
9060 bool AteExtraComma = false;
9061 bool isAtomic = false;
9064
9065 if (Lex.getKind() == lltok::kw_atomic) {
9066 isAtomic = true;
9067 Lex.Lex();
9068 }
9069
9070 bool isVolatile = false;
9071 if (Lex.getKind() == lltok::kw_volatile) {
9072 isVolatile = true;
9073 Lex.Lex();
9074 }
9075
9076 bool IsElementwise = false;
9077 if (Lex.getKind() == lltok::kw_elementwise) {
9078 IsElementwise = true;
9079 Lex.Lex();
9080 }
9081
9082 if (parseTypeAndValue(Val, Loc, PFS) ||
9083 parseToken(lltok::comma, "expected ',' after store operand") ||
9084 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9085 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9086 parseOptionalCommaAlign(Alignment, AteExtraComma))
9087 return true;
9088
9089 if (!Ptr->getType()->isPointerTy())
9090 return error(PtrLoc, "store operand must be a pointer");
9091 if (!Val->getType()->isFirstClassType())
9092 return error(Loc, "store operand must be a first class value");
9093 if (isAtomic && !Alignment)
9094 return error(Loc, "atomic store must have explicit non-zero alignment");
9095 if (Ordering == AtomicOrdering::Acquire ||
9097 return error(Loc, "atomic store cannot use Acquire ordering");
9098
9099 if (IsElementwise && !isAtomic)
9100 return error(Loc, "elementwise store must be atomic");
9101
9102 if (IsElementwise && !isa<FixedVectorType>(Val->getType()))
9103 return error(
9104 Loc, "atomic elementwise store operand must have fixed vector type");
9105
9106 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9107 return error(Loc,
9108 "atomic elementwise store cannot be sequentially consistent");
9109
9110 SmallPtrSet<Type *, 4> Visited;
9111 if (!Alignment && !Val->getType()->isSized(&Visited))
9112 return error(Loc, "storing unsized types is not allowed");
9113 if (!Alignment)
9114 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
9115
9116 Inst = new StoreInst(Val, Ptr,
9117 LoadStoreInstProperties{isVolatile, *Alignment, Ordering,
9118 SSID, IsElementwise},
9119 /*InsertBefore=*/nullptr);
9120 return AteExtraComma ? InstExtraComma : InstNormal;
9121}
9122
9123/// parseCmpXchg
9124/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
9125/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
9126/// 'Align'?
9127int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9128 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
9129 bool AteExtraComma = false;
9130 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
9131 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
9133 bool isVolatile = false;
9134 bool isWeak = false;
9135 MaybeAlign Alignment;
9136
9137 if (EatIfPresent(lltok::kw_weak))
9138 isWeak = true;
9139
9140 if (EatIfPresent(lltok::kw_volatile))
9141 isVolatile = true;
9142
9143 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9144 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
9145 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9146 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
9147 parseTypeAndValue(New, NewLoc, PFS) ||
9148 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
9149 parseOrdering(FailureOrdering) ||
9150 parseOptionalCommaAlign(Alignment, AteExtraComma))
9151 return true;
9152
9153 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
9154 return tokError("invalid cmpxchg success ordering");
9155 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
9156 return tokError("invalid cmpxchg failure ordering");
9157 if (!Ptr->getType()->isPointerTy())
9158 return error(PtrLoc, "cmpxchg operand must be a pointer");
9159 if (Cmp->getType() != New->getType())
9160 return error(NewLoc, "compare value and new value type do not match");
9161 if (!New->getType()->isFirstClassType())
9162 return error(NewLoc, "cmpxchg operand must be a first class value");
9163
9164 const Align DefaultAlignment(
9165 PFS.getFunction().getDataLayout().getTypeStoreSize(
9166 Cmp->getType()));
9167
9168 AtomicCmpXchgInst *CXI =
9169 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
9170 SuccessOrdering, FailureOrdering, SSID);
9171 CXI->setVolatile(isVolatile);
9172 CXI->setWeak(isWeak);
9173
9174 Inst = CXI;
9175 return AteExtraComma ? InstExtraComma : InstNormal;
9176}
9177
9178/// parseAtomicRMW
9179/// ::= 'atomicrmw' 'volatile'? 'elementwise'? BinOp TypeAndValue ','
9180/// TypeAndValue
9181/// 'singlethread'? AtomicOrdering
9182int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9183 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
9184 bool AteExtraComma = false;
9187 bool IsVolatile = false;
9188 bool IsElementwise = false;
9189 bool IsFP = false;
9191 MaybeAlign Alignment;
9192
9193 if (EatIfPresent(lltok::kw_volatile))
9194 IsVolatile = true;
9195 if (EatIfPresent(lltok::kw_elementwise))
9196 IsElementwise = true;
9197
9198 switch (Lex.getKind()) {
9199 default:
9200 return tokError("expected binary operation in atomicrmw");
9214 break;
9217 break;
9220 break;
9221 case lltok::kw_usub_sat:
9223 break;
9224 case lltok::kw_fadd:
9226 IsFP = true;
9227 break;
9228 case lltok::kw_fsub:
9230 IsFP = true;
9231 break;
9232 case lltok::kw_fmax:
9234 IsFP = true;
9235 break;
9236 case lltok::kw_fmin:
9238 IsFP = true;
9239 break;
9240 case lltok::kw_fmaximum:
9242 IsFP = true;
9243 break;
9244 case lltok::kw_fminimum:
9246 IsFP = true;
9247 break;
9250 IsFP = true;
9251 break;
9254 IsFP = true;
9255 break;
9256 }
9257 Lex.Lex(); // Eat the operation.
9258
9259 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9260 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
9261 parseTypeAndValue(Val, ValLoc, PFS) ||
9262 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
9263 parseOptionalCommaAlign(Alignment, AteExtraComma))
9264 return true;
9265
9266 if (Ordering == AtomicOrdering::Unordered)
9267 return tokError("atomicrmw cannot be unordered");
9268 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9269 return tokError("atomicrmw elementwise cannot be sequentially consistent");
9270 if (!Ptr->getType()->isPointerTy())
9271 return error(PtrLoc, "atomicrmw operand must be a pointer");
9272 if (Val->getType()->isScalableTy())
9273 return error(ValLoc, "atomicrmw operand may not be scalable");
9274
9275 Type *ValTy = Val->getType();
9276 if (IsElementwise) {
9277 if (!isa<FixedVectorType>(Val->getType()))
9278 return error(ValLoc,
9279 "atomicrmw elementwise operand must be a fixed vector type");
9280 }
9281
9283 if (!ValTy->isIntOrIntVectorTy() && !ValTy->isFPOrFPVectorTy() &&
9284 !ValTy->isPtrOrPtrVectorTy()) {
9285 return error(
9286 ValLoc,
9288 " operand must be an integer type, a floating-point type, a "
9289 "pointer type, or a fixed vector of any of these types");
9290 }
9291 } else if (IsFP) {
9292 if (!ValTy->isFPOrFPVectorTy()) {
9293 return error(ValLoc, "atomicrmw " +
9295 " operand must be a floating point or fixed "
9296 "vector of floating point type");
9297 }
9298 } else {
9299 if (!ValTy->isIntOrIntVectorTy()) {
9300 return error(
9301 ValLoc,
9303 " operand must be an integer or fixed vector of integer type");
9304 }
9305 }
9306
9307 unsigned Size =
9308 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9309 if (Size < 8 || (Size & (Size - 1)))
9310 return error(ValLoc,
9311 "atomicrmw operand must have a power-of-two byte size");
9312 const Align DefaultAlignment(
9313 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->getType()));
9314 AtomicRMWInst *RMWI = new AtomicRMWInst(Operation, Ptr, Val,
9315 Alignment.value_or(DefaultAlignment),
9316 Ordering, SSID, IsElementwise);
9317 RMWI->setVolatile(IsVolatile);
9318 Inst = RMWI;
9319 return AteExtraComma ? InstExtraComma : InstNormal;
9320}
9321
9322/// parseFence
9323/// ::= 'fence' 'singlethread'? AtomicOrdering
9324int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9327 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
9328 return true;
9329
9330 if (Ordering == AtomicOrdering::Unordered)
9331 return tokError("fence cannot be unordered");
9332 if (Ordering == AtomicOrdering::Monotonic)
9333 return tokError("fence cannot be monotonic");
9334
9335 Inst = new FenceInst(Context, Ordering, SSID);
9336 return InstNormal;
9337}
9338
9339/// parseGetElementPtr
9340/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9341int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9342 Value *Ptr = nullptr;
9343 Value *Val = nullptr;
9344 LocTy Loc, EltLoc;
9345 GEPNoWrapFlags NW;
9346
9347 while (true) {
9348 if (EatIfPresent(lltok::kw_inbounds))
9350 else if (EatIfPresent(lltok::kw_nusw))
9352 else if (EatIfPresent(lltok::kw_nuw))
9354 else
9355 break;
9356 }
9357
9358 Type *Ty = nullptr;
9359 if (parseType(Ty) ||
9360 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
9361 parseTypeAndValue(Ptr, Loc, PFS))
9362 return true;
9363
9364 Type *BaseType = Ptr->getType();
9365 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
9366 if (!BasePointerType)
9367 return error(Loc, "base of getelementptr must be a pointer");
9368
9369 SmallVector<Value*, 16> Indices;
9370 bool AteExtraComma = false;
9371 // GEP returns a vector of pointers if at least one of parameters is a vector.
9372 // All vector parameters should have the same vector width.
9373 ElementCount GEPWidth = BaseType->isVectorTy()
9374 ? cast<VectorType>(BaseType)->getElementCount()
9376
9377 while (EatIfPresent(lltok::comma)) {
9378 if (Lex.getKind() == lltok::MetadataVar) {
9379 AteExtraComma = true;
9380 break;
9381 }
9382 if (parseTypeAndValue(Val, EltLoc, PFS))
9383 return true;
9384 if (!Val->getType()->isIntOrIntVectorTy())
9385 return error(EltLoc, "getelementptr index must be an integer");
9386
9387 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
9388 ElementCount ValNumEl = ValVTy->getElementCount();
9389 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
9390 return error(
9391 EltLoc,
9392 "getelementptr vector index has a wrong number of elements");
9393 GEPWidth = ValNumEl;
9394 }
9395 Indices.push_back(Val);
9396 }
9397
9398 SmallPtrSet<Type*, 4> Visited;
9399 if (!Indices.empty() && !Ty->isSized(&Visited))
9400 return error(Loc, "base element of getelementptr must be sized");
9401
9402 auto *STy = dyn_cast<StructType>(Ty);
9403 if (STy && STy->isScalableTy())
9404 return error(Loc, "getelementptr cannot target structure that contains "
9405 "scalable vector type");
9406
9407 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
9408 return error(Loc, "invalid getelementptr indices");
9409 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
9410 Inst = GEP;
9411 GEP->setNoWrapFlags(NW);
9412 return AteExtraComma ? InstExtraComma : InstNormal;
9413}
9414
9415/// parseExtractValue
9416/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9417int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9418 Value *Val; LocTy Loc;
9419 SmallVector<unsigned, 4> Indices;
9420 bool AteExtraComma;
9421 if (parseTypeAndValue(Val, Loc, PFS) ||
9422 parseIndexList(Indices, AteExtraComma))
9423 return true;
9424
9425 if (!Val->getType()->isAggregateType())
9426 return error(Loc, "extractvalue operand must be aggregate type");
9427
9428 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9429 return error(Loc, "invalid indices for extractvalue");
9430 Inst = ExtractValueInst::Create(Val, Indices);
9431 return AteExtraComma ? InstExtraComma : InstNormal;
9432}
9433
9434/// parseInsertValue
9435/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9436int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9437 Value *Val0, *Val1; LocTy Loc0, Loc1;
9438 SmallVector<unsigned, 4> Indices;
9439 bool AteExtraComma;
9440 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9441 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9442 parseTypeAndValue(Val1, Loc1, PFS) ||
9443 parseIndexList(Indices, AteExtraComma))
9444 return true;
9445
9446 if (!Val0->getType()->isAggregateType())
9447 return error(Loc0, "insertvalue operand must be aggregate type");
9448
9449 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9450 if (!IndexedType)
9451 return error(Loc0, "invalid indices for insertvalue");
9452 if (IndexedType != Val1->getType())
9453 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9454 getTypeString(Val1->getType()) + "' instead of '" +
9455 getTypeString(IndexedType) + "'");
9456 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9457 return AteExtraComma ? InstExtraComma : InstNormal;
9458}
9459
9460//===----------------------------------------------------------------------===//
9461// Embedded metadata.
9462//===----------------------------------------------------------------------===//
9463
9464/// parseMDNodeVector
9465/// ::= { Element (',' Element)* }
9466/// Element
9467/// ::= 'null' | Metadata
9468bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9469 if (parseToken(lltok::lbrace, "expected '{' here"))
9470 return true;
9471
9472 // Check for an empty list.
9473 if (EatIfPresent(lltok::rbrace))
9474 return false;
9475
9476 do {
9477 if (EatIfPresent(lltok::kw_null)) {
9478 Elts.push_back(nullptr);
9479 continue;
9480 }
9481
9482 Metadata *MD;
9483 if (parseMetadata(MD, nullptr))
9484 return true;
9485 Elts.push_back(MD);
9486 } while (EatIfPresent(lltok::comma));
9487
9488 return parseToken(lltok::rbrace, "expected end of metadata node");
9489}
9490
9491//===----------------------------------------------------------------------===//
9492// Use-list order directives.
9493//===----------------------------------------------------------------------===//
9494bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9495 SMLoc Loc) {
9496 if (!V->hasUseList())
9497 return false;
9498 if (V->use_empty())
9499 return error(Loc, "value has no uses");
9500
9501 unsigned NumUses = 0;
9502 SmallDenseMap<const Use *, unsigned, 16> Order;
9503 for (const Use &U : V->uses()) {
9504 if (++NumUses > Indexes.size())
9505 break;
9506 Order[&U] = Indexes[NumUses - 1];
9507 }
9508 if (NumUses < 2)
9509 return error(Loc, "value only has one use");
9510 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9511 return error(Loc,
9512 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9513
9514 V->sortUseList([&](const Use &L, const Use &R) {
9515 return Order.lookup(&L) < Order.lookup(&R);
9516 });
9517 return false;
9518}
9519
9520/// parseUseListOrderIndexes
9521/// ::= '{' uint32 (',' uint32)+ '}'
9522bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9523 SMLoc Loc = Lex.getLoc();
9524 if (parseToken(lltok::lbrace, "expected '{' here"))
9525 return true;
9526 if (Lex.getKind() == lltok::rbrace)
9527 return tokError("expected non-empty list of uselistorder indexes");
9528
9529 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9530 // indexes should be distinct numbers in the range [0, size-1], and should
9531 // not be in order.
9532 unsigned Offset = 0;
9533 unsigned Max = 0;
9534 bool IsOrdered = true;
9535 assert(Indexes.empty() && "Expected empty order vector");
9536 do {
9537 unsigned Index;
9538 if (parseUInt32(Index))
9539 return true;
9540
9541 // Update consistency checks.
9542 Offset += Index - Indexes.size();
9543 Max = std::max(Max, Index);
9544 IsOrdered &= Index == Indexes.size();
9545
9546 Indexes.push_back(Index);
9547 } while (EatIfPresent(lltok::comma));
9548
9549 if (parseToken(lltok::rbrace, "expected '}' here"))
9550 return true;
9551
9552 if (Indexes.size() < 2)
9553 return error(Loc, "expected >= 2 uselistorder indexes");
9554 if (Offset != 0 || Max >= Indexes.size())
9555 return error(Loc,
9556 "expected distinct uselistorder indexes in range [0, size)");
9557 if (IsOrdered)
9558 return error(Loc, "expected uselistorder indexes to change the order");
9559
9560 return false;
9561}
9562
9563/// parseUseListOrder
9564/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9565bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9566 SMLoc Loc = Lex.getLoc();
9567 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9568 return true;
9569
9570 Value *V;
9571 SmallVector<unsigned, 16> Indexes;
9572 if (parseTypeAndValue(V, PFS) ||
9573 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9574 parseUseListOrderIndexes(Indexes))
9575 return true;
9576
9577 return sortUseListOrder(V, Indexes, Loc);
9578}
9579
9580/// ModuleEntry
9581/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9582/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9583bool LLParser::parseModuleEntry(unsigned ID) {
9584 assert(Lex.getKind() == lltok::kw_module);
9585 Lex.Lex();
9586
9587 std::string Path;
9588 if (parseToken(lltok::colon, "expected ':' here") ||
9589 parseToken(lltok::lparen, "expected '(' here") ||
9590 parseToken(lltok::kw_path, "expected 'path' here") ||
9591 parseToken(lltok::colon, "expected ':' here") ||
9592 parseStringConstant(Path) ||
9593 parseToken(lltok::comma, "expected ',' here") ||
9594 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9595 parseToken(lltok::colon, "expected ':' here") ||
9596 parseToken(lltok::lparen, "expected '(' here"))
9597 return true;
9598
9599 ModuleHash Hash;
9600 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9601 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9602 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9603 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9604 parseUInt32(Hash[4]))
9605 return true;
9606
9607 if (parseToken(lltok::rparen, "expected ')' here") ||
9608 parseToken(lltok::rparen, "expected ')' here"))
9609 return true;
9610
9611 auto ModuleEntry = Index->addModule(Path, Hash);
9612 ModuleIdMap[ID] = ModuleEntry->first();
9613
9614 return false;
9615}
9616
9617/// TypeIdEntry
9618/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9619bool LLParser::parseTypeIdEntry(unsigned ID) {
9620 assert(Lex.getKind() == lltok::kw_typeid);
9621 Lex.Lex();
9622
9623 std::string Name;
9624 if (parseToken(lltok::colon, "expected ':' here") ||
9625 parseToken(lltok::lparen, "expected '(' here") ||
9626 parseToken(lltok::kw_name, "expected 'name' here") ||
9627 parseToken(lltok::colon, "expected ':' here") ||
9628 parseStringConstant(Name))
9629 return true;
9630
9631 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9632 if (parseToken(lltok::comma, "expected ',' here") ||
9633 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9634 return true;
9635
9636 // Check if this ID was forward referenced, and if so, update the
9637 // corresponding GUIDs.
9638 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9639 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9640 for (auto TIDRef : FwdRefTIDs->second) {
9641 assert(!*TIDRef.first &&
9642 "Forward referenced type id GUID expected to be 0");
9643 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9644 }
9645 ForwardRefTypeIds.erase(FwdRefTIDs);
9646 }
9647
9648 return false;
9649}
9650
9651/// TypeIdSummary
9652/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9653bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9654 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9655 parseToken(lltok::colon, "expected ':' here") ||
9656 parseToken(lltok::lparen, "expected '(' here") ||
9657 parseTypeTestResolution(TIS.TTRes))
9658 return true;
9659
9660 if (EatIfPresent(lltok::comma)) {
9661 // Expect optional wpdResolutions field
9662 if (parseOptionalWpdResolutions(TIS.WPDRes))
9663 return true;
9664 }
9665
9666 if (parseToken(lltok::rparen, "expected ')' here"))
9667 return true;
9668
9669 return false;
9670}
9671
9674
9675/// TypeIdCompatibleVtableEntry
9676/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9677/// TypeIdCompatibleVtableInfo
9678/// ')'
9679bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9681 Lex.Lex();
9682
9683 std::string Name;
9684 if (parseToken(lltok::colon, "expected ':' here") ||
9685 parseToken(lltok::lparen, "expected '(' here") ||
9686 parseToken(lltok::kw_name, "expected 'name' here") ||
9687 parseToken(lltok::colon, "expected ':' here") ||
9688 parseStringConstant(Name))
9689 return true;
9690
9692 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9693 if (parseToken(lltok::comma, "expected ',' here") ||
9694 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9695 parseToken(lltok::colon, "expected ':' here") ||
9696 parseToken(lltok::lparen, "expected '(' here"))
9697 return true;
9698
9699 IdToIndexMapType IdToIndexMap;
9700 // parse each call edge
9701 do {
9703 if (parseToken(lltok::lparen, "expected '(' here") ||
9704 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9705 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9706 parseToken(lltok::comma, "expected ',' here"))
9707 return true;
9708
9709 LocTy Loc = Lex.getLoc();
9710 unsigned GVId;
9711 ValueInfo VI;
9712 if (parseGVReference(VI, GVId))
9713 return true;
9714
9715 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9716 // forward reference. We will save the location of the ValueInfo needing an
9717 // update, but can only do so once the std::vector is finalized.
9718 if (VI == EmptyVI)
9719 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9720 TI.push_back({Offset, VI});
9721
9722 if (parseToken(lltok::rparen, "expected ')' in call"))
9723 return true;
9724 } while (EatIfPresent(lltok::comma));
9725
9726 // Now that the TI vector is finalized, it is safe to save the locations
9727 // of any forward GV references that need updating later.
9728 for (auto I : IdToIndexMap) {
9729 auto &Infos = ForwardRefValueInfos[I.first];
9730 for (auto P : I.second) {
9731 assert(TI[P.first].VTableVI == EmptyVI &&
9732 "Forward referenced ValueInfo expected to be empty");
9733 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9734 }
9735 }
9736
9737 if (parseToken(lltok::rparen, "expected ')' here") ||
9738 parseToken(lltok::rparen, "expected ')' here"))
9739 return true;
9740
9741 // Check if this ID was forward referenced, and if so, update the
9742 // corresponding GUIDs.
9743 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9744 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9745 for (auto TIDRef : FwdRefTIDs->second) {
9746 assert(!*TIDRef.first &&
9747 "Forward referenced type id GUID expected to be 0");
9748 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9749 }
9750 ForwardRefTypeIds.erase(FwdRefTIDs);
9751 }
9752
9753 return false;
9754}
9755
9756/// TypeTestResolution
9757/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9758/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9759/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9760/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9761/// [',' 'inlinesBits' ':' UInt64]? ')'
9762bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9763 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9764 parseToken(lltok::colon, "expected ':' here") ||
9765 parseToken(lltok::lparen, "expected '(' here") ||
9766 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9767 parseToken(lltok::colon, "expected ':' here"))
9768 return true;
9769
9770 switch (Lex.getKind()) {
9771 case lltok::kw_unknown:
9773 break;
9774 case lltok::kw_unsat:
9776 break;
9779 break;
9780 case lltok::kw_inline:
9782 break;
9783 case lltok::kw_single:
9785 break;
9786 case lltok::kw_allOnes:
9788 break;
9789 default:
9790 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9791 }
9792 Lex.Lex();
9793
9794 if (parseToken(lltok::comma, "expected ',' here") ||
9795 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9796 parseToken(lltok::colon, "expected ':' here") ||
9797 parseUInt32(TTRes.SizeM1BitWidth))
9798 return true;
9799
9800 // parse optional fields
9801 while (EatIfPresent(lltok::comma)) {
9802 switch (Lex.getKind()) {
9804 Lex.Lex();
9805 if (parseToken(lltok::colon, "expected ':'") ||
9806 parseUInt64(TTRes.AlignLog2))
9807 return true;
9808 break;
9809 case lltok::kw_sizeM1:
9810 Lex.Lex();
9811 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9812 return true;
9813 break;
9814 case lltok::kw_bitMask: {
9815 unsigned Val;
9816 Lex.Lex();
9817 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9818 return true;
9819 assert(Val <= 0xff);
9820 TTRes.BitMask = (uint8_t)Val;
9821 break;
9822 }
9824 Lex.Lex();
9825 if (parseToken(lltok::colon, "expected ':'") ||
9826 parseUInt64(TTRes.InlineBits))
9827 return true;
9828 break;
9829 default:
9830 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9831 }
9832 }
9833
9834 if (parseToken(lltok::rparen, "expected ')' here"))
9835 return true;
9836
9837 return false;
9838}
9839
9840/// OptionalWpdResolutions
9841/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9842/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9843bool LLParser::parseOptionalWpdResolutions(
9844 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9845 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9846 parseToken(lltok::colon, "expected ':' here") ||
9847 parseToken(lltok::lparen, "expected '(' here"))
9848 return true;
9849
9850 do {
9852 WholeProgramDevirtResolution WPDRes;
9853 if (parseToken(lltok::lparen, "expected '(' here") ||
9854 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9855 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9856 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9857 parseToken(lltok::rparen, "expected ')' here"))
9858 return true;
9859 WPDResMap[Offset] = WPDRes;
9860 } while (EatIfPresent(lltok::comma));
9861
9862 if (parseToken(lltok::rparen, "expected ')' here"))
9863 return true;
9864
9865 return false;
9866}
9867
9868/// WpdRes
9869/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9870/// [',' OptionalResByArg]? ')'
9871/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9872/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9873/// [',' OptionalResByArg]? ')'
9874/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9875/// [',' OptionalResByArg]? ')'
9876bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9877 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9878 parseToken(lltok::colon, "expected ':' here") ||
9879 parseToken(lltok::lparen, "expected '(' here") ||
9880 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9881 parseToken(lltok::colon, "expected ':' here"))
9882 return true;
9883
9884 switch (Lex.getKind()) {
9885 case lltok::kw_indir:
9887 break;
9890 break;
9893 break;
9894 default:
9895 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9896 }
9897 Lex.Lex();
9898
9899 // parse optional fields
9900 while (EatIfPresent(lltok::comma)) {
9901 switch (Lex.getKind()) {
9903 Lex.Lex();
9904 if (parseToken(lltok::colon, "expected ':' here") ||
9905 parseStringConstant(WPDRes.SingleImplName))
9906 return true;
9907 break;
9908 case lltok::kw_resByArg:
9909 if (parseOptionalResByArg(WPDRes.ResByArg))
9910 return true;
9911 break;
9912 default:
9913 return error(Lex.getLoc(),
9914 "expected optional WholeProgramDevirtResolution field");
9915 }
9916 }
9917
9918 if (parseToken(lltok::rparen, "expected ')' here"))
9919 return true;
9920
9921 return false;
9922}
9923
9924/// OptionalResByArg
9925/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9926/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9927/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9928/// 'virtualConstProp' )
9929/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9930/// [',' 'bit' ':' UInt32]? ')'
9931bool LLParser::parseOptionalResByArg(
9932 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9933 &ResByArg) {
9934 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9935 parseToken(lltok::colon, "expected ':' here") ||
9936 parseToken(lltok::lparen, "expected '(' here"))
9937 return true;
9938
9939 do {
9940 std::vector<uint64_t> Args;
9941 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9942 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9943 parseToken(lltok::colon, "expected ':' here") ||
9944 parseToken(lltok::lparen, "expected '(' here") ||
9945 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9946 parseToken(lltok::colon, "expected ':' here"))
9947 return true;
9948
9949 WholeProgramDevirtResolution::ByArg ByArg;
9950 switch (Lex.getKind()) {
9951 case lltok::kw_indir:
9953 break;
9956 break;
9959 break;
9962 break;
9963 default:
9964 return error(Lex.getLoc(),
9965 "unexpected WholeProgramDevirtResolution::ByArg kind");
9966 }
9967 Lex.Lex();
9968
9969 // parse optional fields
9970 while (EatIfPresent(lltok::comma)) {
9971 switch (Lex.getKind()) {
9972 case lltok::kw_info:
9973 Lex.Lex();
9974 if (parseToken(lltok::colon, "expected ':' here") ||
9975 parseUInt64(ByArg.Info))
9976 return true;
9977 break;
9978 case lltok::kw_byte:
9979 Lex.Lex();
9980 if (parseToken(lltok::colon, "expected ':' here") ||
9981 parseUInt32(ByArg.Byte))
9982 return true;
9983 break;
9984 case lltok::kw_bit:
9985 Lex.Lex();
9986 if (parseToken(lltok::colon, "expected ':' here") ||
9987 parseUInt32(ByArg.Bit))
9988 return true;
9989 break;
9990 default:
9991 return error(Lex.getLoc(),
9992 "expected optional whole program devirt field");
9993 }
9994 }
9995
9996 if (parseToken(lltok::rparen, "expected ')' here"))
9997 return true;
9998
9999 ResByArg[Args] = ByArg;
10000 } while (EatIfPresent(lltok::comma));
10001
10002 if (parseToken(lltok::rparen, "expected ')' here"))
10003 return true;
10004
10005 return false;
10006}
10007
10008/// OptionalResByArg
10009/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
10010bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
10011 if (parseToken(lltok::kw_args, "expected 'args' here") ||
10012 parseToken(lltok::colon, "expected ':' here") ||
10013 parseToken(lltok::lparen, "expected '(' here"))
10014 return true;
10015
10016 do {
10017 uint64_t Val;
10018 if (parseUInt64(Val))
10019 return true;
10020 Args.push_back(Val);
10021 } while (EatIfPresent(lltok::comma));
10022
10023 if (parseToken(lltok::rparen, "expected ')' here"))
10024 return true;
10025
10026 return false;
10027}
10028
10030
10031static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
10032 bool ReadOnly = Fwd->isReadOnly();
10033 bool WriteOnly = Fwd->isWriteOnly();
10034 assert(!(ReadOnly && WriteOnly));
10035 *Fwd = Resolved;
10036 if (ReadOnly)
10037 Fwd->setReadOnly();
10038 if (WriteOnly)
10039 Fwd->setWriteOnly();
10040}
10041
10042/// Stores the given Name/GUID and associated summary into the Index.
10043/// Also updates any forward references to the associated entry ID.
10044bool LLParser::addGlobalValueToIndex(
10045 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
10046 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
10047 // First create the ValueInfo utilizing the Name or GUID.
10048 ValueInfo VI;
10049 if (GUID != 0) {
10050 assert(Name.empty());
10051 VI = Index->getOrInsertValueInfo(GUID);
10052 } else {
10053 assert(!Name.empty());
10054 if (M) {
10055 auto *GV = M->getNamedValue(Name);
10056 if (!GV)
10057 return error(Loc, "Reference to undefined global \"" + Name + "\"");
10058
10059 // Be a little lenient here, to accomodate older files without GUIDs
10060 // already computed and assigned as metadata.
10061 GUID = GV->getGUIDOrFallback();
10062
10063 VI = Index->getOrInsertValueInfo(GV, GUID);
10064 } else {
10065 assert(
10066 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
10067 "Need a source_filename to compute GUID for local");
10069 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
10070 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10071 }
10072 }
10073
10074 // Resolve forward references from calls/refs
10075 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10076 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10077 for (auto VIRef : FwdRefVIs->second) {
10078 assert(VIRef.first->getRef() == FwdVIRef &&
10079 "Forward referenced ValueInfo expected to be empty");
10080 resolveFwdRef(VIRef.first, VI);
10081 }
10082 ForwardRefValueInfos.erase(FwdRefVIs);
10083 }
10084
10085 // Resolve forward references from aliases
10086 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10087 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10088 for (auto AliaseeRef : FwdRefAliasees->second) {
10089 assert(!AliaseeRef.first->hasAliasee() &&
10090 "Forward referencing alias already has aliasee");
10091 assert(Summary && "Aliasee must be a definition");
10092 AliaseeRef.first->setAliasee(VI, Summary.get());
10093 }
10094 ForwardRefAliasees.erase(FwdRefAliasees);
10095 }
10096
10097 // Add the summary if one was provided.
10098 if (Summary)
10099 Index->addGlobalValueSummary(VI, std::move(Summary));
10100
10101 // Save the associated ValueInfo for use in later references by ID.
10102 if (ID == NumberedValueInfos.size())
10103 NumberedValueInfos.push_back(VI);
10104 else {
10105 // Handle non-continuous numbers (to make test simplification easier).
10106 if (ID > NumberedValueInfos.size())
10107 NumberedValueInfos.resize(ID + 1);
10108 NumberedValueInfos[ID] = VI;
10109 }
10110
10111 return false;
10112}
10113
10114/// parseSummaryIndexFlags
10115/// ::= 'flags' ':' UInt64
10116bool LLParser::parseSummaryIndexFlags() {
10117 assert(Lex.getKind() == lltok::kw_flags);
10118 Lex.Lex();
10119
10120 if (parseToken(lltok::colon, "expected ':' here"))
10121 return true;
10123 if (parseUInt64(Flags))
10124 return true;
10125 if (Index)
10126 Index->setFlags(Flags);
10127 return false;
10128}
10129
10130/// parseBlockCount
10131/// ::= 'blockcount' ':' UInt64
10132bool LLParser::parseBlockCount() {
10133 assert(Lex.getKind() == lltok::kw_blockcount);
10134 Lex.Lex();
10135
10136 if (parseToken(lltok::colon, "expected ':' here"))
10137 return true;
10138 uint64_t BlockCount;
10139 if (parseUInt64(BlockCount))
10140 return true;
10141 if (Index)
10142 Index->setBlockCount(BlockCount);
10143 return false;
10144}
10145
10146/// parseGVEntry
10147/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
10148/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
10149/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
10150bool LLParser::parseGVEntry(unsigned ID) {
10151 assert(Lex.getKind() == lltok::kw_gv);
10152 Lex.Lex();
10153
10154 if (parseToken(lltok::colon, "expected ':' here") ||
10155 parseToken(lltok::lparen, "expected '(' here"))
10156 return true;
10157
10158 LocTy Loc = Lex.getLoc();
10159 std::string Name;
10161 switch (Lex.getKind()) {
10162 case lltok::kw_name:
10163 Lex.Lex();
10164 if (parseToken(lltok::colon, "expected ':' here") ||
10165 parseStringConstant(Name))
10166 return true;
10167 // Can't create GUID/ValueInfo until we have the linkage.
10168 break;
10169 case lltok::kw_guid:
10170 Lex.Lex();
10171 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
10172 return true;
10173 break;
10174 default:
10175 return error(Lex.getLoc(), "expected name or guid tag");
10176 }
10177
10178 if (!EatIfPresent(lltok::comma)) {
10179 // No summaries. Wrap up.
10180 if (parseToken(lltok::rparen, "expected ')' here"))
10181 return true;
10182 // This was created for a call to an external or indirect target.
10183 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
10184 // created for indirect calls with VP. A Name with no GUID came from
10185 // an external definition. We pass ExternalLinkage since that is only
10186 // used when the GUID must be computed from Name, and in that case
10187 // the symbol must have external linkage.
10188 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
10189 nullptr, Loc);
10190 }
10191
10192 // Have a list of summaries
10193 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
10194 parseToken(lltok::colon, "expected ':' here") ||
10195 parseToken(lltok::lparen, "expected '(' here"))
10196 return true;
10197 do {
10198 switch (Lex.getKind()) {
10199 case lltok::kw_function:
10200 if (parseFunctionSummary(Name, GUID, ID))
10201 return true;
10202 break;
10203 case lltok::kw_variable:
10204 if (parseVariableSummary(Name, GUID, ID))
10205 return true;
10206 break;
10207 case lltok::kw_alias:
10208 if (parseAliasSummary(Name, GUID, ID))
10209 return true;
10210 break;
10211 default:
10212 return error(Lex.getLoc(), "expected summary type");
10213 }
10214 } while (EatIfPresent(lltok::comma));
10215
10216 if (parseToken(lltok::rparen, "expected ')' here") ||
10217 parseToken(lltok::rparen, "expected ')' here"))
10218 return true;
10219
10220 return false;
10221}
10222
10223/// FunctionSummary
10224/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10225/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10226/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10227/// [',' OptionalRefs]? ')'
10228bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10229 unsigned ID) {
10230 LocTy Loc = Lex.getLoc();
10231 assert(Lex.getKind() == lltok::kw_function);
10232 Lex.Lex();
10233
10234 StringRef ModulePath;
10235 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10237 /*NotEligibleToImport=*/false,
10238 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10239 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10240 unsigned InstCount;
10242 FunctionSummary::TypeIdInfo TypeIdInfo;
10243 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10245 std::vector<CallsiteInfo> Callsites;
10246 std::vector<AllocInfo> Allocs;
10247 // Default is all-zeros (conservative values).
10248 FunctionSummary::FFlags FFlags = {};
10249 if (parseToken(lltok::colon, "expected ':' here") ||
10250 parseToken(lltok::lparen, "expected '(' here") ||
10251 parseModuleReference(ModulePath) ||
10252 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10253 parseToken(lltok::comma, "expected ',' here") ||
10254 parseToken(lltok::kw_insts, "expected 'insts' here") ||
10255 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
10256 return true;
10257
10258 // parse optional fields
10259 while (EatIfPresent(lltok::comma)) {
10260 switch (Lex.getKind()) {
10262 if (parseOptionalFFlags(FFlags))
10263 return true;
10264 break;
10265 case lltok::kw_calls:
10266 if (parseOptionalCalls(Calls))
10267 return true;
10268 break;
10270 if (parseOptionalTypeIdInfo(TypeIdInfo))
10271 return true;
10272 break;
10273 case lltok::kw_refs:
10274 if (parseOptionalRefs(Refs))
10275 return true;
10276 break;
10277 case lltok::kw_params:
10278 if (parseOptionalParamAccesses(ParamAccesses))
10279 return true;
10280 break;
10281 case lltok::kw_allocs:
10282 if (parseOptionalAllocs(Allocs))
10283 return true;
10284 break;
10286 if (parseOptionalCallsites(Callsites))
10287 return true;
10288 break;
10289 default:
10290 return error(Lex.getLoc(), "expected optional function summary field");
10291 }
10292 }
10293
10294 if (parseToken(lltok::rparen, "expected ')' here"))
10295 return true;
10296
10297 auto FS = std::make_unique<FunctionSummary>(
10298 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10299 std::move(TypeIdInfo.TypeTests),
10300 std::move(TypeIdInfo.TypeTestAssumeVCalls),
10301 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10302 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10303 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10304 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10305
10306 FS->setModulePath(ModulePath);
10307
10308 return addGlobalValueToIndex(Name, GUID,
10310 std::move(FS), Loc);
10311}
10312
10313/// VariableSummary
10314/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10315/// [',' OptionalRefs]? ')'
10316bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10317 unsigned ID) {
10318 LocTy Loc = Lex.getLoc();
10319 assert(Lex.getKind() == lltok::kw_variable);
10320 Lex.Lex();
10321
10322 StringRef ModulePath;
10323 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10325 /*NotEligibleToImport=*/false,
10326 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10327 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10328 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10329 /* WriteOnly */ false,
10330 /* Constant */ false,
10333 VTableFuncList VTableFuncs;
10334 if (parseToken(lltok::colon, "expected ':' here") ||
10335 parseToken(lltok::lparen, "expected '(' here") ||
10336 parseModuleReference(ModulePath) ||
10337 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10338 parseToken(lltok::comma, "expected ',' here") ||
10339 parseGVarFlags(GVarFlags))
10340 return true;
10341
10342 // parse optional fields
10343 while (EatIfPresent(lltok::comma)) {
10344 switch (Lex.getKind()) {
10346 if (parseOptionalVTableFuncs(VTableFuncs))
10347 return true;
10348 break;
10349 case lltok::kw_refs:
10350 if (parseOptionalRefs(Refs))
10351 return true;
10352 break;
10353 default:
10354 return error(Lex.getLoc(), "expected optional variable summary field");
10355 }
10356 }
10357
10358 if (parseToken(lltok::rparen, "expected ')' here"))
10359 return true;
10360
10361 auto GS =
10362 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10363
10364 GS->setModulePath(ModulePath);
10365 GS->setVTableFuncs(std::move(VTableFuncs));
10366
10367 return addGlobalValueToIndex(Name, GUID,
10369 std::move(GS), Loc);
10370}
10371
10372/// AliasSummary
10373/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10374/// 'aliasee' ':' GVReference ')'
10375bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10376 unsigned ID) {
10377 assert(Lex.getKind() == lltok::kw_alias);
10378 LocTy Loc = Lex.getLoc();
10379 Lex.Lex();
10380
10381 StringRef ModulePath;
10382 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10384 /*NotEligibleToImport=*/false,
10385 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10386 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10387 if (parseToken(lltok::colon, "expected ':' here") ||
10388 parseToken(lltok::lparen, "expected '(' here") ||
10389 parseModuleReference(ModulePath) ||
10390 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10391 parseToken(lltok::comma, "expected ',' here") ||
10392 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10393 parseToken(lltok::colon, "expected ':' here"))
10394 return true;
10395
10396 ValueInfo AliaseeVI;
10397 unsigned GVId;
10398 auto AS = std::make_unique<AliasSummary>(GVFlags);
10399 AS->setModulePath(ModulePath);
10400
10401 if (!EatIfPresent(lltok::kw_null)) {
10402 if (parseGVReference(AliaseeVI, GVId))
10403 return true;
10404
10405 // Record forward reference if the aliasee is not parsed yet.
10406 if (AliaseeVI.getRef() == FwdVIRef) {
10407 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10408 } else {
10409 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10410 assert(Summary && "Aliasee must be a definition");
10411 AS->setAliasee(AliaseeVI, Summary);
10412 }
10413 }
10414
10415 if (parseToken(lltok::rparen, "expected ')' here"))
10416 return true;
10417
10418 return addGlobalValueToIndex(Name, GUID,
10420 std::move(AS), Loc);
10421}
10422
10423/// Flag
10424/// ::= [0|1]
10425bool LLParser::parseFlag(unsigned &Val) {
10426 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10427 return tokError("expected integer");
10428 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10429 Lex.Lex();
10430 return false;
10431}
10432
10433/// OptionalFFlags
10434/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10435/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10436/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10437/// [',' 'noInline' ':' Flag]? ')'
10438/// [',' 'alwaysInline' ':' Flag]? ')'
10439/// [',' 'noUnwind' ':' Flag]? ')'
10440/// [',' 'mayThrow' ':' Flag]? ')'
10441/// [',' 'hasUnknownCall' ':' Flag]? ')'
10442/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10443
10444bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10445 assert(Lex.getKind() == lltok::kw_funcFlags);
10446 Lex.Lex();
10447
10448 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10449 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10450 return true;
10451
10452 do {
10453 unsigned Val = 0;
10454 switch (Lex.getKind()) {
10455 case lltok::kw_readNone:
10456 Lex.Lex();
10457 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10458 return true;
10459 FFlags.ReadNone = Val;
10460 break;
10461 case lltok::kw_readOnly:
10462 Lex.Lex();
10463 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10464 return true;
10465 FFlags.ReadOnly = Val;
10466 break;
10468 Lex.Lex();
10469 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10470 return true;
10471 FFlags.NoRecurse = Val;
10472 break;
10474 Lex.Lex();
10475 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10476 return true;
10477 FFlags.ReturnDoesNotAlias = Val;
10478 break;
10479 case lltok::kw_noInline:
10480 Lex.Lex();
10481 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10482 return true;
10483 FFlags.NoInline = Val;
10484 break;
10486 Lex.Lex();
10487 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10488 return true;
10489 FFlags.AlwaysInline = Val;
10490 break;
10491 case lltok::kw_noUnwind:
10492 Lex.Lex();
10493 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10494 return true;
10495 FFlags.NoUnwind = Val;
10496 break;
10497 case lltok::kw_mayThrow:
10498 Lex.Lex();
10499 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10500 return true;
10501 FFlags.MayThrow = Val;
10502 break;
10504 Lex.Lex();
10505 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10506 return true;
10507 FFlags.HasUnknownCall = Val;
10508 break;
10510 Lex.Lex();
10511 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10512 return true;
10513 FFlags.MustBeUnreachable = Val;
10514 break;
10515 default:
10516 return error(Lex.getLoc(), "expected function flag type");
10517 }
10518 } while (EatIfPresent(lltok::comma));
10519
10520 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10521 return true;
10522
10523 return false;
10524}
10525
10526/// OptionalCalls
10527/// := 'calls' ':' '(' Call [',' Call]* ')'
10528/// Call ::= '(' 'callee' ':' GVReference
10529/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10530/// [ ',' 'tail' ]? ')'
10531bool LLParser::parseOptionalCalls(
10532 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10533 assert(Lex.getKind() == lltok::kw_calls);
10534 Lex.Lex();
10535
10536 if (parseToken(lltok::colon, "expected ':' in calls") ||
10537 parseToken(lltok::lparen, "expected '(' in calls"))
10538 return true;
10539
10540 IdToIndexMapType IdToIndexMap;
10541 // parse each call edge
10542 do {
10543 ValueInfo VI;
10544 if (parseToken(lltok::lparen, "expected '(' in call") ||
10545 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10546 parseToken(lltok::colon, "expected ':'"))
10547 return true;
10548
10549 LocTy Loc = Lex.getLoc();
10550 unsigned GVId;
10551 if (parseGVReference(VI, GVId))
10552 return true;
10553
10555 unsigned RelBF = 0;
10556 unsigned HasTailCall = false;
10557
10558 // parse optional fields
10559 while (EatIfPresent(lltok::comma)) {
10560 switch (Lex.getKind()) {
10561 case lltok::kw_hotness:
10562 Lex.Lex();
10563 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10564 return true;
10565 break;
10566 // Deprecated, keep in order to support old files.
10567 case lltok::kw_relbf:
10568 Lex.Lex();
10569 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10570 return true;
10571 break;
10572 case lltok::kw_tail:
10573 Lex.Lex();
10574 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10575 return true;
10576 break;
10577 default:
10578 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10579 }
10580 }
10581 // Keep track of the Call array index needing a forward reference.
10582 // We will save the location of the ValueInfo needing an update, but
10583 // can only do so once the std::vector is finalized.
10584 if (VI.getRef() == FwdVIRef)
10585 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10586 Calls.push_back(
10587 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall)});
10588
10589 if (parseToken(lltok::rparen, "expected ')' in call"))
10590 return true;
10591 } while (EatIfPresent(lltok::comma));
10592
10593 // Now that the Calls vector is finalized, it is safe to save the locations
10594 // of any forward GV references that need updating later.
10595 for (auto I : IdToIndexMap) {
10596 auto &Infos = ForwardRefValueInfos[I.first];
10597 for (auto P : I.second) {
10598 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10599 "Forward referenced ValueInfo expected to be empty");
10600 Infos.emplace_back(&Calls[P.first].first, P.second);
10601 }
10602 }
10603
10604 if (parseToken(lltok::rparen, "expected ')' in calls"))
10605 return true;
10606
10607 return false;
10608}
10609
10610/// Hotness
10611/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10612bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10613 switch (Lex.getKind()) {
10614 case lltok::kw_unknown:
10616 break;
10617 case lltok::kw_cold:
10619 break;
10620 case lltok::kw_none:
10622 break;
10623 case lltok::kw_hot:
10625 break;
10626 case lltok::kw_critical:
10628 break;
10629 default:
10630 return error(Lex.getLoc(), "invalid call edge hotness");
10631 }
10632 Lex.Lex();
10633 return false;
10634}
10635
10636/// OptionalVTableFuncs
10637/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10638/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10639bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10640 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10641 Lex.Lex();
10642
10643 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10644 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10645 return true;
10646
10647 IdToIndexMapType IdToIndexMap;
10648 // parse each virtual function pair
10649 do {
10650 ValueInfo VI;
10651 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10652 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10653 parseToken(lltok::colon, "expected ':'"))
10654 return true;
10655
10656 LocTy Loc = Lex.getLoc();
10657 unsigned GVId;
10658 if (parseGVReference(VI, GVId))
10659 return true;
10660
10662 if (parseToken(lltok::comma, "expected comma") ||
10663 parseToken(lltok::kw_offset, "expected offset") ||
10664 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10665 return true;
10666
10667 // Keep track of the VTableFuncs array index needing a forward reference.
10668 // We will save the location of the ValueInfo needing an update, but
10669 // can only do so once the std::vector is finalized.
10670 if (VI == EmptyVI)
10671 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10672 VTableFuncs.push_back({VI, Offset});
10673
10674 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10675 return true;
10676 } while (EatIfPresent(lltok::comma));
10677
10678 // Now that the VTableFuncs vector is finalized, it is safe to save the
10679 // locations of any forward GV references that need updating later.
10680 for (auto I : IdToIndexMap) {
10681 auto &Infos = ForwardRefValueInfos[I.first];
10682 for (auto P : I.second) {
10683 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10684 "Forward referenced ValueInfo expected to be empty");
10685 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10686 }
10687 }
10688
10689 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10690 return true;
10691
10692 return false;
10693}
10694
10695/// ParamNo := 'param' ':' UInt64
10696bool LLParser::parseParamNo(uint64_t &ParamNo) {
10697 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10698 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10699 return true;
10700 return false;
10701}
10702
10703/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10704bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10705 APSInt Lower;
10706 APSInt Upper;
10707 auto ParseAPSInt = [&](APSInt &Val) {
10708 if (Lex.getKind() != lltok::APSInt)
10709 return tokError("expected integer");
10710 Val = Lex.getAPSIntVal();
10711 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10712 Val.setIsSigned(true);
10713 Lex.Lex();
10714 return false;
10715 };
10716 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10717 parseToken(lltok::colon, "expected ':' here") ||
10718 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10719 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10720 parseToken(lltok::rsquare, "expected ']' here"))
10721 return true;
10722
10723 ++Upper;
10724 Range =
10725 (Lower == Upper && !Lower.isMaxValue())
10726 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10727 : ConstantRange(Lower, Upper);
10728
10729 return false;
10730}
10731
10732/// ParamAccessCall
10733/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10734bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10735 IdLocListType &IdLocList) {
10736 if (parseToken(lltok::lparen, "expected '(' here") ||
10737 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10738 parseToken(lltok::colon, "expected ':' here"))
10739 return true;
10740
10741 unsigned GVId;
10742 ValueInfo VI;
10743 LocTy Loc = Lex.getLoc();
10744 if (parseGVReference(VI, GVId))
10745 return true;
10746
10747 Call.Callee = VI;
10748 IdLocList.emplace_back(GVId, Loc);
10749
10750 if (parseToken(lltok::comma, "expected ',' here") ||
10751 parseParamNo(Call.ParamNo) ||
10752 parseToken(lltok::comma, "expected ',' here") ||
10753 parseParamAccessOffset(Call.Offsets))
10754 return true;
10755
10756 if (parseToken(lltok::rparen, "expected ')' here"))
10757 return true;
10758
10759 return false;
10760}
10761
10762/// ParamAccess
10763/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10764/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10765bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10766 IdLocListType &IdLocList) {
10767 if (parseToken(lltok::lparen, "expected '(' here") ||
10768 parseParamNo(Param.ParamNo) ||
10769 parseToken(lltok::comma, "expected ',' here") ||
10770 parseParamAccessOffset(Param.Use))
10771 return true;
10772
10773 if (EatIfPresent(lltok::comma)) {
10774 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10775 parseToken(lltok::colon, "expected ':' here") ||
10776 parseToken(lltok::lparen, "expected '(' here"))
10777 return true;
10778 do {
10779 FunctionSummary::ParamAccess::Call Call;
10780 if (parseParamAccessCall(Call, IdLocList))
10781 return true;
10782 Param.Calls.push_back(Call);
10783 } while (EatIfPresent(lltok::comma));
10784
10785 if (parseToken(lltok::rparen, "expected ')' here"))
10786 return true;
10787 }
10788
10789 if (parseToken(lltok::rparen, "expected ')' here"))
10790 return true;
10791
10792 return false;
10793}
10794
10795/// OptionalParamAccesses
10796/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10797bool LLParser::parseOptionalParamAccesses(
10798 std::vector<FunctionSummary::ParamAccess> &Params) {
10799 assert(Lex.getKind() == lltok::kw_params);
10800 Lex.Lex();
10801
10802 if (parseToken(lltok::colon, "expected ':' here") ||
10803 parseToken(lltok::lparen, "expected '(' here"))
10804 return true;
10805
10806 IdLocListType VContexts;
10807 size_t CallsNum = 0;
10808 do {
10809 FunctionSummary::ParamAccess ParamAccess;
10810 if (parseParamAccess(ParamAccess, VContexts))
10811 return true;
10812 CallsNum += ParamAccess.Calls.size();
10813 assert(VContexts.size() == CallsNum);
10814 (void)CallsNum;
10815 Params.emplace_back(std::move(ParamAccess));
10816 } while (EatIfPresent(lltok::comma));
10817
10818 if (parseToken(lltok::rparen, "expected ')' here"))
10819 return true;
10820
10821 // Now that the Params is finalized, it is safe to save the locations
10822 // of any forward GV references that need updating later.
10823 IdLocListType::const_iterator ItContext = VContexts.begin();
10824 for (auto &PA : Params) {
10825 for (auto &C : PA.Calls) {
10826 if (C.Callee.getRef() == FwdVIRef)
10827 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10828 ItContext->second);
10829 ++ItContext;
10830 }
10831 }
10832 assert(ItContext == VContexts.end());
10833
10834 return false;
10835}
10836
10837/// OptionalRefs
10838/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10839bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10840 assert(Lex.getKind() == lltok::kw_refs);
10841 Lex.Lex();
10842
10843 if (parseToken(lltok::colon, "expected ':' in refs") ||
10844 parseToken(lltok::lparen, "expected '(' in refs"))
10845 return true;
10846
10847 struct ValueContext {
10848 ValueInfo VI;
10849 unsigned GVId;
10850 LocTy Loc;
10851 };
10852 std::vector<ValueContext> VContexts;
10853 // parse each ref edge
10854 do {
10855 ValueContext VC;
10856 VC.Loc = Lex.getLoc();
10857 if (parseGVReference(VC.VI, VC.GVId))
10858 return true;
10859 VContexts.push_back(VC);
10860 } while (EatIfPresent(lltok::comma));
10861
10862 // Sort value contexts so that ones with writeonly
10863 // and readonly ValueInfo are at the end of VContexts vector.
10864 // See FunctionSummary::specialRefCounts()
10865 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10866 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10867 });
10868
10869 IdToIndexMapType IdToIndexMap;
10870 for (auto &VC : VContexts) {
10871 // Keep track of the Refs array index needing a forward reference.
10872 // We will save the location of the ValueInfo needing an update, but
10873 // can only do so once the std::vector is finalized.
10874 if (VC.VI.getRef() == FwdVIRef)
10875 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10876 Refs.push_back(VC.VI);
10877 }
10878
10879 // Now that the Refs vector is finalized, it is safe to save the locations
10880 // of any forward GV references that need updating later.
10881 for (auto I : IdToIndexMap) {
10882 auto &Infos = ForwardRefValueInfos[I.first];
10883 for (auto P : I.second) {
10884 assert(Refs[P.first].getRef() == FwdVIRef &&
10885 "Forward referenced ValueInfo expected to be empty");
10886 Infos.emplace_back(&Refs[P.first], P.second);
10887 }
10888 }
10889
10890 if (parseToken(lltok::rparen, "expected ')' in refs"))
10891 return true;
10892
10893 return false;
10894}
10895
10896/// OptionalTypeIdInfo
10897/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10898/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10899/// [',' TypeCheckedLoadConstVCalls]? ')'
10900bool LLParser::parseOptionalTypeIdInfo(
10901 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10902 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10903 Lex.Lex();
10904
10905 if (parseToken(lltok::colon, "expected ':' here") ||
10906 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10907 return true;
10908
10909 do {
10910 switch (Lex.getKind()) {
10912 if (parseTypeTests(TypeIdInfo.TypeTests))
10913 return true;
10914 break;
10916 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10917 TypeIdInfo.TypeTestAssumeVCalls))
10918 return true;
10919 break;
10921 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10922 TypeIdInfo.TypeCheckedLoadVCalls))
10923 return true;
10924 break;
10926 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10927 TypeIdInfo.TypeTestAssumeConstVCalls))
10928 return true;
10929 break;
10931 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10932 TypeIdInfo.TypeCheckedLoadConstVCalls))
10933 return true;
10934 break;
10935 default:
10936 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10937 }
10938 } while (EatIfPresent(lltok::comma));
10939
10940 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10941 return true;
10942
10943 return false;
10944}
10945
10946/// TypeTests
10947/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10948/// [',' (SummaryID | UInt64)]* ')'
10949bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10950 assert(Lex.getKind() == lltok::kw_typeTests);
10951 Lex.Lex();
10952
10953 if (parseToken(lltok::colon, "expected ':' here") ||
10954 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10955 return true;
10956
10957 IdToIndexMapType IdToIndexMap;
10958 do {
10960 if (Lex.getKind() == lltok::SummaryID) {
10961 unsigned ID = Lex.getUIntVal();
10962 LocTy Loc = Lex.getLoc();
10963 // Keep track of the TypeTests array index needing a forward reference.
10964 // We will save the location of the GUID needing an update, but
10965 // can only do so once the std::vector is finalized.
10966 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10967 Lex.Lex();
10968 } else if (parseUInt64(GUID))
10969 return true;
10970 TypeTests.push_back(GUID);
10971 } while (EatIfPresent(lltok::comma));
10972
10973 // Now that the TypeTests vector is finalized, it is safe to save the
10974 // locations of any forward GV references that need updating later.
10975 for (auto I : IdToIndexMap) {
10976 auto &Ids = ForwardRefTypeIds[I.first];
10977 for (auto P : I.second) {
10978 assert(TypeTests[P.first] == 0 &&
10979 "Forward referenced type id GUID expected to be 0");
10980 Ids.emplace_back(&TypeTests[P.first], P.second);
10981 }
10982 }
10983
10984 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10985 return true;
10986
10987 return false;
10988}
10989
10990/// VFuncIdList
10991/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10992bool LLParser::parseVFuncIdList(
10993 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10994 assert(Lex.getKind() == Kind);
10995 Lex.Lex();
10996
10997 if (parseToken(lltok::colon, "expected ':' here") ||
10998 parseToken(lltok::lparen, "expected '(' here"))
10999 return true;
11000
11001 IdToIndexMapType IdToIndexMap;
11002 do {
11003 FunctionSummary::VFuncId VFuncId;
11004 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
11005 return true;
11006 VFuncIdList.push_back(VFuncId);
11007 } while (EatIfPresent(lltok::comma));
11008
11009 if (parseToken(lltok::rparen, "expected ')' here"))
11010 return true;
11011
11012 // Now that the VFuncIdList vector is finalized, it is safe to save the
11013 // locations of any forward GV references that need updating later.
11014 for (auto I : IdToIndexMap) {
11015 auto &Ids = ForwardRefTypeIds[I.first];
11016 for (auto P : I.second) {
11017 assert(VFuncIdList[P.first].GUID == 0 &&
11018 "Forward referenced type id GUID expected to be 0");
11019 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
11020 }
11021 }
11022
11023 return false;
11024}
11025
11026/// ConstVCallList
11027/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
11028bool LLParser::parseConstVCallList(
11029 lltok::Kind Kind,
11030 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
11031 assert(Lex.getKind() == Kind);
11032 Lex.Lex();
11033
11034 if (parseToken(lltok::colon, "expected ':' here") ||
11035 parseToken(lltok::lparen, "expected '(' here"))
11036 return true;
11037
11038 IdToIndexMapType IdToIndexMap;
11039 do {
11040 FunctionSummary::ConstVCall ConstVCall;
11041 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11042 return true;
11043 ConstVCallList.push_back(ConstVCall);
11044 } while (EatIfPresent(lltok::comma));
11045
11046 if (parseToken(lltok::rparen, "expected ')' here"))
11047 return true;
11048
11049 // Now that the ConstVCallList vector is finalized, it is safe to save the
11050 // locations of any forward GV references that need updating later.
11051 for (auto I : IdToIndexMap) {
11052 auto &Ids = ForwardRefTypeIds[I.first];
11053 for (auto P : I.second) {
11054 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
11055 "Forward referenced type id GUID expected to be 0");
11056 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
11057 }
11058 }
11059
11060 return false;
11061}
11062
11063/// ConstVCall
11064/// ::= '(' VFuncId ',' Args ')'
11065bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11066 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11067 if (parseToken(lltok::lparen, "expected '(' here") ||
11068 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
11069 return true;
11070
11071 if (EatIfPresent(lltok::comma))
11072 if (parseArgs(ConstVCall.Args))
11073 return true;
11074
11075 if (parseToken(lltok::rparen, "expected ')' here"))
11076 return true;
11077
11078 return false;
11079}
11080
11081/// VFuncId
11082/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
11083/// 'offset' ':' UInt64 ')'
11084bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11085 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11086 assert(Lex.getKind() == lltok::kw_vFuncId);
11087 Lex.Lex();
11088
11089 if (parseToken(lltok::colon, "expected ':' here") ||
11090 parseToken(lltok::lparen, "expected '(' here"))
11091 return true;
11092
11093 if (Lex.getKind() == lltok::SummaryID) {
11094 VFuncId.GUID = 0;
11095 unsigned ID = Lex.getUIntVal();
11096 LocTy Loc = Lex.getLoc();
11097 // Keep track of the array index needing a forward reference.
11098 // We will save the location of the GUID needing an update, but
11099 // can only do so once the caller's std::vector is finalized.
11100 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
11101 Lex.Lex();
11102 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
11103 parseToken(lltok::colon, "expected ':' here") ||
11104 parseUInt64(VFuncId.GUID))
11105 return true;
11106
11107 if (parseToken(lltok::comma, "expected ',' here") ||
11108 parseToken(lltok::kw_offset, "expected 'offset' here") ||
11109 parseToken(lltok::colon, "expected ':' here") ||
11110 parseUInt64(VFuncId.Offset) ||
11111 parseToken(lltok::rparen, "expected ')' here"))
11112 return true;
11113
11114 return false;
11115}
11116
11117/// GVFlags
11118/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
11119/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
11120/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
11121/// 'canAutoHide' ':' Flag ',' ')'
11122bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11123 assert(Lex.getKind() == lltok::kw_flags);
11124 Lex.Lex();
11125
11126 if (parseToken(lltok::colon, "expected ':' here") ||
11127 parseToken(lltok::lparen, "expected '(' here"))
11128 return true;
11129
11130 do {
11131 unsigned Flag = 0;
11132 switch (Lex.getKind()) {
11133 case lltok::kw_linkage:
11134 Lex.Lex();
11135 if (parseToken(lltok::colon, "expected ':'"))
11136 return true;
11137 bool HasLinkage;
11138 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
11139 assert(HasLinkage && "Linkage not optional in summary entry");
11140 Lex.Lex();
11141 break;
11143 Lex.Lex();
11144 if (parseToken(lltok::colon, "expected ':'"))
11145 return true;
11146 parseOptionalVisibility(Flag);
11147 GVFlags.Visibility = Flag;
11148 break;
11150 Lex.Lex();
11151 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11152 return true;
11153 GVFlags.NotEligibleToImport = Flag;
11154 break;
11155 case lltok::kw_live:
11156 Lex.Lex();
11157 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11158 return true;
11159 GVFlags.Live = Flag;
11160 break;
11161 case lltok::kw_dsoLocal:
11162 Lex.Lex();
11163 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11164 return true;
11165 GVFlags.DSOLocal = Flag;
11166 break;
11168 Lex.Lex();
11169 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11170 return true;
11171 GVFlags.CanAutoHide = Flag;
11172 break;
11174 Lex.Lex();
11175 if (parseToken(lltok::colon, "expected ':'"))
11176 return true;
11178 if (parseOptionalImportType(Lex.getKind(), IK))
11179 return true;
11180 GVFlags.ImportType = static_cast<unsigned>(IK);
11181 Lex.Lex();
11182 break;
11184 Lex.Lex();
11185 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11186 return true;
11187 GVFlags.NoRenameOnPromotion = Flag;
11188 break;
11189 default:
11190 return error(Lex.getLoc(), "expected gv flag type");
11191 }
11192 } while (EatIfPresent(lltok::comma));
11193
11194 if (parseToken(lltok::rparen, "expected ')' here"))
11195 return true;
11196
11197 return false;
11198}
11199
11200/// GVarFlags
11201/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
11202/// ',' 'writeonly' ':' Flag
11203/// ',' 'constant' ':' Flag ')'
11204bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11205 assert(Lex.getKind() == lltok::kw_varFlags);
11206 Lex.Lex();
11207
11208 if (parseToken(lltok::colon, "expected ':' here") ||
11209 parseToken(lltok::lparen, "expected '(' here"))
11210 return true;
11211
11212 auto ParseRest = [this](unsigned int &Val) {
11213 Lex.Lex();
11214 if (parseToken(lltok::colon, "expected ':'"))
11215 return true;
11216 return parseFlag(Val);
11217 };
11218
11219 do {
11220 unsigned Flag = 0;
11221 switch (Lex.getKind()) {
11222 case lltok::kw_readonly:
11223 if (ParseRest(Flag))
11224 return true;
11225 GVarFlags.MaybeReadOnly = Flag;
11226 break;
11227 case lltok::kw_writeonly:
11228 if (ParseRest(Flag))
11229 return true;
11230 GVarFlags.MaybeWriteOnly = Flag;
11231 break;
11232 case lltok::kw_constant:
11233 if (ParseRest(Flag))
11234 return true;
11235 GVarFlags.Constant = Flag;
11236 break;
11238 if (ParseRest(Flag))
11239 return true;
11240 GVarFlags.VCallVisibility = Flag;
11241 break;
11242 default:
11243 return error(Lex.getLoc(), "expected gvar flag type");
11244 }
11245 } while (EatIfPresent(lltok::comma));
11246 return parseToken(lltok::rparen, "expected ')' here");
11247}
11248
11249/// ModuleReference
11250/// ::= 'module' ':' UInt
11251bool LLParser::parseModuleReference(StringRef &ModulePath) {
11252 // parse module id.
11253 if (parseToken(lltok::kw_module, "expected 'module' here") ||
11254 parseToken(lltok::colon, "expected ':' here") ||
11255 parseToken(lltok::SummaryID, "expected module ID"))
11256 return true;
11257
11258 unsigned ModuleID = Lex.getUIntVal();
11259 auto I = ModuleIdMap.find(ModuleID);
11260 // We should have already parsed all module IDs
11261 assert(I != ModuleIdMap.end());
11262 ModulePath = I->second;
11263 return false;
11264}
11265
11266/// GVReference
11267/// ::= SummaryID
11268bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11269 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
11270 if (!ReadOnly)
11271 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11272 if (parseToken(lltok::SummaryID, "expected GV ID"))
11273 return true;
11274
11275 GVId = Lex.getUIntVal();
11276 // Check if we already have a VI for this GV
11277 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11278 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11279 VI = NumberedValueInfos[GVId];
11280 } else
11281 // We will create a forward reference to the stored location.
11282 VI = ValueInfo(false, FwdVIRef);
11283
11284 if (ReadOnly)
11285 VI.setReadOnly();
11286 if (WriteOnly)
11287 VI.setWriteOnly();
11288 return false;
11289}
11290
11291/// OptionalAllocs
11292/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11293/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11294/// ',' MemProfs ')'
11295/// Version ::= UInt32
11296bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11297 assert(Lex.getKind() == lltok::kw_allocs);
11298 Lex.Lex();
11299
11300 if (parseToken(lltok::colon, "expected ':' in allocs") ||
11301 parseToken(lltok::lparen, "expected '(' in allocs"))
11302 return true;
11303
11304 // parse each alloc
11305 do {
11306 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
11307 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
11308 parseToken(lltok::colon, "expected ':'") ||
11309 parseToken(lltok::lparen, "expected '(' in versions"))
11310 return true;
11311
11312 SmallVector<uint8_t> Versions;
11313 do {
11314 uint8_t V = 0;
11315 if (parseAllocType(V))
11316 return true;
11317 Versions.push_back(V);
11318 } while (EatIfPresent(lltok::comma));
11319
11320 if (parseToken(lltok::rparen, "expected ')' in versions") ||
11321 parseToken(lltok::comma, "expected ',' in alloc"))
11322 return true;
11323
11324 std::vector<MIBInfo> MIBs;
11325 if (parseMemProfs(MIBs))
11326 return true;
11327
11328 Allocs.push_back({Versions, MIBs});
11329
11330 if (parseToken(lltok::rparen, "expected ')' in alloc"))
11331 return true;
11332 } while (EatIfPresent(lltok::comma));
11333
11334 if (parseToken(lltok::rparen, "expected ')' in allocs"))
11335 return true;
11336
11337 return false;
11338}
11339
11340/// MemProfs
11341/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11342/// MemProf ::= '(' 'type' ':' AllocType
11343/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11344/// StackId ::= UInt64
11345bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11346 assert(Lex.getKind() == lltok::kw_memProf);
11347 Lex.Lex();
11348
11349 if (parseToken(lltok::colon, "expected ':' in memprof") ||
11350 parseToken(lltok::lparen, "expected '(' in memprof"))
11351 return true;
11352
11353 // parse each MIB
11354 do {
11355 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
11356 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
11357 parseToken(lltok::colon, "expected ':'"))
11358 return true;
11359
11360 uint8_t AllocType;
11361 if (parseAllocType(AllocType))
11362 return true;
11363
11364 if (parseToken(lltok::comma, "expected ',' in memprof") ||
11365 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
11366 parseToken(lltok::colon, "expected ':'") ||
11367 parseToken(lltok::lparen, "expected '(' in stackIds"))
11368 return true;
11369
11370 SmallVector<unsigned> StackIdIndices;
11371 // Combined index alloc records may not have a stack id list.
11372 if (Lex.getKind() != lltok::rparen) {
11373 do {
11374 uint64_t StackId = 0;
11375 if (parseUInt64(StackId))
11376 return true;
11377 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11378 } while (EatIfPresent(lltok::comma));
11379 }
11380
11381 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11382 return true;
11383
11384 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11385
11386 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11387 return true;
11388 } while (EatIfPresent(lltok::comma));
11389
11390 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11391 return true;
11392
11393 return false;
11394}
11395
11396/// AllocType
11397/// := ('none'|'notcold'|'cold'|'hot')
11398bool LLParser::parseAllocType(uint8_t &AllocType) {
11399 switch (Lex.getKind()) {
11400 case lltok::kw_none:
11402 break;
11403 case lltok::kw_notcold:
11405 break;
11406 case lltok::kw_cold:
11408 break;
11409 case lltok::kw_hot:
11410 AllocType = (uint8_t)AllocationType::Hot;
11411 break;
11412 default:
11413 return error(Lex.getLoc(), "invalid alloc type");
11414 }
11415 Lex.Lex();
11416 return false;
11417}
11418
11419/// OptionalCallsites
11420/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11421/// Callsite ::= '(' 'callee' ':' GVReference
11422/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11423/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11424/// Version ::= UInt32
11425/// StackId ::= UInt64
11426bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11427 assert(Lex.getKind() == lltok::kw_callsites);
11428 Lex.Lex();
11429
11430 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11431 parseToken(lltok::lparen, "expected '(' in callsites"))
11432 return true;
11433
11434 IdToIndexMapType IdToIndexMap;
11435 // parse each callsite
11436 do {
11437 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11438 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11439 parseToken(lltok::colon, "expected ':'"))
11440 return true;
11441
11442 ValueInfo VI;
11443 unsigned GVId = 0;
11444 LocTy Loc = Lex.getLoc();
11445 if (!EatIfPresent(lltok::kw_null)) {
11446 if (parseGVReference(VI, GVId))
11447 return true;
11448 }
11449
11450 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11451 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11452 parseToken(lltok::colon, "expected ':'") ||
11453 parseToken(lltok::lparen, "expected '(' in clones"))
11454 return true;
11455
11456 SmallVector<unsigned> Clones;
11457 do {
11458 unsigned V = 0;
11459 if (parseUInt32(V))
11460 return true;
11461 Clones.push_back(V);
11462 } while (EatIfPresent(lltok::comma));
11463
11464 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11465 parseToken(lltok::comma, "expected ',' in callsite") ||
11466 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11467 parseToken(lltok::colon, "expected ':'") ||
11468 parseToken(lltok::lparen, "expected '(' in stackIds"))
11469 return true;
11470
11471 SmallVector<unsigned> StackIdIndices;
11472 // Synthesized callsite records will not have a stack id list.
11473 if (Lex.getKind() != lltok::rparen) {
11474 do {
11475 uint64_t StackId = 0;
11476 if (parseUInt64(StackId))
11477 return true;
11478 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11479 } while (EatIfPresent(lltok::comma));
11480 }
11481
11482 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11483 return true;
11484
11485 // Keep track of the Callsites array index needing a forward reference.
11486 // We will save the location of the ValueInfo needing an update, but
11487 // can only do so once the SmallVector is finalized.
11488 if (VI.getRef() == FwdVIRef)
11489 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11490 Callsites.push_back({VI, Clones, StackIdIndices});
11491
11492 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11493 return true;
11494 } while (EatIfPresent(lltok::comma));
11495
11496 // Now that the Callsites vector is finalized, it is safe to save the
11497 // locations of any forward GV references that need updating later.
11498 for (auto I : IdToIndexMap) {
11499 auto &Infos = ForwardRefValueInfos[I.first];
11500 for (auto P : I.second) {
11501 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11502 "Forward referenced ValueInfo expected to be empty");
11503 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11504 }
11505 }
11506
11507 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11508 return true;
11509
11510 return false;
11511}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
static uint64_t align(uint64_t Size)
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
@ Default
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Definition Globals.cpp:317
Hexagon Common GEP
#define _
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static SmallVector< MemoryEffects::Location, 2 > keywordToLoc(lltok::Kind Tok)
static std::optional< DenormalMode::DenormalModeKind > keywordToDenormalModeKind(lltok::Kind Tok)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
Definition LLParser.cpp:152
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
static ValueInfo EmptyVI
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
Definition LLParser.cpp:68
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
if(PassOpts->AAPipeline)
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
dot regions Print regions of function to dot file(with no function bodies)"
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
static const char * name
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file provides utility classes that use RAII to save and restore values.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
#define error(X)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Value * RHS
Value * LHS
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
Definition APFloat.cpp:318
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:369
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1242
APSInt extOrTrunc(uint32_t width) const
Definition APSInt.h:119
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:829
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
Definition Attributes.h:143
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:124
@ None
No attributes have been set.
Definition Attributes.h:126
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:427
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:537
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition Constants.h:1598
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1470
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
LLVM_ABI void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
unsigned size() const
Definition DenseMap.h:172
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool any() const
Definition FMF.h:56
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Definition Type.cpp:467
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition Type.cpp:462
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
Argument * arg_iterator
Definition Function.h:73
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:822
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:448
arg_iterator arg_begin()
Definition Function.h:852
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1024
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:331
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
Definition Function.h:1036
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:276
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:692
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
Definition Globals.cpp:749
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:348
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
std::pair< key_type, mapped_type > value_type
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:318
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
Definition Globals.cpp:110
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:158
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:234
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:324
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
Definition Globals.cpp:301
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:613
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition Globals.cpp:660
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind Lex()
Definition LLLexer.h:68
lltok::Kind getKind() const
Definition LLLexer.h:72
LocTy getLoc() const
Definition LLLexer.h:71
LLVM_ABI bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:124
LLLexer::LocTy LocTy
Definition LLParser.h:110
LLVMContext & getContext()
Definition LLParser.h:238
LLVM_ABI bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:108
LLVM_ABI bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:95
LLVM_ABI bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:76
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
Metadata node.
Definition Metadata.h:1069
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1575
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1567
A single uniqued string.
Definition Metadata.h:722
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:615
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1524
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1513
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1533
static MemoryEffectsBase readOnly()
Definition ModRef.h:133
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition ModRef.h:224
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:149
bool isTargetMemLoc(IRMemLocation Loc) const
Whether location is target memory location.
Definition ModRef.h:279
static MemoryEffectsBase writeOnly()
Definition ModRef.h:138
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:166
static MemoryEffectsBase none()
Definition ModRef.h:128
static MemoryEffectsBase unknown()
Definition ModRef.h:123
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:184
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:111
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
Definition Module.h:82
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:911
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:928
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
Definition SMLoc.h:22
constexpr const char * getPointer() const
Definition SMLoc.h:33
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator end()
Definition StringMap.h:213
iterator find(StringRef Key)
Definition StringMap.h:226
StringMapIterBase< Comdat, false > iterator
Definition StringMap.h:208
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:477
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:683
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:767
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
Definition Type.cpp:602
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:504
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Definition Type.cpp:966
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:310
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:242
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:279
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:289
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:230
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
Definition Type.cpp:283
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition Type.cpp:251
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:319
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:273
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:236
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:233
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:510
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
static constexpr uint64_t MaximumAlignment
Definition Value.h:799
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:108
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
Definition Dwarf.cpp:614
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:275
LLVM_ABI unsigned getLanguageDialect(StringRef LanguageDialectString)
Definition Dwarf.cpp:633
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:669
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
Definition Dwarf.cpp:424
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
Definition Dwarf.cpp:386
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
Definition Dwarf.cpp:405
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
Definition Dwarf.cpp:741
#define UINT64_MAX
Definition DataTypes.h:77
#define INT64_MIN
Definition DataTypes.h:74
#define INT64_MAX
Definition DataTypes.h:71
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ X86_StdCall
stdcall is mostly used by the Win32 API.
Definition CallingConv.h:99
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
constexpr bool isAtomic(const T &...O)
Definition SIDefines.h:396
constexpr bool isPacked(const T &...O)
Definition SIDefines.h:340
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ DW_CC_hi_user
Definition Dwarf.h:848
@ DW_ATE_hi_user
Definition Dwarf.h:163
@ DW_LLVM_LANG_DIALECT_max
Definition Dwarf.h:212
@ DW_APPLE_ENUM_KIND_max
Definition Dwarf.h:206
@ DW_LANG_hi_user
Definition Dwarf.h:226
MacinfoRecordType
Definition Dwarf.h:898
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:904
@ DW_VIRTUALITY_max
Definition Dwarf.h:200
@ DW_TAG_hi_user
Definition Dwarf.h:109
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
Definition Dwarf.h:48
@ DW_MACINFO_invalid
Macinfo type for invalid results.
Definition Dwarf.h:50
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Definition Dwarf.h:49
@ kw_msp430_intrcc
Definition LLToken.h:155
@ kw_riscv_vls_cc
Definition LLToken.h:191
@ kw_cxx_fast_tlscc
Definition LLToken.h:174
@ kw_extractvalue
Definition LLToken.h:377
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:512
@ DwarfLangDialect
Definition LLToken.h:515
@ kw_arm_apcscc
Definition LLToken.h:147
@ kw_inteldialect
Definition LLToken.h:129
@ kw_x86_stdcallcc
Definition LLToken.h:142
@ kw_constant
Definition LLToken.h:48
@ kw_initialexec
Definition LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition LLToken.h:153
@ kw_provenance
Definition LLToken.h:225
@ kw_mustBeUnreachable
Definition LLToken.h:423
@ kw_internal
Definition LLToken.h:54
@ kw_target_mem
Definition LLToken.h:211
@ kw_no_sanitize_hwaddress
Definition LLToken.h:491
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:462
@ kw_canAutoHide
Definition LLToken.h:406
@ kw_alwaysInline
Definition LLToken.h:419
@ kw_insertelement
Definition LLToken.h:374
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:194
@ kw_fmaximumnum
Definition LLToken.h:296
@ kw_inaccessiblememonly
Definition LLToken.h:218
@ kw_amdgpu_gfx
Definition LLToken.h:185
@ kw_getelementptr
Definition LLToken.h:371
@ FloatHexLiteral
Definition LLToken.h:532
@ kw_m68k_rtdcc
Definition LLToken.h:188
@ kw_preserve_nonecc
Definition LLToken.h:169
@ kw_x86_fastcallcc
Definition LLToken.h:143
@ kw_visibility
Definition LLToken.h:402
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:193
@ kw_positivezero
Definition LLToken.h:231
@ kw_unordered
Definition LLToken.h:96
@ kw_singleImpl
Definition LLToken.h:465
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:141
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:442
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:151
@ kw_amdgpu_kernel
Definition LLToken.h:184
@ kw_uselistorder
Definition LLToken.h:390
@ kw_blockcount
Definition LLToken.h:400
@ kw_notEligibleToImport
Definition LLToken.h:403
@ kw_linkonce_odr
Definition LLToken.h:56
@ kw_protected
Definition LLToken.h:66
@ kw_dllexport
Definition LLToken.h:61
@ kw_x86_vectorcallcc
Definition LLToken.h:145
@ kw_ptx_device
Definition LLToken.h:159
@ kw_personality
Definition LLToken.h:346
@ DwarfEnumKind
Definition LLToken.h:526
@ kw_declaration
Definition LLToken.h:409
@ kw_elementwise
Definition LLToken.h:94
@ DwarfAttEncoding
Definition LLToken.h:511
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:160
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:422
@ kw_x86_intrcc
Definition LLToken.h:171
@ kw_addrspacecast
Definition LLToken.h:341
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:509
@ kw_x86_thiscallcc
Definition LLToken.h:144
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:192
@ kw_unnamed_addr
Definition LLToken.h:67
@ NameTableKind
Definition LLToken.h:518
@ kw_inlineBits
Definition LLToken.h:460
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:217
@ kw_blockaddress
Definition LLToken.h:379
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:186
@ kw_landingpad
Definition LLToken.h:345
@ kw_aarch64_vector_pcs
Definition LLToken.h:150
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:441
@ FixedPointKind
Definition LLToken.h:519
@ kw_target_mem1
Definition LLToken.h:213
@ kw_ptx_kernel
Definition LLToken.h:158
@ kw_extractelement
Definition LLToken.h:373
@ kw_branchFunnel
Definition LLToken.h:466
@ kw_typeidCompatibleVTable
Definition LLToken.h:447
@ kw_vTableFuncs
Definition LLToken.h:433
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:440
@ kw_no_sanitize_address
Definition LLToken.h:488
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:219
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:494
@ DwarfSourceLangName
Definition LLToken.h:514
@ kw_noRenameOnPromotion
Definition LLToken.h:410
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:183
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:359
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:148
@ kw_read_provenance
Definition LLToken.h:226
@ kw_cleanuppad
Definition LLToken.h:362
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:467
@ kw_target_mem0
Definition LLToken.h:212
@ kw_swifttailcc
Definition LLToken.h:166
@ kw_monotonic
Definition LLToken.h:97
@ kw_typeTestAssumeVCalls
Definition LLToken.h:439
@ kw_preservesign
Definition LLToken.h:230
@ kw_attributes
Definition LLToken.h:197
@ kw_code_model
Definition LLToken.h:123
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:470
@ kw_sideeffect
Definition LLToken.h:128
@ kw_sizeM1BitWidth
Definition LLToken.h:456
@ kw_nodeduplicate
Definition LLToken.h:261
@ kw_avr_signalcc
Definition LLToken.h:157
@ kw_exactmatch
Definition LLToken.h:259
@ kw_fminimumnum
Definition LLToken.h:297
@ kw_unreachable
Definition LLToken.h:357
@ kw_intel_ocl_bicc
Definition LLToken.h:140
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:417
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:152
@ kw_preserve_allcc
Definition LLToken.h:168
@ kw_importType
Definition LLToken.h:407
@ kw_cleanupret
Definition LLToken.h:358
@ kw_shufflevector
Definition LLToken.h:375
@ kw_riscv_vector_cc
Definition LLToken.h:190
@ kw_avr_intrcc
Definition LLToken.h:156
@ kw_definition
Definition LLToken.h:408
@ kw_virtualConstProp
Definition LLToken.h:472
@ kw_vcall_visibility
Definition LLToken.h:461
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:210
@ kw_preserve_mostcc
Definition LLToken.h:167
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:149
@ kw_typeTestRes
Definition LLToken.h:449
@ kw_x86_regcallcc
Definition LLToken.h:146
@ kw_typeIdInfo
Definition LLToken.h:437
@ kw_amdgpu_cs_chain
Definition LLToken.h:182
@ kw_dso_local_equivalent
Definition LLToken.h:380
@ kw_x86_64_sysvcc
Definition LLToken.h:162
@ DbgRecordType
Definition LLToken.h:525
@ kw_address_is_null
Definition LLToken.h:224
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:154
@ kw_uniqueRetVal
Definition LLToken.h:471
@ kw_insertvalue
Definition LLToken.h:378
@ kw_indirectbr
Definition LLToken.h:354
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
AllocFnKind
Definition Attributes.h:53
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
static void assign(DXContainerYAML::SourceInfo::SectionHeader &Dst, const dxbc::SourceInfo::SectionHeader &Src)
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
LLVM_ABI void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
UWTableKind
Definition CodeGen.h:221
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:224
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:223
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:383
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:365
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
IRMemLocation
The locations at which a function might access memory.
Definition ModRef.h:60
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h:36
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2012
DWARFExpression::Operation Op
@ NearestTiesToEven
roundTiesToEven.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2192
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
LLVM_ABI MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
#define N
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static constexpr DenormalMode getInvalid()
static constexpr DenormalMode getIEEE()
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
unsigned NoRenameOnPromotion
This field is written by the ThinLTO prelink stage to decide whether a particular static global value...
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
LLVM_ABI bool set(StringRef Name, std::string Value)
Set a property using a string name.
Definition Module.cpp:1015
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:32
std::map< unsigned, Type * > Types
Definition SlotMapping.h:36
StringMap< Type * > NamedTypes
Definition SlotMapping.h:35
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition SlotMapping.h:34
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:33
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition LLParser.h:54
@ t_PackedConstantStruct
Definition LLParser.h:72
@ t_ConstantStruct
Definition LLParser.h:71
@ t_ConstantSplat
Definition LLParser.h:69
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
unsigned UIntVal
Definition LLParser.h:76
FunctionType * FTy
Definition LLParser.h:77
LLLexer::LocTy Loc
Definition LLParser.h:75
std::string StrVal
Definition LLParser.h:78
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
bool isWriteOnly() const
bool isReadOnly() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.