LLVM 23.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'? 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 Type *Ty;
8987 LocTy ExplicitTypeLoc = Lex.getLoc();
8988 if (parseType(Ty) ||
8989 parseToken(lltok::comma, "expected comma after load's type") ||
8990 parseTypeAndValue(Val, Loc, PFS) ||
8991 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8992 parseOptionalCommaAlign(Alignment, AteExtraComma))
8993 return true;
8994
8995 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8996 return error(Loc, "load operand must be a pointer to a first class type");
8997 if (isAtomic && !Alignment)
8998 return error(Loc, "atomic load must have explicit non-zero alignment");
8999 if (Ordering == AtomicOrdering::Release ||
9001 return error(Loc, "atomic load cannot use Release ordering");
9002
9003 SmallPtrSet<Type *, 4> Visited;
9004 if (!Alignment && !Ty->isSized(&Visited))
9005 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
9006 if (!Alignment)
9007 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9008 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
9009 return AteExtraComma ? InstExtraComma : InstNormal;
9010}
9011
9012/// parseStore
9013
9014/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
9015/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
9016/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
9017int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9018 Value *Val, *Ptr; LocTy Loc, PtrLoc;
9019 MaybeAlign Alignment;
9020 bool AteExtraComma = false;
9021 bool isAtomic = false;
9024
9025 if (Lex.getKind() == lltok::kw_atomic) {
9026 isAtomic = true;
9027 Lex.Lex();
9028 }
9029
9030 bool isVolatile = false;
9031 if (Lex.getKind() == lltok::kw_volatile) {
9032 isVolatile = true;
9033 Lex.Lex();
9034 }
9035
9036 if (parseTypeAndValue(Val, Loc, PFS) ||
9037 parseToken(lltok::comma, "expected ',' after store operand") ||
9038 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9039 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9040 parseOptionalCommaAlign(Alignment, AteExtraComma))
9041 return true;
9042
9043 if (!Ptr->getType()->isPointerTy())
9044 return error(PtrLoc, "store operand must be a pointer");
9045 if (!Val->getType()->isFirstClassType())
9046 return error(Loc, "store operand must be a first class value");
9047 if (isAtomic && !Alignment)
9048 return error(Loc, "atomic store must have explicit non-zero alignment");
9049 if (Ordering == AtomicOrdering::Acquire ||
9051 return error(Loc, "atomic store cannot use Acquire ordering");
9052 SmallPtrSet<Type *, 4> Visited;
9053 if (!Alignment && !Val->getType()->isSized(&Visited))
9054 return error(Loc, "storing unsized types is not allowed");
9055 if (!Alignment)
9056 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
9057
9058 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
9059 return AteExtraComma ? InstExtraComma : InstNormal;
9060}
9061
9062/// parseCmpXchg
9063/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
9064/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
9065/// 'Align'?
9066int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9067 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
9068 bool AteExtraComma = false;
9069 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
9070 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
9072 bool isVolatile = false;
9073 bool isWeak = false;
9074 MaybeAlign Alignment;
9075
9076 if (EatIfPresent(lltok::kw_weak))
9077 isWeak = true;
9078
9079 if (EatIfPresent(lltok::kw_volatile))
9080 isVolatile = true;
9081
9082 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9083 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
9084 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9085 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
9086 parseTypeAndValue(New, NewLoc, PFS) ||
9087 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
9088 parseOrdering(FailureOrdering) ||
9089 parseOptionalCommaAlign(Alignment, AteExtraComma))
9090 return true;
9091
9092 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
9093 return tokError("invalid cmpxchg success ordering");
9094 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
9095 return tokError("invalid cmpxchg failure ordering");
9096 if (!Ptr->getType()->isPointerTy())
9097 return error(PtrLoc, "cmpxchg operand must be a pointer");
9098 if (Cmp->getType() != New->getType())
9099 return error(NewLoc, "compare value and new value type do not match");
9100 if (!New->getType()->isFirstClassType())
9101 return error(NewLoc, "cmpxchg operand must be a first class value");
9102
9103 const Align DefaultAlignment(
9104 PFS.getFunction().getDataLayout().getTypeStoreSize(
9105 Cmp->getType()));
9106
9107 AtomicCmpXchgInst *CXI =
9108 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
9109 SuccessOrdering, FailureOrdering, SSID);
9110 CXI->setVolatile(isVolatile);
9111 CXI->setWeak(isWeak);
9112
9113 Inst = CXI;
9114 return AteExtraComma ? InstExtraComma : InstNormal;
9115}
9116
9117/// parseAtomicRMW
9118/// ::= 'atomicrmw' 'volatile'? 'elementwise'? BinOp TypeAndValue ','
9119/// TypeAndValue
9120/// 'singlethread'? AtomicOrdering
9121int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9122 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
9123 bool AteExtraComma = false;
9126 bool IsVolatile = false;
9127 bool IsElementwise = false;
9128 bool IsFP = false;
9130 MaybeAlign Alignment;
9131
9132 if (EatIfPresent(lltok::kw_volatile))
9133 IsVolatile = true;
9134 if (EatIfPresent(lltok::kw_elementwise))
9135 IsElementwise = true;
9136
9137 switch (Lex.getKind()) {
9138 default:
9139 return tokError("expected binary operation in atomicrmw");
9153 break;
9156 break;
9159 break;
9160 case lltok::kw_usub_sat:
9162 break;
9163 case lltok::kw_fadd:
9165 IsFP = true;
9166 break;
9167 case lltok::kw_fsub:
9169 IsFP = true;
9170 break;
9171 case lltok::kw_fmax:
9173 IsFP = true;
9174 break;
9175 case lltok::kw_fmin:
9177 IsFP = true;
9178 break;
9179 case lltok::kw_fmaximum:
9181 IsFP = true;
9182 break;
9183 case lltok::kw_fminimum:
9185 IsFP = true;
9186 break;
9189 IsFP = true;
9190 break;
9193 IsFP = true;
9194 break;
9195 }
9196 Lex.Lex(); // Eat the operation.
9197
9198 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9199 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
9200 parseTypeAndValue(Val, ValLoc, PFS) ||
9201 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
9202 parseOptionalCommaAlign(Alignment, AteExtraComma))
9203 return true;
9204
9205 if (Ordering == AtomicOrdering::Unordered)
9206 return tokError("atomicrmw cannot be unordered");
9207 if (!Ptr->getType()->isPointerTy())
9208 return error(PtrLoc, "atomicrmw operand must be a pointer");
9209 if (Val->getType()->isScalableTy())
9210 return error(ValLoc, "atomicrmw operand may not be scalable");
9211
9212 // For elementwise ops, the value must be a fixed vector type whose element
9213 // type is legal for the corresponding scalar atomicrmw operation. So assign
9214 // ScalarTy the element type for elementwise ops so we can check this.
9215 Type *ScalarTy = Val->getType();
9216 if (IsElementwise) {
9217 auto *VecTy = dyn_cast<FixedVectorType>(Val->getType());
9218 if (!VecTy)
9219 return error(ValLoc,
9220 "atomicrmw elementwise operand must be a fixed vector type");
9221 ScalarTy = VecTy->getElementType();
9222 }
9223
9225 if (!ScalarTy->isIntegerTy() && !ScalarTy->isFloatingPointTy() &&
9226 !ScalarTy->isPointerTy()) {
9227 return error(
9228 ValLoc,
9230 " operand must be an integer, floating point, or pointer type");
9231 }
9232 } else if (IsFP) {
9233 if (!ScalarTy->isFPOrFPVectorTy()) {
9234 return error(ValLoc, "atomicrmw " +
9236 " operand must be a floating point or fixed "
9237 "vector of floating point type");
9238 }
9239 } else {
9240 if (!ScalarTy->isIntOrIntVectorTy()) {
9241 return error(
9242 ValLoc,
9244 " operand must be an integer or fixed vector of integer type");
9245 }
9246 }
9247
9248 unsigned Size =
9249 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(Val->getType());
9250 if (Size < 8 || (Size & (Size - 1)))
9251 return error(ValLoc,
9252 "atomicrmw operand must have a power-of-two byte size");
9253 const Align DefaultAlignment(
9254 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->getType()));
9255 AtomicRMWInst *RMWI = new AtomicRMWInst(Operation, Ptr, Val,
9256 Alignment.value_or(DefaultAlignment),
9257 Ordering, SSID, IsElementwise);
9258 RMWI->setVolatile(IsVolatile);
9259 Inst = RMWI;
9260 return AteExtraComma ? InstExtraComma : InstNormal;
9261}
9262
9263/// parseFence
9264/// ::= 'fence' 'singlethread'? AtomicOrdering
9265int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9268 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
9269 return true;
9270
9271 if (Ordering == AtomicOrdering::Unordered)
9272 return tokError("fence cannot be unordered");
9273 if (Ordering == AtomicOrdering::Monotonic)
9274 return tokError("fence cannot be monotonic");
9275
9276 Inst = new FenceInst(Context, Ordering, SSID);
9277 return InstNormal;
9278}
9279
9280/// parseGetElementPtr
9281/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9282int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9283 Value *Ptr = nullptr;
9284 Value *Val = nullptr;
9285 LocTy Loc, EltLoc;
9286 GEPNoWrapFlags NW;
9287
9288 while (true) {
9289 if (EatIfPresent(lltok::kw_inbounds))
9291 else if (EatIfPresent(lltok::kw_nusw))
9293 else if (EatIfPresent(lltok::kw_nuw))
9295 else
9296 break;
9297 }
9298
9299 Type *Ty = nullptr;
9300 if (parseType(Ty) ||
9301 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
9302 parseTypeAndValue(Ptr, Loc, PFS))
9303 return true;
9304
9305 Type *BaseType = Ptr->getType();
9306 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
9307 if (!BasePointerType)
9308 return error(Loc, "base of getelementptr must be a pointer");
9309
9310 SmallVector<Value*, 16> Indices;
9311 bool AteExtraComma = false;
9312 // GEP returns a vector of pointers if at least one of parameters is a vector.
9313 // All vector parameters should have the same vector width.
9314 ElementCount GEPWidth = BaseType->isVectorTy()
9315 ? cast<VectorType>(BaseType)->getElementCount()
9317
9318 while (EatIfPresent(lltok::comma)) {
9319 if (Lex.getKind() == lltok::MetadataVar) {
9320 AteExtraComma = true;
9321 break;
9322 }
9323 if (parseTypeAndValue(Val, EltLoc, PFS))
9324 return true;
9325 if (!Val->getType()->isIntOrIntVectorTy())
9326 return error(EltLoc, "getelementptr index must be an integer");
9327
9328 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
9329 ElementCount ValNumEl = ValVTy->getElementCount();
9330 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
9331 return error(
9332 EltLoc,
9333 "getelementptr vector index has a wrong number of elements");
9334 GEPWidth = ValNumEl;
9335 }
9336 Indices.push_back(Val);
9337 }
9338
9339 SmallPtrSet<Type*, 4> Visited;
9340 if (!Indices.empty() && !Ty->isSized(&Visited))
9341 return error(Loc, "base element of getelementptr must be sized");
9342
9343 auto *STy = dyn_cast<StructType>(Ty);
9344 if (STy && STy->isScalableTy())
9345 return error(Loc, "getelementptr cannot target structure that contains "
9346 "scalable vector type");
9347
9348 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
9349 return error(Loc, "invalid getelementptr indices");
9350 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
9351 Inst = GEP;
9352 GEP->setNoWrapFlags(NW);
9353 return AteExtraComma ? InstExtraComma : InstNormal;
9354}
9355
9356/// parseExtractValue
9357/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9358int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9359 Value *Val; LocTy Loc;
9360 SmallVector<unsigned, 4> Indices;
9361 bool AteExtraComma;
9362 if (parseTypeAndValue(Val, Loc, PFS) ||
9363 parseIndexList(Indices, AteExtraComma))
9364 return true;
9365
9366 if (!Val->getType()->isAggregateType())
9367 return error(Loc, "extractvalue operand must be aggregate type");
9368
9369 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9370 return error(Loc, "invalid indices for extractvalue");
9371 Inst = ExtractValueInst::Create(Val, Indices);
9372 return AteExtraComma ? InstExtraComma : InstNormal;
9373}
9374
9375/// parseInsertValue
9376/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9377int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9378 Value *Val0, *Val1; LocTy Loc0, Loc1;
9379 SmallVector<unsigned, 4> Indices;
9380 bool AteExtraComma;
9381 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9382 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9383 parseTypeAndValue(Val1, Loc1, PFS) ||
9384 parseIndexList(Indices, AteExtraComma))
9385 return true;
9386
9387 if (!Val0->getType()->isAggregateType())
9388 return error(Loc0, "insertvalue operand must be aggregate type");
9389
9390 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9391 if (!IndexedType)
9392 return error(Loc0, "invalid indices for insertvalue");
9393 if (IndexedType != Val1->getType())
9394 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9395 getTypeString(Val1->getType()) + "' instead of '" +
9396 getTypeString(IndexedType) + "'");
9397 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9398 return AteExtraComma ? InstExtraComma : InstNormal;
9399}
9400
9401//===----------------------------------------------------------------------===//
9402// Embedded metadata.
9403//===----------------------------------------------------------------------===//
9404
9405/// parseMDNodeVector
9406/// ::= { Element (',' Element)* }
9407/// Element
9408/// ::= 'null' | Metadata
9409bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9410 if (parseToken(lltok::lbrace, "expected '{' here"))
9411 return true;
9412
9413 // Check for an empty list.
9414 if (EatIfPresent(lltok::rbrace))
9415 return false;
9416
9417 do {
9418 if (EatIfPresent(lltok::kw_null)) {
9419 Elts.push_back(nullptr);
9420 continue;
9421 }
9422
9423 Metadata *MD;
9424 if (parseMetadata(MD, nullptr))
9425 return true;
9426 Elts.push_back(MD);
9427 } while (EatIfPresent(lltok::comma));
9428
9429 return parseToken(lltok::rbrace, "expected end of metadata node");
9430}
9431
9432//===----------------------------------------------------------------------===//
9433// Use-list order directives.
9434//===----------------------------------------------------------------------===//
9435bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9436 SMLoc Loc) {
9437 if (!V->hasUseList())
9438 return false;
9439 if (V->use_empty())
9440 return error(Loc, "value has no uses");
9441
9442 unsigned NumUses = 0;
9443 SmallDenseMap<const Use *, unsigned, 16> Order;
9444 for (const Use &U : V->uses()) {
9445 if (++NumUses > Indexes.size())
9446 break;
9447 Order[&U] = Indexes[NumUses - 1];
9448 }
9449 if (NumUses < 2)
9450 return error(Loc, "value only has one use");
9451 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9452 return error(Loc,
9453 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9454
9455 V->sortUseList([&](const Use &L, const Use &R) {
9456 return Order.lookup(&L) < Order.lookup(&R);
9457 });
9458 return false;
9459}
9460
9461/// parseUseListOrderIndexes
9462/// ::= '{' uint32 (',' uint32)+ '}'
9463bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9464 SMLoc Loc = Lex.getLoc();
9465 if (parseToken(lltok::lbrace, "expected '{' here"))
9466 return true;
9467 if (Lex.getKind() == lltok::rbrace)
9468 return tokError("expected non-empty list of uselistorder indexes");
9469
9470 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9471 // indexes should be distinct numbers in the range [0, size-1], and should
9472 // not be in order.
9473 unsigned Offset = 0;
9474 unsigned Max = 0;
9475 bool IsOrdered = true;
9476 assert(Indexes.empty() && "Expected empty order vector");
9477 do {
9478 unsigned Index;
9479 if (parseUInt32(Index))
9480 return true;
9481
9482 // Update consistency checks.
9483 Offset += Index - Indexes.size();
9484 Max = std::max(Max, Index);
9485 IsOrdered &= Index == Indexes.size();
9486
9487 Indexes.push_back(Index);
9488 } while (EatIfPresent(lltok::comma));
9489
9490 if (parseToken(lltok::rbrace, "expected '}' here"))
9491 return true;
9492
9493 if (Indexes.size() < 2)
9494 return error(Loc, "expected >= 2 uselistorder indexes");
9495 if (Offset != 0 || Max >= Indexes.size())
9496 return error(Loc,
9497 "expected distinct uselistorder indexes in range [0, size)");
9498 if (IsOrdered)
9499 return error(Loc, "expected uselistorder indexes to change the order");
9500
9501 return false;
9502}
9503
9504/// parseUseListOrder
9505/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9506bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9507 SMLoc Loc = Lex.getLoc();
9508 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9509 return true;
9510
9511 Value *V;
9512 SmallVector<unsigned, 16> Indexes;
9513 if (parseTypeAndValue(V, PFS) ||
9514 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9515 parseUseListOrderIndexes(Indexes))
9516 return true;
9517
9518 return sortUseListOrder(V, Indexes, Loc);
9519}
9520
9521/// ModuleEntry
9522/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9523/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9524bool LLParser::parseModuleEntry(unsigned ID) {
9525 assert(Lex.getKind() == lltok::kw_module);
9526 Lex.Lex();
9527
9528 std::string Path;
9529 if (parseToken(lltok::colon, "expected ':' here") ||
9530 parseToken(lltok::lparen, "expected '(' here") ||
9531 parseToken(lltok::kw_path, "expected 'path' here") ||
9532 parseToken(lltok::colon, "expected ':' here") ||
9533 parseStringConstant(Path) ||
9534 parseToken(lltok::comma, "expected ',' here") ||
9535 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9536 parseToken(lltok::colon, "expected ':' here") ||
9537 parseToken(lltok::lparen, "expected '(' here"))
9538 return true;
9539
9540 ModuleHash Hash;
9541 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9542 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9543 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9544 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9545 parseUInt32(Hash[4]))
9546 return true;
9547
9548 if (parseToken(lltok::rparen, "expected ')' here") ||
9549 parseToken(lltok::rparen, "expected ')' here"))
9550 return true;
9551
9552 auto ModuleEntry = Index->addModule(Path, Hash);
9553 ModuleIdMap[ID] = ModuleEntry->first();
9554
9555 return false;
9556}
9557
9558/// TypeIdEntry
9559/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9560bool LLParser::parseTypeIdEntry(unsigned ID) {
9561 assert(Lex.getKind() == lltok::kw_typeid);
9562 Lex.Lex();
9563
9564 std::string Name;
9565 if (parseToken(lltok::colon, "expected ':' here") ||
9566 parseToken(lltok::lparen, "expected '(' here") ||
9567 parseToken(lltok::kw_name, "expected 'name' here") ||
9568 parseToken(lltok::colon, "expected ':' here") ||
9569 parseStringConstant(Name))
9570 return true;
9571
9572 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9573 if (parseToken(lltok::comma, "expected ',' here") ||
9574 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9575 return true;
9576
9577 // Check if this ID was forward referenced, and if so, update the
9578 // corresponding GUIDs.
9579 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9580 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9581 for (auto TIDRef : FwdRefTIDs->second) {
9582 assert(!*TIDRef.first &&
9583 "Forward referenced type id GUID expected to be 0");
9584 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9585 }
9586 ForwardRefTypeIds.erase(FwdRefTIDs);
9587 }
9588
9589 return false;
9590}
9591
9592/// TypeIdSummary
9593/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9594bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9595 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9596 parseToken(lltok::colon, "expected ':' here") ||
9597 parseToken(lltok::lparen, "expected '(' here") ||
9598 parseTypeTestResolution(TIS.TTRes))
9599 return true;
9600
9601 if (EatIfPresent(lltok::comma)) {
9602 // Expect optional wpdResolutions field
9603 if (parseOptionalWpdResolutions(TIS.WPDRes))
9604 return true;
9605 }
9606
9607 if (parseToken(lltok::rparen, "expected ')' here"))
9608 return true;
9609
9610 return false;
9611}
9612
9615
9616/// TypeIdCompatibleVtableEntry
9617/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9618/// TypeIdCompatibleVtableInfo
9619/// ')'
9620bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9622 Lex.Lex();
9623
9624 std::string Name;
9625 if (parseToken(lltok::colon, "expected ':' here") ||
9626 parseToken(lltok::lparen, "expected '(' here") ||
9627 parseToken(lltok::kw_name, "expected 'name' here") ||
9628 parseToken(lltok::colon, "expected ':' here") ||
9629 parseStringConstant(Name))
9630 return true;
9631
9633 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9634 if (parseToken(lltok::comma, "expected ',' here") ||
9635 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9636 parseToken(lltok::colon, "expected ':' here") ||
9637 parseToken(lltok::lparen, "expected '(' here"))
9638 return true;
9639
9640 IdToIndexMapType IdToIndexMap;
9641 // parse each call edge
9642 do {
9644 if (parseToken(lltok::lparen, "expected '(' here") ||
9645 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9646 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9647 parseToken(lltok::comma, "expected ',' here"))
9648 return true;
9649
9650 LocTy Loc = Lex.getLoc();
9651 unsigned GVId;
9652 ValueInfo VI;
9653 if (parseGVReference(VI, GVId))
9654 return true;
9655
9656 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9657 // forward reference. We will save the location of the ValueInfo needing an
9658 // update, but can only do so once the std::vector is finalized.
9659 if (VI == EmptyVI)
9660 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9661 TI.push_back({Offset, VI});
9662
9663 if (parseToken(lltok::rparen, "expected ')' in call"))
9664 return true;
9665 } while (EatIfPresent(lltok::comma));
9666
9667 // Now that the TI vector is finalized, it is safe to save the locations
9668 // of any forward GV references that need updating later.
9669 for (auto I : IdToIndexMap) {
9670 auto &Infos = ForwardRefValueInfos[I.first];
9671 for (auto P : I.second) {
9672 assert(TI[P.first].VTableVI == EmptyVI &&
9673 "Forward referenced ValueInfo expected to be empty");
9674 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9675 }
9676 }
9677
9678 if (parseToken(lltok::rparen, "expected ')' here") ||
9679 parseToken(lltok::rparen, "expected ')' here"))
9680 return true;
9681
9682 // Check if this ID was forward referenced, and if so, update the
9683 // corresponding GUIDs.
9684 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9685 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9686 for (auto TIDRef : FwdRefTIDs->second) {
9687 assert(!*TIDRef.first &&
9688 "Forward referenced type id GUID expected to be 0");
9689 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9690 }
9691 ForwardRefTypeIds.erase(FwdRefTIDs);
9692 }
9693
9694 return false;
9695}
9696
9697/// TypeTestResolution
9698/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9699/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9700/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9701/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9702/// [',' 'inlinesBits' ':' UInt64]? ')'
9703bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9704 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9705 parseToken(lltok::colon, "expected ':' here") ||
9706 parseToken(lltok::lparen, "expected '(' here") ||
9707 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9708 parseToken(lltok::colon, "expected ':' here"))
9709 return true;
9710
9711 switch (Lex.getKind()) {
9712 case lltok::kw_unknown:
9714 break;
9715 case lltok::kw_unsat:
9717 break;
9720 break;
9721 case lltok::kw_inline:
9723 break;
9724 case lltok::kw_single:
9726 break;
9727 case lltok::kw_allOnes:
9729 break;
9730 default:
9731 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9732 }
9733 Lex.Lex();
9734
9735 if (parseToken(lltok::comma, "expected ',' here") ||
9736 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9737 parseToken(lltok::colon, "expected ':' here") ||
9738 parseUInt32(TTRes.SizeM1BitWidth))
9739 return true;
9740
9741 // parse optional fields
9742 while (EatIfPresent(lltok::comma)) {
9743 switch (Lex.getKind()) {
9745 Lex.Lex();
9746 if (parseToken(lltok::colon, "expected ':'") ||
9747 parseUInt64(TTRes.AlignLog2))
9748 return true;
9749 break;
9750 case lltok::kw_sizeM1:
9751 Lex.Lex();
9752 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9753 return true;
9754 break;
9755 case lltok::kw_bitMask: {
9756 unsigned Val;
9757 Lex.Lex();
9758 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9759 return true;
9760 assert(Val <= 0xff);
9761 TTRes.BitMask = (uint8_t)Val;
9762 break;
9763 }
9765 Lex.Lex();
9766 if (parseToken(lltok::colon, "expected ':'") ||
9767 parseUInt64(TTRes.InlineBits))
9768 return true;
9769 break;
9770 default:
9771 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9772 }
9773 }
9774
9775 if (parseToken(lltok::rparen, "expected ')' here"))
9776 return true;
9777
9778 return false;
9779}
9780
9781/// OptionalWpdResolutions
9782/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9783/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9784bool LLParser::parseOptionalWpdResolutions(
9785 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9786 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9787 parseToken(lltok::colon, "expected ':' here") ||
9788 parseToken(lltok::lparen, "expected '(' here"))
9789 return true;
9790
9791 do {
9792 uint64_t Offset;
9793 WholeProgramDevirtResolution WPDRes;
9794 if (parseToken(lltok::lparen, "expected '(' here") ||
9795 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9796 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9797 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9798 parseToken(lltok::rparen, "expected ')' here"))
9799 return true;
9800 WPDResMap[Offset] = WPDRes;
9801 } while (EatIfPresent(lltok::comma));
9802
9803 if (parseToken(lltok::rparen, "expected ')' here"))
9804 return true;
9805
9806 return false;
9807}
9808
9809/// WpdRes
9810/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9811/// [',' OptionalResByArg]? ')'
9812/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9813/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9814/// [',' OptionalResByArg]? ')'
9815/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9816/// [',' OptionalResByArg]? ')'
9817bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9818 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9819 parseToken(lltok::colon, "expected ':' here") ||
9820 parseToken(lltok::lparen, "expected '(' here") ||
9821 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9822 parseToken(lltok::colon, "expected ':' here"))
9823 return true;
9824
9825 switch (Lex.getKind()) {
9826 case lltok::kw_indir:
9828 break;
9831 break;
9834 break;
9835 default:
9836 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9837 }
9838 Lex.Lex();
9839
9840 // parse optional fields
9841 while (EatIfPresent(lltok::comma)) {
9842 switch (Lex.getKind()) {
9844 Lex.Lex();
9845 if (parseToken(lltok::colon, "expected ':' here") ||
9846 parseStringConstant(WPDRes.SingleImplName))
9847 return true;
9848 break;
9849 case lltok::kw_resByArg:
9850 if (parseOptionalResByArg(WPDRes.ResByArg))
9851 return true;
9852 break;
9853 default:
9854 return error(Lex.getLoc(),
9855 "expected optional WholeProgramDevirtResolution field");
9856 }
9857 }
9858
9859 if (parseToken(lltok::rparen, "expected ')' here"))
9860 return true;
9861
9862 return false;
9863}
9864
9865/// OptionalResByArg
9866/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9867/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9868/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9869/// 'virtualConstProp' )
9870/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9871/// [',' 'bit' ':' UInt32]? ')'
9872bool LLParser::parseOptionalResByArg(
9873 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9874 &ResByArg) {
9875 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9876 parseToken(lltok::colon, "expected ':' here") ||
9877 parseToken(lltok::lparen, "expected '(' here"))
9878 return true;
9879
9880 do {
9881 std::vector<uint64_t> Args;
9882 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9883 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9884 parseToken(lltok::colon, "expected ':' here") ||
9885 parseToken(lltok::lparen, "expected '(' here") ||
9886 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9887 parseToken(lltok::colon, "expected ':' here"))
9888 return true;
9889
9890 WholeProgramDevirtResolution::ByArg ByArg;
9891 switch (Lex.getKind()) {
9892 case lltok::kw_indir:
9894 break;
9897 break;
9900 break;
9903 break;
9904 default:
9905 return error(Lex.getLoc(),
9906 "unexpected WholeProgramDevirtResolution::ByArg kind");
9907 }
9908 Lex.Lex();
9909
9910 // parse optional fields
9911 while (EatIfPresent(lltok::comma)) {
9912 switch (Lex.getKind()) {
9913 case lltok::kw_info:
9914 Lex.Lex();
9915 if (parseToken(lltok::colon, "expected ':' here") ||
9916 parseUInt64(ByArg.Info))
9917 return true;
9918 break;
9919 case lltok::kw_byte:
9920 Lex.Lex();
9921 if (parseToken(lltok::colon, "expected ':' here") ||
9922 parseUInt32(ByArg.Byte))
9923 return true;
9924 break;
9925 case lltok::kw_bit:
9926 Lex.Lex();
9927 if (parseToken(lltok::colon, "expected ':' here") ||
9928 parseUInt32(ByArg.Bit))
9929 return true;
9930 break;
9931 default:
9932 return error(Lex.getLoc(),
9933 "expected optional whole program devirt field");
9934 }
9935 }
9936
9937 if (parseToken(lltok::rparen, "expected ')' here"))
9938 return true;
9939
9940 ResByArg[Args] = ByArg;
9941 } while (EatIfPresent(lltok::comma));
9942
9943 if (parseToken(lltok::rparen, "expected ')' here"))
9944 return true;
9945
9946 return false;
9947}
9948
9949/// OptionalResByArg
9950/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9951bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9952 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9953 parseToken(lltok::colon, "expected ':' here") ||
9954 parseToken(lltok::lparen, "expected '(' here"))
9955 return true;
9956
9957 do {
9958 uint64_t Val;
9959 if (parseUInt64(Val))
9960 return true;
9961 Args.push_back(Val);
9962 } while (EatIfPresent(lltok::comma));
9963
9964 if (parseToken(lltok::rparen, "expected ')' here"))
9965 return true;
9966
9967 return false;
9968}
9969
9971
9972static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9973 bool ReadOnly = Fwd->isReadOnly();
9974 bool WriteOnly = Fwd->isWriteOnly();
9975 assert(!(ReadOnly && WriteOnly));
9976 *Fwd = Resolved;
9977 if (ReadOnly)
9978 Fwd->setReadOnly();
9979 if (WriteOnly)
9980 Fwd->setWriteOnly();
9981}
9982
9983/// Stores the given Name/GUID and associated summary into the Index.
9984/// Also updates any forward references to the associated entry ID.
9985bool LLParser::addGlobalValueToIndex(
9986 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9987 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9988 // First create the ValueInfo utilizing the Name or GUID.
9989 ValueInfo VI;
9990 if (GUID != 0) {
9991 assert(Name.empty());
9992 VI = Index->getOrInsertValueInfo(GUID);
9993 } else {
9994 assert(!Name.empty());
9995 if (M) {
9996 auto *GV = M->getNamedValue(Name);
9997 if (!GV)
9998 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9999
10000 // Be a little lenient here, to accomodate older files without GUIDs
10001 // already computed and assigned as metadata.
10002 GUID = GV->getGUIDOrFallback();
10003
10004 VI = Index->getOrInsertValueInfo(GV, GUID);
10005 } else {
10006 assert(
10007 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
10008 "Need a source_filename to compute GUID for local");
10010 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
10011 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10012 }
10013 }
10014
10015 // Resolve forward references from calls/refs
10016 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10017 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10018 for (auto VIRef : FwdRefVIs->second) {
10019 assert(VIRef.first->getRef() == FwdVIRef &&
10020 "Forward referenced ValueInfo expected to be empty");
10021 resolveFwdRef(VIRef.first, VI);
10022 }
10023 ForwardRefValueInfos.erase(FwdRefVIs);
10024 }
10025
10026 // Resolve forward references from aliases
10027 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10028 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10029 for (auto AliaseeRef : FwdRefAliasees->second) {
10030 assert(!AliaseeRef.first->hasAliasee() &&
10031 "Forward referencing alias already has aliasee");
10032 assert(Summary && "Aliasee must be a definition");
10033 AliaseeRef.first->setAliasee(VI, Summary.get());
10034 }
10035 ForwardRefAliasees.erase(FwdRefAliasees);
10036 }
10037
10038 // Add the summary if one was provided.
10039 if (Summary)
10040 Index->addGlobalValueSummary(VI, std::move(Summary));
10041
10042 // Save the associated ValueInfo for use in later references by ID.
10043 if (ID == NumberedValueInfos.size())
10044 NumberedValueInfos.push_back(VI);
10045 else {
10046 // Handle non-continuous numbers (to make test simplification easier).
10047 if (ID > NumberedValueInfos.size())
10048 NumberedValueInfos.resize(ID + 1);
10049 NumberedValueInfos[ID] = VI;
10050 }
10051
10052 return false;
10053}
10054
10055/// parseSummaryIndexFlags
10056/// ::= 'flags' ':' UInt64
10057bool LLParser::parseSummaryIndexFlags() {
10058 assert(Lex.getKind() == lltok::kw_flags);
10059 Lex.Lex();
10060
10061 if (parseToken(lltok::colon, "expected ':' here"))
10062 return true;
10063 uint64_t Flags;
10064 if (parseUInt64(Flags))
10065 return true;
10066 if (Index)
10067 Index->setFlags(Flags);
10068 return false;
10069}
10070
10071/// parseBlockCount
10072/// ::= 'blockcount' ':' UInt64
10073bool LLParser::parseBlockCount() {
10074 assert(Lex.getKind() == lltok::kw_blockcount);
10075 Lex.Lex();
10076
10077 if (parseToken(lltok::colon, "expected ':' here"))
10078 return true;
10079 uint64_t BlockCount;
10080 if (parseUInt64(BlockCount))
10081 return true;
10082 if (Index)
10083 Index->setBlockCount(BlockCount);
10084 return false;
10085}
10086
10087/// parseGVEntry
10088/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
10089/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
10090/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
10091bool LLParser::parseGVEntry(unsigned ID) {
10092 assert(Lex.getKind() == lltok::kw_gv);
10093 Lex.Lex();
10094
10095 if (parseToken(lltok::colon, "expected ':' here") ||
10096 parseToken(lltok::lparen, "expected '(' here"))
10097 return true;
10098
10099 LocTy Loc = Lex.getLoc();
10100 std::string Name;
10102 switch (Lex.getKind()) {
10103 case lltok::kw_name:
10104 Lex.Lex();
10105 if (parseToken(lltok::colon, "expected ':' here") ||
10106 parseStringConstant(Name))
10107 return true;
10108 // Can't create GUID/ValueInfo until we have the linkage.
10109 break;
10110 case lltok::kw_guid:
10111 Lex.Lex();
10112 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
10113 return true;
10114 break;
10115 default:
10116 return error(Lex.getLoc(), "expected name or guid tag");
10117 }
10118
10119 if (!EatIfPresent(lltok::comma)) {
10120 // No summaries. Wrap up.
10121 if (parseToken(lltok::rparen, "expected ')' here"))
10122 return true;
10123 // This was created for a call to an external or indirect target.
10124 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
10125 // created for indirect calls with VP. A Name with no GUID came from
10126 // an external definition. We pass ExternalLinkage since that is only
10127 // used when the GUID must be computed from Name, and in that case
10128 // the symbol must have external linkage.
10129 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
10130 nullptr, Loc);
10131 }
10132
10133 // Have a list of summaries
10134 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
10135 parseToken(lltok::colon, "expected ':' here") ||
10136 parseToken(lltok::lparen, "expected '(' here"))
10137 return true;
10138 do {
10139 switch (Lex.getKind()) {
10140 case lltok::kw_function:
10141 if (parseFunctionSummary(Name, GUID, ID))
10142 return true;
10143 break;
10144 case lltok::kw_variable:
10145 if (parseVariableSummary(Name, GUID, ID))
10146 return true;
10147 break;
10148 case lltok::kw_alias:
10149 if (parseAliasSummary(Name, GUID, ID))
10150 return true;
10151 break;
10152 default:
10153 return error(Lex.getLoc(), "expected summary type");
10154 }
10155 } while (EatIfPresent(lltok::comma));
10156
10157 if (parseToken(lltok::rparen, "expected ')' here") ||
10158 parseToken(lltok::rparen, "expected ')' here"))
10159 return true;
10160
10161 return false;
10162}
10163
10164/// FunctionSummary
10165/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10166/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10167/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10168/// [',' OptionalRefs]? ')'
10169bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10170 unsigned ID) {
10171 LocTy Loc = Lex.getLoc();
10172 assert(Lex.getKind() == lltok::kw_function);
10173 Lex.Lex();
10174
10175 StringRef ModulePath;
10176 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10178 /*NotEligibleToImport=*/false,
10179 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10180 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10181 unsigned InstCount;
10183 FunctionSummary::TypeIdInfo TypeIdInfo;
10184 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10186 std::vector<CallsiteInfo> Callsites;
10187 std::vector<AllocInfo> Allocs;
10188 // Default is all-zeros (conservative values).
10189 FunctionSummary::FFlags FFlags = {};
10190 if (parseToken(lltok::colon, "expected ':' here") ||
10191 parseToken(lltok::lparen, "expected '(' here") ||
10192 parseModuleReference(ModulePath) ||
10193 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10194 parseToken(lltok::comma, "expected ',' here") ||
10195 parseToken(lltok::kw_insts, "expected 'insts' here") ||
10196 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
10197 return true;
10198
10199 // parse optional fields
10200 while (EatIfPresent(lltok::comma)) {
10201 switch (Lex.getKind()) {
10203 if (parseOptionalFFlags(FFlags))
10204 return true;
10205 break;
10206 case lltok::kw_calls:
10207 if (parseOptionalCalls(Calls))
10208 return true;
10209 break;
10211 if (parseOptionalTypeIdInfo(TypeIdInfo))
10212 return true;
10213 break;
10214 case lltok::kw_refs:
10215 if (parseOptionalRefs(Refs))
10216 return true;
10217 break;
10218 case lltok::kw_params:
10219 if (parseOptionalParamAccesses(ParamAccesses))
10220 return true;
10221 break;
10222 case lltok::kw_allocs:
10223 if (parseOptionalAllocs(Allocs))
10224 return true;
10225 break;
10227 if (parseOptionalCallsites(Callsites))
10228 return true;
10229 break;
10230 default:
10231 return error(Lex.getLoc(), "expected optional function summary field");
10232 }
10233 }
10234
10235 if (parseToken(lltok::rparen, "expected ')' here"))
10236 return true;
10237
10238 auto FS = std::make_unique<FunctionSummary>(
10239 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10240 std::move(TypeIdInfo.TypeTests),
10241 std::move(TypeIdInfo.TypeTestAssumeVCalls),
10242 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10243 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10244 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10245 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10246
10247 FS->setModulePath(ModulePath);
10248
10249 return addGlobalValueToIndex(Name, GUID,
10251 std::move(FS), Loc);
10252}
10253
10254/// VariableSummary
10255/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10256/// [',' OptionalRefs]? ')'
10257bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10258 unsigned ID) {
10259 LocTy Loc = Lex.getLoc();
10260 assert(Lex.getKind() == lltok::kw_variable);
10261 Lex.Lex();
10262
10263 StringRef ModulePath;
10264 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10266 /*NotEligibleToImport=*/false,
10267 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10268 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10269 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10270 /* WriteOnly */ false,
10271 /* Constant */ false,
10274 VTableFuncList VTableFuncs;
10275 if (parseToken(lltok::colon, "expected ':' here") ||
10276 parseToken(lltok::lparen, "expected '(' here") ||
10277 parseModuleReference(ModulePath) ||
10278 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10279 parseToken(lltok::comma, "expected ',' here") ||
10280 parseGVarFlags(GVarFlags))
10281 return true;
10282
10283 // parse optional fields
10284 while (EatIfPresent(lltok::comma)) {
10285 switch (Lex.getKind()) {
10287 if (parseOptionalVTableFuncs(VTableFuncs))
10288 return true;
10289 break;
10290 case lltok::kw_refs:
10291 if (parseOptionalRefs(Refs))
10292 return true;
10293 break;
10294 default:
10295 return error(Lex.getLoc(), "expected optional variable summary field");
10296 }
10297 }
10298
10299 if (parseToken(lltok::rparen, "expected ')' here"))
10300 return true;
10301
10302 auto GS =
10303 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10304
10305 GS->setModulePath(ModulePath);
10306 GS->setVTableFuncs(std::move(VTableFuncs));
10307
10308 return addGlobalValueToIndex(Name, GUID,
10310 std::move(GS), Loc);
10311}
10312
10313/// AliasSummary
10314/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10315/// 'aliasee' ':' GVReference ')'
10316bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10317 unsigned ID) {
10318 assert(Lex.getKind() == lltok::kw_alias);
10319 LocTy Loc = Lex.getLoc();
10320 Lex.Lex();
10321
10322 StringRef ModulePath;
10323 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10325 /*NotEligibleToImport=*/false,
10326 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10327 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10328 if (parseToken(lltok::colon, "expected ':' here") ||
10329 parseToken(lltok::lparen, "expected '(' here") ||
10330 parseModuleReference(ModulePath) ||
10331 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10332 parseToken(lltok::comma, "expected ',' here") ||
10333 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10334 parseToken(lltok::colon, "expected ':' here"))
10335 return true;
10336
10337 ValueInfo AliaseeVI;
10338 unsigned GVId;
10339 auto AS = std::make_unique<AliasSummary>(GVFlags);
10340 AS->setModulePath(ModulePath);
10341
10342 if (!EatIfPresent(lltok::kw_null)) {
10343 if (parseGVReference(AliaseeVI, GVId))
10344 return true;
10345
10346 // Record forward reference if the aliasee is not parsed yet.
10347 if (AliaseeVI.getRef() == FwdVIRef) {
10348 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10349 } else {
10350 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10351 assert(Summary && "Aliasee must be a definition");
10352 AS->setAliasee(AliaseeVI, Summary);
10353 }
10354 }
10355
10356 if (parseToken(lltok::rparen, "expected ')' here"))
10357 return true;
10358
10359 return addGlobalValueToIndex(Name, GUID,
10361 std::move(AS), Loc);
10362}
10363
10364/// Flag
10365/// ::= [0|1]
10366bool LLParser::parseFlag(unsigned &Val) {
10367 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10368 return tokError("expected integer");
10369 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10370 Lex.Lex();
10371 return false;
10372}
10373
10374/// OptionalFFlags
10375/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10376/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10377/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10378/// [',' 'noInline' ':' Flag]? ')'
10379/// [',' 'alwaysInline' ':' Flag]? ')'
10380/// [',' 'noUnwind' ':' Flag]? ')'
10381/// [',' 'mayThrow' ':' Flag]? ')'
10382/// [',' 'hasUnknownCall' ':' Flag]? ')'
10383/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10384
10385bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10386 assert(Lex.getKind() == lltok::kw_funcFlags);
10387 Lex.Lex();
10388
10389 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10390 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10391 return true;
10392
10393 do {
10394 unsigned Val = 0;
10395 switch (Lex.getKind()) {
10396 case lltok::kw_readNone:
10397 Lex.Lex();
10398 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10399 return true;
10400 FFlags.ReadNone = Val;
10401 break;
10402 case lltok::kw_readOnly:
10403 Lex.Lex();
10404 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10405 return true;
10406 FFlags.ReadOnly = Val;
10407 break;
10409 Lex.Lex();
10410 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10411 return true;
10412 FFlags.NoRecurse = Val;
10413 break;
10415 Lex.Lex();
10416 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10417 return true;
10418 FFlags.ReturnDoesNotAlias = Val;
10419 break;
10420 case lltok::kw_noInline:
10421 Lex.Lex();
10422 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10423 return true;
10424 FFlags.NoInline = Val;
10425 break;
10427 Lex.Lex();
10428 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10429 return true;
10430 FFlags.AlwaysInline = Val;
10431 break;
10432 case lltok::kw_noUnwind:
10433 Lex.Lex();
10434 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10435 return true;
10436 FFlags.NoUnwind = Val;
10437 break;
10438 case lltok::kw_mayThrow:
10439 Lex.Lex();
10440 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10441 return true;
10442 FFlags.MayThrow = Val;
10443 break;
10445 Lex.Lex();
10446 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10447 return true;
10448 FFlags.HasUnknownCall = Val;
10449 break;
10451 Lex.Lex();
10452 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10453 return true;
10454 FFlags.MustBeUnreachable = Val;
10455 break;
10456 default:
10457 return error(Lex.getLoc(), "expected function flag type");
10458 }
10459 } while (EatIfPresent(lltok::comma));
10460
10461 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10462 return true;
10463
10464 return false;
10465}
10466
10467/// OptionalCalls
10468/// := 'calls' ':' '(' Call [',' Call]* ')'
10469/// Call ::= '(' 'callee' ':' GVReference
10470/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10471/// [ ',' 'tail' ]? ')'
10472bool LLParser::parseOptionalCalls(
10473 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10474 assert(Lex.getKind() == lltok::kw_calls);
10475 Lex.Lex();
10476
10477 if (parseToken(lltok::colon, "expected ':' in calls") ||
10478 parseToken(lltok::lparen, "expected '(' in calls"))
10479 return true;
10480
10481 IdToIndexMapType IdToIndexMap;
10482 // parse each call edge
10483 do {
10484 ValueInfo VI;
10485 if (parseToken(lltok::lparen, "expected '(' in call") ||
10486 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10487 parseToken(lltok::colon, "expected ':'"))
10488 return true;
10489
10490 LocTy Loc = Lex.getLoc();
10491 unsigned GVId;
10492 if (parseGVReference(VI, GVId))
10493 return true;
10494
10496 unsigned RelBF = 0;
10497 unsigned HasTailCall = false;
10498
10499 // parse optional fields
10500 while (EatIfPresent(lltok::comma)) {
10501 switch (Lex.getKind()) {
10502 case lltok::kw_hotness:
10503 Lex.Lex();
10504 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10505 return true;
10506 break;
10507 // Deprecated, keep in order to support old files.
10508 case lltok::kw_relbf:
10509 Lex.Lex();
10510 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10511 return true;
10512 break;
10513 case lltok::kw_tail:
10514 Lex.Lex();
10515 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10516 return true;
10517 break;
10518 default:
10519 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10520 }
10521 }
10522 // Keep track of the Call array index needing a forward reference.
10523 // We will save the location of the ValueInfo needing an update, but
10524 // can only do so once the std::vector is finalized.
10525 if (VI.getRef() == FwdVIRef)
10526 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10527 Calls.push_back(
10528 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall)});
10529
10530 if (parseToken(lltok::rparen, "expected ')' in call"))
10531 return true;
10532 } while (EatIfPresent(lltok::comma));
10533
10534 // Now that the Calls vector is finalized, it is safe to save the locations
10535 // of any forward GV references that need updating later.
10536 for (auto I : IdToIndexMap) {
10537 auto &Infos = ForwardRefValueInfos[I.first];
10538 for (auto P : I.second) {
10539 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10540 "Forward referenced ValueInfo expected to be empty");
10541 Infos.emplace_back(&Calls[P.first].first, P.second);
10542 }
10543 }
10544
10545 if (parseToken(lltok::rparen, "expected ')' in calls"))
10546 return true;
10547
10548 return false;
10549}
10550
10551/// Hotness
10552/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10553bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10554 switch (Lex.getKind()) {
10555 case lltok::kw_unknown:
10557 break;
10558 case lltok::kw_cold:
10560 break;
10561 case lltok::kw_none:
10563 break;
10564 case lltok::kw_hot:
10566 break;
10567 case lltok::kw_critical:
10569 break;
10570 default:
10571 return error(Lex.getLoc(), "invalid call edge hotness");
10572 }
10573 Lex.Lex();
10574 return false;
10575}
10576
10577/// OptionalVTableFuncs
10578/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10579/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10580bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10581 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10582 Lex.Lex();
10583
10584 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10585 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10586 return true;
10587
10588 IdToIndexMapType IdToIndexMap;
10589 // parse each virtual function pair
10590 do {
10591 ValueInfo VI;
10592 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10593 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10594 parseToken(lltok::colon, "expected ':'"))
10595 return true;
10596
10597 LocTy Loc = Lex.getLoc();
10598 unsigned GVId;
10599 if (parseGVReference(VI, GVId))
10600 return true;
10601
10602 uint64_t Offset;
10603 if (parseToken(lltok::comma, "expected comma") ||
10604 parseToken(lltok::kw_offset, "expected offset") ||
10605 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10606 return true;
10607
10608 // Keep track of the VTableFuncs array index needing a forward reference.
10609 // We will save the location of the ValueInfo needing an update, but
10610 // can only do so once the std::vector is finalized.
10611 if (VI == EmptyVI)
10612 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10613 VTableFuncs.push_back({VI, Offset});
10614
10615 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10616 return true;
10617 } while (EatIfPresent(lltok::comma));
10618
10619 // Now that the VTableFuncs vector is finalized, it is safe to save the
10620 // locations of any forward GV references that need updating later.
10621 for (auto I : IdToIndexMap) {
10622 auto &Infos = ForwardRefValueInfos[I.first];
10623 for (auto P : I.second) {
10624 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10625 "Forward referenced ValueInfo expected to be empty");
10626 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10627 }
10628 }
10629
10630 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10631 return true;
10632
10633 return false;
10634}
10635
10636/// ParamNo := 'param' ':' UInt64
10637bool LLParser::parseParamNo(uint64_t &ParamNo) {
10638 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10639 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10640 return true;
10641 return false;
10642}
10643
10644/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10645bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10646 APSInt Lower;
10647 APSInt Upper;
10648 auto ParseAPSInt = [&](APSInt &Val) {
10649 if (Lex.getKind() != lltok::APSInt)
10650 return tokError("expected integer");
10651 Val = Lex.getAPSIntVal();
10652 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10653 Val.setIsSigned(true);
10654 Lex.Lex();
10655 return false;
10656 };
10657 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10658 parseToken(lltok::colon, "expected ':' here") ||
10659 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10660 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10661 parseToken(lltok::rsquare, "expected ']' here"))
10662 return true;
10663
10664 ++Upper;
10665 Range =
10666 (Lower == Upper && !Lower.isMaxValue())
10667 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10668 : ConstantRange(Lower, Upper);
10669
10670 return false;
10671}
10672
10673/// ParamAccessCall
10674/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10675bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10676 IdLocListType &IdLocList) {
10677 if (parseToken(lltok::lparen, "expected '(' here") ||
10678 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10679 parseToken(lltok::colon, "expected ':' here"))
10680 return true;
10681
10682 unsigned GVId;
10683 ValueInfo VI;
10684 LocTy Loc = Lex.getLoc();
10685 if (parseGVReference(VI, GVId))
10686 return true;
10687
10688 Call.Callee = VI;
10689 IdLocList.emplace_back(GVId, Loc);
10690
10691 if (parseToken(lltok::comma, "expected ',' here") ||
10692 parseParamNo(Call.ParamNo) ||
10693 parseToken(lltok::comma, "expected ',' here") ||
10694 parseParamAccessOffset(Call.Offsets))
10695 return true;
10696
10697 if (parseToken(lltok::rparen, "expected ')' here"))
10698 return true;
10699
10700 return false;
10701}
10702
10703/// ParamAccess
10704/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10705/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10706bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10707 IdLocListType &IdLocList) {
10708 if (parseToken(lltok::lparen, "expected '(' here") ||
10709 parseParamNo(Param.ParamNo) ||
10710 parseToken(lltok::comma, "expected ',' here") ||
10711 parseParamAccessOffset(Param.Use))
10712 return true;
10713
10714 if (EatIfPresent(lltok::comma)) {
10715 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10716 parseToken(lltok::colon, "expected ':' here") ||
10717 parseToken(lltok::lparen, "expected '(' here"))
10718 return true;
10719 do {
10720 FunctionSummary::ParamAccess::Call Call;
10721 if (parseParamAccessCall(Call, IdLocList))
10722 return true;
10723 Param.Calls.push_back(Call);
10724 } while (EatIfPresent(lltok::comma));
10725
10726 if (parseToken(lltok::rparen, "expected ')' here"))
10727 return true;
10728 }
10729
10730 if (parseToken(lltok::rparen, "expected ')' here"))
10731 return true;
10732
10733 return false;
10734}
10735
10736/// OptionalParamAccesses
10737/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10738bool LLParser::parseOptionalParamAccesses(
10739 std::vector<FunctionSummary::ParamAccess> &Params) {
10740 assert(Lex.getKind() == lltok::kw_params);
10741 Lex.Lex();
10742
10743 if (parseToken(lltok::colon, "expected ':' here") ||
10744 parseToken(lltok::lparen, "expected '(' here"))
10745 return true;
10746
10747 IdLocListType VContexts;
10748 size_t CallsNum = 0;
10749 do {
10750 FunctionSummary::ParamAccess ParamAccess;
10751 if (parseParamAccess(ParamAccess, VContexts))
10752 return true;
10753 CallsNum += ParamAccess.Calls.size();
10754 assert(VContexts.size() == CallsNum);
10755 (void)CallsNum;
10756 Params.emplace_back(std::move(ParamAccess));
10757 } while (EatIfPresent(lltok::comma));
10758
10759 if (parseToken(lltok::rparen, "expected ')' here"))
10760 return true;
10761
10762 // Now that the Params is finalized, it is safe to save the locations
10763 // of any forward GV references that need updating later.
10764 IdLocListType::const_iterator ItContext = VContexts.begin();
10765 for (auto &PA : Params) {
10766 for (auto &C : PA.Calls) {
10767 if (C.Callee.getRef() == FwdVIRef)
10768 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10769 ItContext->second);
10770 ++ItContext;
10771 }
10772 }
10773 assert(ItContext == VContexts.end());
10774
10775 return false;
10776}
10777
10778/// OptionalRefs
10779/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10780bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10781 assert(Lex.getKind() == lltok::kw_refs);
10782 Lex.Lex();
10783
10784 if (parseToken(lltok::colon, "expected ':' in refs") ||
10785 parseToken(lltok::lparen, "expected '(' in refs"))
10786 return true;
10787
10788 struct ValueContext {
10789 ValueInfo VI;
10790 unsigned GVId;
10791 LocTy Loc;
10792 };
10793 std::vector<ValueContext> VContexts;
10794 // parse each ref edge
10795 do {
10796 ValueContext VC;
10797 VC.Loc = Lex.getLoc();
10798 if (parseGVReference(VC.VI, VC.GVId))
10799 return true;
10800 VContexts.push_back(VC);
10801 } while (EatIfPresent(lltok::comma));
10802
10803 // Sort value contexts so that ones with writeonly
10804 // and readonly ValueInfo are at the end of VContexts vector.
10805 // See FunctionSummary::specialRefCounts()
10806 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10807 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10808 });
10809
10810 IdToIndexMapType IdToIndexMap;
10811 for (auto &VC : VContexts) {
10812 // Keep track of the Refs array index needing a forward reference.
10813 // We will save the location of the ValueInfo needing an update, but
10814 // can only do so once the std::vector is finalized.
10815 if (VC.VI.getRef() == FwdVIRef)
10816 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10817 Refs.push_back(VC.VI);
10818 }
10819
10820 // Now that the Refs vector is finalized, it is safe to save the locations
10821 // of any forward GV references that need updating later.
10822 for (auto I : IdToIndexMap) {
10823 auto &Infos = ForwardRefValueInfos[I.first];
10824 for (auto P : I.second) {
10825 assert(Refs[P.first].getRef() == FwdVIRef &&
10826 "Forward referenced ValueInfo expected to be empty");
10827 Infos.emplace_back(&Refs[P.first], P.second);
10828 }
10829 }
10830
10831 if (parseToken(lltok::rparen, "expected ')' in refs"))
10832 return true;
10833
10834 return false;
10835}
10836
10837/// OptionalTypeIdInfo
10838/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10839/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10840/// [',' TypeCheckedLoadConstVCalls]? ')'
10841bool LLParser::parseOptionalTypeIdInfo(
10842 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10843 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10844 Lex.Lex();
10845
10846 if (parseToken(lltok::colon, "expected ':' here") ||
10847 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10848 return true;
10849
10850 do {
10851 switch (Lex.getKind()) {
10853 if (parseTypeTests(TypeIdInfo.TypeTests))
10854 return true;
10855 break;
10857 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10858 TypeIdInfo.TypeTestAssumeVCalls))
10859 return true;
10860 break;
10862 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10863 TypeIdInfo.TypeCheckedLoadVCalls))
10864 return true;
10865 break;
10867 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10868 TypeIdInfo.TypeTestAssumeConstVCalls))
10869 return true;
10870 break;
10872 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10873 TypeIdInfo.TypeCheckedLoadConstVCalls))
10874 return true;
10875 break;
10876 default:
10877 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10878 }
10879 } while (EatIfPresent(lltok::comma));
10880
10881 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10882 return true;
10883
10884 return false;
10885}
10886
10887/// TypeTests
10888/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10889/// [',' (SummaryID | UInt64)]* ')'
10890bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10891 assert(Lex.getKind() == lltok::kw_typeTests);
10892 Lex.Lex();
10893
10894 if (parseToken(lltok::colon, "expected ':' here") ||
10895 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10896 return true;
10897
10898 IdToIndexMapType IdToIndexMap;
10899 do {
10901 if (Lex.getKind() == lltok::SummaryID) {
10902 unsigned ID = Lex.getUIntVal();
10903 LocTy Loc = Lex.getLoc();
10904 // Keep track of the TypeTests array index needing a forward reference.
10905 // We will save the location of the GUID needing an update, but
10906 // can only do so once the std::vector is finalized.
10907 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10908 Lex.Lex();
10909 } else if (parseUInt64(GUID))
10910 return true;
10911 TypeTests.push_back(GUID);
10912 } while (EatIfPresent(lltok::comma));
10913
10914 // Now that the TypeTests vector is finalized, it is safe to save the
10915 // locations of any forward GV references that need updating later.
10916 for (auto I : IdToIndexMap) {
10917 auto &Ids = ForwardRefTypeIds[I.first];
10918 for (auto P : I.second) {
10919 assert(TypeTests[P.first] == 0 &&
10920 "Forward referenced type id GUID expected to be 0");
10921 Ids.emplace_back(&TypeTests[P.first], P.second);
10922 }
10923 }
10924
10925 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10926 return true;
10927
10928 return false;
10929}
10930
10931/// VFuncIdList
10932/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10933bool LLParser::parseVFuncIdList(
10934 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10935 assert(Lex.getKind() == Kind);
10936 Lex.Lex();
10937
10938 if (parseToken(lltok::colon, "expected ':' here") ||
10939 parseToken(lltok::lparen, "expected '(' here"))
10940 return true;
10941
10942 IdToIndexMapType IdToIndexMap;
10943 do {
10944 FunctionSummary::VFuncId VFuncId;
10945 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10946 return true;
10947 VFuncIdList.push_back(VFuncId);
10948 } while (EatIfPresent(lltok::comma));
10949
10950 if (parseToken(lltok::rparen, "expected ')' here"))
10951 return true;
10952
10953 // Now that the VFuncIdList vector is finalized, it is safe to save the
10954 // locations of any forward GV references that need updating later.
10955 for (auto I : IdToIndexMap) {
10956 auto &Ids = ForwardRefTypeIds[I.first];
10957 for (auto P : I.second) {
10958 assert(VFuncIdList[P.first].GUID == 0 &&
10959 "Forward referenced type id GUID expected to be 0");
10960 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10961 }
10962 }
10963
10964 return false;
10965}
10966
10967/// ConstVCallList
10968/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10969bool LLParser::parseConstVCallList(
10970 lltok::Kind Kind,
10971 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10972 assert(Lex.getKind() == Kind);
10973 Lex.Lex();
10974
10975 if (parseToken(lltok::colon, "expected ':' here") ||
10976 parseToken(lltok::lparen, "expected '(' here"))
10977 return true;
10978
10979 IdToIndexMapType IdToIndexMap;
10980 do {
10981 FunctionSummary::ConstVCall ConstVCall;
10982 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10983 return true;
10984 ConstVCallList.push_back(ConstVCall);
10985 } while (EatIfPresent(lltok::comma));
10986
10987 if (parseToken(lltok::rparen, "expected ')' here"))
10988 return true;
10989
10990 // Now that the ConstVCallList vector is finalized, it is safe to save the
10991 // locations of any forward GV references that need updating later.
10992 for (auto I : IdToIndexMap) {
10993 auto &Ids = ForwardRefTypeIds[I.first];
10994 for (auto P : I.second) {
10995 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10996 "Forward referenced type id GUID expected to be 0");
10997 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10998 }
10999 }
11000
11001 return false;
11002}
11003
11004/// ConstVCall
11005/// ::= '(' VFuncId ',' Args ')'
11006bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11007 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11008 if (parseToken(lltok::lparen, "expected '(' here") ||
11009 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
11010 return true;
11011
11012 if (EatIfPresent(lltok::comma))
11013 if (parseArgs(ConstVCall.Args))
11014 return true;
11015
11016 if (parseToken(lltok::rparen, "expected ')' here"))
11017 return true;
11018
11019 return false;
11020}
11021
11022/// VFuncId
11023/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
11024/// 'offset' ':' UInt64 ')'
11025bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11026 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11027 assert(Lex.getKind() == lltok::kw_vFuncId);
11028 Lex.Lex();
11029
11030 if (parseToken(lltok::colon, "expected ':' here") ||
11031 parseToken(lltok::lparen, "expected '(' here"))
11032 return true;
11033
11034 if (Lex.getKind() == lltok::SummaryID) {
11035 VFuncId.GUID = 0;
11036 unsigned ID = Lex.getUIntVal();
11037 LocTy Loc = Lex.getLoc();
11038 // Keep track of the array index needing a forward reference.
11039 // We will save the location of the GUID needing an update, but
11040 // can only do so once the caller's std::vector is finalized.
11041 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
11042 Lex.Lex();
11043 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
11044 parseToken(lltok::colon, "expected ':' here") ||
11045 parseUInt64(VFuncId.GUID))
11046 return true;
11047
11048 if (parseToken(lltok::comma, "expected ',' here") ||
11049 parseToken(lltok::kw_offset, "expected 'offset' here") ||
11050 parseToken(lltok::colon, "expected ':' here") ||
11051 parseUInt64(VFuncId.Offset) ||
11052 parseToken(lltok::rparen, "expected ')' here"))
11053 return true;
11054
11055 return false;
11056}
11057
11058/// GVFlags
11059/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
11060/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
11061/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
11062/// 'canAutoHide' ':' Flag ',' ')'
11063bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11064 assert(Lex.getKind() == lltok::kw_flags);
11065 Lex.Lex();
11066
11067 if (parseToken(lltok::colon, "expected ':' here") ||
11068 parseToken(lltok::lparen, "expected '(' here"))
11069 return true;
11070
11071 do {
11072 unsigned Flag = 0;
11073 switch (Lex.getKind()) {
11074 case lltok::kw_linkage:
11075 Lex.Lex();
11076 if (parseToken(lltok::colon, "expected ':'"))
11077 return true;
11078 bool HasLinkage;
11079 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
11080 assert(HasLinkage && "Linkage not optional in summary entry");
11081 Lex.Lex();
11082 break;
11084 Lex.Lex();
11085 if (parseToken(lltok::colon, "expected ':'"))
11086 return true;
11087 parseOptionalVisibility(Flag);
11088 GVFlags.Visibility = Flag;
11089 break;
11091 Lex.Lex();
11092 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11093 return true;
11094 GVFlags.NotEligibleToImport = Flag;
11095 break;
11096 case lltok::kw_live:
11097 Lex.Lex();
11098 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11099 return true;
11100 GVFlags.Live = Flag;
11101 break;
11102 case lltok::kw_dsoLocal:
11103 Lex.Lex();
11104 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11105 return true;
11106 GVFlags.DSOLocal = Flag;
11107 break;
11109 Lex.Lex();
11110 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11111 return true;
11112 GVFlags.CanAutoHide = Flag;
11113 break;
11115 Lex.Lex();
11116 if (parseToken(lltok::colon, "expected ':'"))
11117 return true;
11119 if (parseOptionalImportType(Lex.getKind(), IK))
11120 return true;
11121 GVFlags.ImportType = static_cast<unsigned>(IK);
11122 Lex.Lex();
11123 break;
11125 Lex.Lex();
11126 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11127 return true;
11128 GVFlags.NoRenameOnPromotion = Flag;
11129 break;
11130 default:
11131 return error(Lex.getLoc(), "expected gv flag type");
11132 }
11133 } while (EatIfPresent(lltok::comma));
11134
11135 if (parseToken(lltok::rparen, "expected ')' here"))
11136 return true;
11137
11138 return false;
11139}
11140
11141/// GVarFlags
11142/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
11143/// ',' 'writeonly' ':' Flag
11144/// ',' 'constant' ':' Flag ')'
11145bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11146 assert(Lex.getKind() == lltok::kw_varFlags);
11147 Lex.Lex();
11148
11149 if (parseToken(lltok::colon, "expected ':' here") ||
11150 parseToken(lltok::lparen, "expected '(' here"))
11151 return true;
11152
11153 auto ParseRest = [this](unsigned int &Val) {
11154 Lex.Lex();
11155 if (parseToken(lltok::colon, "expected ':'"))
11156 return true;
11157 return parseFlag(Val);
11158 };
11159
11160 do {
11161 unsigned Flag = 0;
11162 switch (Lex.getKind()) {
11163 case lltok::kw_readonly:
11164 if (ParseRest(Flag))
11165 return true;
11166 GVarFlags.MaybeReadOnly = Flag;
11167 break;
11168 case lltok::kw_writeonly:
11169 if (ParseRest(Flag))
11170 return true;
11171 GVarFlags.MaybeWriteOnly = Flag;
11172 break;
11173 case lltok::kw_constant:
11174 if (ParseRest(Flag))
11175 return true;
11176 GVarFlags.Constant = Flag;
11177 break;
11179 if (ParseRest(Flag))
11180 return true;
11181 GVarFlags.VCallVisibility = Flag;
11182 break;
11183 default:
11184 return error(Lex.getLoc(), "expected gvar flag type");
11185 }
11186 } while (EatIfPresent(lltok::comma));
11187 return parseToken(lltok::rparen, "expected ')' here");
11188}
11189
11190/// ModuleReference
11191/// ::= 'module' ':' UInt
11192bool LLParser::parseModuleReference(StringRef &ModulePath) {
11193 // parse module id.
11194 if (parseToken(lltok::kw_module, "expected 'module' here") ||
11195 parseToken(lltok::colon, "expected ':' here") ||
11196 parseToken(lltok::SummaryID, "expected module ID"))
11197 return true;
11198
11199 unsigned ModuleID = Lex.getUIntVal();
11200 auto I = ModuleIdMap.find(ModuleID);
11201 // We should have already parsed all module IDs
11202 assert(I != ModuleIdMap.end());
11203 ModulePath = I->second;
11204 return false;
11205}
11206
11207/// GVReference
11208/// ::= SummaryID
11209bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11210 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
11211 if (!ReadOnly)
11212 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11213 if (parseToken(lltok::SummaryID, "expected GV ID"))
11214 return true;
11215
11216 GVId = Lex.getUIntVal();
11217 // Check if we already have a VI for this GV
11218 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11219 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11220 VI = NumberedValueInfos[GVId];
11221 } else
11222 // We will create a forward reference to the stored location.
11223 VI = ValueInfo(false, FwdVIRef);
11224
11225 if (ReadOnly)
11226 VI.setReadOnly();
11227 if (WriteOnly)
11228 VI.setWriteOnly();
11229 return false;
11230}
11231
11232/// OptionalAllocs
11233/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11234/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11235/// ',' MemProfs ')'
11236/// Version ::= UInt32
11237bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11238 assert(Lex.getKind() == lltok::kw_allocs);
11239 Lex.Lex();
11240
11241 if (parseToken(lltok::colon, "expected ':' in allocs") ||
11242 parseToken(lltok::lparen, "expected '(' in allocs"))
11243 return true;
11244
11245 // parse each alloc
11246 do {
11247 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
11248 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
11249 parseToken(lltok::colon, "expected ':'") ||
11250 parseToken(lltok::lparen, "expected '(' in versions"))
11251 return true;
11252
11253 SmallVector<uint8_t> Versions;
11254 do {
11255 uint8_t V = 0;
11256 if (parseAllocType(V))
11257 return true;
11258 Versions.push_back(V);
11259 } while (EatIfPresent(lltok::comma));
11260
11261 if (parseToken(lltok::rparen, "expected ')' in versions") ||
11262 parseToken(lltok::comma, "expected ',' in alloc"))
11263 return true;
11264
11265 std::vector<MIBInfo> MIBs;
11266 if (parseMemProfs(MIBs))
11267 return true;
11268
11269 Allocs.push_back({Versions, MIBs});
11270
11271 if (parseToken(lltok::rparen, "expected ')' in alloc"))
11272 return true;
11273 } while (EatIfPresent(lltok::comma));
11274
11275 if (parseToken(lltok::rparen, "expected ')' in allocs"))
11276 return true;
11277
11278 return false;
11279}
11280
11281/// MemProfs
11282/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11283/// MemProf ::= '(' 'type' ':' AllocType
11284/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11285/// StackId ::= UInt64
11286bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11287 assert(Lex.getKind() == lltok::kw_memProf);
11288 Lex.Lex();
11289
11290 if (parseToken(lltok::colon, "expected ':' in memprof") ||
11291 parseToken(lltok::lparen, "expected '(' in memprof"))
11292 return true;
11293
11294 // parse each MIB
11295 do {
11296 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
11297 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
11298 parseToken(lltok::colon, "expected ':'"))
11299 return true;
11300
11301 uint8_t AllocType;
11302 if (parseAllocType(AllocType))
11303 return true;
11304
11305 if (parseToken(lltok::comma, "expected ',' in memprof") ||
11306 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
11307 parseToken(lltok::colon, "expected ':'") ||
11308 parseToken(lltok::lparen, "expected '(' in stackIds"))
11309 return true;
11310
11311 SmallVector<unsigned> StackIdIndices;
11312 // Combined index alloc records may not have a stack id list.
11313 if (Lex.getKind() != lltok::rparen) {
11314 do {
11315 uint64_t StackId = 0;
11316 if (parseUInt64(StackId))
11317 return true;
11318 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11319 } while (EatIfPresent(lltok::comma));
11320 }
11321
11322 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11323 return true;
11324
11325 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11326
11327 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11328 return true;
11329 } while (EatIfPresent(lltok::comma));
11330
11331 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11332 return true;
11333
11334 return false;
11335}
11336
11337/// AllocType
11338/// := ('none'|'notcold'|'cold'|'hot')
11339bool LLParser::parseAllocType(uint8_t &AllocType) {
11340 switch (Lex.getKind()) {
11341 case lltok::kw_none:
11343 break;
11344 case lltok::kw_notcold:
11346 break;
11347 case lltok::kw_cold:
11349 break;
11350 case lltok::kw_hot:
11351 AllocType = (uint8_t)AllocationType::Hot;
11352 break;
11353 default:
11354 return error(Lex.getLoc(), "invalid alloc type");
11355 }
11356 Lex.Lex();
11357 return false;
11358}
11359
11360/// OptionalCallsites
11361/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11362/// Callsite ::= '(' 'callee' ':' GVReference
11363/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11364/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11365/// Version ::= UInt32
11366/// StackId ::= UInt64
11367bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11368 assert(Lex.getKind() == lltok::kw_callsites);
11369 Lex.Lex();
11370
11371 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11372 parseToken(lltok::lparen, "expected '(' in callsites"))
11373 return true;
11374
11375 IdToIndexMapType IdToIndexMap;
11376 // parse each callsite
11377 do {
11378 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11379 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11380 parseToken(lltok::colon, "expected ':'"))
11381 return true;
11382
11383 ValueInfo VI;
11384 unsigned GVId = 0;
11385 LocTy Loc = Lex.getLoc();
11386 if (!EatIfPresent(lltok::kw_null)) {
11387 if (parseGVReference(VI, GVId))
11388 return true;
11389 }
11390
11391 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11392 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11393 parseToken(lltok::colon, "expected ':'") ||
11394 parseToken(lltok::lparen, "expected '(' in clones"))
11395 return true;
11396
11397 SmallVector<unsigned> Clones;
11398 do {
11399 unsigned V = 0;
11400 if (parseUInt32(V))
11401 return true;
11402 Clones.push_back(V);
11403 } while (EatIfPresent(lltok::comma));
11404
11405 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11406 parseToken(lltok::comma, "expected ',' in callsite") ||
11407 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11408 parseToken(lltok::colon, "expected ':'") ||
11409 parseToken(lltok::lparen, "expected '(' in stackIds"))
11410 return true;
11411
11412 SmallVector<unsigned> StackIdIndices;
11413 // Synthesized callsite records will not have a stack id list.
11414 if (Lex.getKind() != lltok::rparen) {
11415 do {
11416 uint64_t StackId = 0;
11417 if (parseUInt64(StackId))
11418 return true;
11419 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11420 } while (EatIfPresent(lltok::comma));
11421 }
11422
11423 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11424 return true;
11425
11426 // Keep track of the Callsites array index needing a forward reference.
11427 // We will save the location of the ValueInfo needing an update, but
11428 // can only do so once the SmallVector is finalized.
11429 if (VI.getRef() == FwdVIRef)
11430 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11431 Callsites.push_back({VI, Clones, StackIdIndices});
11432
11433 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11434 return true;
11435 } while (EatIfPresent(lltok::comma));
11436
11437 // Now that the Callsites vector is finalized, it is safe to save the
11438 // locations of any forward GV references that need updating later.
11439 for (auto I : IdToIndexMap) {
11440 auto &Infos = ForwardRefValueInfos[I.first];
11441 for (auto P : I.second) {
11442 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11443 "Forward referenced ValueInfo expected to be empty");
11444 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11445 }
11446 }
11447
11448 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11449 return true;
11450
11451 return false;
11452}
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:842
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1014
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:1026
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:599
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:618
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:654
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:726
#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:383
constexpr bool isPacked(const T &...O)
Definition SIDefines.h:330
@ 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:771
@ 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:821
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:827
@ 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:383
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:573
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:284
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:279
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:374
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:189
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:981
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.