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.
472 for (Function &F : llvm::make_early_inc_range(*M))
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;
1630 Alignment = Align(Value);
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");
2528 Alignment = Align(Value);
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");
2557 Alignment = Align(Value);
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/// parseDIImportedEntity:
6704/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6705/// line: 7, name: "foo", elements: !2)
6706bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6707#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6708 REQUIRED(tag, DwarfTagField, ); \
6709 REQUIRED(scope, MDField, ); \
6710 OPTIONAL(entity, MDField, ); \
6711 OPTIONAL(file, MDField, ); \
6712 OPTIONAL(line, LineField, ); \
6713 OPTIONAL(name, MDStringField, ); \
6714 OPTIONAL(elements, MDField, );
6716#undef VISIT_MD_FIELDS
6717
6718 Result = GET_OR_DISTINCT(DIImportedEntity,
6719 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6720 line.Val, name.Val, elements.Val));
6721 return false;
6722}
6723
6724#undef PARSE_MD_FIELD
6725#undef NOP_FIELD
6726#undef REQUIRE_FIELD
6727#undef DECLARE_FIELD
6728
6729/// parseMetadataAsValue
6730/// ::= metadata i32 %local
6731/// ::= metadata i32 @global
6732/// ::= metadata i32 7
6733/// ::= metadata !0
6734/// ::= metadata !{...}
6735/// ::= metadata !"string"
6736bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6737 // Note: the type 'metadata' has already been parsed.
6738 Metadata *MD;
6739 if (parseMetadata(MD, &PFS))
6740 return true;
6741
6742 V = MetadataAsValue::get(Context, MD);
6743 return false;
6744}
6745
6746/// parseValueAsMetadata
6747/// ::= i32 %local
6748/// ::= i32 @global
6749/// ::= i32 7
6750bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6751 PerFunctionState *PFS) {
6752 Type *Ty;
6753 LocTy Loc;
6754 if (parseType(Ty, TypeMsg, Loc))
6755 return true;
6756 if (Ty->isMetadataTy())
6757 return error(Loc, "invalid metadata-value-metadata roundtrip");
6758
6759 Value *V;
6760 if (parseValue(Ty, V, PFS))
6761 return true;
6762
6763 MD = ValueAsMetadata::get(V);
6764 return false;
6765}
6766
6767/// parseMetadata
6768/// ::= i32 %local
6769/// ::= i32 @global
6770/// ::= i32 7
6771/// ::= !42
6772/// ::= !{...}
6773/// ::= !"string"
6774/// ::= !DILocation(...)
6775bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6776 if (Lex.getKind() == lltok::MetadataVar) {
6777 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6778 // so parsing this requires a Function State.
6779 if (Lex.getStrVal() == "DIArgList") {
6780 Metadata *AL;
6781 if (parseDIArgList(AL, PFS))
6782 return true;
6783 MD = AL;
6784 return false;
6785 }
6786 MDNode *N;
6787 if (parseSpecializedMDNode(N)) {
6788 return true;
6789 }
6790 MD = N;
6791 return false;
6792 }
6793
6794 // ValueAsMetadata:
6795 // <type> <value>
6796 if (Lex.getKind() != lltok::exclaim)
6797 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6798
6799 // '!'.
6800 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6801 Lex.Lex();
6802
6803 // MDString:
6804 // ::= '!' STRINGCONSTANT
6805 if (Lex.getKind() == lltok::StringConstant) {
6806 MDString *S;
6807 if (parseMDString(S))
6808 return true;
6809 MD = S;
6810 return false;
6811 }
6812
6813 // MDNode:
6814 // !{ ... }
6815 // !7
6816 MDNode *N;
6817 if (parseMDNodeTail(N))
6818 return true;
6819 MD = N;
6820 return false;
6821}
6822
6823//===----------------------------------------------------------------------===//
6824// Function Parsing.
6825//===----------------------------------------------------------------------===//
6826
6827bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6828 PerFunctionState *PFS) {
6829 if (Ty->isFunctionTy())
6830 return error(ID.Loc, "functions are not values, refer to them as pointers");
6831
6832 switch (ID.Kind) {
6833 case ValID::t_LocalID:
6834 if (!PFS)
6835 return error(ID.Loc, "invalid use of function-local name");
6836 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6837 return V == nullptr;
6838 case ValID::t_LocalName:
6839 if (!PFS)
6840 return error(ID.Loc, "invalid use of function-local name");
6841 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6842 return V == nullptr;
6843 case ValID::t_InlineAsm: {
6844 if (!ID.FTy)
6845 return error(ID.Loc, "invalid type for inline asm constraint string");
6846 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6847 return error(ID.Loc, toString(std::move(Err)));
6848 V = InlineAsm::get(
6849 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6850 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6851 return false;
6852 }
6854 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6855 if (V && ID.NoCFI)
6857 return V == nullptr;
6858 case ValID::t_GlobalID:
6859 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6860 if (V && ID.NoCFI)
6862 return V == nullptr;
6863 case ValID::t_APSInt:
6864 if (!Ty->isIntegerTy() && !Ty->isByteTy())
6865 return error(ID.Loc, "integer/byte constant must have integer/byte type");
6866 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6867 Ty->isIntegerTy() ? V = ConstantInt::get(Context, ID.APSIntVal)
6868 : V = ConstantByte::get(Context, ID.APSIntVal);
6869 return false;
6870 case ValID::t_APFloat:
6871 if (!Ty->isFloatingPointTy() ||
6872 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6873 return error(ID.Loc, "floating point constant invalid for type");
6874
6875 // The lexer has no type info, so builds all half, bfloat, float, and double
6876 // FP constants as double. Fix this here. Long double does not need this.
6877 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6878 // Check for signaling before potentially converting and losing that info.
6879 bool IsSNAN = ID.APFloatVal.isSignaling();
6880 bool Ignored;
6881 if (Ty->isHalfTy())
6882 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6883 &Ignored);
6884 else if (Ty->isBFloatTy())
6885 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6886 &Ignored);
6887 else if (Ty->isFloatTy())
6888 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6889 &Ignored);
6890 if (IsSNAN) {
6891 // The convert call above may quiet an SNaN, so manufacture another
6892 // SNaN. The bitcast works because the payload (significand) parameter
6893 // is truncated to fit.
6894 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6895 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6896 ID.APFloatVal.isNegative(), &Payload);
6897 }
6898 }
6899 V = ConstantFP::get(Context, ID.APFloatVal);
6900
6901 if (V->getType() != Ty)
6902 return error(ID.Loc, "floating point constant does not have type '" +
6903 getTypeString(Ty) + "'");
6904
6905 return false;
6906 case ValID::t_Null:
6907 if (!Ty->isPointerTy())
6908 return error(ID.Loc, "null must be a pointer type");
6910 return false;
6911 case ValID::t_Undef:
6912 // FIXME: LabelTy should not be a first-class type.
6913 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6914 return error(ID.Loc, "invalid type for undef constant");
6915 V = UndefValue::get(Ty);
6916 return false;
6918 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6919 return error(ID.Loc, "invalid empty array initializer");
6920 V = PoisonValue::get(Ty);
6921 return false;
6922 case ValID::t_Zero:
6923 // FIXME: LabelTy should not be a first-class type.
6924 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6925 return error(ID.Loc, "invalid type for null constant");
6926 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6927 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6928 return error(ID.Loc, "invalid type for null constant");
6930 return false;
6931 case ValID::t_None:
6932 if (!Ty->isTokenTy())
6933 return error(ID.Loc, "invalid type for none constant");
6935 return false;
6936 case ValID::t_Poison:
6937 // FIXME: LabelTy should not be a first-class type.
6938 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6939 return error(ID.Loc, "invalid type for poison constant");
6940 V = PoisonValue::get(Ty);
6941 return false;
6942 case ValID::t_Constant:
6943 if (ID.ConstantVal->getType() != Ty)
6944 return error(ID.Loc, "constant expression type mismatch: got type '" +
6945 getTypeString(ID.ConstantVal->getType()) +
6946 "' but expected '" + getTypeString(Ty) + "'");
6947 V = ID.ConstantVal;
6948 return false;
6950 if (!Ty->isVectorTy())
6951 return error(ID.Loc, "vector constant must have vector type");
6952 if (ID.ConstantVal->getType() != Ty->getScalarType())
6953 return error(ID.Loc, "constant expression type mismatch: got type '" +
6954 getTypeString(ID.ConstantVal->getType()) +
6955 "' but expected '" +
6956 getTypeString(Ty->getScalarType()) + "'");
6957 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6958 ID.ConstantVal);
6959 return false;
6962 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6963 if (ST->getNumElements() != ID.UIntVal)
6964 return error(ID.Loc,
6965 "initializer with struct type has wrong # elements");
6966 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6967 return error(ID.Loc, "packed'ness of initializer and type don't match");
6968
6969 // Verify that the elements are compatible with the structtype.
6970 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6971 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6972 return error(
6973 ID.Loc,
6974 "element " + Twine(i) +
6975 " of struct initializer doesn't match struct element type");
6976
6978 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6979 } else
6980 return error(ID.Loc, "constant expression type mismatch");
6981 return false;
6982 }
6983 llvm_unreachable("Invalid ValID");
6984}
6985
6986bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6987 C = nullptr;
6988 ValID ID;
6989 auto Loc = Lex.getLoc();
6990 if (parseValID(ID, /*PFS=*/nullptr, /*ExpectedTy=*/Ty))
6991 return true;
6992 switch (ID.Kind) {
6993 case ValID::t_APSInt:
6994 case ValID::t_APFloat:
6995 case ValID::t_Undef:
6996 case ValID::t_Poison:
6997 case ValID::t_Zero:
6998 case ValID::t_Constant:
7002 Value *V;
7003 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
7004 return true;
7005 assert(isa<Constant>(V) && "Expected a constant value");
7006 C = cast<Constant>(V);
7007 return false;
7008 }
7009 case ValID::t_Null:
7011 return false;
7012 default:
7013 return error(Loc, "expected a constant value");
7014 }
7015}
7016
7017bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
7018 V = nullptr;
7019 ValID ID;
7020
7021 FileLoc Start = getTokLineColumnPos();
7022 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
7023 if (!Ret && ParserContext) {
7024 FileLoc End = getPrevTokEndLineColumnPos();
7025 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
7026 }
7027 return Ret;
7028}
7029
7030bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
7031 Type *Ty = nullptr;
7032 return parseType(Ty) || parseValue(Ty, V, PFS);
7033}
7034
7035bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
7036 PerFunctionState &PFS) {
7037 Value *V;
7038 Loc = Lex.getLoc();
7039 if (parseTypeAndValue(V, PFS))
7040 return true;
7041 if (!isa<BasicBlock>(V))
7042 return error(Loc, "expected a basic block");
7043 BB = cast<BasicBlock>(V);
7044 return false;
7045}
7046
7048 // Exit early for the common (non-debug-intrinsic) case.
7049 // We can make this the only check when we begin supporting all "llvm.dbg"
7050 // intrinsics in the new debug info format.
7051 if (!Name.starts_with("llvm.dbg."))
7052 return false;
7054 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7055 FnID == Intrinsic::dbg_assign;
7056}
7057
7058/// FunctionHeader
7059/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
7060/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
7061/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
7062/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
7063bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
7064 unsigned &FunctionNumber,
7065 SmallVectorImpl<unsigned> &UnnamedArgNums) {
7066 // parse the linkage.
7067 LocTy LinkageLoc = Lex.getLoc();
7068 unsigned Linkage;
7069 unsigned Visibility;
7070 unsigned DLLStorageClass;
7071 bool DSOLocal;
7072 AttrBuilder RetAttrs(M->getContext());
7073 unsigned CC;
7074 bool HasLinkage;
7075 Type *RetType = nullptr;
7076 LocTy RetTypeLoc = Lex.getLoc();
7077 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
7078 DSOLocal) ||
7079 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7080 parseType(RetType, RetTypeLoc, true /*void allowed*/))
7081 return true;
7082
7083 // Verify that the linkage is ok.
7086 break; // always ok.
7088 if (IsDefine)
7089 return error(LinkageLoc, "invalid linkage for function definition");
7090 break;
7098 if (!IsDefine)
7099 return error(LinkageLoc, "invalid linkage for function declaration");
7100 break;
7103 return error(LinkageLoc, "invalid function linkage type");
7104 }
7105
7106 if (!isValidVisibilityForLinkage(Visibility, Linkage))
7107 return error(LinkageLoc,
7108 "symbol with local linkage must have default visibility");
7109
7110 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
7111 return error(LinkageLoc,
7112 "symbol with local linkage cannot have a DLL storage class");
7113
7114 if (!FunctionType::isValidReturnType(RetType))
7115 return error(RetTypeLoc, "invalid function return type");
7116
7117 LocTy NameLoc = Lex.getLoc();
7118
7119 std::string FunctionName;
7120 if (Lex.getKind() == lltok::GlobalVar) {
7121 FunctionName = Lex.getStrVal();
7122 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
7123 FunctionNumber = Lex.getUIntVal();
7124 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
7125 FunctionNumber))
7126 return true;
7127 } else {
7128 return tokError("expected function name");
7129 }
7130
7131 Lex.Lex();
7132
7133 if (Lex.getKind() != lltok::lparen)
7134 return tokError("expected '(' in function argument list");
7135
7137 bool IsVarArg;
7138 AttrBuilder FuncAttrs(M->getContext());
7139 std::vector<unsigned> FwdRefAttrGrps;
7140 LocTy BuiltinLoc;
7141 std::string Section;
7142 std::string Partition;
7143 MaybeAlign Alignment, PrefAlignment;
7144 std::string GC;
7146 unsigned AddrSpace = 0;
7147 Constant *Prefix = nullptr;
7148 Constant *Prologue = nullptr;
7149 Constant *PersonalityFn = nullptr;
7150 Comdat *C;
7151
7152 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7153 parseOptionalUnnamedAddr(UnnamedAddr) ||
7154 parseOptionalProgramAddrSpace(AddrSpace) ||
7155 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
7156 BuiltinLoc) ||
7157 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
7158 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
7159 parseOptionalComdat(FunctionName, C) ||
7160 parseOptionalAlignment(Alignment) ||
7161 parseOptionalPrefAlignment(PrefAlignment) ||
7162 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
7163 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
7164 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
7165 (EatIfPresent(lltok::kw_personality) &&
7166 parseGlobalTypeAndValue(PersonalityFn)))
7167 return true;
7168
7169 if (FuncAttrs.contains(Attribute::Builtin))
7170 return error(BuiltinLoc, "'builtin' attribute not valid on function");
7171
7172 // If the alignment was parsed as an attribute, move to the alignment field.
7173 if (MaybeAlign A = FuncAttrs.getAlignment()) {
7174 Alignment = A;
7175 FuncAttrs.removeAttribute(Attribute::Alignment);
7176 }
7177
7178 // Okay, if we got here, the function is syntactically valid. Convert types
7179 // and do semantic checks.
7180 std::vector<Type*> ParamTypeList;
7182
7183 for (const ArgInfo &Arg : ArgList) {
7184 ParamTypeList.push_back(Arg.Ty);
7185 Attrs.push_back(Arg.Attrs);
7186 }
7187
7188 AttributeList PAL =
7189 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
7190 AttributeSet::get(Context, RetAttrs), Attrs);
7191
7192 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
7193 return error(RetTypeLoc, "functions with 'sret' argument must return void");
7194
7195 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
7196 PointerType *PFT = PointerType::get(Context, AddrSpace);
7197
7198 Fn = nullptr;
7199 GlobalValue *FwdFn = nullptr;
7200 if (!FunctionName.empty()) {
7201 // If this was a definition of a forward reference, remove the definition
7202 // from the forward reference table and fill in the forward ref.
7203 auto FRVI = ForwardRefVals.find(FunctionName);
7204 if (FRVI != ForwardRefVals.end()) {
7205 FwdFn = FRVI->second.first;
7206 if (FwdFn->getType() != PFT)
7207 return error(FRVI->second.second,
7208 "invalid forward reference to "
7209 "function '" +
7210 FunctionName +
7211 "' with wrong type: "
7212 "expected '" +
7213 getTypeString(PFT) + "' but was '" +
7214 getTypeString(FwdFn->getType()) + "'");
7215 ForwardRefVals.erase(FRVI);
7216 } else if ((Fn = M->getFunction(FunctionName))) {
7217 // Reject redefinitions.
7218 return error(NameLoc,
7219 "invalid redefinition of function '" + FunctionName + "'");
7220 } else if (M->getNamedValue(FunctionName)) {
7221 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
7222 }
7223
7224 } else {
7225 // Handle @"", where a name is syntactically specified, but semantically
7226 // missing.
7227 if (FunctionNumber == (unsigned)-1)
7228 FunctionNumber = NumberedVals.getNext();
7229
7230 // If this is a definition of a forward referenced function, make sure the
7231 // types agree.
7232 auto I = ForwardRefValIDs.find(FunctionNumber);
7233 if (I != ForwardRefValIDs.end()) {
7234 FwdFn = I->second.first;
7235 if (FwdFn->getType() != PFT)
7236 return error(NameLoc, "type of definition and forward reference of '@" +
7237 Twine(FunctionNumber) +
7238 "' disagree: "
7239 "expected '" +
7240 getTypeString(PFT) + "' but was '" +
7241 getTypeString(FwdFn->getType()) + "'");
7242 ForwardRefValIDs.erase(I);
7243 }
7244 }
7245
7247 FunctionName, M);
7248
7249 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
7250
7251 if (FunctionName.empty())
7252 NumberedVals.add(FunctionNumber, Fn);
7253
7255 maybeSetDSOLocal(DSOLocal, *Fn);
7258 Fn->setCallingConv(CC);
7259 Fn->setAttributes(PAL);
7260 Fn->setUnnamedAddr(UnnamedAddr);
7261 if (Alignment)
7262 Fn->setAlignment(*Alignment);
7263 Fn->setPreferredAlignment(PrefAlignment);
7264 Fn->setSection(Section);
7265 Fn->setPartition(Partition);
7266 Fn->setComdat(C);
7267 Fn->setPersonalityFn(PersonalityFn);
7268 if (!GC.empty()) Fn->setGC(GC);
7269 Fn->setPrefixData(Prefix);
7270 Fn->setPrologueData(Prologue);
7271 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7272
7273 // Add all of the arguments we parsed to the function.
7274 Function::arg_iterator ArgIt = Fn->arg_begin();
7275 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7276 if (ParserContext && ArgList[i].IdentLoc)
7277 ParserContext->addInstructionOrArgumentLocation(
7278 &*ArgIt, ArgList[i].IdentLoc.value());
7279 // If the argument has a name, insert it into the argument symbol table.
7280 if (ArgList[i].Name.empty()) continue;
7281
7282 // Set the name, if it conflicted, it will be auto-renamed.
7283 ArgIt->setName(ArgList[i].Name);
7284
7285 if (ArgIt->getName() != ArgList[i].Name)
7286 return error(ArgList[i].Loc,
7287 "redefinition of argument '%" + ArgList[i].Name + "'");
7288 }
7289
7290 if (FwdFn) {
7291 FwdFn->replaceAllUsesWith(Fn);
7292 FwdFn->eraseFromParent();
7293 }
7294
7295 if (IsDefine)
7296 return false;
7297
7298 // Check the declaration has no block address forward references.
7299 ValID ID;
7300 if (FunctionName.empty()) {
7301 ID.Kind = ValID::t_GlobalID;
7302 ID.UIntVal = FunctionNumber;
7303 } else {
7304 ID.Kind = ValID::t_GlobalName;
7305 ID.StrVal = FunctionName;
7306 }
7307 auto Blocks = ForwardRefBlockAddresses.find(ID);
7308 if (Blocks != ForwardRefBlockAddresses.end())
7309 return error(Blocks->first.Loc,
7310 "cannot take blockaddress inside a declaration");
7311 return false;
7312}
7313
7314bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7315 ValID ID;
7316 if (FunctionNumber == -1) {
7317 ID.Kind = ValID::t_GlobalName;
7318 ID.StrVal = std::string(F.getName());
7319 } else {
7320 ID.Kind = ValID::t_GlobalID;
7321 ID.UIntVal = FunctionNumber;
7322 }
7323
7324 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7325 if (Blocks == P.ForwardRefBlockAddresses.end())
7326 return false;
7327
7328 for (const auto &I : Blocks->second) {
7329 const ValID &BBID = I.first;
7330 GlobalValue *GV = I.second;
7331
7332 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7333 "Expected local id or name");
7334 BasicBlock *BB;
7335 if (BBID.Kind == ValID::t_LocalName)
7336 BB = getBB(BBID.StrVal, BBID.Loc);
7337 else
7338 BB = getBB(BBID.UIntVal, BBID.Loc);
7339 if (!BB)
7340 return P.error(BBID.Loc, "referenced value is not a basic block");
7341
7342 Value *ResolvedVal = BlockAddress::get(&F, BB);
7343 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7344 ResolvedVal);
7345 if (!ResolvedVal)
7346 return true;
7347 GV->replaceAllUsesWith(ResolvedVal);
7348 GV->eraseFromParent();
7349 }
7350
7351 P.ForwardRefBlockAddresses.erase(Blocks);
7352 return false;
7353}
7354
7355/// parseFunctionBody
7356/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7357bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7358 ArrayRef<unsigned> UnnamedArgNums) {
7359 if (Lex.getKind() != lltok::lbrace)
7360 return tokError("expected '{' in function body");
7361 Lex.Lex(); // eat the {.
7362
7363 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7364
7365 // Resolve block addresses and allow basic blocks to be forward-declared
7366 // within this function.
7367 if (PFS.resolveForwardRefBlockAddresses())
7368 return true;
7369 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7370
7371 // We need at least one basic block.
7372 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7373 return tokError("function body requires at least one basic block");
7374
7375 while (Lex.getKind() != lltok::rbrace &&
7376 Lex.getKind() != lltok::kw_uselistorder)
7377 if (parseBasicBlock(PFS))
7378 return true;
7379
7380 while (Lex.getKind() != lltok::rbrace)
7381 if (parseUseListOrder(&PFS))
7382 return true;
7383
7384 // Eat the }.
7385 Lex.Lex();
7386
7387 // Verify function is ok.
7388 return PFS.finishFunction();
7389}
7390
7391/// parseBasicBlock
7392/// ::= (LabelStr|LabelID)? Instruction*
7393bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7394 FileLoc BBStart = getTokLineColumnPos();
7395
7396 // If this basic block starts out with a name, remember it.
7397 std::string Name;
7398 int NameID = -1;
7399 LocTy NameLoc = Lex.getLoc();
7400 if (Lex.getKind() == lltok::LabelStr) {
7401 Name = Lex.getStrVal();
7402 Lex.Lex();
7403 } else if (Lex.getKind() == lltok::LabelID) {
7404 NameID = Lex.getUIntVal();
7405 Lex.Lex();
7406 }
7407
7408 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7409 if (!BB)
7410 return true;
7411
7412 std::string NameStr;
7413
7414 // Parse the instructions and debug values in this block until we get a
7415 // terminator.
7416 Instruction *Inst;
7417 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7418 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7419 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7420 do {
7421 // Handle debug records first - there should always be an instruction
7422 // following the debug records, i.e. they cannot appear after the block
7423 // terminator.
7424 while (Lex.getKind() == lltok::hash) {
7425 if (SeenOldDbgInfoFormat)
7426 return error(Lex.getLoc(), "debug record should not appear in a module "
7427 "containing debug info intrinsics");
7428 SeenNewDbgInfoFormat = true;
7429 Lex.Lex();
7430
7431 DbgRecord *DR;
7432 if (parseDebugRecord(DR, PFS))
7433 return true;
7434 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7435 }
7436
7437 FileLoc InstStart = getTokLineColumnPos();
7438 // This instruction may have three possibilities for a name: a) none
7439 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7440 LocTy NameLoc = Lex.getLoc();
7441 int NameID = -1;
7442 NameStr = "";
7443
7444 if (Lex.getKind() == lltok::LocalVarID) {
7445 NameID = Lex.getUIntVal();
7446 Lex.Lex();
7447 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7448 return true;
7449 } else if (Lex.getKind() == lltok::LocalVar) {
7450 NameStr = Lex.getStrVal();
7451 Lex.Lex();
7452 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7453 return true;
7454 }
7455
7456 switch (parseInstruction(Inst, BB, PFS)) {
7457 default:
7458 llvm_unreachable("Unknown parseInstruction result!");
7459 case InstError: return true;
7460 case InstNormal:
7461 Inst->insertInto(BB, BB->end());
7462
7463 // With a normal result, we check to see if the instruction is followed by
7464 // a comma and metadata.
7465 if (EatIfPresent(lltok::comma))
7466 if (parseInstructionMetadata(*Inst))
7467 return true;
7468 break;
7469 case InstExtraComma:
7470 Inst->insertInto(BB, BB->end());
7471
7472 // If the instruction parser ate an extra comma at the end of it, it
7473 // *must* be followed by metadata.
7474 if (parseInstructionMetadata(*Inst))
7475 return true;
7476 break;
7477 }
7478
7479 // Set the name on the instruction.
7480 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7481 return true;
7482
7483 // Attach any preceding debug values to this instruction.
7484 for (DbgRecordPtr &DR : TrailingDbgRecord)
7485 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7486 TrailingDbgRecord.clear();
7487 if (ParserContext) {
7488 ParserContext->addInstructionOrArgumentLocation(
7489 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7490 }
7491 } while (!Inst->isTerminator());
7492
7493 if (ParserContext)
7494 ParserContext->addBlockLocation(
7495 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7496
7497 assert(TrailingDbgRecord.empty() &&
7498 "All debug values should have been attached to an instruction.");
7499
7500 return false;
7501}
7502
7503/// parseDebugRecord
7504/// ::= #dbg_label '(' MDNode ')'
7505/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7506/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7507bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7508 using RecordKind = DbgRecord::Kind;
7509 using LocType = DbgVariableRecord::LocationType;
7510 LocTy DVRLoc = Lex.getLoc();
7511 if (Lex.getKind() != lltok::DbgRecordType)
7512 return error(DVRLoc, "expected debug record type here");
7513 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7514 .Case("declare", RecordKind::ValueKind)
7515 .Case("value", RecordKind::ValueKind)
7516 .Case("assign", RecordKind::ValueKind)
7517 .Case("label", RecordKind::LabelKind)
7518 .Case("declare_value", RecordKind::ValueKind);
7519
7520 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7521 // full DbgVariableRecord processing stage.
7522 if (RecordType == RecordKind::LabelKind) {
7523 Lex.Lex();
7524 if (parseToken(lltok::lparen, "Expected '(' here"))
7525 return true;
7526 MDNode *Label;
7527 if (parseMDNode(Label))
7528 return true;
7529 if (parseToken(lltok::comma, "Expected ',' here"))
7530 return true;
7531 MDNode *DbgLoc;
7532 if (parseMDNode(DbgLoc))
7533 return true;
7534 if (parseToken(lltok::rparen, "Expected ')' here"))
7535 return true;
7537 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7538 return false;
7539 }
7540
7541 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7542 .Case("declare", LocType::Declare)
7543 .Case("value", LocType::Value)
7544 .Case("assign", LocType::Assign)
7545 .Case("declare_value", LocType::DeclareValue);
7546
7547 Lex.Lex();
7548 if (parseToken(lltok::lparen, "Expected '(' here"))
7549 return true;
7550
7551 // Parse Value field.
7552 Metadata *ValLocMD;
7553 if (parseMetadata(ValLocMD, &PFS))
7554 return true;
7555 if (parseToken(lltok::comma, "Expected ',' here"))
7556 return true;
7557
7558 // Parse Variable field.
7559 MDNode *Variable;
7560 if (parseMDNode(Variable))
7561 return true;
7562 if (parseToken(lltok::comma, "Expected ',' here"))
7563 return true;
7564
7565 // Parse Expression field.
7566 MDNode *Expression;
7567 if (parseMDNode(Expression))
7568 return true;
7569 if (parseToken(lltok::comma, "Expected ',' here"))
7570 return true;
7571
7572 // Parse additional fields for #dbg_assign.
7573 MDNode *AssignID = nullptr;
7574 Metadata *AddressLocation = nullptr;
7575 MDNode *AddressExpression = nullptr;
7576 if (ValueType == LocType::Assign) {
7577 // Parse DIAssignID.
7578 if (parseMDNode(AssignID))
7579 return true;
7580 if (parseToken(lltok::comma, "Expected ',' here"))
7581 return true;
7582
7583 // Parse address ValueAsMetadata.
7584 if (parseMetadata(AddressLocation, &PFS))
7585 return true;
7586 if (parseToken(lltok::comma, "Expected ',' here"))
7587 return true;
7588
7589 // Parse address DIExpression.
7590 if (parseMDNode(AddressExpression))
7591 return true;
7592 if (parseToken(lltok::comma, "Expected ',' here"))
7593 return true;
7594 }
7595
7596 /// Parse DILocation.
7597 MDNode *DebugLoc;
7598 if (parseMDNode(DebugLoc))
7599 return true;
7600
7601 if (parseToken(lltok::rparen, "Expected ')' here"))
7602 return true;
7604 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7605 AddressExpression);
7606 PendingDbgRecords.emplace_back(DVRLoc, DR, DebugLoc);
7607 return false;
7608}
7609//===----------------------------------------------------------------------===//
7610// Instruction Parsing.
7611//===----------------------------------------------------------------------===//
7612
7613/// parseInstruction - parse one of the many different instructions.
7614///
7615int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7616 PerFunctionState &PFS) {
7617 lltok::Kind Token = Lex.getKind();
7618 if (Token == lltok::Eof)
7619 return tokError("found end of file when expecting more instructions");
7620 LocTy Loc = Lex.getLoc();
7621 unsigned KeywordVal = Lex.getUIntVal();
7622 Lex.Lex(); // Eat the keyword.
7623
7624 switch (Token) {
7625 default:
7626 return error(Loc, "expected instruction opcode");
7627 // Terminator Instructions.
7628 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7629 case lltok::kw_ret:
7630 return parseRet(Inst, BB, PFS);
7631 case lltok::kw_br:
7632 return parseBr(Inst, PFS);
7633 case lltok::kw_switch:
7634 return parseSwitch(Inst, PFS);
7636 return parseIndirectBr(Inst, PFS);
7637 case lltok::kw_invoke:
7638 return parseInvoke(Inst, PFS);
7639 case lltok::kw_resume:
7640 return parseResume(Inst, PFS);
7642 return parseCleanupRet(Inst, PFS);
7643 case lltok::kw_catchret:
7644 return parseCatchRet(Inst, PFS);
7646 return parseCatchSwitch(Inst, PFS);
7647 case lltok::kw_catchpad:
7648 return parseCatchPad(Inst, PFS);
7650 return parseCleanupPad(Inst, PFS);
7651 case lltok::kw_callbr:
7652 return parseCallBr(Inst, PFS);
7653 // Unary Operators.
7654 case lltok::kw_fneg: {
7655 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7656 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7657 if (Res != 0)
7658 return Res;
7659 if (FMF.any())
7660 Inst->setFastMathFlags(FMF);
7661 return false;
7662 }
7663 // Binary Operators.
7664 case lltok::kw_add:
7665 case lltok::kw_sub:
7666 case lltok::kw_mul:
7667 case lltok::kw_shl: {
7668 bool NUW = EatIfPresent(lltok::kw_nuw);
7669 bool NSW = EatIfPresent(lltok::kw_nsw);
7670 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7671
7672 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7673 return true;
7674
7675 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7676 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7677 return false;
7678 }
7679 case lltok::kw_fadd:
7680 case lltok::kw_fsub:
7681 case lltok::kw_fmul:
7682 case lltok::kw_fdiv:
7683 case lltok::kw_frem: {
7684 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7685 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7686 if (Res != 0)
7687 return Res;
7688 if (FMF.any())
7689 Inst->setFastMathFlags(FMF);
7690 return 0;
7691 }
7692
7693 case lltok::kw_sdiv:
7694 case lltok::kw_udiv:
7695 case lltok::kw_lshr:
7696 case lltok::kw_ashr: {
7697 bool Exact = EatIfPresent(lltok::kw_exact);
7698
7699 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7700 return true;
7701 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7702 return false;
7703 }
7704
7705 case lltok::kw_urem:
7706 case lltok::kw_srem:
7707 return parseArithmetic(Inst, PFS, KeywordVal,
7708 /*IsFP*/ false);
7709 case lltok::kw_or: {
7710 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7711 if (parseLogical(Inst, PFS, KeywordVal))
7712 return true;
7713 if (Disjoint)
7714 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7715 return false;
7716 }
7717 case lltok::kw_and:
7718 case lltok::kw_xor:
7719 return parseLogical(Inst, PFS, KeywordVal);
7720 case lltok::kw_icmp: {
7721 bool SameSign = EatIfPresent(lltok::kw_samesign);
7722 if (parseCompare(Inst, PFS, KeywordVal))
7723 return true;
7724 if (SameSign)
7725 cast<ICmpInst>(Inst)->setSameSign();
7726 return false;
7727 }
7728 case lltok::kw_fcmp: {
7729 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7730 int Res = parseCompare(Inst, PFS, KeywordVal);
7731 if (Res != 0)
7732 return Res;
7733 if (FMF.any())
7734 Inst->setFastMathFlags(FMF);
7735 return 0;
7736 }
7737
7738 // Casts.
7739 case lltok::kw_uitofp: {
7740 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7741 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7742 bool Res = parseCast(Inst, PFS, KeywordVal);
7743 if (Res != 0)
7744 return Res;
7745 if (NonNeg)
7746 Inst->setNonNeg();
7747 Inst->setFastMathFlags(FMF);
7748 return 0;
7749 }
7750 case lltok::kw_zext: {
7751 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7752 bool Res = parseCast(Inst, PFS, KeywordVal);
7753 if (Res != 0)
7754 return Res;
7755 if (NonNeg)
7756 Inst->setNonNeg();
7757 return 0;
7758 }
7759 case lltok::kw_trunc: {
7760 bool NUW = EatIfPresent(lltok::kw_nuw);
7761 bool NSW = EatIfPresent(lltok::kw_nsw);
7762 if (!NUW)
7763 NUW = EatIfPresent(lltok::kw_nuw);
7764 if (parseCast(Inst, PFS, KeywordVal))
7765 return true;
7766 if (NUW)
7767 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7768 if (NSW)
7769 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7770 return false;
7771 }
7772 case lltok::kw_sext:
7773 case lltok::kw_bitcast:
7775 case lltok::kw_fptoui:
7776 case lltok::kw_fptosi:
7777 case lltok::kw_inttoptr:
7779 case lltok::kw_ptrtoint:
7780 return parseCast(Inst, PFS, KeywordVal);
7781 case lltok::kw_fptrunc:
7782 case lltok::kw_fpext:
7783 case lltok::kw_sitofp: {
7784 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7785 if (parseCast(Inst, PFS, KeywordVal))
7786 return true;
7787 if (FMF.any())
7788 Inst->setFastMathFlags(FMF);
7789 return false;
7790 }
7791
7792 // Other.
7793 case lltok::kw_select: {
7794 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7795 int Res = parseSelect(Inst, PFS);
7796 if (Res != 0)
7797 return Res;
7798 if (FMF.any()) {
7799 if (!isa<FPMathOperator>(Inst)) {
7800 Inst->deleteValue();
7801 return error(Loc, "fast-math-flags specified for select without "
7802 "floating-point scalar or vector return type");
7803 }
7804 Inst->setFastMathFlags(FMF);
7805 }
7806 return 0;
7807 }
7808 case lltok::kw_va_arg:
7809 return parseVAArg(Inst, PFS);
7811 return parseExtractElement(Inst, PFS);
7813 return parseInsertElement(Inst, PFS);
7815 return parseShuffleVector(Inst, PFS);
7816 case lltok::kw_phi: {
7817 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7818 int Res = parsePHI(Inst, PFS);
7819 if (Res != 0)
7820 return Res;
7821 if (FMF.any()) {
7822 if (!isa<FPMathOperator>(Inst)) {
7823 Inst->deleteValue();
7824 return error(Loc, "fast-math-flags specified for phi without "
7825 "floating-point scalar or vector return type");
7826 }
7827 Inst->setFastMathFlags(FMF);
7828 }
7829 return 0;
7830 }
7832 return parseLandingPad(Inst, PFS);
7833 case lltok::kw_freeze:
7834 return parseFreeze(Inst, PFS);
7835 // Call.
7836 case lltok::kw_call:
7837 return parseCall(Inst, PFS, CallInst::TCK_None);
7838 case lltok::kw_tail:
7839 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7840 case lltok::kw_musttail:
7841 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7842 case lltok::kw_notail:
7843 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7844 // Memory.
7845 case lltok::kw_alloca:
7846 return parseAlloc(Inst, PFS);
7847 case lltok::kw_load:
7848 return parseLoad(Inst, PFS);
7849 case lltok::kw_store:
7850 return parseStore(Inst, PFS);
7851 case lltok::kw_cmpxchg:
7852 return parseCmpXchg(Inst, PFS);
7854 return parseAtomicRMW(Inst, PFS);
7855 case lltok::kw_fence:
7856 return parseFence(Inst, PFS);
7858 return parseGetElementPtr(Inst, PFS);
7860 return parseExtractValue(Inst, PFS);
7862 return parseInsertValue(Inst, PFS);
7863 }
7864}
7865
7866/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7867bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7868 if (Opc == Instruction::FCmp) {
7869 switch (Lex.getKind()) {
7870 default:
7871 return tokError("expected fcmp predicate (e.g. 'oeq')");
7872 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7873 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7874 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7875 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7876 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7877 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7878 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7879 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7880 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7881 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7882 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7883 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7884 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7885 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7886 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7887 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7888 }
7889 } else {
7890 switch (Lex.getKind()) {
7891 default:
7892 return tokError("expected icmp predicate (e.g. 'eq')");
7893 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7894 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7895 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7896 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7897 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7898 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7899 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7900 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7901 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7902 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7903 }
7904 }
7905 Lex.Lex();
7906 return false;
7907}
7908
7909//===----------------------------------------------------------------------===//
7910// Terminator Instructions.
7911//===----------------------------------------------------------------------===//
7912
7913/// parseRet - parse a return instruction.
7914/// ::= 'ret' void (',' !dbg, !1)*
7915/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7916bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7917 PerFunctionState &PFS) {
7918 SMLoc TypeLoc = Lex.getLoc();
7919 Type *Ty = nullptr;
7920 if (parseType(Ty, true /*void allowed*/))
7921 return true;
7922
7923 Type *ResType = PFS.getFunction().getReturnType();
7924
7925 if (Ty->isVoidTy()) {
7926 if (!ResType->isVoidTy())
7927 return error(TypeLoc, "value doesn't match function result type '" +
7928 getTypeString(ResType) + "'");
7929
7930 Inst = ReturnInst::Create(Context);
7931 return false;
7932 }
7933
7934 Value *RV;
7935 if (parseValue(Ty, RV, PFS))
7936 return true;
7937
7938 if (ResType != RV->getType())
7939 return error(TypeLoc, "value doesn't match function result type '" +
7940 getTypeString(ResType) + "'");
7941
7942 Inst = ReturnInst::Create(Context, RV);
7943 return false;
7944}
7945
7946/// parseBr
7947/// ::= 'br' TypeAndValue
7948/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7949bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7950 LocTy Loc, Loc2;
7951 Value *Op0;
7952 BasicBlock *Op1, *Op2;
7953 if (parseTypeAndValue(Op0, Loc, PFS))
7954 return true;
7955
7956 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7957 Inst = UncondBrInst::Create(BB);
7958 return false;
7959 }
7960
7961 if (Op0->getType() != Type::getInt1Ty(Context))
7962 return error(Loc, "branch condition must have 'i1' type");
7963
7964 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7965 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7966 parseToken(lltok::comma, "expected ',' after true destination") ||
7967 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7968 return true;
7969
7970 Inst = CondBrInst::Create(Op0, Op1, Op2);
7971 return false;
7972}
7973
7974/// parseSwitch
7975/// Instruction
7976/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7977/// JumpTable
7978/// ::= (TypeAndValue ',' TypeAndValue)*
7979bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7980 LocTy CondLoc, BBLoc;
7981 Value *Cond;
7982 BasicBlock *DefaultBB;
7983 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7984 parseToken(lltok::comma, "expected ',' after switch condition") ||
7985 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7986 parseToken(lltok::lsquare, "expected '[' with switch table"))
7987 return true;
7988
7989 if (!Cond->getType()->isIntegerTy())
7990 return error(CondLoc, "switch condition must have integer type");
7991
7992 // parse the jump table pairs.
7993 SmallPtrSet<Value*, 32> SeenCases;
7995 while (Lex.getKind() != lltok::rsquare) {
7996 Value *Constant;
7997 BasicBlock *DestBB;
7998
7999 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8000 parseToken(lltok::comma, "expected ',' after case value") ||
8001 parseTypeAndBasicBlock(DestBB, PFS))
8002 return true;
8003
8004 if (!SeenCases.insert(Constant).second)
8005 return error(CondLoc, "duplicate case value in switch");
8006 if (!isa<ConstantInt>(Constant))
8007 return error(CondLoc, "case value is not a constant integer");
8008
8009 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
8010 }
8011
8012 Lex.Lex(); // Eat the ']'.
8013
8014 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
8015 for (const auto &[OnVal, Dest] : Table)
8016 SI->addCase(OnVal, Dest);
8017 Inst = SI;
8018 return false;
8019}
8020
8021/// parseIndirectBr
8022/// Instruction
8023/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
8024bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8025 LocTy AddrLoc;
8026 Value *Address;
8027 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
8028 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
8029 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
8030 return true;
8031
8032 if (!Address->getType()->isPointerTy())
8033 return error(AddrLoc, "indirectbr address must have pointer type");
8034
8035 // parse the destination list.
8036 SmallVector<BasicBlock*, 16> DestList;
8037
8038 if (Lex.getKind() != lltok::rsquare) {
8039 BasicBlock *DestBB;
8040 if (parseTypeAndBasicBlock(DestBB, PFS))
8041 return true;
8042 DestList.push_back(DestBB);
8043
8044 while (EatIfPresent(lltok::comma)) {
8045 if (parseTypeAndBasicBlock(DestBB, PFS))
8046 return true;
8047 DestList.push_back(DestBB);
8048 }
8049 }
8050
8051 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8052 return true;
8053
8054 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
8055 for (BasicBlock *Dest : DestList)
8056 IBI->addDestination(Dest);
8057 Inst = IBI;
8058 return false;
8059}
8060
8061// If RetType is a non-function pointer type, then this is the short syntax
8062// for the call, which means that RetType is just the return type. Infer the
8063// rest of the function argument types from the arguments that are present.
8064bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
8065 FunctionType *&FuncTy) {
8066 FuncTy = dyn_cast<FunctionType>(RetType);
8067 if (!FuncTy) {
8068 // Pull out the types of all of the arguments...
8069 SmallVector<Type *, 8> ParamTypes;
8070 ParamTypes.reserve(ArgList.size());
8071 for (const ParamInfo &Arg : ArgList)
8072 ParamTypes.push_back(Arg.V->getType());
8073
8074 if (!FunctionType::isValidReturnType(RetType))
8075 return true;
8076
8077 FuncTy = FunctionType::get(RetType, ParamTypes, false);
8078 }
8079 return false;
8080}
8081
8082/// parseInvoke
8083/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
8084/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
8085bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8086 LocTy CallLoc = Lex.getLoc();
8087 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8088 std::vector<unsigned> FwdRefAttrGrps;
8089 LocTy NoBuiltinLoc;
8090 unsigned CC;
8091 unsigned InvokeAddrSpace;
8092 Type *RetType = nullptr;
8093 LocTy RetTypeLoc;
8094 ValID CalleeID;
8097
8098 BasicBlock *NormalBB, *UnwindBB;
8099 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8100 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8101 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8102 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8103 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8104 NoBuiltinLoc) ||
8105 parseOptionalOperandBundles(BundleList, PFS) ||
8106 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
8107 parseTypeAndBasicBlock(NormalBB, PFS) ||
8108 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
8109 parseTypeAndBasicBlock(UnwindBB, PFS))
8110 return true;
8111
8112 // If RetType is a non-function pointer type, then this is the short syntax
8113 // for the call, which means that RetType is just the return type. Infer the
8114 // rest of the function argument types from the arguments that are present.
8115 FunctionType *Ty;
8116 if (resolveFunctionType(RetType, ArgList, Ty))
8117 return error(RetTypeLoc, "Invalid result type for LLVM function");
8118
8119 CalleeID.FTy = Ty;
8120
8121 // Look up the callee.
8122 Value *Callee;
8123 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
8124 Callee, &PFS))
8125 return true;
8126
8127 // Set up the Attribute for the function.
8128 SmallVector<Value *, 8> Args;
8130
8131 // Loop through FunctionType's arguments and ensure they are specified
8132 // correctly. Also, gather any parameter attributes.
8133 FunctionType::param_iterator I = Ty->param_begin();
8134 FunctionType::param_iterator E = Ty->param_end();
8135 for (const ParamInfo &Arg : ArgList) {
8136 Type *ExpectedTy = nullptr;
8137 if (I != E) {
8138 ExpectedTy = *I++;
8139 } else if (!Ty->isVarArg()) {
8140 return error(Arg.Loc, "too many arguments specified");
8141 }
8142
8143 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8144 return error(Arg.Loc, "argument is not of expected type '" +
8145 getTypeString(ExpectedTy) + "'");
8146 Args.push_back(Arg.V);
8147 ArgAttrs.push_back(Arg.Attrs);
8148 }
8149
8150 if (I != E)
8151 return error(CallLoc, "not enough parameters specified for call");
8152
8153 // Finish off the Attribute and check them
8154 AttributeList PAL =
8155 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8156 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8157
8158 InvokeInst *II =
8159 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
8160 II->setCallingConv(CC);
8161 II->setAttributes(PAL);
8162 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
8163 Inst = II;
8164 return false;
8165}
8166
8167/// parseResume
8168/// ::= 'resume' TypeAndValue
8169bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8170 Value *Exn; LocTy ExnLoc;
8171 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8172 return true;
8173
8174 ResumeInst *RI = ResumeInst::Create(Exn);
8175 Inst = RI;
8176 return false;
8177}
8178
8179bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8180 PerFunctionState &PFS) {
8181 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
8182 return true;
8183
8184 while (Lex.getKind() != lltok::rsquare) {
8185 // If this isn't the first argument, we need a comma.
8186 if (!Args.empty() &&
8187 parseToken(lltok::comma, "expected ',' in argument list"))
8188 return true;
8189
8190 // parse the argument.
8191 LocTy ArgLoc;
8192 Type *ArgTy = nullptr;
8193 if (parseType(ArgTy, ArgLoc))
8194 return true;
8195
8196 Value *V;
8197 if (ArgTy->isMetadataTy()) {
8198 if (parseMetadataAsValue(V, PFS))
8199 return true;
8200 } else {
8201 if (parseValue(ArgTy, V, PFS))
8202 return true;
8203 }
8204 Args.push_back(V);
8205 }
8206
8207 Lex.Lex(); // Lex the ']'.
8208 return false;
8209}
8210
8211/// parseCleanupRet
8212/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
8213bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8214 Value *CleanupPad = nullptr;
8215
8216 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
8217 return true;
8218
8219 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
8220 return true;
8221
8222 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
8223 return true;
8224
8225 BasicBlock *UnwindBB = nullptr;
8226 if (Lex.getKind() == lltok::kw_to) {
8227 Lex.Lex();
8228 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
8229 return true;
8230 } else {
8231 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8232 return true;
8233 }
8234 }
8235
8236 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
8237 return false;
8238}
8239
8240/// parseCatchRet
8241/// ::= 'catchret' from Parent Value 'to' TypeAndValue
8242bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8243 Value *CatchPad = nullptr;
8244
8245 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
8246 return true;
8247
8248 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
8249 return true;
8250
8251 BasicBlock *BB;
8252 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
8253 parseTypeAndBasicBlock(BB, PFS))
8254 return true;
8255
8256 Inst = CatchReturnInst::Create(CatchPad, BB);
8257 return false;
8258}
8259
8260/// parseCatchSwitch
8261/// ::= 'catchswitch' within Parent
8262bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8263 Value *ParentPad;
8264
8265 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
8266 return true;
8267
8268 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8269 Lex.getKind() != lltok::LocalVarID)
8270 return tokError("expected scope value for catchswitch");
8271
8272 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8273 return true;
8274
8275 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
8276 return true;
8277
8279 do {
8280 BasicBlock *DestBB;
8281 if (parseTypeAndBasicBlock(DestBB, PFS))
8282 return true;
8283 Table.push_back(DestBB);
8284 } while (EatIfPresent(lltok::comma));
8285
8286 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
8287 return true;
8288
8289 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
8290 return true;
8291
8292 BasicBlock *UnwindBB = nullptr;
8293 if (EatIfPresent(lltok::kw_to)) {
8294 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
8295 return true;
8296 } else {
8297 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8298 return true;
8299 }
8300
8301 auto *CatchSwitch =
8302 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
8303 for (BasicBlock *DestBB : Table)
8304 CatchSwitch->addHandler(DestBB);
8305 Inst = CatchSwitch;
8306 return false;
8307}
8308
8309/// parseCatchPad
8310/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
8311bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8312 Value *CatchSwitch = nullptr;
8313
8314 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
8315 return true;
8316
8317 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
8318 return tokError("expected scope value for catchpad");
8319
8320 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
8321 return true;
8322
8323 SmallVector<Value *, 8> Args;
8324 if (parseExceptionArgs(Args, PFS))
8325 return true;
8326
8327 Inst = CatchPadInst::Create(CatchSwitch, Args);
8328 return false;
8329}
8330
8331/// parseCleanupPad
8332/// ::= 'cleanuppad' within Parent ParamList
8333bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8334 Value *ParentPad = nullptr;
8335
8336 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
8337 return true;
8338
8339 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8340 Lex.getKind() != lltok::LocalVarID)
8341 return tokError("expected scope value for cleanuppad");
8342
8343 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8344 return true;
8345
8346 SmallVector<Value *, 8> Args;
8347 if (parseExceptionArgs(Args, PFS))
8348 return true;
8349
8350 Inst = CleanupPadInst::Create(ParentPad, Args);
8351 return false;
8352}
8353
8354//===----------------------------------------------------------------------===//
8355// Unary Operators.
8356//===----------------------------------------------------------------------===//
8357
8358/// parseUnaryOp
8359/// ::= UnaryOp TypeAndValue ',' Value
8360///
8361/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8362/// operand is allowed.
8363bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8364 unsigned Opc, bool IsFP) {
8365 LocTy Loc; Value *LHS;
8366 if (parseTypeAndValue(LHS, Loc, PFS))
8367 return true;
8368
8369 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8371
8372 if (!Valid)
8373 return error(Loc, "invalid operand type for instruction");
8374
8376 return false;
8377}
8378
8379/// parseCallBr
8380/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8381/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8382/// '[' LabelList ']'
8383bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8384 LocTy CallLoc = Lex.getLoc();
8385 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8386 std::vector<unsigned> FwdRefAttrGrps;
8387 LocTy NoBuiltinLoc;
8388 unsigned CC;
8389 Type *RetType = nullptr;
8390 LocTy RetTypeLoc;
8391 ValID CalleeID;
8394
8395 BasicBlock *DefaultDest;
8396 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8397 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8398 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8399 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8400 NoBuiltinLoc) ||
8401 parseOptionalOperandBundles(BundleList, PFS) ||
8402 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8403 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8404 parseToken(lltok::lsquare, "expected '[' in callbr"))
8405 return true;
8406
8407 // parse the destination list.
8408 SmallVector<BasicBlock *, 16> IndirectDests;
8409
8410 if (Lex.getKind() != lltok::rsquare) {
8411 BasicBlock *DestBB;
8412 if (parseTypeAndBasicBlock(DestBB, PFS))
8413 return true;
8414 IndirectDests.push_back(DestBB);
8415
8416 while (EatIfPresent(lltok::comma)) {
8417 if (parseTypeAndBasicBlock(DestBB, PFS))
8418 return true;
8419 IndirectDests.push_back(DestBB);
8420 }
8421 }
8422
8423 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8424 return true;
8425
8426 // If RetType is a non-function pointer type, then this is the short syntax
8427 // for the call, which means that RetType is just the return type. Infer the
8428 // rest of the function argument types from the arguments that are present.
8429 FunctionType *Ty;
8430 if (resolveFunctionType(RetType, ArgList, Ty))
8431 return error(RetTypeLoc, "Invalid result type for LLVM function");
8432
8433 CalleeID.FTy = Ty;
8434
8435 // Look up the callee.
8436 Value *Callee;
8437 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8438 &PFS))
8439 return true;
8440
8441 // Set up the Attribute for the function.
8442 SmallVector<Value *, 8> Args;
8444
8445 // Loop through FunctionType's arguments and ensure they are specified
8446 // correctly. Also, gather any parameter attributes.
8447 FunctionType::param_iterator I = Ty->param_begin();
8448 FunctionType::param_iterator E = Ty->param_end();
8449 for (const ParamInfo &Arg : ArgList) {
8450 Type *ExpectedTy = nullptr;
8451 if (I != E) {
8452 ExpectedTy = *I++;
8453 } else if (!Ty->isVarArg()) {
8454 return error(Arg.Loc, "too many arguments specified");
8455 }
8456
8457 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8458 return error(Arg.Loc, "argument is not of expected type '" +
8459 getTypeString(ExpectedTy) + "'");
8460 Args.push_back(Arg.V);
8461 ArgAttrs.push_back(Arg.Attrs);
8462 }
8463
8464 if (I != E)
8465 return error(CallLoc, "not enough parameters specified for call");
8466
8467 // Finish off the Attribute and check them
8468 AttributeList PAL =
8469 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8470 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8471
8472 CallBrInst *CBI =
8473 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8474 BundleList);
8475 CBI->setCallingConv(CC);
8476 CBI->setAttributes(PAL);
8477 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8478 Inst = CBI;
8479 return false;
8480}
8481
8482//===----------------------------------------------------------------------===//
8483// Binary Operators.
8484//===----------------------------------------------------------------------===//
8485
8486/// parseArithmetic
8487/// ::= ArithmeticOps TypeAndValue ',' Value
8488///
8489/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8490/// operand is allowed.
8491bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8492 unsigned Opc, bool IsFP) {
8493 LocTy Loc; Value *LHS, *RHS;
8494 if (parseTypeAndValue(LHS, Loc, PFS) ||
8495 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8496 parseValue(LHS->getType(), RHS, PFS))
8497 return true;
8498
8499 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8501
8502 if (!Valid)
8503 return error(Loc, "invalid operand type for instruction");
8504
8506 return false;
8507}
8508
8509/// parseLogical
8510/// ::= ArithmeticOps TypeAndValue ',' Value {
8511bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8512 unsigned Opc) {
8513 LocTy Loc; Value *LHS, *RHS;
8514 if (parseTypeAndValue(LHS, Loc, PFS) ||
8515 parseToken(lltok::comma, "expected ',' in logical operation") ||
8516 parseValue(LHS->getType(), RHS, PFS))
8517 return true;
8518
8519 if (!LHS->getType()->isIntOrIntVectorTy())
8520 return error(Loc,
8521 "instruction requires integer or integer vector operands");
8522
8524 return false;
8525}
8526
8527/// parseCompare
8528/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8529/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8530bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8531 unsigned Opc) {
8532 // parse the integer/fp comparison predicate.
8533 LocTy Loc;
8534 unsigned Pred;
8535 Value *LHS, *RHS;
8536 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8537 parseToken(lltok::comma, "expected ',' after compare value") ||
8538 parseValue(LHS->getType(), RHS, PFS))
8539 return true;
8540
8541 if (Opc == Instruction::FCmp) {
8542 if (!LHS->getType()->isFPOrFPVectorTy())
8543 return error(Loc, "fcmp requires floating point operands");
8544 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8545 } else {
8546 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8547 if (!LHS->getType()->isIntOrIntVectorTy() &&
8549 return error(Loc, "icmp requires integer operands");
8550 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8551 }
8552 return false;
8553}
8554
8555//===----------------------------------------------------------------------===//
8556// Other Instructions.
8557//===----------------------------------------------------------------------===//
8558
8559/// parseCast
8560/// ::= CastOpc TypeAndValue 'to' Type
8561bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8562 unsigned Opc) {
8563 LocTy Loc;
8564 Value *Op;
8565 Type *DestTy = nullptr;
8566 if (parseTypeAndValue(Op, Loc, PFS) ||
8567 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8568 parseType(DestTy))
8569 return true;
8570
8572 return error(Loc, "invalid cast opcode for cast from '" +
8573 getTypeString(Op->getType()) + "' to '" +
8574 getTypeString(DestTy) + "'");
8575 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8576 return false;
8577}
8578
8579/// parseSelect
8580/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8581bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8582 LocTy Loc;
8583 Value *Op0, *Op1, *Op2;
8584 if (parseTypeAndValue(Op0, Loc, PFS) ||
8585 parseToken(lltok::comma, "expected ',' after select condition") ||
8586 parseTypeAndValue(Op1, PFS) ||
8587 parseToken(lltok::comma, "expected ',' after select value") ||
8588 parseTypeAndValue(Op2, PFS))
8589 return true;
8590
8591 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8592 return error(Loc, Reason);
8593
8594 Inst = SelectInst::Create(Op0, Op1, Op2);
8595 return false;
8596}
8597
8598/// parseVAArg
8599/// ::= 'va_arg' TypeAndValue ',' Type
8600bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8601 Value *Op;
8602 Type *EltTy = nullptr;
8603 LocTy TypeLoc;
8604 if (parseTypeAndValue(Op, PFS) ||
8605 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8606 parseType(EltTy, TypeLoc))
8607 return true;
8608
8609 if (!EltTy->isFirstClassType())
8610 return error(TypeLoc, "va_arg requires operand with first class type");
8611
8612 Inst = new VAArgInst(Op, EltTy);
8613 return false;
8614}
8615
8616/// parseExtractElement
8617/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8618bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8619 LocTy Loc;
8620 Value *Op0, *Op1;
8621 if (parseTypeAndValue(Op0, Loc, PFS) ||
8622 parseToken(lltok::comma, "expected ',' after extract value") ||
8623 parseTypeAndValue(Op1, PFS))
8624 return true;
8625
8627 return error(Loc, "invalid extractelement operands");
8628
8629 Inst = ExtractElementInst::Create(Op0, Op1);
8630 return false;
8631}
8632
8633/// parseInsertElement
8634/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8635bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8636 LocTy Loc;
8637 Value *Op0, *Op1, *Op2;
8638 if (parseTypeAndValue(Op0, Loc, PFS) ||
8639 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8640 parseTypeAndValue(Op1, PFS) ||
8641 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8642 parseTypeAndValue(Op2, PFS))
8643 return true;
8644
8645 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8646 return error(Loc, "invalid insertelement operands");
8647
8648 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8649 return false;
8650}
8651
8652/// parseShuffleVector
8653/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8654bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8655 LocTy Loc;
8656 Value *Op0, *Op1, *Op2;
8657 if (parseTypeAndValue(Op0, Loc, PFS) ||
8658 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8659 parseTypeAndValue(Op1, PFS) ||
8660 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8661 parseTypeAndValue(Op2, PFS))
8662 return true;
8663
8664 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8665 return error(Loc, "invalid shufflevector operands");
8666
8667 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8668 return false;
8669}
8670
8671/// parsePHI
8672/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8673int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8674 Type *Ty = nullptr; LocTy TypeLoc;
8675 Value *Op0, *Op1;
8676
8677 if (parseType(Ty, TypeLoc))
8678 return true;
8679
8680 if (!Ty->isFirstClassType())
8681 return error(TypeLoc, "phi node must have first class type");
8682
8683 bool First = true;
8684 bool AteExtraComma = false;
8686
8687 while (true) {
8688 if (First) {
8689 if (Lex.getKind() != lltok::lsquare)
8690 break;
8691 First = false;
8692 } else if (!EatIfPresent(lltok::comma))
8693 break;
8694
8695 if (Lex.getKind() == lltok::MetadataVar) {
8696 AteExtraComma = true;
8697 break;
8698 }
8699
8700 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8701 parseValue(Ty, Op0, PFS) ||
8702 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8703 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8704 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8705 return true;
8706
8707 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8708 }
8709
8710 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8711 for (const auto &[Val, BB] : PHIVals)
8712 PN->addIncoming(Val, BB);
8713 Inst = PN;
8714 return AteExtraComma ? InstExtraComma : InstNormal;
8715}
8716
8717/// parseLandingPad
8718/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8719/// Clause
8720/// ::= 'catch' TypeAndValue
8721/// ::= 'filter'
8722/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8723bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8724 Type *Ty = nullptr; LocTy TyLoc;
8725
8726 if (parseType(Ty, TyLoc))
8727 return true;
8728
8729 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8730 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8731
8732 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8734 if (EatIfPresent(lltok::kw_catch))
8736 else if (EatIfPresent(lltok::kw_filter))
8738 else
8739 return tokError("expected 'catch' or 'filter' clause type");
8740
8741 Value *V;
8742 LocTy VLoc;
8743 if (parseTypeAndValue(V, VLoc, PFS))
8744 return true;
8745
8746 // A 'catch' type expects a non-array constant. A filter clause expects an
8747 // array constant.
8748 if (CT == LandingPadInst::Catch) {
8749 if (isa<ArrayType>(V->getType()))
8750 return error(VLoc, "'catch' clause has an invalid type");
8751 } else {
8752 if (!isa<ArrayType>(V->getType()))
8753 return error(VLoc, "'filter' clause has an invalid type");
8754 }
8755
8757 if (!CV)
8758 return error(VLoc, "clause argument must be a constant");
8759 LP->addClause(CV);
8760 }
8761
8762 Inst = LP.release();
8763 return false;
8764}
8765
8766/// parseFreeze
8767/// ::= 'freeze' Type Value
8768bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8769 LocTy Loc;
8770 Value *Op;
8771 if (parseTypeAndValue(Op, Loc, PFS))
8772 return true;
8773
8774 Inst = new FreezeInst(Op);
8775 return false;
8776}
8777
8778/// parseCall
8779/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8780/// OptionalAttrs Type Value ParameterList OptionalAttrs
8781/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8782/// OptionalAttrs Type Value ParameterList OptionalAttrs
8783/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8784/// OptionalAttrs Type Value ParameterList OptionalAttrs
8785/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8786/// OptionalAttrs Type Value ParameterList OptionalAttrs
8787bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8789 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8790 std::vector<unsigned> FwdRefAttrGrps;
8791 LocTy BuiltinLoc;
8792 unsigned CallAddrSpace;
8793 unsigned CC;
8794 Type *RetType = nullptr;
8795 LocTy RetTypeLoc;
8796 ValID CalleeID;
8799 LocTy CallLoc = Lex.getLoc();
8800
8801 if (TCK != CallInst::TCK_None &&
8802 parseToken(lltok::kw_call,
8803 "expected 'tail call', 'musttail call', or 'notail call'"))
8804 return true;
8805
8806 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8807
8808 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8809 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8810 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8811 parseValID(CalleeID, &PFS) ||
8812 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8813 PFS.getFunction().isVarArg()) ||
8814 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8815 parseOptionalOperandBundles(BundleList, PFS))
8816 return true;
8817
8818 // If RetType is a non-function pointer type, then this is the short syntax
8819 // for the call, which means that RetType is just the return type. Infer the
8820 // rest of the function argument types from the arguments that are present.
8821 FunctionType *Ty;
8822 if (resolveFunctionType(RetType, ArgList, Ty))
8823 return error(RetTypeLoc, "Invalid result type for LLVM function");
8824
8825 CalleeID.FTy = Ty;
8826
8827 // Look up the callee.
8828 Value *Callee;
8829 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8830 Callee, &PFS))
8831 return true;
8832
8833 // Set up the Attribute for the function.
8835
8836 SmallVector<Value*, 8> Args;
8837
8838 // Loop through FunctionType's arguments and ensure they are specified
8839 // correctly. Also, gather any parameter attributes.
8840 FunctionType::param_iterator I = Ty->param_begin();
8841 FunctionType::param_iterator E = Ty->param_end();
8842 for (const ParamInfo &Arg : ArgList) {
8843 Type *ExpectedTy = nullptr;
8844 if (I != E) {
8845 ExpectedTy = *I++;
8846 } else if (!Ty->isVarArg()) {
8847 return error(Arg.Loc, "too many arguments specified");
8848 }
8849
8850 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8851 return error(Arg.Loc, "argument is not of expected type '" +
8852 getTypeString(ExpectedTy) + "'");
8853 Args.push_back(Arg.V);
8854 Attrs.push_back(Arg.Attrs);
8855 }
8856
8857 if (I != E)
8858 return error(CallLoc, "not enough parameters specified for call");
8859
8860 // Finish off the Attribute and check them
8861 AttributeList PAL =
8862 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8863 AttributeSet::get(Context, RetAttrs), Attrs);
8864
8865 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8866 CI->setTailCallKind(TCK);
8867 CI->setCallingConv(CC);
8868 if (FMF.any()) {
8869 if (!isa<FPMathOperator>(CI)) {
8870 CI->deleteValue();
8871 return error(CallLoc, "fast-math-flags specified for call without "
8872 "floating-point scalar or vector return type");
8873 }
8874 CI->setFastMathFlags(FMF);
8875 }
8876
8877 if (CalleeID.Kind == ValID::t_GlobalName &&
8878 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8879 if (SeenNewDbgInfoFormat) {
8880 CI->deleteValue();
8881 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8882 "using non-intrinsic debug info");
8883 }
8884 SeenOldDbgInfoFormat = true;
8885 }
8886 CI->setAttributes(PAL);
8887 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8888 Inst = CI;
8889 return false;
8890}
8891
8892//===----------------------------------------------------------------------===//
8893// Memory Instructions.
8894//===----------------------------------------------------------------------===//
8895
8896/// parseAlloc
8897/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8898/// (',' 'align' i32)? (',', 'addrspace(n))?
8899int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8900 Value *Size = nullptr;
8901 LocTy SizeLoc, TyLoc, ASLoc;
8902 MaybeAlign Alignment;
8903 unsigned AddrSpace = 0;
8904 Type *Ty = nullptr;
8905
8906 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8907 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8908
8909 if (parseType(Ty, TyLoc))
8910 return true;
8911
8913 return error(TyLoc, "invalid type for alloca");
8914
8915 bool AteExtraComma = false;
8916 if (EatIfPresent(lltok::comma)) {
8917 if (Lex.getKind() == lltok::kw_align) {
8918 if (parseOptionalAlignment(Alignment))
8919 return true;
8920 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8921 return true;
8922 } else if (Lex.getKind() == lltok::kw_addrspace) {
8923 ASLoc = Lex.getLoc();
8924 if (parseOptionalAddrSpace(AddrSpace))
8925 return true;
8926 } else if (Lex.getKind() == lltok::MetadataVar) {
8927 AteExtraComma = true;
8928 } else {
8929 if (parseTypeAndValue(Size, SizeLoc, PFS))
8930 return true;
8931 if (EatIfPresent(lltok::comma)) {
8932 if (Lex.getKind() == lltok::kw_align) {
8933 if (parseOptionalAlignment(Alignment))
8934 return true;
8935 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8936 return true;
8937 } else if (Lex.getKind() == lltok::kw_addrspace) {
8938 ASLoc = Lex.getLoc();
8939 if (parseOptionalAddrSpace(AddrSpace))
8940 return true;
8941 } else if (Lex.getKind() == lltok::MetadataVar) {
8942 AteExtraComma = true;
8943 }
8944 }
8945 }
8946 }
8947
8948 if (Size && !Size->getType()->isIntegerTy())
8949 return error(SizeLoc, "element count must have integer type");
8950
8951 SmallPtrSet<Type *, 4> Visited;
8952 if (!Alignment && !Ty->isSized(&Visited))
8953 return error(TyLoc, "Cannot allocate unsized type");
8954 if (!Alignment)
8955 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8956 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8957 AI->setUsedWithInAlloca(IsInAlloca);
8958 AI->setSwiftError(IsSwiftError);
8959 Inst = AI;
8960 return AteExtraComma ? InstExtraComma : InstNormal;
8961}
8962
8963/// parseLoad
8964/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8965/// ::= 'load' 'atomic' 'volatile'? 'elementwise'? TypeAndValue
8966/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8967int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8968 Value *Val; LocTy Loc;
8969 MaybeAlign Alignment;
8970 bool AteExtraComma = false;
8971 bool isAtomic = false;
8974
8975 if (Lex.getKind() == lltok::kw_atomic) {
8976 isAtomic = true;
8977 Lex.Lex();
8978 }
8979
8980 bool isVolatile = false;
8981 if (Lex.getKind() == lltok::kw_volatile) {
8982 isVolatile = true;
8983 Lex.Lex();
8984 }
8985
8986 bool IsElementwise = false;
8987 if (Lex.getKind() == lltok::kw_elementwise) {
8988 IsElementwise = true;
8989 Lex.Lex();
8990 }
8991
8992 Type *Ty;
8993 LocTy ExplicitTypeLoc = Lex.getLoc();
8994 if (parseType(Ty) ||
8995 parseToken(lltok::comma, "expected comma after load's type") ||
8996 parseTypeAndValue(Val, Loc, PFS) ||
8997 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8998 parseOptionalCommaAlign(Alignment, AteExtraComma))
8999 return true;
9000
9001 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
9002 return error(Loc, "load operand must be a pointer to a first class type");
9003
9004 if (IsElementwise && !isAtomic)
9005 return error(Loc, "elementwise load must be atomic");
9006
9007 if (IsElementwise && !isa<FixedVectorType>(Ty))
9008 return error(ExplicitTypeLoc,
9009 "atomic elementwise load operand must have fixed vector type");
9010
9011 if (isAtomic && !Alignment)
9012 return error(Loc, "atomic load must have explicit non-zero alignment");
9013
9014 if (Ordering == AtomicOrdering::Release ||
9016 return error(Loc, "atomic load cannot use Release ordering");
9017 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9018 return error(Loc,
9019 "atomic elementwise load cannot be sequentially consistent");
9020
9021 SmallPtrSet<Type *, 4> Visited;
9022 if (!Alignment && !Ty->isSized(&Visited))
9023 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
9024 if (!Alignment)
9025 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9026 Inst = new LoadInst(Ty, Val, "",
9027 LoadStoreInstProperties{isVolatile, *Alignment, Ordering,
9028 SSID, IsElementwise},
9029 /*InsertBefore=*/nullptr);
9030 return AteExtraComma ? InstExtraComma : InstNormal;
9031}
9032
9033/// parseStore
9034
9035/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
9036/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
9037/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
9038int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9039 Value *Val, *Ptr; LocTy Loc, PtrLoc;
9040 MaybeAlign Alignment;
9041 bool AteExtraComma = false;
9042 bool isAtomic = false;
9045
9046 if (Lex.getKind() == lltok::kw_atomic) {
9047 isAtomic = true;
9048 Lex.Lex();
9049 }
9050
9051 bool isVolatile = false;
9052 if (Lex.getKind() == lltok::kw_volatile) {
9053 isVolatile = true;
9054 Lex.Lex();
9055 }
9056
9057 if (parseTypeAndValue(Val, Loc, PFS) ||
9058 parseToken(lltok::comma, "expected ',' after store operand") ||
9059 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9060 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9061 parseOptionalCommaAlign(Alignment, AteExtraComma))
9062 return true;
9063
9064 if (!Ptr->getType()->isPointerTy())
9065 return error(PtrLoc, "store operand must be a pointer");
9066 if (!Val->getType()->isFirstClassType())
9067 return error(Loc, "store operand must be a first class value");
9068 if (isAtomic && !Alignment)
9069 return error(Loc, "atomic store must have explicit non-zero alignment");
9070 if (Ordering == AtomicOrdering::Acquire ||
9072 return error(Loc, "atomic store cannot use Acquire ordering");
9073 SmallPtrSet<Type *, 4> Visited;
9074 if (!Alignment && !Val->getType()->isSized(&Visited))
9075 return error(Loc, "storing unsized types is not allowed");
9076 if (!Alignment)
9077 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
9078
9079 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
9080 return AteExtraComma ? InstExtraComma : InstNormal;
9081}
9082
9083/// parseCmpXchg
9084/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
9085/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
9086/// 'Align'?
9087int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9088 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
9089 bool AteExtraComma = false;
9090 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
9091 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
9093 bool isVolatile = false;
9094 bool isWeak = false;
9095 MaybeAlign Alignment;
9096
9097 if (EatIfPresent(lltok::kw_weak))
9098 isWeak = true;
9099
9100 if (EatIfPresent(lltok::kw_volatile))
9101 isVolatile = true;
9102
9103 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9104 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
9105 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9106 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
9107 parseTypeAndValue(New, NewLoc, PFS) ||
9108 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
9109 parseOrdering(FailureOrdering) ||
9110 parseOptionalCommaAlign(Alignment, AteExtraComma))
9111 return true;
9112
9113 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
9114 return tokError("invalid cmpxchg success ordering");
9115 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
9116 return tokError("invalid cmpxchg failure ordering");
9117 if (!Ptr->getType()->isPointerTy())
9118 return error(PtrLoc, "cmpxchg operand must be a pointer");
9119 if (Cmp->getType() != New->getType())
9120 return error(NewLoc, "compare value and new value type do not match");
9121 if (!New->getType()->isFirstClassType())
9122 return error(NewLoc, "cmpxchg operand must be a first class value");
9123
9124 const Align DefaultAlignment(
9125 PFS.getFunction().getDataLayout().getTypeStoreSize(
9126 Cmp->getType()));
9127
9128 AtomicCmpXchgInst *CXI =
9129 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
9130 SuccessOrdering, FailureOrdering, SSID);
9131 CXI->setVolatile(isVolatile);
9132 CXI->setWeak(isWeak);
9133
9134 Inst = CXI;
9135 return AteExtraComma ? InstExtraComma : InstNormal;
9136}
9137
9138/// parseAtomicRMW
9139/// ::= 'atomicrmw' 'volatile'? 'elementwise'? BinOp TypeAndValue ','
9140/// TypeAndValue
9141/// 'singlethread'? AtomicOrdering
9142int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9143 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
9144 bool AteExtraComma = false;
9147 bool IsVolatile = false;
9148 bool IsElementwise = false;
9149 bool IsFP = false;
9151 MaybeAlign Alignment;
9152
9153 if (EatIfPresent(lltok::kw_volatile))
9154 IsVolatile = true;
9155 if (EatIfPresent(lltok::kw_elementwise))
9156 IsElementwise = true;
9157
9158 switch (Lex.getKind()) {
9159 default:
9160 return tokError("expected binary operation in atomicrmw");
9174 break;
9177 break;
9180 break;
9181 case lltok::kw_usub_sat:
9183 break;
9184 case lltok::kw_fadd:
9186 IsFP = true;
9187 break;
9188 case lltok::kw_fsub:
9190 IsFP = true;
9191 break;
9192 case lltok::kw_fmax:
9194 IsFP = true;
9195 break;
9196 case lltok::kw_fmin:
9198 IsFP = true;
9199 break;
9200 case lltok::kw_fmaximum:
9202 IsFP = true;
9203 break;
9204 case lltok::kw_fminimum:
9206 IsFP = true;
9207 break;
9210 IsFP = true;
9211 break;
9214 IsFP = true;
9215 break;
9216 }
9217 Lex.Lex(); // Eat the operation.
9218
9219 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9220 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
9221 parseTypeAndValue(Val, ValLoc, PFS) ||
9222 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
9223 parseOptionalCommaAlign(Alignment, AteExtraComma))
9224 return true;
9225
9226 if (Ordering == AtomicOrdering::Unordered)
9227 return tokError("atomicrmw cannot be unordered");
9228 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9229 return tokError("atomicrmw elementwise cannot be sequentially consistent");
9230 if (!Ptr->getType()->isPointerTy())
9231 return error(PtrLoc, "atomicrmw operand must be a pointer");
9232 if (Val->getType()->isScalableTy())
9233 return error(ValLoc, "atomicrmw operand may not be scalable");
9234
9235 Type *ValTy = Val->getType();
9236 if (IsElementwise) {
9237 if (!isa<FixedVectorType>(Val->getType()))
9238 return error(ValLoc,
9239 "atomicrmw elementwise operand must be a fixed vector type");
9240 }
9241
9243 if (!ValTy->isIntOrIntVectorTy() && !ValTy->isFPOrFPVectorTy() &&
9244 !ValTy->isPtrOrPtrVectorTy()) {
9245 return error(
9246 ValLoc,
9248 " operand must be an integer type, a floating-point type, a "
9249 "pointer type, or a fixed vector of any of these types");
9250 }
9251 } else if (IsFP) {
9252 if (!ValTy->isFPOrFPVectorTy()) {
9253 return error(ValLoc, "atomicrmw " +
9255 " operand must be a floating point or fixed "
9256 "vector of floating point type");
9257 }
9258 } else {
9259 if (!ValTy->isIntOrIntVectorTy()) {
9260 return error(
9261 ValLoc,
9263 " operand must be an integer or fixed vector of integer type");
9264 }
9265 }
9266
9267 unsigned Size =
9268 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9269 if (Size < 8 || (Size & (Size - 1)))
9270 return error(ValLoc,
9271 "atomicrmw operand must have a power-of-two byte size");
9272 const Align DefaultAlignment(
9273 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->getType()));
9274 AtomicRMWInst *RMWI = new AtomicRMWInst(Operation, Ptr, Val,
9275 Alignment.value_or(DefaultAlignment),
9276 Ordering, SSID, IsElementwise);
9277 RMWI->setVolatile(IsVolatile);
9278 Inst = RMWI;
9279 return AteExtraComma ? InstExtraComma : InstNormal;
9280}
9281
9282/// parseFence
9283/// ::= 'fence' 'singlethread'? AtomicOrdering
9284int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9287 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
9288 return true;
9289
9290 if (Ordering == AtomicOrdering::Unordered)
9291 return tokError("fence cannot be unordered");
9292 if (Ordering == AtomicOrdering::Monotonic)
9293 return tokError("fence cannot be monotonic");
9294
9295 Inst = new FenceInst(Context, Ordering, SSID);
9296 return InstNormal;
9297}
9298
9299/// parseGetElementPtr
9300/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9301int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9302 Value *Ptr = nullptr;
9303 Value *Val = nullptr;
9304 LocTy Loc, EltLoc;
9305 GEPNoWrapFlags NW;
9306
9307 while (true) {
9308 if (EatIfPresent(lltok::kw_inbounds))
9310 else if (EatIfPresent(lltok::kw_nusw))
9312 else if (EatIfPresent(lltok::kw_nuw))
9314 else
9315 break;
9316 }
9317
9318 Type *Ty = nullptr;
9319 if (parseType(Ty) ||
9320 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
9321 parseTypeAndValue(Ptr, Loc, PFS))
9322 return true;
9323
9324 Type *BaseType = Ptr->getType();
9325 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
9326 if (!BasePointerType)
9327 return error(Loc, "base of getelementptr must be a pointer");
9328
9329 SmallVector<Value*, 16> Indices;
9330 bool AteExtraComma = false;
9331 // GEP returns a vector of pointers if at least one of parameters is a vector.
9332 // All vector parameters should have the same vector width.
9333 ElementCount GEPWidth = BaseType->isVectorTy()
9334 ? cast<VectorType>(BaseType)->getElementCount()
9336
9337 while (EatIfPresent(lltok::comma)) {
9338 if (Lex.getKind() == lltok::MetadataVar) {
9339 AteExtraComma = true;
9340 break;
9341 }
9342 if (parseTypeAndValue(Val, EltLoc, PFS))
9343 return true;
9344 if (!Val->getType()->isIntOrIntVectorTy())
9345 return error(EltLoc, "getelementptr index must be an integer");
9346
9347 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
9348 ElementCount ValNumEl = ValVTy->getElementCount();
9349 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
9350 return error(
9351 EltLoc,
9352 "getelementptr vector index has a wrong number of elements");
9353 GEPWidth = ValNumEl;
9354 }
9355 Indices.push_back(Val);
9356 }
9357
9358 SmallPtrSet<Type*, 4> Visited;
9359 if (!Indices.empty() && !Ty->isSized(&Visited))
9360 return error(Loc, "base element of getelementptr must be sized");
9361
9362 auto *STy = dyn_cast<StructType>(Ty);
9363 if (STy && STy->isScalableTy())
9364 return error(Loc, "getelementptr cannot target structure that contains "
9365 "scalable vector type");
9366
9367 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
9368 return error(Loc, "invalid getelementptr indices");
9369 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
9370 Inst = GEP;
9371 GEP->setNoWrapFlags(NW);
9372 return AteExtraComma ? InstExtraComma : InstNormal;
9373}
9374
9375/// parseExtractValue
9376/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9377int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9378 Value *Val; LocTy Loc;
9379 SmallVector<unsigned, 4> Indices;
9380 bool AteExtraComma;
9381 if (parseTypeAndValue(Val, Loc, PFS) ||
9382 parseIndexList(Indices, AteExtraComma))
9383 return true;
9384
9385 if (!Val->getType()->isAggregateType())
9386 return error(Loc, "extractvalue operand must be aggregate type");
9387
9388 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9389 return error(Loc, "invalid indices for extractvalue");
9390 Inst = ExtractValueInst::Create(Val, Indices);
9391 return AteExtraComma ? InstExtraComma : InstNormal;
9392}
9393
9394/// parseInsertValue
9395/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9396int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9397 Value *Val0, *Val1; LocTy Loc0, Loc1;
9398 SmallVector<unsigned, 4> Indices;
9399 bool AteExtraComma;
9400 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9401 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9402 parseTypeAndValue(Val1, Loc1, PFS) ||
9403 parseIndexList(Indices, AteExtraComma))
9404 return true;
9405
9406 if (!Val0->getType()->isAggregateType())
9407 return error(Loc0, "insertvalue operand must be aggregate type");
9408
9409 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9410 if (!IndexedType)
9411 return error(Loc0, "invalid indices for insertvalue");
9412 if (IndexedType != Val1->getType())
9413 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9414 getTypeString(Val1->getType()) + "' instead of '" +
9415 getTypeString(IndexedType) + "'");
9416 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9417 return AteExtraComma ? InstExtraComma : InstNormal;
9418}
9419
9420//===----------------------------------------------------------------------===//
9421// Embedded metadata.
9422//===----------------------------------------------------------------------===//
9423
9424/// parseMDNodeVector
9425/// ::= { Element (',' Element)* }
9426/// Element
9427/// ::= 'null' | Metadata
9428bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9429 if (parseToken(lltok::lbrace, "expected '{' here"))
9430 return true;
9431
9432 // Check for an empty list.
9433 if (EatIfPresent(lltok::rbrace))
9434 return false;
9435
9436 do {
9437 if (EatIfPresent(lltok::kw_null)) {
9438 Elts.push_back(nullptr);
9439 continue;
9440 }
9441
9442 Metadata *MD;
9443 if (parseMetadata(MD, nullptr))
9444 return true;
9445 Elts.push_back(MD);
9446 } while (EatIfPresent(lltok::comma));
9447
9448 return parseToken(lltok::rbrace, "expected end of metadata node");
9449}
9450
9451//===----------------------------------------------------------------------===//
9452// Use-list order directives.
9453//===----------------------------------------------------------------------===//
9454bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9455 SMLoc Loc) {
9456 if (!V->hasUseList())
9457 return false;
9458 if (V->use_empty())
9459 return error(Loc, "value has no uses");
9460
9461 unsigned NumUses = 0;
9462 SmallDenseMap<const Use *, unsigned, 16> Order;
9463 for (const Use &U : V->uses()) {
9464 if (++NumUses > Indexes.size())
9465 break;
9466 Order[&U] = Indexes[NumUses - 1];
9467 }
9468 if (NumUses < 2)
9469 return error(Loc, "value only has one use");
9470 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9471 return error(Loc,
9472 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9473
9474 V->sortUseList([&](const Use &L, const Use &R) {
9475 return Order.lookup(&L) < Order.lookup(&R);
9476 });
9477 return false;
9478}
9479
9480/// parseUseListOrderIndexes
9481/// ::= '{' uint32 (',' uint32)+ '}'
9482bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9483 SMLoc Loc = Lex.getLoc();
9484 if (parseToken(lltok::lbrace, "expected '{' here"))
9485 return true;
9486 if (Lex.getKind() == lltok::rbrace)
9487 return tokError("expected non-empty list of uselistorder indexes");
9488
9489 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9490 // indexes should be distinct numbers in the range [0, size-1], and should
9491 // not be in order.
9492 unsigned Offset = 0;
9493 unsigned Max = 0;
9494 bool IsOrdered = true;
9495 assert(Indexes.empty() && "Expected empty order vector");
9496 do {
9497 unsigned Index;
9498 if (parseUInt32(Index))
9499 return true;
9500
9501 // Update consistency checks.
9502 Offset += Index - Indexes.size();
9503 Max = std::max(Max, Index);
9504 IsOrdered &= Index == Indexes.size();
9505
9506 Indexes.push_back(Index);
9507 } while (EatIfPresent(lltok::comma));
9508
9509 if (parseToken(lltok::rbrace, "expected '}' here"))
9510 return true;
9511
9512 if (Indexes.size() < 2)
9513 return error(Loc, "expected >= 2 uselistorder indexes");
9514 if (Offset != 0 || Max >= Indexes.size())
9515 return error(Loc,
9516 "expected distinct uselistorder indexes in range [0, size)");
9517 if (IsOrdered)
9518 return error(Loc, "expected uselistorder indexes to change the order");
9519
9520 return false;
9521}
9522
9523/// parseUseListOrder
9524/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9525bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9526 SMLoc Loc = Lex.getLoc();
9527 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9528 return true;
9529
9530 Value *V;
9531 SmallVector<unsigned, 16> Indexes;
9532 if (parseTypeAndValue(V, PFS) ||
9533 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9534 parseUseListOrderIndexes(Indexes))
9535 return true;
9536
9537 return sortUseListOrder(V, Indexes, Loc);
9538}
9539
9540/// ModuleEntry
9541/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9542/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9543bool LLParser::parseModuleEntry(unsigned ID) {
9544 assert(Lex.getKind() == lltok::kw_module);
9545 Lex.Lex();
9546
9547 std::string Path;
9548 if (parseToken(lltok::colon, "expected ':' here") ||
9549 parseToken(lltok::lparen, "expected '(' here") ||
9550 parseToken(lltok::kw_path, "expected 'path' here") ||
9551 parseToken(lltok::colon, "expected ':' here") ||
9552 parseStringConstant(Path) ||
9553 parseToken(lltok::comma, "expected ',' here") ||
9554 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9555 parseToken(lltok::colon, "expected ':' here") ||
9556 parseToken(lltok::lparen, "expected '(' here"))
9557 return true;
9558
9559 ModuleHash Hash;
9560 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9561 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9562 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9563 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9564 parseUInt32(Hash[4]))
9565 return true;
9566
9567 if (parseToken(lltok::rparen, "expected ')' here") ||
9568 parseToken(lltok::rparen, "expected ')' here"))
9569 return true;
9570
9571 auto ModuleEntry = Index->addModule(Path, Hash);
9572 ModuleIdMap[ID] = ModuleEntry->first();
9573
9574 return false;
9575}
9576
9577/// TypeIdEntry
9578/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9579bool LLParser::parseTypeIdEntry(unsigned ID) {
9580 assert(Lex.getKind() == lltok::kw_typeid);
9581 Lex.Lex();
9582
9583 std::string Name;
9584 if (parseToken(lltok::colon, "expected ':' here") ||
9585 parseToken(lltok::lparen, "expected '(' here") ||
9586 parseToken(lltok::kw_name, "expected 'name' here") ||
9587 parseToken(lltok::colon, "expected ':' here") ||
9588 parseStringConstant(Name))
9589 return true;
9590
9591 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9592 if (parseToken(lltok::comma, "expected ',' here") ||
9593 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9594 return true;
9595
9596 // Check if this ID was forward referenced, and if so, update the
9597 // corresponding GUIDs.
9598 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9599 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9600 for (auto TIDRef : FwdRefTIDs->second) {
9601 assert(!*TIDRef.first &&
9602 "Forward referenced type id GUID expected to be 0");
9603 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9604 }
9605 ForwardRefTypeIds.erase(FwdRefTIDs);
9606 }
9607
9608 return false;
9609}
9610
9611/// TypeIdSummary
9612/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9613bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9614 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9615 parseToken(lltok::colon, "expected ':' here") ||
9616 parseToken(lltok::lparen, "expected '(' here") ||
9617 parseTypeTestResolution(TIS.TTRes))
9618 return true;
9619
9620 if (EatIfPresent(lltok::comma)) {
9621 // Expect optional wpdResolutions field
9622 if (parseOptionalWpdResolutions(TIS.WPDRes))
9623 return true;
9624 }
9625
9626 if (parseToken(lltok::rparen, "expected ')' here"))
9627 return true;
9628
9629 return false;
9630}
9631
9634
9635/// TypeIdCompatibleVtableEntry
9636/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9637/// TypeIdCompatibleVtableInfo
9638/// ')'
9639bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9641 Lex.Lex();
9642
9643 std::string Name;
9644 if (parseToken(lltok::colon, "expected ':' here") ||
9645 parseToken(lltok::lparen, "expected '(' here") ||
9646 parseToken(lltok::kw_name, "expected 'name' here") ||
9647 parseToken(lltok::colon, "expected ':' here") ||
9648 parseStringConstant(Name))
9649 return true;
9650
9652 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9653 if (parseToken(lltok::comma, "expected ',' here") ||
9654 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9655 parseToken(lltok::colon, "expected ':' here") ||
9656 parseToken(lltok::lparen, "expected '(' here"))
9657 return true;
9658
9659 IdToIndexMapType IdToIndexMap;
9660 // parse each call edge
9661 do {
9663 if (parseToken(lltok::lparen, "expected '(' here") ||
9664 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9665 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9666 parseToken(lltok::comma, "expected ',' here"))
9667 return true;
9668
9669 LocTy Loc = Lex.getLoc();
9670 unsigned GVId;
9671 ValueInfo VI;
9672 if (parseGVReference(VI, GVId))
9673 return true;
9674
9675 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9676 // forward reference. We will save the location of the ValueInfo needing an
9677 // update, but can only do so once the std::vector is finalized.
9678 if (VI == EmptyVI)
9679 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9680 TI.push_back({Offset, VI});
9681
9682 if (parseToken(lltok::rparen, "expected ')' in call"))
9683 return true;
9684 } while (EatIfPresent(lltok::comma));
9685
9686 // Now that the TI vector is finalized, it is safe to save the locations
9687 // of any forward GV references that need updating later.
9688 for (auto I : IdToIndexMap) {
9689 auto &Infos = ForwardRefValueInfos[I.first];
9690 for (auto P : I.second) {
9691 assert(TI[P.first].VTableVI == EmptyVI &&
9692 "Forward referenced ValueInfo expected to be empty");
9693 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9694 }
9695 }
9696
9697 if (parseToken(lltok::rparen, "expected ')' here") ||
9698 parseToken(lltok::rparen, "expected ')' here"))
9699 return true;
9700
9701 // Check if this ID was forward referenced, and if so, update the
9702 // corresponding GUIDs.
9703 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9704 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9705 for (auto TIDRef : FwdRefTIDs->second) {
9706 assert(!*TIDRef.first &&
9707 "Forward referenced type id GUID expected to be 0");
9708 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9709 }
9710 ForwardRefTypeIds.erase(FwdRefTIDs);
9711 }
9712
9713 return false;
9714}
9715
9716/// TypeTestResolution
9717/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9718/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9719/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9720/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9721/// [',' 'inlinesBits' ':' UInt64]? ')'
9722bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9723 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9724 parseToken(lltok::colon, "expected ':' here") ||
9725 parseToken(lltok::lparen, "expected '(' here") ||
9726 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9727 parseToken(lltok::colon, "expected ':' here"))
9728 return true;
9729
9730 switch (Lex.getKind()) {
9731 case lltok::kw_unknown:
9733 break;
9734 case lltok::kw_unsat:
9736 break;
9739 break;
9740 case lltok::kw_inline:
9742 break;
9743 case lltok::kw_single:
9745 break;
9746 case lltok::kw_allOnes:
9748 break;
9749 default:
9750 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9751 }
9752 Lex.Lex();
9753
9754 if (parseToken(lltok::comma, "expected ',' here") ||
9755 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9756 parseToken(lltok::colon, "expected ':' here") ||
9757 parseUInt32(TTRes.SizeM1BitWidth))
9758 return true;
9759
9760 // parse optional fields
9761 while (EatIfPresent(lltok::comma)) {
9762 switch (Lex.getKind()) {
9764 Lex.Lex();
9765 if (parseToken(lltok::colon, "expected ':'") ||
9766 parseUInt64(TTRes.AlignLog2))
9767 return true;
9768 break;
9769 case lltok::kw_sizeM1:
9770 Lex.Lex();
9771 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9772 return true;
9773 break;
9774 case lltok::kw_bitMask: {
9775 unsigned Val;
9776 Lex.Lex();
9777 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9778 return true;
9779 assert(Val <= 0xff);
9780 TTRes.BitMask = (uint8_t)Val;
9781 break;
9782 }
9784 Lex.Lex();
9785 if (parseToken(lltok::colon, "expected ':'") ||
9786 parseUInt64(TTRes.InlineBits))
9787 return true;
9788 break;
9789 default:
9790 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9791 }
9792 }
9793
9794 if (parseToken(lltok::rparen, "expected ')' here"))
9795 return true;
9796
9797 return false;
9798}
9799
9800/// OptionalWpdResolutions
9801/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9802/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9803bool LLParser::parseOptionalWpdResolutions(
9804 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9805 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9806 parseToken(lltok::colon, "expected ':' here") ||
9807 parseToken(lltok::lparen, "expected '(' here"))
9808 return true;
9809
9810 do {
9811 uint64_t Offset;
9812 WholeProgramDevirtResolution WPDRes;
9813 if (parseToken(lltok::lparen, "expected '(' here") ||
9814 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9815 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9816 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9817 parseToken(lltok::rparen, "expected ')' here"))
9818 return true;
9819 WPDResMap[Offset] = WPDRes;
9820 } while (EatIfPresent(lltok::comma));
9821
9822 if (parseToken(lltok::rparen, "expected ')' here"))
9823 return true;
9824
9825 return false;
9826}
9827
9828/// WpdRes
9829/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9830/// [',' OptionalResByArg]? ')'
9831/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9832/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9833/// [',' OptionalResByArg]? ')'
9834/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9835/// [',' OptionalResByArg]? ')'
9836bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9837 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9838 parseToken(lltok::colon, "expected ':' here") ||
9839 parseToken(lltok::lparen, "expected '(' here") ||
9840 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9841 parseToken(lltok::colon, "expected ':' here"))
9842 return true;
9843
9844 switch (Lex.getKind()) {
9845 case lltok::kw_indir:
9847 break;
9850 break;
9853 break;
9854 default:
9855 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9856 }
9857 Lex.Lex();
9858
9859 // parse optional fields
9860 while (EatIfPresent(lltok::comma)) {
9861 switch (Lex.getKind()) {
9863 Lex.Lex();
9864 if (parseToken(lltok::colon, "expected ':' here") ||
9865 parseStringConstant(WPDRes.SingleImplName))
9866 return true;
9867 break;
9868 case lltok::kw_resByArg:
9869 if (parseOptionalResByArg(WPDRes.ResByArg))
9870 return true;
9871 break;
9872 default:
9873 return error(Lex.getLoc(),
9874 "expected optional WholeProgramDevirtResolution field");
9875 }
9876 }
9877
9878 if (parseToken(lltok::rparen, "expected ')' here"))
9879 return true;
9880
9881 return false;
9882}
9883
9884/// OptionalResByArg
9885/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9886/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9887/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9888/// 'virtualConstProp' )
9889/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9890/// [',' 'bit' ':' UInt32]? ')'
9891bool LLParser::parseOptionalResByArg(
9892 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9893 &ResByArg) {
9894 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9895 parseToken(lltok::colon, "expected ':' here") ||
9896 parseToken(lltok::lparen, "expected '(' here"))
9897 return true;
9898
9899 do {
9900 std::vector<uint64_t> Args;
9901 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9902 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9903 parseToken(lltok::colon, "expected ':' here") ||
9904 parseToken(lltok::lparen, "expected '(' here") ||
9905 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9906 parseToken(lltok::colon, "expected ':' here"))
9907 return true;
9908
9909 WholeProgramDevirtResolution::ByArg ByArg;
9910 switch (Lex.getKind()) {
9911 case lltok::kw_indir:
9913 break;
9916 break;
9919 break;
9922 break;
9923 default:
9924 return error(Lex.getLoc(),
9925 "unexpected WholeProgramDevirtResolution::ByArg kind");
9926 }
9927 Lex.Lex();
9928
9929 // parse optional fields
9930 while (EatIfPresent(lltok::comma)) {
9931 switch (Lex.getKind()) {
9932 case lltok::kw_info:
9933 Lex.Lex();
9934 if (parseToken(lltok::colon, "expected ':' here") ||
9935 parseUInt64(ByArg.Info))
9936 return true;
9937 break;
9938 case lltok::kw_byte:
9939 Lex.Lex();
9940 if (parseToken(lltok::colon, "expected ':' here") ||
9941 parseUInt32(ByArg.Byte))
9942 return true;
9943 break;
9944 case lltok::kw_bit:
9945 Lex.Lex();
9946 if (parseToken(lltok::colon, "expected ':' here") ||
9947 parseUInt32(ByArg.Bit))
9948 return true;
9949 break;
9950 default:
9951 return error(Lex.getLoc(),
9952 "expected optional whole program devirt field");
9953 }
9954 }
9955
9956 if (parseToken(lltok::rparen, "expected ')' here"))
9957 return true;
9958
9959 ResByArg[Args] = ByArg;
9960 } while (EatIfPresent(lltok::comma));
9961
9962 if (parseToken(lltok::rparen, "expected ')' here"))
9963 return true;
9964
9965 return false;
9966}
9967
9968/// OptionalResByArg
9969/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9970bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9971 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9972 parseToken(lltok::colon, "expected ':' here") ||
9973 parseToken(lltok::lparen, "expected '(' here"))
9974 return true;
9975
9976 do {
9977 uint64_t Val;
9978 if (parseUInt64(Val))
9979 return true;
9980 Args.push_back(Val);
9981 } while (EatIfPresent(lltok::comma));
9982
9983 if (parseToken(lltok::rparen, "expected ')' here"))
9984 return true;
9985
9986 return false;
9987}
9988
9990
9991static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9992 bool ReadOnly = Fwd->isReadOnly();
9993 bool WriteOnly = Fwd->isWriteOnly();
9994 assert(!(ReadOnly && WriteOnly));
9995 *Fwd = Resolved;
9996 if (ReadOnly)
9997 Fwd->setReadOnly();
9998 if (WriteOnly)
9999 Fwd->setWriteOnly();
10000}
10001
10002/// Stores the given Name/GUID and associated summary into the Index.
10003/// Also updates any forward references to the associated entry ID.
10004bool LLParser::addGlobalValueToIndex(
10005 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
10006 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
10007 // First create the ValueInfo utilizing the Name or GUID.
10008 ValueInfo VI;
10009 if (GUID != 0) {
10010 assert(Name.empty());
10011 VI = Index->getOrInsertValueInfo(GUID);
10012 } else {
10013 assert(!Name.empty());
10014 if (M) {
10015 auto *GV = M->getNamedValue(Name);
10016 if (!GV)
10017 return error(Loc, "Reference to undefined global \"" + Name + "\"");
10018
10019 // Be a little lenient here, to accomodate older files without GUIDs
10020 // already computed and assigned as metadata.
10021 GUID = GV->getGUIDOrFallback();
10022
10023 VI = Index->getOrInsertValueInfo(GV, GUID);
10024 } else {
10025 assert(
10026 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
10027 "Need a source_filename to compute GUID for local");
10029 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
10030 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10031 }
10032 }
10033
10034 // Resolve forward references from calls/refs
10035 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10036 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10037 for (auto VIRef : FwdRefVIs->second) {
10038 assert(VIRef.first->getRef() == FwdVIRef &&
10039 "Forward referenced ValueInfo expected to be empty");
10040 resolveFwdRef(VIRef.first, VI);
10041 }
10042 ForwardRefValueInfos.erase(FwdRefVIs);
10043 }
10044
10045 // Resolve forward references from aliases
10046 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10047 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10048 for (auto AliaseeRef : FwdRefAliasees->second) {
10049 assert(!AliaseeRef.first->hasAliasee() &&
10050 "Forward referencing alias already has aliasee");
10051 assert(Summary && "Aliasee must be a definition");
10052 AliaseeRef.first->setAliasee(VI, Summary.get());
10053 }
10054 ForwardRefAliasees.erase(FwdRefAliasees);
10055 }
10056
10057 // Add the summary if one was provided.
10058 if (Summary)
10059 Index->addGlobalValueSummary(VI, std::move(Summary));
10060
10061 // Save the associated ValueInfo for use in later references by ID.
10062 if (ID == NumberedValueInfos.size())
10063 NumberedValueInfos.push_back(VI);
10064 else {
10065 // Handle non-continuous numbers (to make test simplification easier).
10066 if (ID > NumberedValueInfos.size())
10067 NumberedValueInfos.resize(ID + 1);
10068 NumberedValueInfos[ID] = VI;
10069 }
10070
10071 return false;
10072}
10073
10074/// parseSummaryIndexFlags
10075/// ::= 'flags' ':' UInt64
10076bool LLParser::parseSummaryIndexFlags() {
10077 assert(Lex.getKind() == lltok::kw_flags);
10078 Lex.Lex();
10079
10080 if (parseToken(lltok::colon, "expected ':' here"))
10081 return true;
10082 uint64_t Flags;
10083 if (parseUInt64(Flags))
10084 return true;
10085 if (Index)
10086 Index->setFlags(Flags);
10087 return false;
10088}
10089
10090/// parseBlockCount
10091/// ::= 'blockcount' ':' UInt64
10092bool LLParser::parseBlockCount() {
10093 assert(Lex.getKind() == lltok::kw_blockcount);
10094 Lex.Lex();
10095
10096 if (parseToken(lltok::colon, "expected ':' here"))
10097 return true;
10098 uint64_t BlockCount;
10099 if (parseUInt64(BlockCount))
10100 return true;
10101 if (Index)
10102 Index->setBlockCount(BlockCount);
10103 return false;
10104}
10105
10106/// parseGVEntry
10107/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
10108/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
10109/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
10110bool LLParser::parseGVEntry(unsigned ID) {
10111 assert(Lex.getKind() == lltok::kw_gv);
10112 Lex.Lex();
10113
10114 if (parseToken(lltok::colon, "expected ':' here") ||
10115 parseToken(lltok::lparen, "expected '(' here"))
10116 return true;
10117
10118 LocTy Loc = Lex.getLoc();
10119 std::string Name;
10121 switch (Lex.getKind()) {
10122 case lltok::kw_name:
10123 Lex.Lex();
10124 if (parseToken(lltok::colon, "expected ':' here") ||
10125 parseStringConstant(Name))
10126 return true;
10127 // Can't create GUID/ValueInfo until we have the linkage.
10128 break;
10129 case lltok::kw_guid:
10130 Lex.Lex();
10131 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
10132 return true;
10133 break;
10134 default:
10135 return error(Lex.getLoc(), "expected name or guid tag");
10136 }
10137
10138 if (!EatIfPresent(lltok::comma)) {
10139 // No summaries. Wrap up.
10140 if (parseToken(lltok::rparen, "expected ')' here"))
10141 return true;
10142 // This was created for a call to an external or indirect target.
10143 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
10144 // created for indirect calls with VP. A Name with no GUID came from
10145 // an external definition. We pass ExternalLinkage since that is only
10146 // used when the GUID must be computed from Name, and in that case
10147 // the symbol must have external linkage.
10148 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
10149 nullptr, Loc);
10150 }
10151
10152 // Have a list of summaries
10153 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
10154 parseToken(lltok::colon, "expected ':' here") ||
10155 parseToken(lltok::lparen, "expected '(' here"))
10156 return true;
10157 do {
10158 switch (Lex.getKind()) {
10159 case lltok::kw_function:
10160 if (parseFunctionSummary(Name, GUID, ID))
10161 return true;
10162 break;
10163 case lltok::kw_variable:
10164 if (parseVariableSummary(Name, GUID, ID))
10165 return true;
10166 break;
10167 case lltok::kw_alias:
10168 if (parseAliasSummary(Name, GUID, ID))
10169 return true;
10170 break;
10171 default:
10172 return error(Lex.getLoc(), "expected summary type");
10173 }
10174 } while (EatIfPresent(lltok::comma));
10175
10176 if (parseToken(lltok::rparen, "expected ')' here") ||
10177 parseToken(lltok::rparen, "expected ')' here"))
10178 return true;
10179
10180 return false;
10181}
10182
10183/// FunctionSummary
10184/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10185/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10186/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10187/// [',' OptionalRefs]? ')'
10188bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10189 unsigned ID) {
10190 LocTy Loc = Lex.getLoc();
10191 assert(Lex.getKind() == lltok::kw_function);
10192 Lex.Lex();
10193
10194 StringRef ModulePath;
10195 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10197 /*NotEligibleToImport=*/false,
10198 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10199 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10200 unsigned InstCount;
10202 FunctionSummary::TypeIdInfo TypeIdInfo;
10203 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10205 std::vector<CallsiteInfo> Callsites;
10206 std::vector<AllocInfo> Allocs;
10207 // Default is all-zeros (conservative values).
10208 FunctionSummary::FFlags FFlags = {};
10209 if (parseToken(lltok::colon, "expected ':' here") ||
10210 parseToken(lltok::lparen, "expected '(' here") ||
10211 parseModuleReference(ModulePath) ||
10212 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10213 parseToken(lltok::comma, "expected ',' here") ||
10214 parseToken(lltok::kw_insts, "expected 'insts' here") ||
10215 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
10216 return true;
10217
10218 // parse optional fields
10219 while (EatIfPresent(lltok::comma)) {
10220 switch (Lex.getKind()) {
10222 if (parseOptionalFFlags(FFlags))
10223 return true;
10224 break;
10225 case lltok::kw_calls:
10226 if (parseOptionalCalls(Calls))
10227 return true;
10228 break;
10230 if (parseOptionalTypeIdInfo(TypeIdInfo))
10231 return true;
10232 break;
10233 case lltok::kw_refs:
10234 if (parseOptionalRefs(Refs))
10235 return true;
10236 break;
10237 case lltok::kw_params:
10238 if (parseOptionalParamAccesses(ParamAccesses))
10239 return true;
10240 break;
10241 case lltok::kw_allocs:
10242 if (parseOptionalAllocs(Allocs))
10243 return true;
10244 break;
10246 if (parseOptionalCallsites(Callsites))
10247 return true;
10248 break;
10249 default:
10250 return error(Lex.getLoc(), "expected optional function summary field");
10251 }
10252 }
10253
10254 if (parseToken(lltok::rparen, "expected ')' here"))
10255 return true;
10256
10257 auto FS = std::make_unique<FunctionSummary>(
10258 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10259 std::move(TypeIdInfo.TypeTests),
10260 std::move(TypeIdInfo.TypeTestAssumeVCalls),
10261 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10262 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10263 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10264 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10265
10266 FS->setModulePath(ModulePath);
10267
10268 return addGlobalValueToIndex(Name, GUID,
10270 std::move(FS), Loc);
10271}
10272
10273/// VariableSummary
10274/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10275/// [',' OptionalRefs]? ')'
10276bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10277 unsigned ID) {
10278 LocTy Loc = Lex.getLoc();
10279 assert(Lex.getKind() == lltok::kw_variable);
10280 Lex.Lex();
10281
10282 StringRef ModulePath;
10283 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10285 /*NotEligibleToImport=*/false,
10286 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10287 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10288 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10289 /* WriteOnly */ false,
10290 /* Constant */ false,
10293 VTableFuncList VTableFuncs;
10294 if (parseToken(lltok::colon, "expected ':' here") ||
10295 parseToken(lltok::lparen, "expected '(' here") ||
10296 parseModuleReference(ModulePath) ||
10297 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10298 parseToken(lltok::comma, "expected ',' here") ||
10299 parseGVarFlags(GVarFlags))
10300 return true;
10301
10302 // parse optional fields
10303 while (EatIfPresent(lltok::comma)) {
10304 switch (Lex.getKind()) {
10306 if (parseOptionalVTableFuncs(VTableFuncs))
10307 return true;
10308 break;
10309 case lltok::kw_refs:
10310 if (parseOptionalRefs(Refs))
10311 return true;
10312 break;
10313 default:
10314 return error(Lex.getLoc(), "expected optional variable summary field");
10315 }
10316 }
10317
10318 if (parseToken(lltok::rparen, "expected ')' here"))
10319 return true;
10320
10321 auto GS =
10322 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10323
10324 GS->setModulePath(ModulePath);
10325 GS->setVTableFuncs(std::move(VTableFuncs));
10326
10327 return addGlobalValueToIndex(Name, GUID,
10329 std::move(GS), Loc);
10330}
10331
10332/// AliasSummary
10333/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10334/// 'aliasee' ':' GVReference ')'
10335bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10336 unsigned ID) {
10337 assert(Lex.getKind() == lltok::kw_alias);
10338 LocTy Loc = Lex.getLoc();
10339 Lex.Lex();
10340
10341 StringRef ModulePath;
10342 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10344 /*NotEligibleToImport=*/false,
10345 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10346 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10347 if (parseToken(lltok::colon, "expected ':' here") ||
10348 parseToken(lltok::lparen, "expected '(' here") ||
10349 parseModuleReference(ModulePath) ||
10350 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10351 parseToken(lltok::comma, "expected ',' here") ||
10352 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10353 parseToken(lltok::colon, "expected ':' here"))
10354 return true;
10355
10356 ValueInfo AliaseeVI;
10357 unsigned GVId;
10358 auto AS = std::make_unique<AliasSummary>(GVFlags);
10359 AS->setModulePath(ModulePath);
10360
10361 if (!EatIfPresent(lltok::kw_null)) {
10362 if (parseGVReference(AliaseeVI, GVId))
10363 return true;
10364
10365 // Record forward reference if the aliasee is not parsed yet.
10366 if (AliaseeVI.getRef() == FwdVIRef) {
10367 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10368 } else {
10369 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10370 assert(Summary && "Aliasee must be a definition");
10371 AS->setAliasee(AliaseeVI, Summary);
10372 }
10373 }
10374
10375 if (parseToken(lltok::rparen, "expected ')' here"))
10376 return true;
10377
10378 return addGlobalValueToIndex(Name, GUID,
10380 std::move(AS), Loc);
10381}
10382
10383/// Flag
10384/// ::= [0|1]
10385bool LLParser::parseFlag(unsigned &Val) {
10386 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10387 return tokError("expected integer");
10388 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10389 Lex.Lex();
10390 return false;
10391}
10392
10393/// OptionalFFlags
10394/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10395/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10396/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10397/// [',' 'noInline' ':' Flag]? ')'
10398/// [',' 'alwaysInline' ':' Flag]? ')'
10399/// [',' 'noUnwind' ':' Flag]? ')'
10400/// [',' 'mayThrow' ':' Flag]? ')'
10401/// [',' 'hasUnknownCall' ':' Flag]? ')'
10402/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10403
10404bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10405 assert(Lex.getKind() == lltok::kw_funcFlags);
10406 Lex.Lex();
10407
10408 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10409 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10410 return true;
10411
10412 do {
10413 unsigned Val = 0;
10414 switch (Lex.getKind()) {
10415 case lltok::kw_readNone:
10416 Lex.Lex();
10417 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10418 return true;
10419 FFlags.ReadNone = Val;
10420 break;
10421 case lltok::kw_readOnly:
10422 Lex.Lex();
10423 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10424 return true;
10425 FFlags.ReadOnly = Val;
10426 break;
10428 Lex.Lex();
10429 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10430 return true;
10431 FFlags.NoRecurse = Val;
10432 break;
10434 Lex.Lex();
10435 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10436 return true;
10437 FFlags.ReturnDoesNotAlias = Val;
10438 break;
10439 case lltok::kw_noInline:
10440 Lex.Lex();
10441 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10442 return true;
10443 FFlags.NoInline = Val;
10444 break;
10446 Lex.Lex();
10447 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10448 return true;
10449 FFlags.AlwaysInline = Val;
10450 break;
10451 case lltok::kw_noUnwind:
10452 Lex.Lex();
10453 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10454 return true;
10455 FFlags.NoUnwind = Val;
10456 break;
10457 case lltok::kw_mayThrow:
10458 Lex.Lex();
10459 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10460 return true;
10461 FFlags.MayThrow = Val;
10462 break;
10464 Lex.Lex();
10465 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10466 return true;
10467 FFlags.HasUnknownCall = Val;
10468 break;
10470 Lex.Lex();
10471 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10472 return true;
10473 FFlags.MustBeUnreachable = Val;
10474 break;
10475 default:
10476 return error(Lex.getLoc(), "expected function flag type");
10477 }
10478 } while (EatIfPresent(lltok::comma));
10479
10480 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10481 return true;
10482
10483 return false;
10484}
10485
10486/// OptionalCalls
10487/// := 'calls' ':' '(' Call [',' Call]* ')'
10488/// Call ::= '(' 'callee' ':' GVReference
10489/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10490/// [ ',' 'tail' ]? ')'
10491bool LLParser::parseOptionalCalls(
10492 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10493 assert(Lex.getKind() == lltok::kw_calls);
10494 Lex.Lex();
10495
10496 if (parseToken(lltok::colon, "expected ':' in calls") ||
10497 parseToken(lltok::lparen, "expected '(' in calls"))
10498 return true;
10499
10500 IdToIndexMapType IdToIndexMap;
10501 // parse each call edge
10502 do {
10503 ValueInfo VI;
10504 if (parseToken(lltok::lparen, "expected '(' in call") ||
10505 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10506 parseToken(lltok::colon, "expected ':'"))
10507 return true;
10508
10509 LocTy Loc = Lex.getLoc();
10510 unsigned GVId;
10511 if (parseGVReference(VI, GVId))
10512 return true;
10513
10515 unsigned RelBF = 0;
10516 unsigned HasTailCall = false;
10517
10518 // parse optional fields
10519 while (EatIfPresent(lltok::comma)) {
10520 switch (Lex.getKind()) {
10521 case lltok::kw_hotness:
10522 Lex.Lex();
10523 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10524 return true;
10525 break;
10526 // Deprecated, keep in order to support old files.
10527 case lltok::kw_relbf:
10528 Lex.Lex();
10529 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10530 return true;
10531 break;
10532 case lltok::kw_tail:
10533 Lex.Lex();
10534 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10535 return true;
10536 break;
10537 default:
10538 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10539 }
10540 }
10541 // Keep track of the Call array index needing a forward reference.
10542 // We will save the location of the ValueInfo needing an update, but
10543 // can only do so once the std::vector is finalized.
10544 if (VI.getRef() == FwdVIRef)
10545 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10546 Calls.push_back(
10547 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall)});
10548
10549 if (parseToken(lltok::rparen, "expected ')' in call"))
10550 return true;
10551 } while (EatIfPresent(lltok::comma));
10552
10553 // Now that the Calls vector is finalized, it is safe to save the locations
10554 // of any forward GV references that need updating later.
10555 for (auto I : IdToIndexMap) {
10556 auto &Infos = ForwardRefValueInfos[I.first];
10557 for (auto P : I.second) {
10558 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10559 "Forward referenced ValueInfo expected to be empty");
10560 Infos.emplace_back(&Calls[P.first].first, P.second);
10561 }
10562 }
10563
10564 if (parseToken(lltok::rparen, "expected ')' in calls"))
10565 return true;
10566
10567 return false;
10568}
10569
10570/// Hotness
10571/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10572bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10573 switch (Lex.getKind()) {
10574 case lltok::kw_unknown:
10576 break;
10577 case lltok::kw_cold:
10579 break;
10580 case lltok::kw_none:
10582 break;
10583 case lltok::kw_hot:
10585 break;
10586 case lltok::kw_critical:
10588 break;
10589 default:
10590 return error(Lex.getLoc(), "invalid call edge hotness");
10591 }
10592 Lex.Lex();
10593 return false;
10594}
10595
10596/// OptionalVTableFuncs
10597/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10598/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10599bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10600 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10601 Lex.Lex();
10602
10603 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10604 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10605 return true;
10606
10607 IdToIndexMapType IdToIndexMap;
10608 // parse each virtual function pair
10609 do {
10610 ValueInfo VI;
10611 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10612 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10613 parseToken(lltok::colon, "expected ':'"))
10614 return true;
10615
10616 LocTy Loc = Lex.getLoc();
10617 unsigned GVId;
10618 if (parseGVReference(VI, GVId))
10619 return true;
10620
10621 uint64_t Offset;
10622 if (parseToken(lltok::comma, "expected comma") ||
10623 parseToken(lltok::kw_offset, "expected offset") ||
10624 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10625 return true;
10626
10627 // Keep track of the VTableFuncs array index needing a forward reference.
10628 // We will save the location of the ValueInfo needing an update, but
10629 // can only do so once the std::vector is finalized.
10630 if (VI == EmptyVI)
10631 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10632 VTableFuncs.push_back({VI, Offset});
10633
10634 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10635 return true;
10636 } while (EatIfPresent(lltok::comma));
10637
10638 // Now that the VTableFuncs vector is finalized, it is safe to save the
10639 // locations of any forward GV references that need updating later.
10640 for (auto I : IdToIndexMap) {
10641 auto &Infos = ForwardRefValueInfos[I.first];
10642 for (auto P : I.second) {
10643 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10644 "Forward referenced ValueInfo expected to be empty");
10645 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10646 }
10647 }
10648
10649 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10650 return true;
10651
10652 return false;
10653}
10654
10655/// ParamNo := 'param' ':' UInt64
10656bool LLParser::parseParamNo(uint64_t &ParamNo) {
10657 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10658 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10659 return true;
10660 return false;
10661}
10662
10663/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10664bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10665 APSInt Lower;
10666 APSInt Upper;
10667 auto ParseAPSInt = [&](APSInt &Val) {
10668 if (Lex.getKind() != lltok::APSInt)
10669 return tokError("expected integer");
10670 Val = Lex.getAPSIntVal();
10671 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10672 Val.setIsSigned(true);
10673 Lex.Lex();
10674 return false;
10675 };
10676 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10677 parseToken(lltok::colon, "expected ':' here") ||
10678 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10679 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10680 parseToken(lltok::rsquare, "expected ']' here"))
10681 return true;
10682
10683 ++Upper;
10684 Range =
10685 (Lower == Upper && !Lower.isMaxValue())
10686 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10687 : ConstantRange(Lower, Upper);
10688
10689 return false;
10690}
10691
10692/// ParamAccessCall
10693/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10694bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10695 IdLocListType &IdLocList) {
10696 if (parseToken(lltok::lparen, "expected '(' here") ||
10697 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10698 parseToken(lltok::colon, "expected ':' here"))
10699 return true;
10700
10701 unsigned GVId;
10702 ValueInfo VI;
10703 LocTy Loc = Lex.getLoc();
10704 if (parseGVReference(VI, GVId))
10705 return true;
10706
10707 Call.Callee = VI;
10708 IdLocList.emplace_back(GVId, Loc);
10709
10710 if (parseToken(lltok::comma, "expected ',' here") ||
10711 parseParamNo(Call.ParamNo) ||
10712 parseToken(lltok::comma, "expected ',' here") ||
10713 parseParamAccessOffset(Call.Offsets))
10714 return true;
10715
10716 if (parseToken(lltok::rparen, "expected ')' here"))
10717 return true;
10718
10719 return false;
10720}
10721
10722/// ParamAccess
10723/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10724/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10725bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10726 IdLocListType &IdLocList) {
10727 if (parseToken(lltok::lparen, "expected '(' here") ||
10728 parseParamNo(Param.ParamNo) ||
10729 parseToken(lltok::comma, "expected ',' here") ||
10730 parseParamAccessOffset(Param.Use))
10731 return true;
10732
10733 if (EatIfPresent(lltok::comma)) {
10734 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10735 parseToken(lltok::colon, "expected ':' here") ||
10736 parseToken(lltok::lparen, "expected '(' here"))
10737 return true;
10738 do {
10739 FunctionSummary::ParamAccess::Call Call;
10740 if (parseParamAccessCall(Call, IdLocList))
10741 return true;
10742 Param.Calls.push_back(Call);
10743 } while (EatIfPresent(lltok::comma));
10744
10745 if (parseToken(lltok::rparen, "expected ')' here"))
10746 return true;
10747 }
10748
10749 if (parseToken(lltok::rparen, "expected ')' here"))
10750 return true;
10751
10752 return false;
10753}
10754
10755/// OptionalParamAccesses
10756/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10757bool LLParser::parseOptionalParamAccesses(
10758 std::vector<FunctionSummary::ParamAccess> &Params) {
10759 assert(Lex.getKind() == lltok::kw_params);
10760 Lex.Lex();
10761
10762 if (parseToken(lltok::colon, "expected ':' here") ||
10763 parseToken(lltok::lparen, "expected '(' here"))
10764 return true;
10765
10766 IdLocListType VContexts;
10767 size_t CallsNum = 0;
10768 do {
10769 FunctionSummary::ParamAccess ParamAccess;
10770 if (parseParamAccess(ParamAccess, VContexts))
10771 return true;
10772 CallsNum += ParamAccess.Calls.size();
10773 assert(VContexts.size() == CallsNum);
10774 (void)CallsNum;
10775 Params.emplace_back(std::move(ParamAccess));
10776 } while (EatIfPresent(lltok::comma));
10777
10778 if (parseToken(lltok::rparen, "expected ')' here"))
10779 return true;
10780
10781 // Now that the Params is finalized, it is safe to save the locations
10782 // of any forward GV references that need updating later.
10783 IdLocListType::const_iterator ItContext = VContexts.begin();
10784 for (auto &PA : Params) {
10785 for (auto &C : PA.Calls) {
10786 if (C.Callee.getRef() == FwdVIRef)
10787 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10788 ItContext->second);
10789 ++ItContext;
10790 }
10791 }
10792 assert(ItContext == VContexts.end());
10793
10794 return false;
10795}
10796
10797/// OptionalRefs
10798/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10799bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10800 assert(Lex.getKind() == lltok::kw_refs);
10801 Lex.Lex();
10802
10803 if (parseToken(lltok::colon, "expected ':' in refs") ||
10804 parseToken(lltok::lparen, "expected '(' in refs"))
10805 return true;
10806
10807 struct ValueContext {
10808 ValueInfo VI;
10809 unsigned GVId;
10810 LocTy Loc;
10811 };
10812 std::vector<ValueContext> VContexts;
10813 // parse each ref edge
10814 do {
10815 ValueContext VC;
10816 VC.Loc = Lex.getLoc();
10817 if (parseGVReference(VC.VI, VC.GVId))
10818 return true;
10819 VContexts.push_back(VC);
10820 } while (EatIfPresent(lltok::comma));
10821
10822 // Sort value contexts so that ones with writeonly
10823 // and readonly ValueInfo are at the end of VContexts vector.
10824 // See FunctionSummary::specialRefCounts()
10825 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10826 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10827 });
10828
10829 IdToIndexMapType IdToIndexMap;
10830 for (auto &VC : VContexts) {
10831 // Keep track of the Refs array index needing a forward reference.
10832 // We will save the location of the ValueInfo needing an update, but
10833 // can only do so once the std::vector is finalized.
10834 if (VC.VI.getRef() == FwdVIRef)
10835 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10836 Refs.push_back(VC.VI);
10837 }
10838
10839 // Now that the Refs vector is finalized, it is safe to save the locations
10840 // of any forward GV references that need updating later.
10841 for (auto I : IdToIndexMap) {
10842 auto &Infos = ForwardRefValueInfos[I.first];
10843 for (auto P : I.second) {
10844 assert(Refs[P.first].getRef() == FwdVIRef &&
10845 "Forward referenced ValueInfo expected to be empty");
10846 Infos.emplace_back(&Refs[P.first], P.second);
10847 }
10848 }
10849
10850 if (parseToken(lltok::rparen, "expected ')' in refs"))
10851 return true;
10852
10853 return false;
10854}
10855
10856/// OptionalTypeIdInfo
10857/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10858/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10859/// [',' TypeCheckedLoadConstVCalls]? ')'
10860bool LLParser::parseOptionalTypeIdInfo(
10861 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10862 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10863 Lex.Lex();
10864
10865 if (parseToken(lltok::colon, "expected ':' here") ||
10866 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10867 return true;
10868
10869 do {
10870 switch (Lex.getKind()) {
10872 if (parseTypeTests(TypeIdInfo.TypeTests))
10873 return true;
10874 break;
10876 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10877 TypeIdInfo.TypeTestAssumeVCalls))
10878 return true;
10879 break;
10881 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10882 TypeIdInfo.TypeCheckedLoadVCalls))
10883 return true;
10884 break;
10886 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10887 TypeIdInfo.TypeTestAssumeConstVCalls))
10888 return true;
10889 break;
10891 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10892 TypeIdInfo.TypeCheckedLoadConstVCalls))
10893 return true;
10894 break;
10895 default:
10896 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10897 }
10898 } while (EatIfPresent(lltok::comma));
10899
10900 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10901 return true;
10902
10903 return false;
10904}
10905
10906/// TypeTests
10907/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10908/// [',' (SummaryID | UInt64)]* ')'
10909bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10910 assert(Lex.getKind() == lltok::kw_typeTests);
10911 Lex.Lex();
10912
10913 if (parseToken(lltok::colon, "expected ':' here") ||
10914 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10915 return true;
10916
10917 IdToIndexMapType IdToIndexMap;
10918 do {
10920 if (Lex.getKind() == lltok::SummaryID) {
10921 unsigned ID = Lex.getUIntVal();
10922 LocTy Loc = Lex.getLoc();
10923 // Keep track of the TypeTests array index needing a forward reference.
10924 // We will save the location of the GUID needing an update, but
10925 // can only do so once the std::vector is finalized.
10926 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10927 Lex.Lex();
10928 } else if (parseUInt64(GUID))
10929 return true;
10930 TypeTests.push_back(GUID);
10931 } while (EatIfPresent(lltok::comma));
10932
10933 // Now that the TypeTests vector is finalized, it is safe to save the
10934 // locations of any forward GV references that need updating later.
10935 for (auto I : IdToIndexMap) {
10936 auto &Ids = ForwardRefTypeIds[I.first];
10937 for (auto P : I.second) {
10938 assert(TypeTests[P.first] == 0 &&
10939 "Forward referenced type id GUID expected to be 0");
10940 Ids.emplace_back(&TypeTests[P.first], P.second);
10941 }
10942 }
10943
10944 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10945 return true;
10946
10947 return false;
10948}
10949
10950/// VFuncIdList
10951/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10952bool LLParser::parseVFuncIdList(
10953 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10954 assert(Lex.getKind() == Kind);
10955 Lex.Lex();
10956
10957 if (parseToken(lltok::colon, "expected ':' here") ||
10958 parseToken(lltok::lparen, "expected '(' here"))
10959 return true;
10960
10961 IdToIndexMapType IdToIndexMap;
10962 do {
10963 FunctionSummary::VFuncId VFuncId;
10964 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10965 return true;
10966 VFuncIdList.push_back(VFuncId);
10967 } while (EatIfPresent(lltok::comma));
10968
10969 if (parseToken(lltok::rparen, "expected ')' here"))
10970 return true;
10971
10972 // Now that the VFuncIdList vector is finalized, it is safe to save the
10973 // locations of any forward GV references that need updating later.
10974 for (auto I : IdToIndexMap) {
10975 auto &Ids = ForwardRefTypeIds[I.first];
10976 for (auto P : I.second) {
10977 assert(VFuncIdList[P.first].GUID == 0 &&
10978 "Forward referenced type id GUID expected to be 0");
10979 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10980 }
10981 }
10982
10983 return false;
10984}
10985
10986/// ConstVCallList
10987/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10988bool LLParser::parseConstVCallList(
10989 lltok::Kind Kind,
10990 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10991 assert(Lex.getKind() == Kind);
10992 Lex.Lex();
10993
10994 if (parseToken(lltok::colon, "expected ':' here") ||
10995 parseToken(lltok::lparen, "expected '(' here"))
10996 return true;
10997
10998 IdToIndexMapType IdToIndexMap;
10999 do {
11000 FunctionSummary::ConstVCall ConstVCall;
11001 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11002 return true;
11003 ConstVCallList.push_back(ConstVCall);
11004 } while (EatIfPresent(lltok::comma));
11005
11006 if (parseToken(lltok::rparen, "expected ')' here"))
11007 return true;
11008
11009 // Now that the ConstVCallList vector is finalized, it is safe to save the
11010 // locations of any forward GV references that need updating later.
11011 for (auto I : IdToIndexMap) {
11012 auto &Ids = ForwardRefTypeIds[I.first];
11013 for (auto P : I.second) {
11014 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
11015 "Forward referenced type id GUID expected to be 0");
11016 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
11017 }
11018 }
11019
11020 return false;
11021}
11022
11023/// ConstVCall
11024/// ::= '(' VFuncId ',' Args ')'
11025bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11026 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11027 if (parseToken(lltok::lparen, "expected '(' here") ||
11028 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
11029 return true;
11030
11031 if (EatIfPresent(lltok::comma))
11032 if (parseArgs(ConstVCall.Args))
11033 return true;
11034
11035 if (parseToken(lltok::rparen, "expected ')' here"))
11036 return true;
11037
11038 return false;
11039}
11040
11041/// VFuncId
11042/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
11043/// 'offset' ':' UInt64 ')'
11044bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11045 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11046 assert(Lex.getKind() == lltok::kw_vFuncId);
11047 Lex.Lex();
11048
11049 if (parseToken(lltok::colon, "expected ':' here") ||
11050 parseToken(lltok::lparen, "expected '(' here"))
11051 return true;
11052
11053 if (Lex.getKind() == lltok::SummaryID) {
11054 VFuncId.GUID = 0;
11055 unsigned ID = Lex.getUIntVal();
11056 LocTy Loc = Lex.getLoc();
11057 // Keep track of the array index needing a forward reference.
11058 // We will save the location of the GUID needing an update, but
11059 // can only do so once the caller's std::vector is finalized.
11060 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
11061 Lex.Lex();
11062 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
11063 parseToken(lltok::colon, "expected ':' here") ||
11064 parseUInt64(VFuncId.GUID))
11065 return true;
11066
11067 if (parseToken(lltok::comma, "expected ',' here") ||
11068 parseToken(lltok::kw_offset, "expected 'offset' here") ||
11069 parseToken(lltok::colon, "expected ':' here") ||
11070 parseUInt64(VFuncId.Offset) ||
11071 parseToken(lltok::rparen, "expected ')' here"))
11072 return true;
11073
11074 return false;
11075}
11076
11077/// GVFlags
11078/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
11079/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
11080/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
11081/// 'canAutoHide' ':' Flag ',' ')'
11082bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11083 assert(Lex.getKind() == lltok::kw_flags);
11084 Lex.Lex();
11085
11086 if (parseToken(lltok::colon, "expected ':' here") ||
11087 parseToken(lltok::lparen, "expected '(' here"))
11088 return true;
11089
11090 do {
11091 unsigned Flag = 0;
11092 switch (Lex.getKind()) {
11093 case lltok::kw_linkage:
11094 Lex.Lex();
11095 if (parseToken(lltok::colon, "expected ':'"))
11096 return true;
11097 bool HasLinkage;
11098 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
11099 assert(HasLinkage && "Linkage not optional in summary entry");
11100 Lex.Lex();
11101 break;
11103 Lex.Lex();
11104 if (parseToken(lltok::colon, "expected ':'"))
11105 return true;
11106 parseOptionalVisibility(Flag);
11107 GVFlags.Visibility = Flag;
11108 break;
11110 Lex.Lex();
11111 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11112 return true;
11113 GVFlags.NotEligibleToImport = Flag;
11114 break;
11115 case lltok::kw_live:
11116 Lex.Lex();
11117 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11118 return true;
11119 GVFlags.Live = Flag;
11120 break;
11121 case lltok::kw_dsoLocal:
11122 Lex.Lex();
11123 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11124 return true;
11125 GVFlags.DSOLocal = Flag;
11126 break;
11128 Lex.Lex();
11129 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11130 return true;
11131 GVFlags.CanAutoHide = Flag;
11132 break;
11134 Lex.Lex();
11135 if (parseToken(lltok::colon, "expected ':'"))
11136 return true;
11138 if (parseOptionalImportType(Lex.getKind(), IK))
11139 return true;
11140 GVFlags.ImportType = static_cast<unsigned>(IK);
11141 Lex.Lex();
11142 break;
11144 Lex.Lex();
11145 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11146 return true;
11147 GVFlags.NoRenameOnPromotion = Flag;
11148 break;
11149 default:
11150 return error(Lex.getLoc(), "expected gv flag type");
11151 }
11152 } while (EatIfPresent(lltok::comma));
11153
11154 if (parseToken(lltok::rparen, "expected ')' here"))
11155 return true;
11156
11157 return false;
11158}
11159
11160/// GVarFlags
11161/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
11162/// ',' 'writeonly' ':' Flag
11163/// ',' 'constant' ':' Flag ')'
11164bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11165 assert(Lex.getKind() == lltok::kw_varFlags);
11166 Lex.Lex();
11167
11168 if (parseToken(lltok::colon, "expected ':' here") ||
11169 parseToken(lltok::lparen, "expected '(' here"))
11170 return true;
11171
11172 auto ParseRest = [this](unsigned int &Val) {
11173 Lex.Lex();
11174 if (parseToken(lltok::colon, "expected ':'"))
11175 return true;
11176 return parseFlag(Val);
11177 };
11178
11179 do {
11180 unsigned Flag = 0;
11181 switch (Lex.getKind()) {
11182 case lltok::kw_readonly:
11183 if (ParseRest(Flag))
11184 return true;
11185 GVarFlags.MaybeReadOnly = Flag;
11186 break;
11187 case lltok::kw_writeonly:
11188 if (ParseRest(Flag))
11189 return true;
11190 GVarFlags.MaybeWriteOnly = Flag;
11191 break;
11192 case lltok::kw_constant:
11193 if (ParseRest(Flag))
11194 return true;
11195 GVarFlags.Constant = Flag;
11196 break;
11198 if (ParseRest(Flag))
11199 return true;
11200 GVarFlags.VCallVisibility = Flag;
11201 break;
11202 default:
11203 return error(Lex.getLoc(), "expected gvar flag type");
11204 }
11205 } while (EatIfPresent(lltok::comma));
11206 return parseToken(lltok::rparen, "expected ')' here");
11207}
11208
11209/// ModuleReference
11210/// ::= 'module' ':' UInt
11211bool LLParser::parseModuleReference(StringRef &ModulePath) {
11212 // parse module id.
11213 if (parseToken(lltok::kw_module, "expected 'module' here") ||
11214 parseToken(lltok::colon, "expected ':' here") ||
11215 parseToken(lltok::SummaryID, "expected module ID"))
11216 return true;
11217
11218 unsigned ModuleID = Lex.getUIntVal();
11219 auto I = ModuleIdMap.find(ModuleID);
11220 // We should have already parsed all module IDs
11221 assert(I != ModuleIdMap.end());
11222 ModulePath = I->second;
11223 return false;
11224}
11225
11226/// GVReference
11227/// ::= SummaryID
11228bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11229 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
11230 if (!ReadOnly)
11231 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11232 if (parseToken(lltok::SummaryID, "expected GV ID"))
11233 return true;
11234
11235 GVId = Lex.getUIntVal();
11236 // Check if we already have a VI for this GV
11237 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11238 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11239 VI = NumberedValueInfos[GVId];
11240 } else
11241 // We will create a forward reference to the stored location.
11242 VI = ValueInfo(false, FwdVIRef);
11243
11244 if (ReadOnly)
11245 VI.setReadOnly();
11246 if (WriteOnly)
11247 VI.setWriteOnly();
11248 return false;
11249}
11250
11251/// OptionalAllocs
11252/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11253/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11254/// ',' MemProfs ')'
11255/// Version ::= UInt32
11256bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11257 assert(Lex.getKind() == lltok::kw_allocs);
11258 Lex.Lex();
11259
11260 if (parseToken(lltok::colon, "expected ':' in allocs") ||
11261 parseToken(lltok::lparen, "expected '(' in allocs"))
11262 return true;
11263
11264 // parse each alloc
11265 do {
11266 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
11267 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
11268 parseToken(lltok::colon, "expected ':'") ||
11269 parseToken(lltok::lparen, "expected '(' in versions"))
11270 return true;
11271
11272 SmallVector<uint8_t> Versions;
11273 do {
11274 uint8_t V = 0;
11275 if (parseAllocType(V))
11276 return true;
11277 Versions.push_back(V);
11278 } while (EatIfPresent(lltok::comma));
11279
11280 if (parseToken(lltok::rparen, "expected ')' in versions") ||
11281 parseToken(lltok::comma, "expected ',' in alloc"))
11282 return true;
11283
11284 std::vector<MIBInfo> MIBs;
11285 if (parseMemProfs(MIBs))
11286 return true;
11287
11288 Allocs.push_back({Versions, MIBs});
11289
11290 if (parseToken(lltok::rparen, "expected ')' in alloc"))
11291 return true;
11292 } while (EatIfPresent(lltok::comma));
11293
11294 if (parseToken(lltok::rparen, "expected ')' in allocs"))
11295 return true;
11296
11297 return false;
11298}
11299
11300/// MemProfs
11301/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11302/// MemProf ::= '(' 'type' ':' AllocType
11303/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11304/// StackId ::= UInt64
11305bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11306 assert(Lex.getKind() == lltok::kw_memProf);
11307 Lex.Lex();
11308
11309 if (parseToken(lltok::colon, "expected ':' in memprof") ||
11310 parseToken(lltok::lparen, "expected '(' in memprof"))
11311 return true;
11312
11313 // parse each MIB
11314 do {
11315 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
11316 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
11317 parseToken(lltok::colon, "expected ':'"))
11318 return true;
11319
11320 uint8_t AllocType;
11321 if (parseAllocType(AllocType))
11322 return true;
11323
11324 if (parseToken(lltok::comma, "expected ',' in memprof") ||
11325 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
11326 parseToken(lltok::colon, "expected ':'") ||
11327 parseToken(lltok::lparen, "expected '(' in stackIds"))
11328 return true;
11329
11330 SmallVector<unsigned> StackIdIndices;
11331 // Combined index alloc records may not have a stack id list.
11332 if (Lex.getKind() != lltok::rparen) {
11333 do {
11334 uint64_t StackId = 0;
11335 if (parseUInt64(StackId))
11336 return true;
11337 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11338 } while (EatIfPresent(lltok::comma));
11339 }
11340
11341 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11342 return true;
11343
11344 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11345
11346 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11347 return true;
11348 } while (EatIfPresent(lltok::comma));
11349
11350 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11351 return true;
11352
11353 return false;
11354}
11355
11356/// AllocType
11357/// := ('none'|'notcold'|'cold'|'hot')
11358bool LLParser::parseAllocType(uint8_t &AllocType) {
11359 switch (Lex.getKind()) {
11360 case lltok::kw_none:
11362 break;
11363 case lltok::kw_notcold:
11365 break;
11366 case lltok::kw_cold:
11368 break;
11369 case lltok::kw_hot:
11370 AllocType = (uint8_t)AllocationType::Hot;
11371 break;
11372 default:
11373 return error(Lex.getLoc(), "invalid alloc type");
11374 }
11375 Lex.Lex();
11376 return false;
11377}
11378
11379/// OptionalCallsites
11380/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11381/// Callsite ::= '(' 'callee' ':' GVReference
11382/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11383/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11384/// Version ::= UInt32
11385/// StackId ::= UInt64
11386bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11387 assert(Lex.getKind() == lltok::kw_callsites);
11388 Lex.Lex();
11389
11390 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11391 parseToken(lltok::lparen, "expected '(' in callsites"))
11392 return true;
11393
11394 IdToIndexMapType IdToIndexMap;
11395 // parse each callsite
11396 do {
11397 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11398 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11399 parseToken(lltok::colon, "expected ':'"))
11400 return true;
11401
11402 ValueInfo VI;
11403 unsigned GVId = 0;
11404 LocTy Loc = Lex.getLoc();
11405 if (!EatIfPresent(lltok::kw_null)) {
11406 if (parseGVReference(VI, GVId))
11407 return true;
11408 }
11409
11410 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11411 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11412 parseToken(lltok::colon, "expected ':'") ||
11413 parseToken(lltok::lparen, "expected '(' in clones"))
11414 return true;
11415
11416 SmallVector<unsigned> Clones;
11417 do {
11418 unsigned V = 0;
11419 if (parseUInt32(V))
11420 return true;
11421 Clones.push_back(V);
11422 } while (EatIfPresent(lltok::comma));
11423
11424 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11425 parseToken(lltok::comma, "expected ',' in callsite") ||
11426 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11427 parseToken(lltok::colon, "expected ':'") ||
11428 parseToken(lltok::lparen, "expected '(' in stackIds"))
11429 return true;
11430
11431 SmallVector<unsigned> StackIdIndices;
11432 // Synthesized callsite records will not have a stack id list.
11433 if (Lex.getKind() != lltok::rparen) {
11434 do {
11435 uint64_t StackId = 0;
11436 if (parseUInt64(StackId))
11437 return true;
11438 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11439 } while (EatIfPresent(lltok::comma));
11440 }
11441
11442 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11443 return true;
11444
11445 // Keep track of the Callsites array index needing a forward reference.
11446 // We will save the location of the ValueInfo needing an update, but
11447 // can only do so once the SmallVector is finalized.
11448 if (VI.getRef() == FwdVIRef)
11449 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11450 Callsites.push_back({VI, Clones, StackIdIndices});
11451
11452 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11453 return true;
11454 } while (EatIfPresent(lltok::comma));
11455
11456 // Now that the Callsites vector is finalized, it is safe to save the
11457 // locations of any forward GV references that need updating later.
11458 for (auto I : IdToIndexMap) {
11459 auto &Infos = ForwardRefValueInfos[I.first];
11460 for (auto P : I.second) {
11461 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11462 "Forward referenced ValueInfo expected to be empty");
11463 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11464 }
11465 }
11466
11467 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11468 return true;
11469
11470 return false;
11471}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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< 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 make_scope_exit function, which executes user-defined cleanup logic at scope ex...
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:298
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:303
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:361
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1246
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:474
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:818
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:444
arg_iterator arg_begin()
Definition Function.h:845
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1017
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:1029
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:1573
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1565
A single uniqued string.
Definition Metadata.h:722
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1522
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1511
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1531
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:110
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 LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:940
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
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:978
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:509
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:613
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:274
LLVM_ABI unsigned getLanguageDialect(StringRef LanguageDialectString)
Definition Dwarf.cpp:632
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:668
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
Definition Dwarf.cpp:423
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
Definition Dwarf.cpp:385
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
Definition Dwarf.cpp:404
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
Definition Dwarf.cpp:740
#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
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ 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:389
constexpr bool isPacked(const T &...O)
Definition SIDefines.h:333
@ 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:154
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:157
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:156
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:378
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:991
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.