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 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
192 // Check whether there is only a single use left, which would be in our
193 // own NumberedMetadata.
194 if (Info.first->getNumTemporaryUses() == 1) {
195 NumberedMetadata.erase(ID);
196 ForwardRefMDNodes.erase(ID);
197 }
198 }
199}
200
201/// validateEndOfModule - Do final validity and basic correctness checks at the
202/// end of the module.
203bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
204 if (!M)
205 return false;
206
207 // We should have already returned an error if we observed both intrinsics and
208 // records in this IR.
209 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
210 "Mixed debug intrinsics/records seen without a parsing error?");
211
212 // Handle any function attribute group forward references.
213 for (const auto &RAG : ForwardRefAttrGroups) {
214 Value *V = RAG.first;
215 const std::vector<unsigned> &Attrs = RAG.second;
216 AttrBuilder B(Context);
217
218 for (const auto &Attr : Attrs) {
219 auto R = NumberedAttrBuilders.find(Attr);
220 if (R != NumberedAttrBuilders.end())
221 B.merge(R->second);
222 }
223
224 if (Function *Fn = dyn_cast<Function>(V)) {
225 AttributeList AS = Fn->getAttributes();
226 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
227 AS = AS.removeFnAttributes(Context);
228
229 FnAttrs.merge(B);
230
231 // If the alignment was parsed as an attribute, move to the alignment
232 // field.
233 if (MaybeAlign A = FnAttrs.getAlignment()) {
234 Fn->setAlignment(*A);
235 FnAttrs.removeAttribute(Attribute::Alignment);
236 }
237
238 AS = AS.addFnAttributes(Context, FnAttrs);
239 Fn->setAttributes(AS);
240 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
241 AttributeList AS = CI->getAttributes();
242 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
243 AS = AS.removeFnAttributes(Context);
244 FnAttrs.merge(B);
245 AS = AS.addFnAttributes(Context, FnAttrs);
246 CI->setAttributes(AS);
247 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
248 AttributeList AS = II->getAttributes();
249 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
250 AS = AS.removeFnAttributes(Context);
251 FnAttrs.merge(B);
252 AS = AS.addFnAttributes(Context, FnAttrs);
253 II->setAttributes(AS);
254 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
255 AttributeList AS = CBI->getAttributes();
256 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
257 AS = AS.removeFnAttributes(Context);
258 FnAttrs.merge(B);
259 AS = AS.addFnAttributes(Context, FnAttrs);
260 CBI->setAttributes(AS);
261 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
262 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
263 Attrs.merge(B);
264 GV->setAttributes(AttributeSet::get(Context,Attrs));
265 } else {
266 llvm_unreachable("invalid object with forward attribute group reference");
267 }
268 }
269
270 // If there are entries in ForwardRefBlockAddresses at this point, the
271 // function was never defined.
272 if (!ForwardRefBlockAddresses.empty())
273 return error(ForwardRefBlockAddresses.begin()->first.Loc,
274 "expected function name in blockaddress");
275
276 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
277 GlobalValue *FwdRef) {
278 GlobalValue *GV = nullptr;
279 if (GVRef.Kind == ValID::t_GlobalName) {
280 GV = M->getNamedValue(GVRef.StrVal);
281 } else {
282 GV = NumberedVals.get(GVRef.UIntVal);
283 }
284
285 if (!GV)
286 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
287 "' referenced by dso_local_equivalent");
288
289 if (!GV->getValueType()->isFunctionTy())
290 return error(GVRef.Loc,
291 "expected a function, alias to function, or ifunc "
292 "in dso_local_equivalent");
293
294 auto *Equiv = DSOLocalEquivalent::get(GV);
295 FwdRef->replaceAllUsesWith(Equiv);
296 FwdRef->eraseFromParent();
297 return false;
298 };
299
300 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
301 // point, they are references after the function was defined. Resolve those
302 // now.
303 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
304 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
305 return true;
306 }
307 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
308 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
309 return true;
310 }
311 ForwardRefDSOLocalEquivalentIDs.clear();
312 ForwardRefDSOLocalEquivalentNames.clear();
313
314 for (const auto &NT : NumberedTypes)
315 if (NT.second.second.isValid())
316 return error(NT.second.second,
317 "use of undefined type '%" + Twine(NT.first) + "'");
318
319 for (const auto &[Name, TypeInfo] : NamedTypes)
320 if (TypeInfo.second.isValid())
321 return error(TypeInfo.second,
322 "use of undefined type named '" + Name + "'");
323
324 if (!ForwardRefComdats.empty())
325 return error(ForwardRefComdats.begin()->second,
326 "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first + "'");
328
329 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
330 if (StringRef(Name).starts_with("llvm.")) {
332 // Automatically create declarations for intrinsics. Intrinsics can only
333 // be called directly, so the call function type directly determines the
334 // declaration function type.
335 //
336 // Additionally, automatically add the required mangling suffix to the
337 // intrinsic name. This means that we may replace a single forward
338 // declaration with multiple functions here.
339 for (Use &U : make_early_inc_range(Info.first->uses())) {
340 auto *CB = dyn_cast<CallBase>(U.getUser());
341 if (!CB || !CB->isCallee(&U))
342 return error(Info.second, "intrinsic can only be used as callee");
343
344 std::string ErrorMsg;
345 raw_string_ostream ErrorOS(ErrorMsg);
346
347 SmallVector<Type *> OverloadTys;
348 if (IID != Intrinsic::not_intrinsic &&
349 Intrinsic::isSignatureValid(IID, CB->getFunctionType(), OverloadTys,
350 ErrorOS)) {
351 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
352 } else {
353 // Try to upgrade the intrinsic.
354 Function *TmpF = Function::Create(CB->getFunctionType(),
356 Function *NewF = nullptr;
357 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
358 if (IID == Intrinsic::not_intrinsic)
359 return error(Info.second, "unknown intrinsic '" + Name + "'");
360 return error(Info.second, ErrorMsg);
361 }
362
363 U.set(TmpF);
364 UpgradeIntrinsicCall(CB, NewF);
365 if (TmpF->use_empty())
366 TmpF->eraseFromParent();
367 }
368 }
369
370 Info.first->eraseFromParent();
371 ForwardRefVals.erase(Name);
372 continue;
373 }
374
375 // If incomplete IR is allowed, also add declarations for
376 // non-intrinsics.
378 continue;
379
380 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
381 FunctionType *FTy = nullptr;
382 for (Use &U : V->uses()) {
383 auto *CB = dyn_cast<CallBase>(U.getUser());
384 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
385 return nullptr;
386 FTy = CB->getFunctionType();
387 }
388 return FTy;
389 };
390
391 // First check whether this global is only used in calls with the same
392 // type, in which case we'll insert a function. Otherwise, fall back to
393 // using a dummy i8 type.
394 Type *Ty = GetCommonFunctionType(Info.first);
395 if (!Ty)
396 Ty = Type::getInt8Ty(Context);
397
398 GlobalValue *GV;
399 if (auto *FTy = dyn_cast<FunctionType>(Ty))
401 else
402 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
404 /*Initializer*/ nullptr, Name);
405 Info.first->replaceAllUsesWith(GV);
406 Info.first->eraseFromParent();
407 ForwardRefVals.erase(Name);
408 }
409
410 if (!ForwardRefVals.empty())
411 return error(ForwardRefVals.begin()->second.second,
412 "use of undefined value '@" + ForwardRefVals.begin()->first +
413 "'");
414
415 if (!ForwardRefValIDs.empty())
416 return error(ForwardRefValIDs.begin()->second.second,
417 "use of undefined value '@" +
418 Twine(ForwardRefValIDs.begin()->first) + "'");
419
420 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
421 dropUnknownMetadataReferences();
422
423 if (!ForwardRefMDNodes.empty())
424 return error(ForwardRefMDNodes.begin()->second.second,
425 "use of undefined metadata '!" +
426 Twine(ForwardRefMDNodes.begin()->first) + "'");
427
428 // Resolve metadata cycles.
429 for (auto &N : NumberedMetadata) {
430 if (N.second && !N.second->isResolved())
431 N.second->resolveCycles();
432 }
433
435 NewDistinctSPs.clear();
436
437 for (auto *Inst : InstsWithTBAATag) {
438 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
439 // With incomplete IR, the tbaa metadata may have been dropped.
441 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
442 if (MD) {
443 auto *UpgradedMD = UpgradeTBAANode(*MD);
444 if (MD != UpgradedMD)
445 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
446 }
447 }
448
449 // Look for intrinsic functions and CallInst that need to be upgraded. We use
450 // make_early_inc_range here because we may remove some functions.
451 for (Function &F : llvm::make_early_inc_range(*M))
453
454 if (UpgradeDebugInfo)
456
461
462 if (!Slots)
463 return false;
464 // Initialize the slot mapping.
465 // Because by this point we've parsed and validated everything, we can "steal"
466 // the mapping from LLParser as it doesn't need it anymore.
467 Slots->GlobalValues = std::move(NumberedVals);
468 Slots->MetadataNodes = std::move(NumberedMetadata);
469 for (const auto &I : NamedTypes)
470 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
471 for (const auto &I : NumberedTypes)
472 Slots->Types.insert(std::make_pair(I.first, I.second.first));
473
474 return false;
475}
476
477/// Do final validity and basic correctness checks at the end of the index.
478bool LLParser::validateEndOfIndex() {
479 if (!Index)
480 return false;
481
482 if (!ForwardRefValueInfos.empty())
483 return error(ForwardRefValueInfos.begin()->second.front().second,
484 "use of undefined summary '^" +
485 Twine(ForwardRefValueInfos.begin()->first) + "'");
486
487 if (!ForwardRefAliasees.empty())
488 return error(ForwardRefAliasees.begin()->second.front().second,
489 "use of undefined summary '^" +
490 Twine(ForwardRefAliasees.begin()->first) + "'");
491
492 if (!ForwardRefTypeIds.empty())
493 return error(ForwardRefTypeIds.begin()->second.front().second,
494 "use of undefined type id summary '^" +
495 Twine(ForwardRefTypeIds.begin()->first) + "'");
496
497 return false;
498}
499
500//===----------------------------------------------------------------------===//
501// Top-Level Entities
502//===----------------------------------------------------------------------===//
503
504bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
505 // Delay parsing of the data layout string until the target triple is known.
506 // Then, pass both the the target triple and the tentative data layout string
507 // to DataLayoutCallback, allowing to override the DL string.
508 // This enables importing modules with invalid DL strings.
509 std::string TentativeDLStr = M->getDataLayoutStr();
510 LocTy DLStrLoc;
511
512 bool Done = false;
513 while (!Done) {
514 switch (Lex.getKind()) {
515 case lltok::kw_target:
516 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
517 return true;
518 break;
520 if (parseSourceFileName())
521 return true;
522 break;
523 default:
524 Done = true;
525 }
526 }
527 // Run the override callback to potentially change the data layout string, and
528 // parse the data layout string.
529 if (auto LayoutOverride =
530 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
531 TentativeDLStr = *LayoutOverride;
532 DLStrLoc = {};
533 }
534 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
535 if (!MaybeDL)
536 return error(DLStrLoc, toString(MaybeDL.takeError()));
537 M->setDataLayout(MaybeDL.get());
538 return false;
539}
540
541bool LLParser::parseTopLevelEntities() {
542 // If there is no Module, then parse just the summary index entries.
543 if (!M) {
544 while (true) {
545 switch (Lex.getKind()) {
546 case lltok::Eof:
547 return false;
548 case lltok::SummaryID:
549 if (parseSummaryEntry())
550 return true;
551 break;
553 if (parseSourceFileName())
554 return true;
555 break;
556 default:
557 // Skip everything else
558 Lex.Lex();
559 }
560 }
561 }
562 while (true) {
563 switch (Lex.getKind()) {
564 default:
565 return tokError("expected top-level entity");
566 case lltok::Eof: return false;
568 if (parseDeclare())
569 return true;
570 break;
571 case lltok::kw_define:
572 if (parseDefine())
573 return true;
574 break;
575 case lltok::kw_module:
576 if (parseModuleAsm())
577 return true;
578 break;
580 if (parseUnnamedType())
581 return true;
582 break;
583 case lltok::LocalVar:
584 if (parseNamedType())
585 return true;
586 break;
587 case lltok::GlobalID:
588 if (parseUnnamedGlobal())
589 return true;
590 break;
591 case lltok::GlobalVar:
592 if (parseNamedGlobal())
593 return true;
594 break;
595 case lltok::ComdatVar: if (parseComdat()) return true; break;
596 case lltok::exclaim:
597 if (parseStandaloneMetadata())
598 return true;
599 break;
600 case lltok::SummaryID:
601 if (parseSummaryEntry())
602 return true;
603 break;
605 if (parseNamedMetadata())
606 return true;
607 break;
609 if (parseUnnamedAttrGrp())
610 return true;
611 break;
613 if (parseUseListOrder())
614 return true;
615 break;
617 if (parseUseListOrderBB())
618 return true;
619 break;
620 }
621 }
622}
623
624/// toplevelentity
625/// ::= 'module' 'asm' STRINGCONSTANT
626bool LLParser::parseModuleAsm() {
627 assert(Lex.getKind() == lltok::kw_module);
628 Lex.Lex();
629
630 std::string AsmStr;
631 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
632 parseStringConstant(AsmStr))
633 return true;
634
635 M->appendModuleInlineAsm(AsmStr);
636 return false;
637}
638
639/// toplevelentity
640/// ::= 'target' 'triple' '=' STRINGCONSTANT
641/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
642bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
643 LocTy &DLStrLoc) {
644 assert(Lex.getKind() == lltok::kw_target);
645 std::string Str;
646 switch (Lex.Lex()) {
647 default:
648 return tokError("unknown target property");
649 case lltok::kw_triple:
650 Lex.Lex();
651 if (parseToken(lltok::equal, "expected '=' after target triple") ||
652 parseStringConstant(Str))
653 return true;
654 M->setTargetTriple(Triple(std::move(Str)));
655 return false;
657 Lex.Lex();
658 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
659 return true;
660 DLStrLoc = Lex.getLoc();
661 if (parseStringConstant(TentativeDLStr))
662 return true;
663 return false;
664 }
665}
666
667/// toplevelentity
668/// ::= 'source_filename' '=' STRINGCONSTANT
669bool LLParser::parseSourceFileName() {
670 assert(Lex.getKind() == lltok::kw_source_filename);
671 Lex.Lex();
672 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
673 parseStringConstant(SourceFileName))
674 return true;
675 if (M)
676 M->setSourceFileName(SourceFileName);
677 return false;
678}
679
680/// parseUnnamedType:
681/// ::= LocalVarID '=' 'type' type
682bool LLParser::parseUnnamedType() {
683 LocTy TypeLoc = Lex.getLoc();
684 unsigned TypeID = Lex.getUIntVal();
685 Lex.Lex(); // eat LocalVarID;
686
687 if (parseToken(lltok::equal, "expected '=' after name") ||
688 parseToken(lltok::kw_type, "expected 'type' after '='"))
689 return true;
690
691 Type *Result = nullptr;
692 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
693 return true;
694
695 if (!isa<StructType>(Result)) {
696 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
697 if (Entry.first)
698 return error(TypeLoc, "non-struct types may not be recursive");
699 Entry.first = Result;
700 Entry.second = SMLoc();
701 }
702
703 return false;
704}
705
706/// toplevelentity
707/// ::= LocalVar '=' 'type' type
708bool LLParser::parseNamedType() {
709 std::string Name = Lex.getStrVal();
710 LocTy NameLoc = Lex.getLoc();
711 Lex.Lex(); // eat LocalVar.
712
713 if (parseToken(lltok::equal, "expected '=' after name") ||
714 parseToken(lltok::kw_type, "expected 'type' after name"))
715 return true;
716
717 Type *Result = nullptr;
718 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
719 return true;
720
721 if (!isa<StructType>(Result)) {
722 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
723 if (Entry.first)
724 return error(NameLoc, "non-struct types may not be recursive");
725 Entry.first = Result;
726 Entry.second = SMLoc();
727 }
728
729 return false;
730}
731
732/// toplevelentity
733/// ::= 'declare' FunctionHeader
734bool LLParser::parseDeclare() {
735 assert(Lex.getKind() == lltok::kw_declare);
736 Lex.Lex();
737
738 std::vector<std::pair<unsigned, MDNode *>> MDs;
739 while (Lex.getKind() == lltok::MetadataVar) {
740 unsigned MDK;
741 MDNode *N;
742 if (parseMetadataAttachment(MDK, N))
743 return true;
744 MDs.push_back({MDK, N});
745 }
746
747 Function *F;
748 unsigned FunctionNumber = -1;
749 SmallVector<unsigned> UnnamedArgNums;
750 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
751 return true;
752 for (auto &MD : MDs)
753 F->addMetadata(MD.first, *MD.second);
754 return false;
755}
756
757/// toplevelentity
758/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
759bool LLParser::parseDefine() {
760 assert(Lex.getKind() == lltok::kw_define);
761
762 FileLoc FunctionStart = getTokLineColumnPos();
763 Lex.Lex();
764
765 Function *F;
766 unsigned FunctionNumber = -1;
767 SmallVector<unsigned> UnnamedArgNums;
768 bool RetValue =
769 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
770 parseOptionalFunctionMetadata(*F) ||
771 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
772 if (ParserContext)
773 ParserContext->addFunctionLocation(
774 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
775
776 return RetValue;
777}
778
779/// parseGlobalType
780/// ::= 'constant'
781/// ::= 'global'
782bool LLParser::parseGlobalType(bool &IsConstant) {
783 if (Lex.getKind() == lltok::kw_constant)
784 IsConstant = true;
785 else if (Lex.getKind() == lltok::kw_global)
786 IsConstant = false;
787 else {
788 IsConstant = false;
789 return tokError("expected 'global' or 'constant'");
790 }
791 Lex.Lex();
792 return false;
793}
794
795bool LLParser::parseOptionalUnnamedAddr(
796 GlobalVariable::UnnamedAddr &UnnamedAddr) {
797 if (EatIfPresent(lltok::kw_unnamed_addr))
799 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
801 else
802 UnnamedAddr = GlobalValue::UnnamedAddr::None;
803 return false;
804}
805
806/// parseUnnamedGlobal:
807/// OptionalVisibility (ALIAS | IFUNC) ...
808/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
809/// OptionalDLLStorageClass
810/// ... -> global variable
811/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
812/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
813/// OptionalVisibility
814/// OptionalDLLStorageClass
815/// ... -> global variable
816bool LLParser::parseUnnamedGlobal() {
817 unsigned VarID;
818 std::string Name;
819 LocTy NameLoc = Lex.getLoc();
820
821 // Handle the GlobalID form.
822 if (Lex.getKind() == lltok::GlobalID) {
823 VarID = Lex.getUIntVal();
824 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
825 return true;
826
827 Lex.Lex(); // eat GlobalID;
828 if (parseToken(lltok::equal, "expected '=' after name"))
829 return true;
830 } else {
831 VarID = NumberedVals.getNext();
832 }
833
834 bool HasLinkage;
835 unsigned Linkage, Visibility, DLLStorageClass;
836 bool DSOLocal;
838 GlobalVariable::UnnamedAddr UnnamedAddr;
839 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
840 DSOLocal) ||
841 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
842 return true;
843
844 switch (Lex.getKind()) {
845 default:
846 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
847 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
848 case lltok::kw_alias:
849 case lltok::kw_ifunc:
850 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
851 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
852 }
853}
854
855/// parseNamedGlobal:
856/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
857/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
858/// OptionalVisibility OptionalDLLStorageClass
859/// ... -> global variable
860bool LLParser::parseNamedGlobal() {
861 assert(Lex.getKind() == lltok::GlobalVar);
862 LocTy NameLoc = Lex.getLoc();
863 std::string Name = Lex.getStrVal();
864 Lex.Lex();
865
866 bool HasLinkage;
867 unsigned Linkage, Visibility, DLLStorageClass;
868 bool DSOLocal;
870 GlobalVariable::UnnamedAddr UnnamedAddr;
871 if (parseToken(lltok::equal, "expected '=' in global variable") ||
872 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
873 DSOLocal) ||
874 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
875 return true;
876
877 switch (Lex.getKind()) {
878 default:
879 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
880 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
881 case lltok::kw_alias:
882 case lltok::kw_ifunc:
883 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
884 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
885 }
886}
887
888bool LLParser::parseComdat() {
889 assert(Lex.getKind() == lltok::ComdatVar);
890 std::string Name = Lex.getStrVal();
891 LocTy NameLoc = Lex.getLoc();
892 Lex.Lex();
893
894 if (parseToken(lltok::equal, "expected '=' here"))
895 return true;
896
897 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
898 return tokError("expected comdat type");
899
901 switch (Lex.getKind()) {
902 default:
903 return tokError("unknown selection kind");
904 case lltok::kw_any:
905 SK = Comdat::Any;
906 break;
909 break;
911 SK = Comdat::Largest;
912 break;
915 break;
917 SK = Comdat::SameSize;
918 break;
919 }
920 Lex.Lex();
921
922 // See if the comdat was forward referenced, if so, use the comdat.
923 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
924 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
925 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
926 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
927
928 Comdat *C;
929 if (I != ComdatSymTab.end())
930 C = &I->second;
931 else
932 C = M->getOrInsertComdat(Name);
933 C->setSelectionKind(SK);
934
935 return false;
936}
937
938// MDString:
939// ::= '!' STRINGCONSTANT
940bool LLParser::parseMDString(MDString *&Result) {
941 std::string Str;
942 if (parseStringConstant(Str))
943 return true;
944 Result = MDString::get(Context, Str);
945 return false;
946}
947
948// MDNode:
949// ::= '!' MDNodeNumber
950bool LLParser::parseMDNodeID(MDNode *&Result) {
951 // !{ ..., !42, ... }
952 LocTy IDLoc = Lex.getLoc();
953 unsigned MID = 0;
954 if (parseUInt32(MID))
955 return true;
956
957 // If not a forward reference, just return it now.
958 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
959 if (!Inserted) {
960 Result = It->second;
961 return false;
962 }
963
964 // Otherwise, create MDNode forward reference.
965 auto &FwdRef = ForwardRefMDNodes[MID];
966 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
967
968 Result = FwdRef.first.get();
969 It->second.reset(Result);
970 return false;
971}
972
973/// parseNamedMetadata:
974/// !foo = !{ !1, !2 }
975bool LLParser::parseNamedMetadata() {
976 assert(Lex.getKind() == lltok::MetadataVar);
977 std::string Name = Lex.getStrVal();
978 Lex.Lex();
979
980 if (parseToken(lltok::equal, "expected '=' here") ||
981 parseToken(lltok::exclaim, "Expected '!' here") ||
982 parseToken(lltok::lbrace, "Expected '{' here"))
983 return true;
984
985 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
986 if (Lex.getKind() != lltok::rbrace)
987 do {
988 MDNode *N = nullptr;
989 // parse DIExpressions inline as a special case. They are still MDNodes,
990 // so they can still appear in named metadata. Remove this logic if they
991 // become plain Metadata.
992 if (Lex.getKind() == lltok::MetadataVar &&
993 Lex.getStrVal() == "DIExpression") {
994 if (parseDIExpression(N, /*IsDistinct=*/false))
995 return true;
996 // DIArgLists should only appear inline in a function, as they may
997 // contain LocalAsMetadata arguments which require a function context.
998 } else if (Lex.getKind() == lltok::MetadataVar &&
999 Lex.getStrVal() == "DIArgList") {
1000 return tokError("found DIArgList outside of function");
1001 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1002 parseMDNodeID(N)) {
1003 return true;
1004 }
1005 NMD->addOperand(N);
1006 } while (EatIfPresent(lltok::comma));
1007
1008 return parseToken(lltok::rbrace, "expected end of metadata node");
1009}
1010
1011/// parseStandaloneMetadata:
1012/// !42 = !{...}
1013bool LLParser::parseStandaloneMetadata() {
1014 assert(Lex.getKind() == lltok::exclaim);
1015 Lex.Lex();
1016 unsigned MetadataID = 0;
1017
1018 MDNode *Init;
1019 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1020 return true;
1021
1022 // Detect common error, from old metadata syntax.
1023 if (Lex.getKind() == lltok::Type)
1024 return tokError("unexpected type in metadata definition");
1025
1026 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1027 if (Lex.getKind() == lltok::MetadataVar) {
1028 if (parseSpecializedMDNode(Init, IsDistinct))
1029 return true;
1030 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1031 parseMDTuple(Init, IsDistinct))
1032 return true;
1033
1034 // See if this was forward referenced, if so, handle it.
1035 auto FI = ForwardRefMDNodes.find(MetadataID);
1036 if (FI != ForwardRefMDNodes.end()) {
1037 auto *ToReplace = FI->second.first.get();
1038 // DIAssignID has its own special forward-reference "replacement" for
1039 // attachments (the temporary attachments are never actually attached).
1040 if (isa<DIAssignID>(Init)) {
1041 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1042 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1043 "Inst unexpectedly already has DIAssignID attachment");
1044 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1045 }
1046 }
1047
1048 ToReplace->replaceAllUsesWith(Init);
1049 ForwardRefMDNodes.erase(FI);
1050
1051 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1052 } else {
1053 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1054 if (!Inserted)
1055 return tokError("Metadata id is already used");
1056 It->second.reset(Init);
1057 }
1058
1059 return false;
1060}
1061
1062// Skips a single module summary entry.
1063bool LLParser::skipModuleSummaryEntry() {
1064 // Each module summary entry consists of a tag for the entry
1065 // type, followed by a colon, then the fields which may be surrounded by
1066 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1067 // support is in place we will look for the tokens corresponding to the
1068 // expected tags.
1069 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1070 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
1071 Lex.getKind() != lltok::kw_blockcount)
1072 return tokError(
1073 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1074 "start of summary entry");
1075 if (Lex.getKind() == lltok::kw_flags)
1076 return parseSummaryIndexFlags();
1077 if (Lex.getKind() == lltok::kw_blockcount)
1078 return parseBlockCount();
1079 Lex.Lex();
1080 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1081 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1082 return true;
1083 // Now walk through the parenthesized entry, until the number of open
1084 // parentheses goes back down to 0 (the first '(' was parsed above).
1085 unsigned NumOpenParen = 1;
1086 do {
1087 switch (Lex.getKind()) {
1088 case lltok::lparen:
1089 NumOpenParen++;
1090 break;
1091 case lltok::rparen:
1092 NumOpenParen--;
1093 break;
1094 case lltok::Eof:
1095 return tokError("found end of file while parsing summary entry");
1096 default:
1097 // Skip everything in between parentheses.
1098 break;
1099 }
1100 Lex.Lex();
1101 } while (NumOpenParen > 0);
1102 return false;
1103}
1104
1105/// SummaryEntry
1106/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1107bool LLParser::parseSummaryEntry() {
1108 assert(Lex.getKind() == lltok::SummaryID);
1109 unsigned SummaryID = Lex.getUIntVal();
1110
1111 // For summary entries, colons should be treated as distinct tokens,
1112 // not an indication of the end of a label token.
1113 Lex.setIgnoreColonInIdentifiers(true);
1114
1115 Lex.Lex();
1116 if (parseToken(lltok::equal, "expected '=' here"))
1117 return true;
1118
1119 // If we don't have an index object, skip the summary entry.
1120 if (!Index)
1121 return skipModuleSummaryEntry();
1122
1123 bool result = false;
1124 switch (Lex.getKind()) {
1125 case lltok::kw_gv:
1126 result = parseGVEntry(SummaryID);
1127 break;
1128 case lltok::kw_module:
1129 result = parseModuleEntry(SummaryID);
1130 break;
1131 case lltok::kw_typeid:
1132 result = parseTypeIdEntry(SummaryID);
1133 break;
1135 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1136 break;
1137 case lltok::kw_flags:
1138 result = parseSummaryIndexFlags();
1139 break;
1141 result = parseBlockCount();
1142 break;
1143 default:
1144 result = error(Lex.getLoc(), "unexpected summary kind");
1145 break;
1146 }
1147 Lex.setIgnoreColonInIdentifiers(false);
1148 return result;
1149}
1150
1159
1160// If there was an explicit dso_local, update GV. In the absence of an explicit
1161// dso_local we keep the default value.
1162static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1163 if (DSOLocal)
1164 GV.setDSOLocal(true);
1165}
1166
1167/// parseAliasOrIFunc:
1168/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1169/// OptionalVisibility OptionalDLLStorageClass
1170/// OptionalThreadLocal OptionalUnnamedAddr
1171/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1172///
1173/// AliaseeOrResolver
1174/// ::= TypeAndValue
1175///
1176/// SymbolAttrs
1177/// ::= ',' 'partition' StringConstant
1178///
1179/// Everything through OptionalUnnamedAddr has already been parsed.
1180///
1181bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1182 LocTy NameLoc, unsigned L, unsigned Visibility,
1183 unsigned DLLStorageClass, bool DSOLocal,
1185 GlobalVariable::UnnamedAddr UnnamedAddr) {
1186 bool IsAlias;
1187 if (Lex.getKind() == lltok::kw_alias)
1188 IsAlias = true;
1189 else if (Lex.getKind() == lltok::kw_ifunc)
1190 IsAlias = false;
1191 else
1192 llvm_unreachable("Not an alias or ifunc!");
1193 Lex.Lex();
1194
1196
1197 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1198 return error(NameLoc, "invalid linkage type for alias");
1199
1200 if (!isValidVisibilityForLinkage(Visibility, L))
1201 return error(NameLoc,
1202 "symbol with local linkage must have default visibility");
1203
1204 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1205 return error(NameLoc,
1206 "symbol with local linkage cannot have a DLL storage class");
1207
1208 Type *Ty;
1209 LocTy ExplicitTypeLoc = Lex.getLoc();
1210 if (parseType(Ty) ||
1211 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1212 return true;
1213
1214 Constant *Aliasee;
1215 LocTy AliaseeLoc = Lex.getLoc();
1216 if (Lex.getKind() != lltok::kw_bitcast &&
1217 Lex.getKind() != lltok::kw_getelementptr &&
1218 Lex.getKind() != lltok::kw_addrspacecast &&
1219 Lex.getKind() != lltok::kw_inttoptr) {
1220 if (parseGlobalTypeAndValue(Aliasee))
1221 return true;
1222 } else {
1223 // The bitcast dest type is not present, it is implied by the dest type.
1224 ValID ID;
1225 if (parseValID(ID, /*PFS=*/nullptr))
1226 return true;
1227 if (ID.Kind != ValID::t_Constant)
1228 return error(AliaseeLoc, "invalid aliasee");
1229 Aliasee = ID.ConstantVal;
1230 }
1231
1232 Type *AliaseeType = Aliasee->getType();
1233 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1234 if (!PTy)
1235 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1236 unsigned AddrSpace = PTy->getAddressSpace();
1237
1238 GlobalValue *GVal = nullptr;
1239
1240 // See if the alias was forward referenced, if so, prepare to replace the
1241 // forward reference.
1242 if (!Name.empty()) {
1243 auto I = ForwardRefVals.find(Name);
1244 if (I != ForwardRefVals.end()) {
1245 GVal = I->second.first;
1246 ForwardRefVals.erase(Name);
1247 } else if (M->getNamedValue(Name)) {
1248 return error(NameLoc, "redefinition of global '@" + Name + "'");
1249 }
1250 } else {
1251 auto I = ForwardRefValIDs.find(NameID);
1252 if (I != ForwardRefValIDs.end()) {
1253 GVal = I->second.first;
1254 ForwardRefValIDs.erase(I);
1255 }
1256 }
1257
1258 // Okay, create the alias/ifunc but do not insert it into the module yet.
1259 std::unique_ptr<GlobalAlias> GA;
1260 std::unique_ptr<GlobalIFunc> GI;
1261 GlobalValue *GV;
1262 if (IsAlias) {
1263 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1264 /*Parent=*/nullptr));
1265 GV = GA.get();
1266 } else {
1267 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1268 /*Parent=*/nullptr));
1269 GV = GI.get();
1270 }
1271 GV->setThreadLocalMode(TLM);
1274 GV->setUnnamedAddr(UnnamedAddr);
1275 maybeSetDSOLocal(DSOLocal, *GV);
1276
1277 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1278 // Now parse them if there are any.
1279 while (Lex.getKind() == lltok::comma) {
1280 Lex.Lex();
1281
1282 if (Lex.getKind() == lltok::kw_partition) {
1283 Lex.Lex();
1284 GV->setPartition(Lex.getStrVal());
1285 if (parseToken(lltok::StringConstant, "expected partition string"))
1286 return true;
1287 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1288 if (parseGlobalObjectMetadataAttachment(*GI))
1289 return true;
1290 } else {
1291 return tokError("unknown alias or ifunc property!");
1292 }
1293 }
1294
1295 if (Name.empty())
1296 NumberedVals.add(NameID, GV);
1297
1298 if (GVal) {
1299 // Verify that types agree.
1300 if (GVal->getType() != GV->getType())
1301 return error(
1302 ExplicitTypeLoc,
1303 "forward reference and definition of alias have different types");
1304
1305 // If they agree, just RAUW the old value with the alias and remove the
1306 // forward ref info.
1307 GVal->replaceAllUsesWith(GV);
1308 GVal->eraseFromParent();
1309 }
1310
1311 // Insert into the module, we know its name won't collide now.
1312 if (IsAlias)
1313 M->insertAlias(GA.release());
1314 else
1315 M->insertIFunc(GI.release());
1316 assert(GV->getName() == Name && "Should not be a name conflict!");
1317
1318 return false;
1319}
1320
1321static bool isSanitizer(lltok::Kind Kind) {
1322 switch (Kind) {
1325 case lltok::kw_sanitize_memtag:
1327 return true;
1328 default:
1329 return false;
1330 }
1331}
1332
1333bool LLParser::parseSanitizer(GlobalVariable *GV) {
1334 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1336 if (GV->hasSanitizerMetadata())
1337 Meta = GV->getSanitizerMetadata();
1338
1339 switch (Lex.getKind()) {
1341 Meta.NoAddress = true;
1342 break;
1344 Meta.NoHWAddress = true;
1345 break;
1346 case lltok::kw_sanitize_memtag:
1347 Meta.Memtag = true;
1348 break;
1350 Meta.IsDynInit = true;
1351 break;
1352 default:
1353 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1354 }
1355 GV->setSanitizerMetadata(Meta);
1356 Lex.Lex();
1357 return false;
1358}
1359
1360/// parseGlobal
1361/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1362/// OptionalVisibility OptionalDLLStorageClass
1363/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1364/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1365/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1366/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1367/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1368/// Const OptionalAttrs
1369///
1370/// Everything up to and including OptionalUnnamedAddr has been parsed
1371/// already.
1372///
1373bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1374 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1375 unsigned Visibility, unsigned DLLStorageClass,
1376 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1377 GlobalVariable::UnnamedAddr UnnamedAddr) {
1378 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1379 return error(NameLoc,
1380 "symbol with local linkage must have default visibility");
1381
1382 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1383 return error(NameLoc,
1384 "symbol with local linkage cannot have a DLL storage class");
1385
1386 unsigned AddrSpace;
1387 bool IsConstant, IsExternallyInitialized;
1388 LocTy IsExternallyInitializedLoc;
1389 LocTy TyLoc;
1390
1391 Type *Ty = nullptr;
1392 if (parseOptionalAddrSpace(AddrSpace) ||
1393 parseOptionalToken(lltok::kw_externally_initialized,
1394 IsExternallyInitialized,
1395 &IsExternallyInitializedLoc) ||
1396 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1397 return true;
1398
1399 // If the linkage is specified and is external, then no initializer is
1400 // present.
1401 Constant *Init = nullptr;
1402 if (!HasLinkage ||
1405 if (parseGlobalValue(Ty, Init))
1406 return true;
1407 }
1408
1410 return error(TyLoc, "invalid type for global variable");
1411
1412 GlobalValue *GVal = nullptr;
1413
1414 // See if the global was forward referenced, if so, use the global.
1415 if (!Name.empty()) {
1416 auto I = ForwardRefVals.find(Name);
1417 if (I != ForwardRefVals.end()) {
1418 GVal = I->second.first;
1419 ForwardRefVals.erase(I);
1420 } else if (M->getNamedValue(Name)) {
1421 return error(NameLoc, "redefinition of global '@" + Name + "'");
1422 }
1423 } else {
1424 // Handle @"", where a name is syntactically specified, but semantically
1425 // missing.
1426 if (NameID == (unsigned)-1)
1427 NameID = NumberedVals.getNext();
1428
1429 auto I = ForwardRefValIDs.find(NameID);
1430 if (I != ForwardRefValIDs.end()) {
1431 GVal = I->second.first;
1432 ForwardRefValIDs.erase(I);
1433 }
1434 }
1435
1436 GlobalVariable *GV = new GlobalVariable(
1437 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1439
1440 if (Name.empty())
1441 NumberedVals.add(NameID, GV);
1442
1443 // Set the parsed properties on the global.
1444 if (Init)
1445 GV->setInitializer(Init);
1446 GV->setConstant(IsConstant);
1448 maybeSetDSOLocal(DSOLocal, *GV);
1451 GV->setExternallyInitialized(IsExternallyInitialized);
1452 GV->setThreadLocalMode(TLM);
1453 GV->setUnnamedAddr(UnnamedAddr);
1454
1455 if (GVal) {
1456 if (GVal->getAddressSpace() != AddrSpace)
1457 return error(
1458 TyLoc,
1459 "forward reference and definition of global have different types");
1460
1461 GVal->replaceAllUsesWith(GV);
1462 GVal->eraseFromParent();
1463 }
1464
1465 // parse attributes on the global.
1466 while (Lex.getKind() == lltok::comma) {
1467 Lex.Lex();
1468
1469 if (Lex.getKind() == lltok::kw_section) {
1470 Lex.Lex();
1471 GV->setSection(Lex.getStrVal());
1472 if (parseToken(lltok::StringConstant, "expected global section string"))
1473 return true;
1474 } else if (Lex.getKind() == lltok::kw_partition) {
1475 Lex.Lex();
1476 GV->setPartition(Lex.getStrVal());
1477 if (parseToken(lltok::StringConstant, "expected partition string"))
1478 return true;
1479 } else if (Lex.getKind() == lltok::kw_align) {
1480 MaybeAlign Alignment;
1481 if (parseOptionalAlignment(Alignment))
1482 return true;
1483 if (Alignment)
1484 GV->setAlignment(*Alignment);
1485 } else if (Lex.getKind() == lltok::kw_code_model) {
1487 if (parseOptionalCodeModel(CodeModel))
1488 return true;
1489 GV->setCodeModel(CodeModel);
1490 } else if (Lex.getKind() == lltok::MetadataVar) {
1491 if (parseGlobalObjectMetadataAttachment(*GV))
1492 return true;
1493 } else if (isSanitizer(Lex.getKind())) {
1494 if (parseSanitizer(GV))
1495 return true;
1496 } else {
1497 Comdat *C;
1498 if (parseOptionalComdat(Name, C))
1499 return true;
1500 if (C)
1501 GV->setComdat(C);
1502 else
1503 return tokError("unknown global variable property!");
1504 }
1505 }
1506
1507 AttrBuilder Attrs(M->getContext());
1508 LocTy BuiltinLoc;
1509 std::vector<unsigned> FwdRefAttrGrps;
1510 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1511 return true;
1512 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1513 GV->setAttributes(AttributeSet::get(Context, Attrs));
1514 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1515 }
1516
1517 return false;
1518}
1519
1520/// parseUnnamedAttrGrp
1521/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1522bool LLParser::parseUnnamedAttrGrp() {
1523 assert(Lex.getKind() == lltok::kw_attributes);
1524 LocTy AttrGrpLoc = Lex.getLoc();
1525 Lex.Lex();
1526
1527 if (Lex.getKind() != lltok::AttrGrpID)
1528 return tokError("expected attribute group id");
1529
1530 unsigned VarID = Lex.getUIntVal();
1531 std::vector<unsigned> unused;
1532 LocTy BuiltinLoc;
1533 Lex.Lex();
1534
1535 if (parseToken(lltok::equal, "expected '=' here") ||
1536 parseToken(lltok::lbrace, "expected '{' here"))
1537 return true;
1538
1539 auto R = NumberedAttrBuilders.find(VarID);
1540 if (R == NumberedAttrBuilders.end())
1541 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1542
1543 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1544 parseToken(lltok::rbrace, "expected end of attribute group"))
1545 return true;
1546
1547 if (!R->second.hasAttributes())
1548 return error(AttrGrpLoc, "attribute group has no attributes");
1549
1550 return false;
1551}
1552
1554 switch (Kind) {
1555#define GET_ATTR_NAMES
1556#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1557 case lltok::kw_##DISPLAY_NAME: \
1558 return Attribute::ENUM_NAME;
1559#include "llvm/IR/Attributes.inc"
1560 default:
1561 return Attribute::None;
1562 }
1563}
1564
1565bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1566 bool InAttrGroup) {
1567 if (Attribute::isTypeAttrKind(Attr))
1568 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1569
1570 switch (Attr) {
1571 case Attribute::Alignment: {
1572 MaybeAlign Alignment;
1573 if (InAttrGroup) {
1574 uint32_t Value = 0;
1575 Lex.Lex();
1576 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1577 return true;
1578 Alignment = Align(Value);
1579 } else {
1580 if (parseOptionalAlignment(Alignment, true))
1581 return true;
1582 }
1583 B.addAlignmentAttr(Alignment);
1584 return false;
1585 }
1586 case Attribute::StackAlignment: {
1587 unsigned Alignment;
1588 if (InAttrGroup) {
1589 Lex.Lex();
1590 if (parseToken(lltok::equal, "expected '=' here") ||
1591 parseUInt32(Alignment))
1592 return true;
1593 } else {
1594 if (parseOptionalStackAlignment(Alignment))
1595 return true;
1596 }
1597 B.addStackAlignmentAttr(Alignment);
1598 return false;
1599 }
1600 case Attribute::AllocSize: {
1601 unsigned ElemSizeArg;
1602 std::optional<unsigned> NumElemsArg;
1603 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1604 return true;
1605 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1606 return false;
1607 }
1608 case Attribute::VScaleRange: {
1609 unsigned MinValue, MaxValue;
1610 if (parseVScaleRangeArguments(MinValue, MaxValue))
1611 return true;
1612 B.addVScaleRangeAttr(MinValue,
1613 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1614 return false;
1615 }
1616 case Attribute::Dereferenceable: {
1617 std::optional<uint64_t> Bytes;
1618 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1619 return true;
1620 assert(Bytes.has_value());
1621 B.addDereferenceableAttr(Bytes.value());
1622 return false;
1623 }
1624 case Attribute::DeadOnReturn: {
1625 std::optional<uint64_t> Bytes;
1626 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1627 /*ErrorNoBytes=*/false))
1628 return true;
1629 if (Bytes.has_value()) {
1630 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1631 } else {
1632 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1633 }
1634 return false;
1635 }
1636 case Attribute::DereferenceableOrNull: {
1637 std::optional<uint64_t> Bytes;
1638 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1639 return true;
1640 assert(Bytes.has_value());
1641 B.addDereferenceableOrNullAttr(Bytes.value());
1642 return false;
1643 }
1644 case Attribute::UWTable: {
1646 if (parseOptionalUWTableKind(Kind))
1647 return true;
1648 B.addUWTableAttr(Kind);
1649 return false;
1650 }
1651 case Attribute::AllocKind: {
1653 if (parseAllocKind(Kind))
1654 return true;
1655 B.addAllocKindAttr(Kind);
1656 return false;
1657 }
1658 case Attribute::Memory: {
1659 std::optional<MemoryEffects> ME = parseMemoryAttr();
1660 if (!ME)
1661 return true;
1662 B.addMemoryAttr(*ME);
1663 return false;
1664 }
1665 case Attribute::DenormalFPEnv: {
1666 std::optional<DenormalFPEnv> Mode = parseDenormalFPEnvAttr();
1667 if (!Mode)
1668 return true;
1669
1670 B.addDenormalFPEnvAttr(*Mode);
1671 return false;
1672 }
1673 case Attribute::NoFPClass: {
1674 if (FPClassTest NoFPClass =
1675 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1676 B.addNoFPClassAttr(NoFPClass);
1677 return false;
1678 }
1679
1680 return true;
1681 }
1682 case Attribute::Range:
1683 return parseRangeAttr(B);
1684 case Attribute::Initializes:
1685 return parseInitializesAttr(B);
1686 case Attribute::Captures:
1687 return parseCapturesAttr(B);
1688 default:
1689 B.addAttribute(Attr);
1690 Lex.Lex();
1691 return false;
1692 }
1693}
1694
1696 switch (Kind) {
1697 case lltok::kw_readnone:
1698 ME &= MemoryEffects::none();
1699 return true;
1700 case lltok::kw_readonly:
1702 return true;
1703 case lltok::kw_writeonly:
1705 return true;
1708 return true;
1711 return true;
1714 return true;
1715 default:
1716 return false;
1717 }
1718}
1719
1720/// parseFnAttributeValuePairs
1721/// ::= <attr> | <attr> '=' <value>
1722bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1723 std::vector<unsigned> &FwdRefAttrGrps,
1724 bool InAttrGrp, LocTy &BuiltinLoc) {
1725 bool HaveError = false;
1726
1727 B.clear();
1728
1730 while (true) {
1731 lltok::Kind Token = Lex.getKind();
1732 if (Token == lltok::rbrace)
1733 break; // Finished.
1734
1735 if (Token == lltok::StringConstant) {
1736 if (parseStringAttribute(B))
1737 return true;
1738 continue;
1739 }
1740
1741 if (Token == lltok::AttrGrpID) {
1742 // Allow a function to reference an attribute group:
1743 //
1744 // define void @foo() #1 { ... }
1745 if (InAttrGrp) {
1746 HaveError |= error(
1747 Lex.getLoc(),
1748 "cannot have an attribute group reference in an attribute group");
1749 } else {
1750 // Save the reference to the attribute group. We'll fill it in later.
1751 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1752 }
1753 Lex.Lex();
1754 continue;
1755 }
1756
1757 SMLoc Loc = Lex.getLoc();
1758 if (Token == lltok::kw_builtin)
1759 BuiltinLoc = Loc;
1760
1761 if (upgradeMemoryAttr(ME, Token)) {
1762 Lex.Lex();
1763 continue;
1764 }
1765
1767 if (Attr == Attribute::None) {
1768 if (!InAttrGrp)
1769 break;
1770 return error(Lex.getLoc(), "unterminated attribute group");
1771 }
1772
1773 if (parseEnumAttribute(Attr, B, InAttrGrp))
1774 return true;
1775
1776 // As a hack, we allow function alignment to be initially parsed as an
1777 // attribute on a function declaration/definition or added to an attribute
1778 // group and later moved to the alignment field.
1779 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1780 HaveError |= error(Loc, "this attribute does not apply to functions");
1781 }
1782
1783 if (ME != MemoryEffects::unknown())
1784 B.addMemoryAttr(ME);
1785 return HaveError;
1786}
1787
1788//===----------------------------------------------------------------------===//
1789// GlobalValue Reference/Resolution Routines.
1790//===----------------------------------------------------------------------===//
1791
1793 // The used global type does not matter. We will later RAUW it with a
1794 // global/function of the correct type.
1795 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1798 PTy->getAddressSpace());
1799}
1800
1801Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1802 Value *Val) {
1803 Type *ValTy = Val->getType();
1804 if (ValTy == Ty)
1805 return Val;
1806 if (Ty->isLabelTy())
1807 error(Loc, "'" + Name + "' is not a basic block");
1808 else
1809 error(Loc, "'" + Name + "' defined with type '" +
1810 getTypeString(Val->getType()) + "' but expected '" +
1811 getTypeString(Ty) + "'");
1812 return nullptr;
1813}
1814
1815/// getGlobalVal - Get a value with the specified name or ID, creating a
1816/// forward reference record if needed. This can return null if the value
1817/// exists but does not have the right type.
1818GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1819 LocTy Loc) {
1821 if (!PTy) {
1822 error(Loc, "global variable reference must have pointer type");
1823 return nullptr;
1824 }
1825
1826 // Look this name up in the normal function symbol table.
1827 GlobalValue *Val =
1828 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1829
1830 // If this is a forward reference for the value, see if we already created a
1831 // forward ref record.
1832 if (!Val) {
1833 auto I = ForwardRefVals.find(Name);
1834 if (I != ForwardRefVals.end())
1835 Val = I->second.first;
1836 }
1837
1838 // If we have the value in the symbol table or fwd-ref table, return it.
1839 if (Val)
1841 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1842
1843 // Otherwise, create a new forward reference for this value and remember it.
1844 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1845 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1846 return FwdVal;
1847}
1848
1849GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1851 if (!PTy) {
1852 error(Loc, "global variable reference must have pointer type");
1853 return nullptr;
1854 }
1855
1856 GlobalValue *Val = NumberedVals.get(ID);
1857
1858 // If this is a forward reference for the value, see if we already created a
1859 // forward ref record.
1860 if (!Val) {
1861 auto I = ForwardRefValIDs.find(ID);
1862 if (I != ForwardRefValIDs.end())
1863 Val = I->second.first;
1864 }
1865
1866 // If we have the value in the symbol table or fwd-ref table, return it.
1867 if (Val)
1869 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1870
1871 // Otherwise, create a new forward reference for this value and remember it.
1872 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1873 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1874 return FwdVal;
1875}
1876
1877//===----------------------------------------------------------------------===//
1878// Comdat Reference/Resolution Routines.
1879//===----------------------------------------------------------------------===//
1880
1881Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1882 // Look this name up in the comdat symbol table.
1883 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1884 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1885 if (I != ComdatSymTab.end())
1886 return &I->second;
1887
1888 // Otherwise, create a new forward reference for this value and remember it.
1889 Comdat *C = M->getOrInsertComdat(Name);
1890 ForwardRefComdats[Name] = Loc;
1891 return C;
1892}
1893
1894//===----------------------------------------------------------------------===//
1895// Helper Routines.
1896//===----------------------------------------------------------------------===//
1897
1898/// parseToken - If the current token has the specified kind, eat it and return
1899/// success. Otherwise, emit the specified error and return failure.
1900bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1901 if (Lex.getKind() != T)
1902 return tokError(ErrMsg);
1903 Lex.Lex();
1904 return false;
1905}
1906
1907/// parseStringConstant
1908/// ::= StringConstant
1909bool LLParser::parseStringConstant(std::string &Result) {
1910 if (Lex.getKind() != lltok::StringConstant)
1911 return tokError("expected string constant");
1912 Result = Lex.getStrVal();
1913 Lex.Lex();
1914 return false;
1915}
1916
1917/// parseUInt32
1918/// ::= uint32
1919bool LLParser::parseUInt32(uint32_t &Val) {
1920 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1921 return tokError("expected integer");
1922 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1923 if (Val64 != unsigned(Val64))
1924 return tokError("expected 32-bit integer (too large)");
1925 Val = Val64;
1926 Lex.Lex();
1927 return false;
1928}
1929
1930/// parseUInt64
1931/// ::= uint64
1932bool LLParser::parseUInt64(uint64_t &Val) {
1933 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1934 return tokError("expected integer");
1935 Val = Lex.getAPSIntVal().getLimitedValue();
1936 Lex.Lex();
1937 return false;
1938}
1939
1940/// parseTLSModel
1941/// := 'localdynamic'
1942/// := 'initialexec'
1943/// := 'localexec'
1944bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1945 switch (Lex.getKind()) {
1946 default:
1947 return tokError("expected localdynamic, initialexec or localexec");
1950 break;
1953 break;
1956 break;
1957 }
1958
1959 Lex.Lex();
1960 return false;
1961}
1962
1963/// parseOptionalThreadLocal
1964/// := /*empty*/
1965/// := 'thread_local'
1966/// := 'thread_local' '(' tlsmodel ')'
1967bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1969 if (!EatIfPresent(lltok::kw_thread_local))
1970 return false;
1971
1973 if (Lex.getKind() == lltok::lparen) {
1974 Lex.Lex();
1975 return parseTLSModel(TLM) ||
1976 parseToken(lltok::rparen, "expected ')' after thread local model");
1977 }
1978 return false;
1979}
1980
1981/// parseOptionalAddrSpace
1982/// := /*empty*/
1983/// := 'addrspace' '(' uint32 ')'
1984bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1985 AddrSpace = DefaultAS;
1986 if (!EatIfPresent(lltok::kw_addrspace))
1987 return false;
1988
1989 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1990 if (Lex.getKind() == lltok::StringConstant) {
1991 const std::string &AddrSpaceStr = Lex.getStrVal();
1992 if (AddrSpaceStr == "A") {
1993 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1994 } else if (AddrSpaceStr == "G") {
1995 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1996 } else if (AddrSpaceStr == "P") {
1997 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1998 } else if (std::optional<unsigned> AS =
1999 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2000 AddrSpace = *AS;
2001 } else {
2002 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
2003 }
2004 Lex.Lex();
2005 return false;
2006 }
2007 if (Lex.getKind() != lltok::APSInt)
2008 return tokError("expected integer or string constant");
2009 SMLoc Loc = Lex.getLoc();
2010 if (parseUInt32(AddrSpace))
2011 return true;
2012 if (!isUInt<24>(AddrSpace))
2013 return error(Loc, "invalid address space, must be a 24-bit integer");
2014 return false;
2015 };
2016
2017 return parseToken(lltok::lparen, "expected '(' in address space") ||
2018 ParseAddrspaceValue(AddrSpace) ||
2019 parseToken(lltok::rparen, "expected ')' in address space");
2020}
2021
2022/// parseStringAttribute
2023/// := StringConstant
2024/// := StringConstant '=' StringConstant
2025bool LLParser::parseStringAttribute(AttrBuilder &B) {
2026 std::string Attr = Lex.getStrVal();
2027 Lex.Lex();
2028 std::string Val;
2029 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
2030 return true;
2031 B.addAttribute(Attr, Val);
2032 return false;
2033}
2034
2035/// Parse a potentially empty list of parameter or return attributes.
2036bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2037 bool HaveError = false;
2038
2039 B.clear();
2040
2041 while (true) {
2042 lltok::Kind Token = Lex.getKind();
2043 if (Token == lltok::StringConstant) {
2044 if (parseStringAttribute(B))
2045 return true;
2046 continue;
2047 }
2048
2049 if (Token == lltok::kw_nocapture) {
2050 Lex.Lex();
2051 B.addCapturesAttr(CaptureInfo::none());
2052 continue;
2053 }
2054
2055 SMLoc Loc = Lex.getLoc();
2057 if (Attr == Attribute::None)
2058 return HaveError;
2059
2060 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2061 return true;
2062
2063 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2064 HaveError |= error(Loc, "this attribute does not apply to parameters");
2065 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2066 HaveError |= error(Loc, "this attribute does not apply to return values");
2067 }
2068}
2069
2070static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2071 HasLinkage = true;
2072 switch (Kind) {
2073 default:
2074 HasLinkage = false;
2076 case lltok::kw_private:
2078 case lltok::kw_internal:
2080 case lltok::kw_weak:
2082 case lltok::kw_weak_odr:
2084 case lltok::kw_linkonce:
2092 case lltok::kw_common:
2096 case lltok::kw_external:
2098 }
2099}
2100
2101/// parseOptionalLinkage
2102/// ::= /*empty*/
2103/// ::= 'private'
2104/// ::= 'internal'
2105/// ::= 'weak'
2106/// ::= 'weak_odr'
2107/// ::= 'linkonce'
2108/// ::= 'linkonce_odr'
2109/// ::= 'available_externally'
2110/// ::= 'appending'
2111/// ::= 'common'
2112/// ::= 'extern_weak'
2113/// ::= 'external'
2114bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2115 unsigned &Visibility,
2116 unsigned &DLLStorageClass, bool &DSOLocal) {
2117 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2118 if (HasLinkage)
2119 Lex.Lex();
2120 parseOptionalDSOLocal(DSOLocal);
2121 parseOptionalVisibility(Visibility);
2122 parseOptionalDLLStorageClass(DLLStorageClass);
2123
2124 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2125 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2126 }
2127
2128 return false;
2129}
2130
2131void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2132 switch (Lex.getKind()) {
2133 default:
2134 DSOLocal = false;
2135 break;
2137 DSOLocal = true;
2138 Lex.Lex();
2139 break;
2141 DSOLocal = false;
2142 Lex.Lex();
2143 break;
2144 }
2145}
2146
2147/// parseOptionalVisibility
2148/// ::= /*empty*/
2149/// ::= 'default'
2150/// ::= 'hidden'
2151/// ::= 'protected'
2152///
2153void LLParser::parseOptionalVisibility(unsigned &Res) {
2154 switch (Lex.getKind()) {
2155 default:
2157 return;
2158 case lltok::kw_default:
2160 break;
2161 case lltok::kw_hidden:
2163 break;
2166 break;
2167 }
2168 Lex.Lex();
2169}
2170
2171bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2173 switch (Kind) {
2174 default:
2175 return tokError("unknown import kind. Expect definition or declaration.");
2178 return false;
2181 return false;
2182 }
2183}
2184
2185/// parseOptionalDLLStorageClass
2186/// ::= /*empty*/
2187/// ::= 'dllimport'
2188/// ::= 'dllexport'
2189///
2190void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2191 switch (Lex.getKind()) {
2192 default:
2194 return;
2197 break;
2200 break;
2201 }
2202 Lex.Lex();
2203}
2204
2205/// parseOptionalCallingConv
2206/// ::= /*empty*/
2207/// ::= 'ccc'
2208/// ::= 'fastcc'
2209/// ::= 'intel_ocl_bicc'
2210/// ::= 'coldcc'
2211/// ::= 'cfguard_checkcc'
2212/// ::= 'x86_stdcallcc'
2213/// ::= 'x86_fastcallcc'
2214/// ::= 'x86_thiscallcc'
2215/// ::= 'x86_vectorcallcc'
2216/// ::= 'arm_apcscc'
2217/// ::= 'arm_aapcscc'
2218/// ::= 'arm_aapcs_vfpcc'
2219/// ::= 'aarch64_vector_pcs'
2220/// ::= 'aarch64_sve_vector_pcs'
2221/// ::= 'aarch64_sme_preservemost_from_x0'
2222/// ::= 'aarch64_sme_preservemost_from_x1'
2223/// ::= 'aarch64_sme_preservemost_from_x2'
2224/// ::= 'msp430_intrcc'
2225/// ::= 'avr_intrcc'
2226/// ::= 'avr_signalcc'
2227/// ::= 'ptx_kernel'
2228/// ::= 'ptx_device'
2229/// ::= 'spir_func'
2230/// ::= 'spir_kernel'
2231/// ::= 'x86_64_sysvcc'
2232/// ::= 'win64cc'
2233/// ::= 'anyregcc'
2234/// ::= 'preserve_mostcc'
2235/// ::= 'preserve_allcc'
2236/// ::= 'preserve_nonecc'
2237/// ::= 'ghccc'
2238/// ::= 'swiftcc'
2239/// ::= 'swifttailcc'
2240/// ::= 'x86_intrcc'
2241/// ::= 'hhvmcc'
2242/// ::= 'hhvm_ccc'
2243/// ::= 'cxx_fast_tlscc'
2244/// ::= 'amdgpu_vs'
2245/// ::= 'amdgpu_ls'
2246/// ::= 'amdgpu_hs'
2247/// ::= 'amdgpu_es'
2248/// ::= 'amdgpu_gs'
2249/// ::= 'amdgpu_ps'
2250/// ::= 'amdgpu_cs'
2251/// ::= 'amdgpu_cs_chain'
2252/// ::= 'amdgpu_cs_chain_preserve'
2253/// ::= 'amdgpu_kernel'
2254/// ::= 'tailcc'
2255/// ::= 'm68k_rtdcc'
2256/// ::= 'graalcc'
2257/// ::= 'riscv_vector_cc'
2258/// ::= 'riscv_vls_cc'
2259/// ::= 'cc' UINT
2260///
2261bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2262 switch (Lex.getKind()) {
2263 default: CC = CallingConv::C; return false;
2264 case lltok::kw_ccc: CC = CallingConv::C; break;
2265 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2266 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2279 break;
2282 break;
2285 break;
2288 break;
2298 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2299 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2303 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2304 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2307 case lltok::kw_hhvmcc:
2309 break;
2310 case lltok::kw_hhvm_ccc:
2312 break;
2324 break;
2327 break;
2331 break;
2332 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2334 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2337 break;
2339 // Default ABI_VLEN
2341 Lex.Lex();
2342 if (!EatIfPresent(lltok::lparen))
2343 break;
2344 uint32_t ABIVlen;
2345 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2346 return true;
2347 switch (ABIVlen) {
2348 default:
2349 return tokError("unknown RISC-V ABI VLEN");
2350#define CC_VLS_CASE(ABIVlen) \
2351 case ABIVlen: \
2352 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2353 break;
2354 CC_VLS_CASE(32)
2355 CC_VLS_CASE(64)
2356 CC_VLS_CASE(128)
2357 CC_VLS_CASE(256)
2358 CC_VLS_CASE(512)
2359 CC_VLS_CASE(1024)
2360 CC_VLS_CASE(2048)
2361 CC_VLS_CASE(4096)
2362 CC_VLS_CASE(8192)
2363 CC_VLS_CASE(16384)
2364 CC_VLS_CASE(32768)
2365 CC_VLS_CASE(65536)
2366#undef CC_VLS_CASE
2367 }
2368 return false;
2371 break;
2374 break;
2377 break;
2378 case lltok::kw_cc: {
2379 Lex.Lex();
2380 return parseUInt32(CC);
2381 }
2382 }
2383
2384 Lex.Lex();
2385 return false;
2386}
2387
2388/// parseMetadataAttachment
2389/// ::= !dbg !42
2390bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2391 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2392
2393 std::string Name = Lex.getStrVal();
2394 Kind = M->getMDKindID(Name);
2395 Lex.Lex();
2396
2397 return parseMDNode(MD);
2398}
2399
2400/// parseInstructionMetadata
2401/// ::= !dbg !42 (',' !dbg !57)*
2402bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2403 do {
2404 if (Lex.getKind() != lltok::MetadataVar)
2405 return tokError("expected metadata after comma");
2406
2407 unsigned MDK;
2408 MDNode *N;
2409 if (parseMetadataAttachment(MDK, N))
2410 return true;
2411
2412 if (MDK == LLVMContext::MD_DIAssignID)
2413 TempDIAssignIDAttachments[N].push_back(&Inst);
2414 else
2415 Inst.setMetadata(MDK, N);
2416
2417 if (MDK == LLVMContext::MD_tbaa)
2418 InstsWithTBAATag.push_back(&Inst);
2419
2420 // If this is the end of the list, we're done.
2421 } while (EatIfPresent(lltok::comma));
2422 return false;
2423}
2424
2425/// parseGlobalObjectMetadataAttachment
2426/// ::= !dbg !57
2427bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2428 unsigned MDK;
2429 MDNode *N;
2430 if (parseMetadataAttachment(MDK, N))
2431 return true;
2432
2433 GO.addMetadata(MDK, *N);
2434 return false;
2435}
2436
2437/// parseOptionalFunctionMetadata
2438/// ::= (!dbg !57)*
2439bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2440 while (Lex.getKind() == lltok::MetadataVar)
2441 if (parseGlobalObjectMetadataAttachment(F))
2442 return true;
2443 return false;
2444}
2445
2446/// parseOptionalAlignment
2447/// ::= /* empty */
2448/// ::= 'align' 4
2449bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2450 Alignment = std::nullopt;
2451 if (!EatIfPresent(lltok::kw_align))
2452 return false;
2453 LocTy AlignLoc = Lex.getLoc();
2454 uint64_t Value = 0;
2455
2456 LocTy ParenLoc = Lex.getLoc();
2457 bool HaveParens = false;
2458 if (AllowParens) {
2459 if (EatIfPresent(lltok::lparen))
2460 HaveParens = true;
2461 }
2462
2463 if (parseUInt64(Value))
2464 return true;
2465
2466 if (HaveParens && !EatIfPresent(lltok::rparen))
2467 return error(ParenLoc, "expected ')'");
2468
2469 if (!isPowerOf2_64(Value))
2470 return error(AlignLoc, "alignment is not a power of two");
2472 return error(AlignLoc, "huge alignments are not supported yet");
2473 Alignment = Align(Value);
2474 return false;
2475}
2476
2477/// parseOptionalPrefAlignment
2478/// ::= /* empty */
2479/// ::= 'prefalign' '(' 4 ')'
2480bool LLParser::parseOptionalPrefAlignment(MaybeAlign &Alignment) {
2481 Alignment = std::nullopt;
2482 if (!EatIfPresent(lltok::kw_prefalign))
2483 return false;
2484 LocTy AlignLoc = Lex.getLoc();
2485 uint64_t Value = 0;
2486
2487 LocTy ParenLoc = Lex.getLoc();
2488 if (!EatIfPresent(lltok::lparen))
2489 return error(ParenLoc, "expected '('");
2490
2491 if (parseUInt64(Value))
2492 return true;
2493
2494 ParenLoc = Lex.getLoc();
2495 if (!EatIfPresent(lltok::rparen))
2496 return error(ParenLoc, "expected ')'");
2497
2498 if (!isPowerOf2_64(Value))
2499 return error(AlignLoc, "alignment is not a power of two");
2501 return error(AlignLoc, "huge alignments are not supported yet");
2502 Alignment = Align(Value);
2503 return false;
2504}
2505
2506/// parseOptionalCodeModel
2507/// ::= /* empty */
2508/// ::= 'code_model' "large"
2509bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2510 Lex.Lex();
2511 auto StrVal = Lex.getStrVal();
2512 auto ErrMsg = "expected global code model string";
2513 if (StrVal == "tiny")
2514 model = CodeModel::Tiny;
2515 else if (StrVal == "small")
2516 model = CodeModel::Small;
2517 else if (StrVal == "kernel")
2518 model = CodeModel::Kernel;
2519 else if (StrVal == "medium")
2520 model = CodeModel::Medium;
2521 else if (StrVal == "large")
2522 model = CodeModel::Large;
2523 else
2524 return tokError(ErrMsg);
2525 if (parseToken(lltok::StringConstant, ErrMsg))
2526 return true;
2527 return false;
2528}
2529
2530/// parseOptionalAttrBytes
2531/// ::= /* empty */
2532/// ::= AttrKind '(' 4 ')'
2533///
2534/// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or
2535/// 'dead_on_return'
2536bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind,
2537 std::optional<uint64_t> &Bytes,
2538 bool ErrorNoBytes) {
2539 assert((AttrKind == lltok::kw_dereferenceable ||
2540 AttrKind == lltok::kw_dereferenceable_or_null ||
2541 AttrKind == lltok::kw_dead_on_return) &&
2542 "contract!");
2543
2544 Bytes = 0;
2545 if (!EatIfPresent(AttrKind))
2546 return false;
2547 LocTy ParenLoc = Lex.getLoc();
2548 if (!EatIfPresent(lltok::lparen)) {
2549 if (ErrorNoBytes)
2550 return error(ParenLoc, "expected '('");
2551 Bytes = std::nullopt;
2552 return false;
2553 }
2554 LocTy DerefLoc = Lex.getLoc();
2555 if (parseUInt64(Bytes.value()))
2556 return true;
2557 ParenLoc = Lex.getLoc();
2558 if (!EatIfPresent(lltok::rparen))
2559 return error(ParenLoc, "expected ')'");
2560 if (!Bytes.value())
2561 return error(DerefLoc, "byte count specified must be non-zero");
2562 return false;
2563}
2564
2565bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2566 Lex.Lex();
2568 if (!EatIfPresent(lltok::lparen))
2569 return false;
2570 LocTy KindLoc = Lex.getLoc();
2571 if (Lex.getKind() == lltok::kw_sync)
2573 else if (Lex.getKind() == lltok::kw_async)
2575 else
2576 return error(KindLoc, "expected unwind table kind");
2577 Lex.Lex();
2578 return parseToken(lltok::rparen, "expected ')'");
2579}
2580
2581bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2582 Lex.Lex();
2583 LocTy ParenLoc = Lex.getLoc();
2584 if (!EatIfPresent(lltok::lparen))
2585 return error(ParenLoc, "expected '('");
2586 LocTy KindLoc = Lex.getLoc();
2587 std::string Arg;
2588 if (parseStringConstant(Arg))
2589 return error(KindLoc, "expected allockind value");
2590 for (StringRef A : llvm::split(Arg, ",")) {
2591 if (A == "alloc") {
2593 } else if (A == "realloc") {
2595 } else if (A == "free") {
2597 } else if (A == "uninitialized") {
2599 } else if (A == "zeroed") {
2601 } else if (A == "aligned") {
2603 } else {
2604 return error(KindLoc, Twine("unknown allockind ") + A);
2605 }
2606 }
2607 ParenLoc = Lex.getLoc();
2608 if (!EatIfPresent(lltok::rparen))
2609 return error(ParenLoc, "expected ')'");
2610 if (Kind == AllocFnKind::Unknown)
2611 return error(KindLoc, "expected allockind value");
2612 return false;
2613}
2614
2616 using Loc = IRMemLocation;
2617
2618 switch (Tok) {
2619 case lltok::kw_argmem:
2620 return {Loc::ArgMem};
2622 return {Loc::InaccessibleMem};
2623 case lltok::kw_errnomem:
2624 return {Loc::ErrnoMem};
2626 return {Loc::TargetMem0};
2628 return {Loc::TargetMem1};
2629 case lltok::kw_target_mem: {
2632 Targets.push_back(Loc);
2633 return Targets;
2634 }
2635 default:
2636 return {};
2637 }
2638}
2639
2640static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2641 switch (Tok) {
2642 case lltok::kw_none:
2643 return ModRefInfo::NoModRef;
2644 case lltok::kw_read:
2645 return ModRefInfo::Ref;
2646 case lltok::kw_write:
2647 return ModRefInfo::Mod;
2649 return ModRefInfo::ModRef;
2650 default:
2651 return std::nullopt;
2652 }
2653}
2654
2655static std::optional<DenormalMode::DenormalModeKind>
2657 switch (Tok) {
2658 case lltok::kw_ieee:
2659 return DenormalMode::IEEE;
2664 case lltok::kw_dynamic:
2665 return DenormalMode::Dynamic;
2666 default:
2667 return std::nullopt;
2668 }
2669}
2670
2671std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2673
2674 // We use syntax like memory(argmem: read), so the colon should not be
2675 // interpreted as a label terminator.
2676 Lex.setIgnoreColonInIdentifiers(true);
2677 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2678
2679 Lex.Lex();
2680 if (!EatIfPresent(lltok::lparen)) {
2681 tokError("expected '('");
2682 return std::nullopt;
2683 }
2684
2685 bool SeenLoc = false;
2686 bool SeenTargetLoc = false;
2687 do {
2688 SmallVector<IRMemLocation, 2> Locs = keywordToLoc(Lex.getKind());
2689 if (!Locs.empty()) {
2690 Lex.Lex();
2691 if (!EatIfPresent(lltok::colon)) {
2692 tokError("expected ':' after location");
2693 return std::nullopt;
2694 }
2695 }
2696
2697 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2698 if (!MR) {
2699 if (Locs.empty())
2700 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2701 "or access kind (none, read, write, readwrite)");
2702 else
2703 tokError("expected access kind (none, read, write, readwrite)");
2704 return std::nullopt;
2705 }
2706
2707 Lex.Lex();
2708 if (!Locs.empty()) {
2709 SeenLoc = true;
2710 for (IRMemLocation Loc : Locs) {
2711 ME = ME.getWithModRef(Loc, *MR);
2712 if (ME.isTargetMemLoc(Loc) && Locs.size() == 1)
2713 SeenTargetLoc = true;
2714 }
2715 if (Locs.size() > 1 && SeenTargetLoc) {
2716 tokError("target memory default access kind must be specified first");
2717 return std::nullopt;
2718 }
2719
2720 } else {
2721 if (SeenLoc) {
2722 tokError("default access kind must be specified first");
2723 return std::nullopt;
2724 }
2725 ME = MemoryEffects(*MR);
2726 }
2727
2728 if (EatIfPresent(lltok::rparen))
2729 return ME;
2730 } while (EatIfPresent(lltok::comma));
2731
2732 tokError("unterminated memory attribute");
2733 return std::nullopt;
2734}
2735
2736std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2737 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2738 keywordToDenormalModeKind(Lex.getKind());
2739 if (!OutputMode) {
2740 tokError("expected denormal behavior kind (ieee, preservesign, "
2741 "positivezero, dynamic)");
2742 return {};
2743 }
2744
2745 Lex.Lex();
2746
2747 std::optional<DenormalMode::DenormalModeKind> InputMode;
2748 if (EatIfPresent(lltok::bar)) {
2749 InputMode = keywordToDenormalModeKind(Lex.getKind());
2750 if (!InputMode) {
2751 tokError("expected denormal behavior kind (ieee, preservesign, "
2752 "positivezero, dynamic)");
2753 return {};
2754 }
2755
2756 Lex.Lex();
2757 } else {
2758 // Single item, input == output mode
2759 InputMode = OutputMode;
2760 }
2761
2762 return DenormalMode(*OutputMode, *InputMode);
2763}
2764
2765std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2766 // We use syntax like denormal_fpenv(float: preservesign), so the colon should
2767 // not be interpreted as a label terminator.
2768 Lex.setIgnoreColonInIdentifiers(true);
2769 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2770
2771 Lex.Lex();
2772
2773 if (parseToken(lltok::lparen, "expected '('"))
2774 return {};
2775
2776 DenormalMode DefaultMode = DenormalMode::getIEEE();
2777 DenormalMode F32Mode = DenormalMode::getInvalid();
2778
2779 bool HasDefaultSection = false;
2780 if (Lex.getKind() != lltok::Type) {
2781 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2782 if (!ParsedDefaultMode)
2783 return {};
2784 DefaultMode = *ParsedDefaultMode;
2785 HasDefaultSection = true;
2786 }
2787
2788 bool HasComma = EatIfPresent(lltok::comma);
2789 if (Lex.getKind() == lltok::Type) {
2790 if (HasDefaultSection && !HasComma) {
2791 tokError("expected ',' before float:");
2792 return {};
2793 }
2794
2795 Type *Ty = nullptr;
2796 if (parseType(Ty) || !Ty->isFloatTy()) {
2797 tokError("expected float:");
2798 return {};
2799 }
2800
2801 if (parseToken(lltok::colon, "expected ':' before float denormal_fpenv"))
2802 return {};
2803
2804 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2805 if (!ParsedF32Mode)
2806 return {};
2807
2808 F32Mode = *ParsedF32Mode;
2809 }
2810
2811 if (parseToken(lltok::rparen, "unterminated denormal_fpenv"))
2812 return {};
2813
2814 return DenormalFPEnv(DefaultMode, F32Mode);
2815}
2816
2817static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2818 switch (Tok) {
2819 case lltok::kw_all:
2820 return fcAllFlags;
2821 case lltok::kw_nan:
2822 return fcNan;
2823 case lltok::kw_snan:
2824 return fcSNan;
2825 case lltok::kw_qnan:
2826 return fcQNan;
2827 case lltok::kw_inf:
2828 return fcInf;
2829 case lltok::kw_ninf:
2830 return fcNegInf;
2831 case lltok::kw_pinf:
2832 return fcPosInf;
2833 case lltok::kw_norm:
2834 return fcNormal;
2835 case lltok::kw_nnorm:
2836 return fcNegNormal;
2837 case lltok::kw_pnorm:
2838 return fcPosNormal;
2839 case lltok::kw_sub:
2840 return fcSubnormal;
2841 case lltok::kw_nsub:
2842 return fcNegSubnormal;
2843 case lltok::kw_psub:
2844 return fcPosSubnormal;
2845 case lltok::kw_zero:
2846 return fcZero;
2847 case lltok::kw_nzero:
2848 return fcNegZero;
2849 case lltok::kw_pzero:
2850 return fcPosZero;
2851 default:
2852 return 0;
2853 }
2854}
2855
2856unsigned LLParser::parseNoFPClassAttr() {
2857 unsigned Mask = fcNone;
2858
2859 Lex.Lex();
2860 if (!EatIfPresent(lltok::lparen)) {
2861 tokError("expected '('");
2862 return 0;
2863 }
2864
2865 do {
2866 uint64_t Value = 0;
2867 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2868 if (TestMask != 0) {
2869 Mask |= TestMask;
2870 // TODO: Disallow overlapping masks to avoid copy paste errors
2871 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2872 !parseUInt64(Value)) {
2873 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2874 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2875 return 0;
2876 }
2877
2878 if (!EatIfPresent(lltok::rparen)) {
2879 error(Lex.getLoc(), "expected ')'");
2880 return 0;
2881 }
2882
2883 return Value;
2884 } else {
2885 error(Lex.getLoc(), "expected nofpclass test mask");
2886 return 0;
2887 }
2888
2889 Lex.Lex();
2890 if (EatIfPresent(lltok::rparen))
2891 return Mask;
2892 } while (1);
2893
2894 llvm_unreachable("unterminated nofpclass attribute");
2895}
2896
2897/// parseOptionalCommaAlign
2898/// ::=
2899/// ::= ',' align 4
2900///
2901/// This returns with AteExtraComma set to true if it ate an excess comma at the
2902/// end.
2903bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2904 bool &AteExtraComma) {
2905 AteExtraComma = false;
2906 while (EatIfPresent(lltok::comma)) {
2907 // Metadata at the end is an early exit.
2908 if (Lex.getKind() == lltok::MetadataVar) {
2909 AteExtraComma = true;
2910 return false;
2911 }
2912
2913 if (Lex.getKind() != lltok::kw_align)
2914 return error(Lex.getLoc(), "expected metadata or 'align'");
2915
2916 if (parseOptionalAlignment(Alignment))
2917 return true;
2918 }
2919
2920 return false;
2921}
2922
2923/// parseOptionalCommaAddrSpace
2924/// ::=
2925/// ::= ',' addrspace(1)
2926///
2927/// This returns with AteExtraComma set to true if it ate an excess comma at the
2928/// end.
2929bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2930 bool &AteExtraComma) {
2931 AteExtraComma = false;
2932 while (EatIfPresent(lltok::comma)) {
2933 // Metadata at the end is an early exit.
2934 if (Lex.getKind() == lltok::MetadataVar) {
2935 AteExtraComma = true;
2936 return false;
2937 }
2938
2939 Loc = Lex.getLoc();
2940 if (Lex.getKind() != lltok::kw_addrspace)
2941 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2942
2943 if (parseOptionalAddrSpace(AddrSpace))
2944 return true;
2945 }
2946
2947 return false;
2948}
2949
2950bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2951 std::optional<unsigned> &HowManyArg) {
2952 Lex.Lex();
2953
2954 auto StartParen = Lex.getLoc();
2955 if (!EatIfPresent(lltok::lparen))
2956 return error(StartParen, "expected '('");
2957
2958 if (parseUInt32(BaseSizeArg))
2959 return true;
2960
2961 if (EatIfPresent(lltok::comma)) {
2962 auto HowManyAt = Lex.getLoc();
2963 unsigned HowMany;
2964 if (parseUInt32(HowMany))
2965 return true;
2966 if (HowMany == BaseSizeArg)
2967 return error(HowManyAt,
2968 "'allocsize' indices can't refer to the same parameter");
2969 HowManyArg = HowMany;
2970 } else
2971 HowManyArg = std::nullopt;
2972
2973 auto EndParen = Lex.getLoc();
2974 if (!EatIfPresent(lltok::rparen))
2975 return error(EndParen, "expected ')'");
2976 return false;
2977}
2978
2979bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2980 unsigned &MaxValue) {
2981 Lex.Lex();
2982
2983 auto StartParen = Lex.getLoc();
2984 if (!EatIfPresent(lltok::lparen))
2985 return error(StartParen, "expected '('");
2986
2987 if (parseUInt32(MinValue))
2988 return true;
2989
2990 if (EatIfPresent(lltok::comma)) {
2991 if (parseUInt32(MaxValue))
2992 return true;
2993 } else
2994 MaxValue = MinValue;
2995
2996 auto EndParen = Lex.getLoc();
2997 if (!EatIfPresent(lltok::rparen))
2998 return error(EndParen, "expected ')'");
2999 return false;
3000}
3001
3002/// parseScopeAndOrdering
3003/// if isAtomic: ::= SyncScope? AtomicOrdering
3004/// else: ::=
3005///
3006/// This sets Scope and Ordering to the parsed values.
3007bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
3008 AtomicOrdering &Ordering) {
3009 if (!IsAtomic)
3010 return false;
3011
3012 return parseScope(SSID) || parseOrdering(Ordering);
3013}
3014
3015/// parseScope
3016/// ::= syncscope("singlethread" | "<target scope>")?
3017///
3018/// This sets synchronization scope ID to the ID of the parsed value.
3019bool LLParser::parseScope(SyncScope::ID &SSID) {
3020 SSID = SyncScope::System;
3021 if (EatIfPresent(lltok::kw_syncscope)) {
3022 auto StartParenAt = Lex.getLoc();
3023 if (!EatIfPresent(lltok::lparen))
3024 return error(StartParenAt, "Expected '(' in syncscope");
3025
3026 std::string SSN;
3027 auto SSNAt = Lex.getLoc();
3028 if (parseStringConstant(SSN))
3029 return error(SSNAt, "Expected synchronization scope name");
3030
3031 auto EndParenAt = Lex.getLoc();
3032 if (!EatIfPresent(lltok::rparen))
3033 return error(EndParenAt, "Expected ')' in syncscope");
3034
3035 SSID = Context.getOrInsertSyncScopeID(SSN);
3036 }
3037
3038 return false;
3039}
3040
3041/// parseOrdering
3042/// ::= AtomicOrdering
3043///
3044/// This sets Ordering to the parsed value.
3045bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
3046 switch (Lex.getKind()) {
3047 default:
3048 return tokError("Expected ordering on atomic instruction");
3051 // Not specified yet:
3052 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
3056 case lltok::kw_seq_cst:
3058 break;
3059 }
3060 Lex.Lex();
3061 return false;
3062}
3063
3064/// parseOptionalStackAlignment
3065/// ::= /* empty */
3066/// ::= 'alignstack' '(' 4 ')'
3067bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
3068 Alignment = 0;
3069 if (!EatIfPresent(lltok::kw_alignstack))
3070 return false;
3071 LocTy ParenLoc = Lex.getLoc();
3072 if (!EatIfPresent(lltok::lparen))
3073 return error(ParenLoc, "expected '('");
3074 LocTy AlignLoc = Lex.getLoc();
3075 if (parseUInt32(Alignment))
3076 return true;
3077 ParenLoc = Lex.getLoc();
3078 if (!EatIfPresent(lltok::rparen))
3079 return error(ParenLoc, "expected ')'");
3080 if (!isPowerOf2_32(Alignment))
3081 return error(AlignLoc, "stack alignment is not a power of two");
3082 return false;
3083}
3084
3085/// parseIndexList - This parses the index list for an insert/extractvalue
3086/// instruction. This sets AteExtraComma in the case where we eat an extra
3087/// comma at the end of the line and find that it is followed by metadata.
3088/// Clients that don't allow metadata can call the version of this function that
3089/// only takes one argument.
3090///
3091/// parseIndexList
3092/// ::= (',' uint32)+
3093///
3094bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
3095 bool &AteExtraComma) {
3096 AteExtraComma = false;
3097
3098 if (Lex.getKind() != lltok::comma)
3099 return tokError("expected ',' as start of index list");
3100
3101 while (EatIfPresent(lltok::comma)) {
3102 if (Lex.getKind() == lltok::MetadataVar) {
3103 if (Indices.empty())
3104 return tokError("expected index");
3105 AteExtraComma = true;
3106 return false;
3107 }
3108 unsigned Idx = 0;
3109 if (parseUInt32(Idx))
3110 return true;
3111 Indices.push_back(Idx);
3112 }
3113
3114 return false;
3115}
3116
3117//===----------------------------------------------------------------------===//
3118// Type Parsing.
3119//===----------------------------------------------------------------------===//
3120
3121/// parseType - parse a type.
3122bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
3123 SMLoc TypeLoc = Lex.getLoc();
3124 switch (Lex.getKind()) {
3125 default:
3126 return tokError(Msg);
3127 case lltok::Type:
3128 // Type ::= 'float' | 'void' (etc)
3129 Result = Lex.getTyVal();
3130 Lex.Lex();
3131
3132 // Handle "ptr" opaque pointer type.
3133 //
3134 // Type ::= ptr ('addrspace' '(' uint32 ')')?
3135 if (Result->isPointerTy()) {
3136 unsigned AddrSpace;
3137 if (parseOptionalAddrSpace(AddrSpace))
3138 return true;
3139 Result = PointerType::get(getContext(), AddrSpace);
3140
3141 // Give a nice error for 'ptr*'.
3142 if (Lex.getKind() == lltok::star)
3143 return tokError("ptr* is invalid - use ptr instead");
3144
3145 // Fall through to parsing the type suffixes only if this 'ptr' is a
3146 // function return. Otherwise, return success, implicitly rejecting other
3147 // suffixes.
3148 if (Lex.getKind() != lltok::lparen)
3149 return false;
3150 }
3151 break;
3152 case lltok::kw_target: {
3153 // Type ::= TargetExtType
3154 if (parseTargetExtType(Result))
3155 return true;
3156 break;
3157 }
3158 case lltok::lbrace:
3159 // Type ::= StructType
3160 if (parseAnonStructType(Result, false))
3161 return true;
3162 break;
3163 case lltok::lsquare:
3164 // Type ::= '[' ... ']'
3165 Lex.Lex(); // eat the lsquare.
3166 if (parseArrayVectorType(Result, false))
3167 return true;
3168 break;
3169 case lltok::less: // Either vector or packed struct.
3170 // Type ::= '<' ... '>'
3171 Lex.Lex();
3172 if (Lex.getKind() == lltok::lbrace) {
3173 if (parseAnonStructType(Result, true) ||
3174 parseToken(lltok::greater, "expected '>' at end of packed struct"))
3175 return true;
3176 } else if (parseArrayVectorType(Result, true))
3177 return true;
3178 break;
3179 case lltok::LocalVar: {
3180 // Type ::= %foo
3181 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3182
3183 // If the type hasn't been defined yet, create a forward definition and
3184 // remember where that forward def'n was seen (in case it never is defined).
3185 if (!Entry.first) {
3186 Entry.first = StructType::create(Context, Lex.getStrVal());
3187 Entry.second = Lex.getLoc();
3188 }
3189 Result = Entry.first;
3190 Lex.Lex();
3191 break;
3192 }
3193
3194 case lltok::LocalVarID: {
3195 // Type ::= %4
3196 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3197
3198 // If the type hasn't been defined yet, create a forward definition and
3199 // remember where that forward def'n was seen (in case it never is defined).
3200 if (!Entry.first) {
3201 Entry.first = StructType::create(Context);
3202 Entry.second = Lex.getLoc();
3203 }
3204 Result = Entry.first;
3205 Lex.Lex();
3206 break;
3207 }
3208 }
3209
3210 // parse the type suffixes.
3211 while (true) {
3212 switch (Lex.getKind()) {
3213 // End of type.
3214 default:
3215 if (!AllowVoid && Result->isVoidTy())
3216 return error(TypeLoc, "void type only allowed for function results");
3217 return false;
3218
3219 // Type ::= Type '*'
3220 case lltok::star:
3221 if (Result->isLabelTy())
3222 return tokError("basic block pointers are invalid");
3223 if (Result->isVoidTy())
3224 return tokError("pointers to void are invalid - use i8* instead");
3226 return tokError("pointer to this type is invalid");
3227 Result = PointerType::getUnqual(Context);
3228 Lex.Lex();
3229 break;
3230
3231 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3232 case lltok::kw_addrspace: {
3233 if (Result->isLabelTy())
3234 return tokError("basic block pointers are invalid");
3235 if (Result->isVoidTy())
3236 return tokError("pointers to void are invalid; use i8* instead");
3238 return tokError("pointer to this type is invalid");
3239 unsigned AddrSpace;
3240 if (parseOptionalAddrSpace(AddrSpace) ||
3241 parseToken(lltok::star, "expected '*' in address space"))
3242 return true;
3243
3244 Result = PointerType::get(Context, AddrSpace);
3245 break;
3246 }
3247
3248 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3249 case lltok::lparen:
3250 if (parseFunctionType(Result))
3251 return true;
3252 break;
3253 }
3254 }
3255}
3256
3257/// parseParameterList
3258/// ::= '(' ')'
3259/// ::= '(' Arg (',' Arg)* ')'
3260/// Arg
3261/// ::= Type OptionalAttributes Value OptionalAttributes
3262bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3263 PerFunctionState &PFS, bool IsMustTailCall,
3264 bool InVarArgsFunc) {
3265 if (parseToken(lltok::lparen, "expected '(' in call"))
3266 return true;
3267
3268 while (Lex.getKind() != lltok::rparen) {
3269 // If this isn't the first argument, we need a comma.
3270 if (!ArgList.empty() &&
3271 parseToken(lltok::comma, "expected ',' in argument list"))
3272 return true;
3273
3274 // parse an ellipsis if this is a musttail call in a variadic function.
3275 if (Lex.getKind() == lltok::dotdotdot) {
3276 const char *Msg = "unexpected ellipsis in argument list for ";
3277 if (!IsMustTailCall)
3278 return tokError(Twine(Msg) + "non-musttail call");
3279 if (!InVarArgsFunc)
3280 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3281 Lex.Lex(); // Lex the '...', it is purely for readability.
3282 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3283 }
3284
3285 // parse the argument.
3286 LocTy ArgLoc;
3287 Type *ArgTy = nullptr;
3288 Value *V;
3289 if (parseType(ArgTy, ArgLoc))
3290 return true;
3292 return error(ArgLoc, "invalid type for function argument");
3293
3294 AttrBuilder ArgAttrs(M->getContext());
3295
3296 if (ArgTy->isMetadataTy()) {
3297 if (parseMetadataAsValue(V, PFS))
3298 return true;
3299 } else {
3300 // Otherwise, handle normal operands.
3301 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3302 return true;
3303 }
3304 ArgList.push_back(ParamInfo(
3305 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3306 }
3307
3308 if (IsMustTailCall && InVarArgsFunc)
3309 return tokError("expected '...' at end of argument list for musttail call "
3310 "in varargs function");
3311
3312 Lex.Lex(); // Lex the ')'.
3313 return false;
3314}
3315
3316/// parseRequiredTypeAttr
3317/// ::= attrname(<ty>)
3318bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3319 Attribute::AttrKind AttrKind) {
3320 Type *Ty = nullptr;
3321 if (!EatIfPresent(AttrToken))
3322 return true;
3323 if (!EatIfPresent(lltok::lparen))
3324 return error(Lex.getLoc(), "expected '('");
3325 if (parseType(Ty))
3326 return true;
3327 if (!EatIfPresent(lltok::rparen))
3328 return error(Lex.getLoc(), "expected ')'");
3329
3330 B.addTypeAttr(AttrKind, Ty);
3331 return false;
3332}
3333
3334/// parseRangeAttr
3335/// ::= range(<ty> <n>,<n>)
3336bool LLParser::parseRangeAttr(AttrBuilder &B) {
3337 Lex.Lex();
3338
3339 APInt Lower;
3340 APInt Upper;
3341 Type *Ty = nullptr;
3342 LocTy TyLoc;
3343
3344 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3345 if (Lex.getKind() != lltok::APSInt)
3346 return tokError("expected integer");
3347 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3348 return tokError(
3349 "integer is too large for the bit width of specified type");
3350 Val = Lex.getAPSIntVal().extend(BitWidth);
3351 Lex.Lex();
3352 return false;
3353 };
3354
3355 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3356 return true;
3357 if (!Ty->isIntegerTy())
3358 return error(TyLoc, "the range must have integer type!");
3359
3360 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3361
3362 if (ParseAPSInt(BitWidth, Lower) ||
3363 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3364 return true;
3365 if (Lower == Upper && !Lower.isZero())
3366 return tokError("the range represent the empty set but limits aren't 0!");
3367
3368 if (parseToken(lltok::rparen, "expected ')'"))
3369 return true;
3370
3371 B.addRangeAttr(ConstantRange(Lower, Upper));
3372 return false;
3373}
3374
3375/// parseInitializesAttr
3376/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3377bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3378 Lex.Lex();
3379
3380 auto ParseAPSInt = [&](APInt &Val) {
3381 if (Lex.getKind() != lltok::APSInt)
3382 return tokError("expected integer");
3383 Val = Lex.getAPSIntVal().extend(64);
3384 Lex.Lex();
3385 return false;
3386 };
3387
3388 if (parseToken(lltok::lparen, "expected '('"))
3389 return true;
3390
3392 // Parse each constant range.
3393 do {
3394 APInt Lower, Upper;
3395 if (parseToken(lltok::lparen, "expected '('"))
3396 return true;
3397
3398 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3399 ParseAPSInt(Upper))
3400 return true;
3401
3402 if (Lower == Upper)
3403 return tokError("the range should not represent the full or empty set!");
3404
3405 if (parseToken(lltok::rparen, "expected ')'"))
3406 return true;
3407
3408 RangeList.push_back(ConstantRange(Lower, Upper));
3409 } while (EatIfPresent(lltok::comma));
3410
3411 if (parseToken(lltok::rparen, "expected ')'"))
3412 return true;
3413
3414 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3415 if (!CRLOrNull.has_value())
3416 return tokError("Invalid (unordered or overlapping) range list");
3417 B.addInitializesAttr(*CRLOrNull);
3418 return false;
3419}
3420
3421bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3423 std::optional<CaptureComponents> Ret;
3424
3425 // We use syntax like captures(ret: address, provenance), so the colon
3426 // should not be interpreted as a label terminator.
3427 Lex.setIgnoreColonInIdentifiers(true);
3428 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
3429
3430 Lex.Lex();
3431 if (parseToken(lltok::lparen, "expected '('"))
3432 return true;
3433
3434 CaptureComponents *Current = &Other;
3435 bool SeenComponent = false;
3436 while (true) {
3437 if (EatIfPresent(lltok::kw_ret)) {
3438 if (parseToken(lltok::colon, "expected ':'"))
3439 return true;
3440 if (Ret)
3441 return tokError("duplicate 'ret' location");
3443 Current = &*Ret;
3444 SeenComponent = false;
3445 }
3446
3447 if (EatIfPresent(lltok::kw_none)) {
3448 if (SeenComponent)
3449 return tokError("cannot use 'none' with other component");
3450 *Current = CaptureComponents::None;
3451 } else {
3452 if (SeenComponent && capturesNothing(*Current))
3453 return tokError("cannot use 'none' with other component");
3454
3455 if (EatIfPresent(lltok::kw_address_is_null))
3457 else if (EatIfPresent(lltok::kw_address))
3458 *Current |= CaptureComponents::Address;
3459 else if (EatIfPresent(lltok::kw_provenance))
3461 else if (EatIfPresent(lltok::kw_read_provenance))
3463 else
3464 return tokError("expected one of 'none', 'address', 'address_is_null', "
3465 "'provenance' or 'read_provenance'");
3466 }
3467
3468 SeenComponent = true;
3469 if (EatIfPresent(lltok::rparen))
3470 break;
3471
3472 if (parseToken(lltok::comma, "expected ',' or ')'"))
3473 return true;
3474 }
3475
3476 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3477 return false;
3478}
3479
3480/// parseOptionalOperandBundles
3481/// ::= /*empty*/
3482/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3483///
3484/// OperandBundle
3485/// ::= bundle-tag '(' ')'
3486/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3487///
3488/// bundle-tag ::= String Constant
3489bool LLParser::parseOptionalOperandBundles(
3490 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3491 LocTy BeginLoc = Lex.getLoc();
3492 if (!EatIfPresent(lltok::lsquare))
3493 return false;
3494
3495 while (Lex.getKind() != lltok::rsquare) {
3496 // If this isn't the first operand bundle, we need a comma.
3497 if (!BundleList.empty() &&
3498 parseToken(lltok::comma, "expected ',' in input list"))
3499 return true;
3500
3501 std::string Tag;
3502 if (parseStringConstant(Tag))
3503 return true;
3504
3505 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3506 return true;
3507
3508 std::vector<Value *> Inputs;
3509 while (Lex.getKind() != lltok::rparen) {
3510 // If this isn't the first input, we need a comma.
3511 if (!Inputs.empty() &&
3512 parseToken(lltok::comma, "expected ',' in input list"))
3513 return true;
3514
3515 Type *Ty = nullptr;
3516 Value *Input = nullptr;
3517 if (parseType(Ty))
3518 return true;
3519 if (Ty->isMetadataTy()) {
3520 if (parseMetadataAsValue(Input, PFS))
3521 return true;
3522 } else if (parseValue(Ty, Input, PFS)) {
3523 return true;
3524 }
3525 Inputs.push_back(Input);
3526 }
3527
3528 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3529
3530 Lex.Lex(); // Lex the ')'.
3531 }
3532
3533 if (BundleList.empty())
3534 return error(BeginLoc, "operand bundle set must not be empty");
3535
3536 Lex.Lex(); // Lex the ']'.
3537 return false;
3538}
3539
3540bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3541 unsigned NextID, unsigned ID) {
3542 if (ID < NextID)
3543 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3544 Twine(NextID) + "' or greater");
3545
3546 return false;
3547}
3548
3549/// parseArgumentList - parse the argument list for a function type or function
3550/// prototype.
3551/// ::= '(' ArgTypeListI ')'
3552/// ArgTypeListI
3553/// ::= /*empty*/
3554/// ::= '...'
3555/// ::= ArgTypeList ',' '...'
3556/// ::= ArgType (',' ArgType)*
3557///
3558bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3559 SmallVectorImpl<unsigned> &UnnamedArgNums,
3560 bool &IsVarArg) {
3561 unsigned CurValID = 0;
3562 IsVarArg = false;
3563 assert(Lex.getKind() == lltok::lparen);
3564 Lex.Lex(); // eat the (.
3565
3566 if (Lex.getKind() != lltok::rparen) {
3567 do {
3568 // Handle ... at end of arg list.
3569 if (EatIfPresent(lltok::dotdotdot)) {
3570 IsVarArg = true;
3571 break;
3572 }
3573
3574 // Otherwise must be an argument type.
3575 LocTy TypeLoc = Lex.getLoc();
3576 Type *ArgTy = nullptr;
3577 AttrBuilder Attrs(M->getContext());
3578 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3579 return true;
3580
3581 if (ArgTy->isVoidTy())
3582 return error(TypeLoc, "argument can not have void type");
3583
3584 std::string Name;
3585 FileLoc IdentStart;
3586 FileLoc IdentEnd;
3587 bool Unnamed = false;
3588 if (Lex.getKind() == lltok::LocalVar) {
3589 Name = Lex.getStrVal();
3590 IdentStart = getTokLineColumnPos();
3591 Lex.Lex();
3592 IdentEnd = getPrevTokEndLineColumnPos();
3593 } else {
3594 unsigned ArgID;
3595 if (Lex.getKind() == lltok::LocalVarID) {
3596 ArgID = Lex.getUIntVal();
3597 IdentStart = getTokLineColumnPos();
3598 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3599 return true;
3600 Lex.Lex();
3601 IdentEnd = getPrevTokEndLineColumnPos();
3602 } else {
3603 ArgID = CurValID;
3604 Unnamed = true;
3605 }
3606 UnnamedArgNums.push_back(ArgID);
3607 CurValID = ArgID + 1;
3608 }
3609
3611 return error(TypeLoc, "invalid type for function argument");
3612
3613 ArgList.emplace_back(
3614 TypeLoc, ArgTy,
3615 Unnamed ? std::nullopt
3616 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3617 AttributeSet::get(ArgTy->getContext(), Attrs), std::move(Name));
3618 } while (EatIfPresent(lltok::comma));
3619 }
3620
3621 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3622}
3623
3624/// parseFunctionType
3625/// ::= Type ArgumentList OptionalAttrs
3626bool LLParser::parseFunctionType(Type *&Result) {
3627 assert(Lex.getKind() == lltok::lparen);
3628
3630 return tokError("invalid function return type");
3631
3633 bool IsVarArg;
3634 SmallVector<unsigned> UnnamedArgNums;
3635 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3636 return true;
3637
3638 // Reject names on the arguments lists.
3639 for (const ArgInfo &Arg : ArgList) {
3640 if (!Arg.Name.empty())
3641 return error(Arg.Loc, "argument name invalid in function type");
3642 if (Arg.Attrs.hasAttributes())
3643 return error(Arg.Loc, "argument attributes invalid in function type");
3644 }
3645
3646 SmallVector<Type*, 16> ArgListTy;
3647 for (const ArgInfo &Arg : ArgList)
3648 ArgListTy.push_back(Arg.Ty);
3649
3650 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3651 return false;
3652}
3653
3654/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3655/// other structs.
3656bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3658 if (parseStructBody(Elts))
3659 return true;
3660
3661 Result = StructType::get(Context, Elts, Packed);
3662 return false;
3663}
3664
3665/// parseStructDefinition - parse a struct in a 'type' definition.
3666bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3667 std::pair<Type *, LocTy> &Entry,
3668 Type *&ResultTy) {
3669 // If the type was already defined, diagnose the redefinition.
3670 if (Entry.first && !Entry.second.isValid())
3671 return error(TypeLoc, "redefinition of type");
3672
3673 // If we have opaque, just return without filling in the definition for the
3674 // struct. This counts as a definition as far as the .ll file goes.
3675 if (EatIfPresent(lltok::kw_opaque)) {
3676 // This type is being defined, so clear the location to indicate this.
3677 Entry.second = SMLoc();
3678
3679 // If this type number has never been uttered, create it.
3680 if (!Entry.first)
3681 Entry.first = StructType::create(Context, Name);
3682 ResultTy = Entry.first;
3683 return false;
3684 }
3685
3686 // If the type starts with '<', then it is either a packed struct or a vector.
3687 bool isPacked = EatIfPresent(lltok::less);
3688
3689 // If we don't have a struct, then we have a random type alias, which we
3690 // accept for compatibility with old files. These types are not allowed to be
3691 // forward referenced and not allowed to be recursive.
3692 if (Lex.getKind() != lltok::lbrace) {
3693 if (Entry.first)
3694 return error(TypeLoc, "forward references to non-struct type");
3695
3696 ResultTy = nullptr;
3697 if (isPacked)
3698 return parseArrayVectorType(ResultTy, true);
3699 return parseType(ResultTy);
3700 }
3701
3702 // This type is being defined, so clear the location to indicate this.
3703 Entry.second = SMLoc();
3704
3705 // If this type number has never been uttered, create it.
3706 if (!Entry.first)
3707 Entry.first = StructType::create(Context, Name);
3708
3709 StructType *STy = cast<StructType>(Entry.first);
3710
3712 if (parseStructBody(Body) ||
3713 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3714 return true;
3715
3716 if (auto E = STy->setBodyOrError(Body, isPacked))
3717 return tokError(toString(std::move(E)));
3718
3719 ResultTy = STy;
3720 return false;
3721}
3722
3723/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3724/// StructType
3725/// ::= '{' '}'
3726/// ::= '{' Type (',' Type)* '}'
3727/// ::= '<' '{' '}' '>'
3728/// ::= '<' '{' Type (',' Type)* '}' '>'
3729bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3730 assert(Lex.getKind() == lltok::lbrace);
3731 Lex.Lex(); // Consume the '{'
3732
3733 // Handle the empty struct.
3734 if (EatIfPresent(lltok::rbrace))
3735 return false;
3736
3737 LocTy EltTyLoc = Lex.getLoc();
3738 Type *Ty = nullptr;
3739 if (parseType(Ty))
3740 return true;
3741 Body.push_back(Ty);
3742
3744 return error(EltTyLoc, "invalid element type for struct");
3745
3746 while (EatIfPresent(lltok::comma)) {
3747 EltTyLoc = Lex.getLoc();
3748 if (parseType(Ty))
3749 return true;
3750
3752 return error(EltTyLoc, "invalid element type for struct");
3753
3754 Body.push_back(Ty);
3755 }
3756
3757 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3758}
3759
3760/// parseArrayVectorType - parse an array or vector type, assuming the first
3761/// token has already been consumed.
3762/// Type
3763/// ::= '[' APSINTVAL 'x' Types ']'
3764/// ::= '<' APSINTVAL 'x' Types '>'
3765/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3766bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3767 bool Scalable = false;
3768
3769 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3770 Lex.Lex(); // consume the 'vscale'
3771 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3772 return true;
3773
3774 Scalable = true;
3775 }
3776
3777 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3778 Lex.getAPSIntVal().getBitWidth() > 64)
3779 return tokError("expected number in address space");
3780
3781 LocTy SizeLoc = Lex.getLoc();
3782 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3783 Lex.Lex();
3784
3785 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3786 return true;
3787
3788 LocTy TypeLoc = Lex.getLoc();
3789 Type *EltTy = nullptr;
3790 if (parseType(EltTy))
3791 return true;
3792
3793 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3794 "expected end of sequential type"))
3795 return true;
3796
3797 if (IsVector) {
3798 if (Size == 0)
3799 return error(SizeLoc, "zero element vector is illegal");
3800 if ((unsigned)Size != Size)
3801 return error(SizeLoc, "size too large for vector");
3803 return error(TypeLoc, "invalid vector element type");
3804 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3805 } else {
3807 return error(TypeLoc, "invalid array element type");
3808 Result = ArrayType::get(EltTy, Size);
3809 }
3810 return false;
3811}
3812
3813/// parseTargetExtType - handle target extension type syntax
3814/// TargetExtType
3815/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3816///
3817/// TargetExtTypeParams
3818/// ::= /*empty*/
3819/// ::= ',' Type TargetExtTypeParams
3820///
3821/// TargetExtIntParams
3822/// ::= /*empty*/
3823/// ::= ',' uint32 TargetExtIntParams
3824bool LLParser::parseTargetExtType(Type *&Result) {
3825 Lex.Lex(); // Eat the 'target' keyword.
3826
3827 // Get the mandatory type name.
3828 std::string TypeName;
3829 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3830 parseStringConstant(TypeName))
3831 return true;
3832
3833 // Parse all of the integer and type parameters at the same time; the use of
3834 // SeenInt will allow us to catch cases where type parameters follow integer
3835 // parameters.
3836 SmallVector<Type *> TypeParams;
3837 SmallVector<unsigned> IntParams;
3838 bool SeenInt = false;
3839 while (Lex.getKind() == lltok::comma) {
3840 Lex.Lex(); // Eat the comma.
3841
3842 if (Lex.getKind() == lltok::APSInt) {
3843 SeenInt = true;
3844 unsigned IntVal;
3845 if (parseUInt32(IntVal))
3846 return true;
3847 IntParams.push_back(IntVal);
3848 } else if (SeenInt) {
3849 // The only other kind of parameter we support is type parameters, which
3850 // must precede the integer parameters. This is therefore an error.
3851 return tokError("expected uint32 param");
3852 } else {
3853 Type *TypeParam;
3854 if (parseType(TypeParam, /*AllowVoid=*/true))
3855 return true;
3856 TypeParams.push_back(TypeParam);
3857 }
3858 }
3859
3860 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3861 return true;
3862
3863 auto TTy =
3864 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3865 if (auto E = TTy.takeError())
3866 return tokError(toString(std::move(E)));
3867
3868 Result = *TTy;
3869 return false;
3870}
3871
3872//===----------------------------------------------------------------------===//
3873// Function Semantic Analysis.
3874//===----------------------------------------------------------------------===//
3875
3876LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3877 int functionNumber,
3878 ArrayRef<unsigned> UnnamedArgNums)
3879 : P(p), F(f), FunctionNumber(functionNumber) {
3880
3881 // Insert unnamed arguments into the NumberedVals list.
3882 auto It = UnnamedArgNums.begin();
3883 for (Argument &A : F.args()) {
3884 if (!A.hasName()) {
3885 unsigned ArgNum = *It++;
3886 NumberedVals.add(ArgNum, &A);
3887 }
3888 }
3889}
3890
3891LLParser::PerFunctionState::~PerFunctionState() {
3892 // If there were any forward referenced non-basicblock values, delete them.
3893
3894 for (const auto &P : ForwardRefVals) {
3895 if (isa<BasicBlock>(P.second.first))
3896 continue;
3897 P.second.first->replaceAllUsesWith(
3898 PoisonValue::get(P.second.first->getType()));
3899 P.second.first->deleteValue();
3900 }
3901
3902 for (const auto &P : ForwardRefValIDs) {
3903 if (isa<BasicBlock>(P.second.first))
3904 continue;
3905 P.second.first->replaceAllUsesWith(
3906 PoisonValue::get(P.second.first->getType()));
3907 P.second.first->deleteValue();
3908 }
3909}
3910
3911bool LLParser::PerFunctionState::finishFunction() {
3912 if (!ForwardRefVals.empty())
3913 return P.error(ForwardRefVals.begin()->second.second,
3914 "use of undefined value '%" + ForwardRefVals.begin()->first +
3915 "'");
3916 if (!ForwardRefValIDs.empty())
3917 return P.error(ForwardRefValIDs.begin()->second.second,
3918 "use of undefined value '%" +
3919 Twine(ForwardRefValIDs.begin()->first) + "'");
3920 return false;
3921}
3922
3923/// getVal - Get a value with the specified name or ID, creating a
3924/// forward reference record if needed. This can return null if the value
3925/// exists but does not have the right type.
3926Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3927 LocTy Loc) {
3928 // Look this name up in the normal function symbol table.
3929 Value *Val = F.getValueSymbolTable()->lookup(Name);
3930
3931 // If this is a forward reference for the value, see if we already created a
3932 // forward ref record.
3933 if (!Val) {
3934 auto I = ForwardRefVals.find(Name);
3935 if (I != ForwardRefVals.end())
3936 Val = I->second.first;
3937 }
3938
3939 // If we have the value in the symbol table or fwd-ref table, return it.
3940 if (Val)
3941 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3942
3943 // Don't make placeholders with invalid type.
3944 if (!Ty->isFirstClassType()) {
3945 P.error(Loc, "invalid use of a non-first-class type");
3946 return nullptr;
3947 }
3948
3949 // Otherwise, create a new forward reference for this value and remember it.
3950 Value *FwdVal;
3951 if (Ty->isLabelTy()) {
3952 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3953 } else {
3954 FwdVal = new Argument(Ty, Name);
3955 }
3956 if (FwdVal->getName() != Name) {
3957 P.error(Loc, "name is too long which can result in name collisions, "
3958 "consider making the name shorter or "
3959 "increasing -non-global-value-max-name-size");
3960 return nullptr;
3961 }
3962
3963 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3964 return FwdVal;
3965}
3966
3967Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3968 // Look this name up in the normal function symbol table.
3969 Value *Val = NumberedVals.get(ID);
3970
3971 // If this is a forward reference for the value, see if we already created a
3972 // forward ref record.
3973 if (!Val) {
3974 auto I = ForwardRefValIDs.find(ID);
3975 if (I != ForwardRefValIDs.end())
3976 Val = I->second.first;
3977 }
3978
3979 // If we have the value in the symbol table or fwd-ref table, return it.
3980 if (Val)
3981 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3982
3983 if (!Ty->isFirstClassType()) {
3984 P.error(Loc, "invalid use of a non-first-class type");
3985 return nullptr;
3986 }
3987
3988 // Otherwise, create a new forward reference for this value and remember it.
3989 Value *FwdVal;
3990 if (Ty->isLabelTy()) {
3991 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3992 } else {
3993 FwdVal = new Argument(Ty);
3994 }
3995
3996 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3997 return FwdVal;
3998}
3999
4000/// setInstName - After an instruction is parsed and inserted into its
4001/// basic block, this installs its name.
4002bool LLParser::PerFunctionState::setInstName(int NameID,
4003 const std::string &NameStr,
4004 LocTy NameLoc, Instruction *Inst) {
4005 // If this instruction has void type, it cannot have a name or ID specified.
4006 if (Inst->getType()->isVoidTy()) {
4007 if (NameID != -1 || !NameStr.empty())
4008 return P.error(NameLoc, "instructions returning void cannot have a name");
4009 return false;
4010 }
4011
4012 // If this was a numbered instruction, verify that the instruction is the
4013 // expected value and resolve any forward references.
4014 if (NameStr.empty()) {
4015 // If neither a name nor an ID was specified, just use the next ID.
4016 if (NameID == -1)
4017 NameID = NumberedVals.getNext();
4018
4019 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
4020 NameID))
4021 return true;
4022
4023 auto FI = ForwardRefValIDs.find(NameID);
4024 if (FI != ForwardRefValIDs.end()) {
4025 Value *Sentinel = FI->second.first;
4026 if (Sentinel->getType() != Inst->getType())
4027 return P.error(NameLoc, "instruction forward referenced with type '" +
4028 getTypeString(FI->second.first->getType()) +
4029 "'");
4030
4031 Sentinel->replaceAllUsesWith(Inst);
4032 Sentinel->deleteValue();
4033 ForwardRefValIDs.erase(FI);
4034 }
4035
4036 NumberedVals.add(NameID, Inst);
4037 return false;
4038 }
4039
4040 // Otherwise, the instruction had a name. Resolve forward refs and set it.
4041 auto FI = ForwardRefVals.find(NameStr);
4042 if (FI != ForwardRefVals.end()) {
4043 Value *Sentinel = FI->second.first;
4044 if (Sentinel->getType() != Inst->getType())
4045 return P.error(NameLoc, "instruction forward referenced with type '" +
4046 getTypeString(FI->second.first->getType()) +
4047 "'");
4048
4049 Sentinel->replaceAllUsesWith(Inst);
4050 Sentinel->deleteValue();
4051 ForwardRefVals.erase(FI);
4052 }
4053
4054 // Set the name on the instruction.
4055 Inst->setName(NameStr);
4056
4057 if (Inst->getName() != NameStr)
4058 return P.error(NameLoc, "multiple definition of local value named '" +
4059 NameStr + "'");
4060 return false;
4061}
4062
4063/// getBB - Get a basic block with the specified name or ID, creating a
4064/// forward reference record if needed.
4065BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
4066 LocTy Loc) {
4068 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
4069}
4070
4071BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
4073 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
4074}
4075
4076/// defineBB - Define the specified basic block, which is either named or
4077/// unnamed. If there is an error, this returns null otherwise it returns
4078/// the block being defined.
4079BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
4080 int NameID, LocTy Loc) {
4081 BasicBlock *BB;
4082 if (Name.empty()) {
4083 if (NameID != -1) {
4084 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
4085 return nullptr;
4086 } else {
4087 NameID = NumberedVals.getNext();
4088 }
4089 BB = getBB(NameID, Loc);
4090 if (!BB) {
4091 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
4092 return nullptr;
4093 }
4094 } else {
4095 BB = getBB(Name, Loc);
4096 if (!BB) {
4097 P.error(Loc, "unable to create block named '" + Name + "'");
4098 return nullptr;
4099 }
4100 }
4101
4102 // Move the block to the end of the function. Forward ref'd blocks are
4103 // inserted wherever they happen to be referenced.
4104 F.splice(F.end(), &F, BB->getIterator());
4105
4106 // Remove the block from forward ref sets.
4107 if (Name.empty()) {
4108 ForwardRefValIDs.erase(NameID);
4109 NumberedVals.add(NameID, BB);
4110 } else {
4111 // BB forward references are already in the function symbol table.
4112 ForwardRefVals.erase(Name);
4113 }
4114
4115 return BB;
4116}
4117
4118//===----------------------------------------------------------------------===//
4119// Constants.
4120//===----------------------------------------------------------------------===//
4121
4122/// parseValID - parse an abstract value that doesn't necessarily have a
4123/// type implied. For example, if we parse "4" we don't know what integer type
4124/// it has. The value will later be combined with its type and checked for
4125/// basic correctness. PFS is used to convert function-local operands of
4126/// metadata (since metadata operands are not just parsed here but also
4127/// converted to values). PFS can be null when we are not parsing metadata
4128/// values inside a function.
4129bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
4130 ID.Loc = Lex.getLoc();
4131 switch (Lex.getKind()) {
4132 default:
4133 return tokError("expected value token");
4134 case lltok::GlobalID: // @42
4135 ID.UIntVal = Lex.getUIntVal();
4136 ID.Kind = ValID::t_GlobalID;
4137 break;
4138 case lltok::GlobalVar: // @foo
4139 ID.StrVal = Lex.getStrVal();
4140 ID.Kind = ValID::t_GlobalName;
4141 break;
4142 case lltok::LocalVarID: // %42
4143 ID.UIntVal = Lex.getUIntVal();
4144 ID.Kind = ValID::t_LocalID;
4145 break;
4146 case lltok::LocalVar: // %foo
4147 ID.StrVal = Lex.getStrVal();
4148 ID.Kind = ValID::t_LocalName;
4149 break;
4150 case lltok::APSInt:
4151 ID.APSIntVal = Lex.getAPSIntVal();
4152 ID.Kind = ValID::t_APSInt;
4153 break;
4154 case lltok::APFloat: {
4155 ID.APFloatVal = Lex.getAPFloatVal();
4156 ID.Kind = ValID::t_APFloat;
4157 break;
4158 }
4159 case lltok::FloatLiteral: {
4160 if (!ExpectedTy)
4161 return error(ID.Loc, "unexpected floating-point literal");
4162 if (!ExpectedTy->isFloatingPointTy())
4163 return error(ID.Loc, "floating-point constant invalid for type");
4164 ID.APFloatVal = APFloat(ExpectedTy->getFltSemantics());
4165 auto Except = ID.APFloatVal.convertFromString(
4166 Lex.getStrVal(), RoundingMode::NearestTiesToEven);
4167 assert(Except && "Invalid float strings should be caught by the lexer");
4168 // Forbid overflowing and underflowing literals, but permit inexact
4169 // literals. Underflow is thrown when the result is denormal, so to allow
4170 // denormals, only reject underflowing literals that resulted in a zero.
4171 if (*Except & APFloat::opOverflow)
4172 return error(ID.Loc, "floating-point constant overflowed type");
4173 if ((*Except & APFloat::opUnderflow) && ID.APFloatVal.isZero())
4174 return error(ID.Loc, "floating-point constant underflowed type");
4175 ID.Kind = ValID::t_APFloat;
4176 break;
4177 }
4179 if (!ExpectedTy)
4180 return error(ID.Loc, "unexpected floating-point literal");
4181 const auto &Semantics = ExpectedTy->getFltSemantics();
4182 const APInt &Bits = Lex.getAPSIntVal();
4183 if (APFloat::getSizeInBits(Semantics) != Bits.getBitWidth())
4184 return error(ID.Loc, "float hex literal has incorrect number of bits");
4185 ID.APFloatVal = APFloat(Semantics, Bits);
4186 ID.Kind = ValID::t_APFloat;
4187 break;
4188 }
4189 case lltok::kw_true:
4190 ID.ConstantVal = ConstantInt::getTrue(Context);
4191 ID.Kind = ValID::t_Constant;
4192 break;
4193 case lltok::kw_false:
4194 ID.ConstantVal = ConstantInt::getFalse(Context);
4195 ID.Kind = ValID::t_Constant;
4196 break;
4197 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
4198 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
4199 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
4200 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
4201 case lltok::kw_none: ID.Kind = ValID::t_None; break;
4202
4203 case lltok::lbrace: {
4204 // ValID ::= '{' ConstVector '}'
4205 Lex.Lex();
4207 if (parseGlobalValueVector(Elts) ||
4208 parseToken(lltok::rbrace, "expected end of struct constant"))
4209 return true;
4210
4211 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4212 ID.UIntVal = Elts.size();
4213 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4214 Elts.size() * sizeof(Elts[0]));
4216 return false;
4217 }
4218 case lltok::less: {
4219 // ValID ::= '<' ConstVector '>' --> Vector.
4220 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
4221 Lex.Lex();
4222 bool isPackedStruct = EatIfPresent(lltok::lbrace);
4223
4225 LocTy FirstEltLoc = Lex.getLoc();
4226 if (parseGlobalValueVector(Elts) ||
4227 (isPackedStruct &&
4228 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4229 parseToken(lltok::greater, "expected end of constant"))
4230 return true;
4231
4232 if (isPackedStruct) {
4233 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4234 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4235 Elts.size() * sizeof(Elts[0]));
4236 ID.UIntVal = Elts.size();
4238 return false;
4239 }
4240
4241 if (Elts.empty())
4242 return error(ID.Loc, "constant vector must not be empty");
4243
4244 if (!Elts[0]->getType()->isIntegerTy() && !Elts[0]->getType()->isByteTy() &&
4245 !Elts[0]->getType()->isFloatingPointTy() &&
4246 !Elts[0]->getType()->isPointerTy())
4247 return error(
4248 FirstEltLoc,
4249 "vector elements must have integer, byte, pointer or floating point "
4250 "type");
4251
4252 // Verify that all the vector elements have the same type.
4253 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4254 if (Elts[i]->getType() != Elts[0]->getType())
4255 return error(FirstEltLoc, "vector element #" + Twine(i) +
4256 " is not of type '" +
4257 getTypeString(Elts[0]->getType()));
4258
4259 ID.ConstantVal = ConstantVector::get(Elts);
4260 ID.Kind = ValID::t_Constant;
4261 return false;
4262 }
4263 case lltok::lsquare: { // Array Constant
4264 Lex.Lex();
4266 LocTy FirstEltLoc = Lex.getLoc();
4267 if (parseGlobalValueVector(Elts) ||
4268 parseToken(lltok::rsquare, "expected end of array constant"))
4269 return true;
4270
4271 // Handle empty element.
4272 if (Elts.empty()) {
4273 // Use undef instead of an array because it's inconvenient to determine
4274 // the element type at this point, there being no elements to examine.
4275 ID.Kind = ValID::t_EmptyArray;
4276 return false;
4277 }
4278
4279 if (!Elts[0]->getType()->isFirstClassType())
4280 return error(FirstEltLoc, "invalid array element type: " +
4281 getTypeString(Elts[0]->getType()));
4282
4283 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4284
4285 // Verify all elements are correct type!
4286 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4287 if (Elts[i]->getType() != Elts[0]->getType())
4288 return error(FirstEltLoc, "array element #" + Twine(i) +
4289 " is not of type '" +
4290 getTypeString(Elts[0]->getType()));
4291 }
4292
4293 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4294 ID.Kind = ValID::t_Constant;
4295 return false;
4296 }
4297 case lltok::kw_c: { // c "foo"
4298 Lex.Lex();
4299 ArrayType *ATy = cast<ArrayType>(ExpectedTy);
4300 ID.ConstantVal = ConstantDataArray::getString(
4301 Context, Lex.getStrVal(), false, ATy->getElementType()->isByteTy());
4302 if (parseToken(lltok::StringConstant, "expected string"))
4303 return true;
4304 ID.Kind = ValID::t_Constant;
4305 return false;
4306 }
4307 case lltok::kw_asm: {
4308 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4309 // STRINGCONSTANT
4310 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4311 Lex.Lex();
4312 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4313 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4314 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4315 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4316 parseStringConstant(ID.StrVal) ||
4317 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4318 parseToken(lltok::StringConstant, "expected constraint string"))
4319 return true;
4320 ID.StrVal2 = Lex.getStrVal();
4321 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4322 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4323 ID.Kind = ValID::t_InlineAsm;
4324 return false;
4325 }
4326
4328 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4329 Lex.Lex();
4330
4331 ValID Fn, Label;
4332
4333 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4334 parseValID(Fn, PFS) ||
4335 parseToken(lltok::comma,
4336 "expected comma in block address expression") ||
4337 parseValID(Label, PFS) ||
4338 parseToken(lltok::rparen, "expected ')' in block address expression"))
4339 return true;
4340
4342 return error(Fn.Loc, "expected function name in blockaddress");
4343 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4344 return error(Label.Loc, "expected basic block name in blockaddress");
4345
4346 // Try to find the function (but skip it if it's forward-referenced).
4347 GlobalValue *GV = nullptr;
4348 if (Fn.Kind == ValID::t_GlobalID) {
4349 GV = NumberedVals.get(Fn.UIntVal);
4350 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4351 GV = M->getNamedValue(Fn.StrVal);
4352 }
4353 Function *F = nullptr;
4354 if (GV) {
4355 // Confirm that it's actually a function with a definition.
4356 if (!isa<Function>(GV))
4357 return error(Fn.Loc, "expected function name in blockaddress");
4358 F = cast<Function>(GV);
4359 if (F->isDeclaration())
4360 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4361 }
4362
4363 if (!F) {
4364 // Make a global variable as a placeholder for this reference.
4365 GlobalValue *&FwdRef =
4366 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4367 if (!FwdRef) {
4368 unsigned FwdDeclAS;
4369 if (ExpectedTy) {
4370 // If we know the type that the blockaddress is being assigned to,
4371 // we can use the address space of that type.
4372 if (!ExpectedTy->isPointerTy())
4373 return error(ID.Loc,
4374 "type of blockaddress must be a pointer and not '" +
4375 getTypeString(ExpectedTy) + "'");
4376 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4377 } else if (PFS) {
4378 // Otherwise, we default the address space of the current function.
4379 FwdDeclAS = PFS->getFunction().getAddressSpace();
4380 } else {
4381 llvm_unreachable("Unknown address space for blockaddress");
4382 }
4383 FwdRef = new GlobalVariable(
4384 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4385 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4386 }
4387
4388 ID.ConstantVal = FwdRef;
4389 ID.Kind = ValID::t_Constant;
4390 return false;
4391 }
4392
4393 // We found the function; now find the basic block. Don't use PFS, since we
4394 // might be inside a constant expression.
4395 BasicBlock *BB;
4396 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4397 if (Label.Kind == ValID::t_LocalID)
4398 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4399 else
4400 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4401 if (!BB)
4402 return error(Label.Loc, "referenced value is not a basic block");
4403 } else {
4404 if (Label.Kind == ValID::t_LocalID)
4405 return error(Label.Loc, "cannot take address of numeric label after "
4406 "the function is defined");
4408 F->getValueSymbolTable()->lookup(Label.StrVal));
4409 if (!BB)
4410 return error(Label.Loc, "referenced value is not a basic block");
4411 }
4412
4413 ID.ConstantVal = BlockAddress::get(F, BB);
4414 ID.Kind = ValID::t_Constant;
4415 return false;
4416 }
4417
4419 // ValID ::= 'dso_local_equivalent' @foo
4420 Lex.Lex();
4421
4422 ValID Fn;
4423
4424 if (parseValID(Fn, PFS))
4425 return true;
4426
4428 return error(Fn.Loc,
4429 "expected global value name in dso_local_equivalent");
4430
4431 // Try to find the function (but skip it if it's forward-referenced).
4432 GlobalValue *GV = nullptr;
4433 if (Fn.Kind == ValID::t_GlobalID) {
4434 GV = NumberedVals.get(Fn.UIntVal);
4435 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4436 GV = M->getNamedValue(Fn.StrVal);
4437 }
4438
4439 if (!GV) {
4440 // Make a placeholder global variable as a placeholder for this reference.
4441 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4442 ? ForwardRefDSOLocalEquivalentIDs
4443 : ForwardRefDSOLocalEquivalentNames;
4444 GlobalValue *&FwdRef = FwdRefMap[Fn];
4445 if (!FwdRef) {
4446 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4447 GlobalValue::InternalLinkage, nullptr, "",
4449 }
4450
4451 ID.ConstantVal = FwdRef;
4452 ID.Kind = ValID::t_Constant;
4453 return false;
4454 }
4455
4456 if (!GV->getValueType()->isFunctionTy())
4457 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4458 "in dso_local_equivalent");
4459
4460 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4461 ID.Kind = ValID::t_Constant;
4462 return false;
4463 }
4464
4465 case lltok::kw_no_cfi: {
4466 // ValID ::= 'no_cfi' @foo
4467 Lex.Lex();
4468
4469 if (parseValID(ID, PFS))
4470 return true;
4471
4472 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4473 return error(ID.Loc, "expected global value name in no_cfi");
4474
4475 ID.NoCFI = true;
4476 return false;
4477 }
4478 case lltok::kw_ptrauth: {
4479 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4480 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4481 // )? )? ')'
4482 Lex.Lex();
4483
4484 Constant *Ptr, *Key;
4485 Constant *Disc = nullptr, *AddrDisc = nullptr,
4486 *DeactivationSymbol = nullptr;
4487
4488 if (parseToken(lltok::lparen,
4489 "expected '(' in constant ptrauth expression") ||
4490 parseGlobalTypeAndValue(Ptr) ||
4491 parseToken(lltok::comma,
4492 "expected comma in constant ptrauth expression") ||
4493 parseGlobalTypeAndValue(Key))
4494 return true;
4495 // If present, parse the optional disc/addrdisc/ds.
4496 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(Disc))
4497 return true;
4498 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4499 return true;
4500 if (EatIfPresent(lltok::comma) &&
4501 parseGlobalTypeAndValue(DeactivationSymbol))
4502 return true;
4503 if (parseToken(lltok::rparen,
4504 "expected ')' in constant ptrauth expression"))
4505 return true;
4506
4507 if (!Ptr->getType()->isPointerTy())
4508 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4509
4510 auto *KeyC = dyn_cast<ConstantInt>(Key);
4511 if (!KeyC || KeyC->getBitWidth() != 32)
4512 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4513
4514 ConstantInt *DiscC = nullptr;
4515 if (Disc) {
4516 DiscC = dyn_cast<ConstantInt>(Disc);
4517 if (!DiscC || DiscC->getBitWidth() != 64)
4518 return error(
4519 ID.Loc,
4520 "constant ptrauth integer discriminator must be i64 constant");
4521 } else {
4522 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4523 }
4524
4525 if (AddrDisc) {
4526 if (!AddrDisc->getType()->isPointerTy())
4527 return error(
4528 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4529 } else {
4530 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4531 }
4532
4533 if (!DeactivationSymbol)
4534 DeactivationSymbol =
4536 if (!DeactivationSymbol->getType()->isPointerTy())
4537 return error(ID.Loc,
4538 "constant ptrauth deactivation symbol must be a pointer");
4539
4540 ID.ConstantVal =
4541 ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc, DeactivationSymbol);
4542 ID.Kind = ValID::t_Constant;
4543 return false;
4544 }
4545
4546 case lltok::kw_trunc:
4547 case lltok::kw_bitcast:
4549 case lltok::kw_inttoptr:
4551 case lltok::kw_ptrtoint: {
4552 unsigned Opc = Lex.getUIntVal();
4553 Type *DestTy = nullptr;
4554 Constant *SrcVal;
4555 Lex.Lex();
4556 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4557 parseGlobalTypeAndValue(SrcVal) ||
4558 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4559 parseType(DestTy) ||
4560 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4561 return true;
4562 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4563 return error(ID.Loc, "invalid cast opcode for cast from '" +
4564 getTypeString(SrcVal->getType()) + "' to '" +
4565 getTypeString(DestTy) + "'");
4567 SrcVal, DestTy);
4568 ID.Kind = ValID::t_Constant;
4569 return false;
4570 }
4572 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4574 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4575 case lltok::kw_udiv:
4576 return error(ID.Loc, "udiv constexprs are no longer supported");
4577 case lltok::kw_sdiv:
4578 return error(ID.Loc, "sdiv constexprs are no longer supported");
4579 case lltok::kw_urem:
4580 return error(ID.Loc, "urem constexprs are no longer supported");
4581 case lltok::kw_srem:
4582 return error(ID.Loc, "srem constexprs are no longer supported");
4583 case lltok::kw_fadd:
4584 return error(ID.Loc, "fadd constexprs are no longer supported");
4585 case lltok::kw_fsub:
4586 return error(ID.Loc, "fsub constexprs are no longer supported");
4587 case lltok::kw_fmul:
4588 return error(ID.Loc, "fmul constexprs are no longer supported");
4589 case lltok::kw_fdiv:
4590 return error(ID.Loc, "fdiv constexprs are no longer supported");
4591 case lltok::kw_frem:
4592 return error(ID.Loc, "frem constexprs are no longer supported");
4593 case lltok::kw_and:
4594 return error(ID.Loc, "and constexprs are no longer supported");
4595 case lltok::kw_or:
4596 return error(ID.Loc, "or constexprs are no longer supported");
4597 case lltok::kw_lshr:
4598 return error(ID.Loc, "lshr constexprs are no longer supported");
4599 case lltok::kw_ashr:
4600 return error(ID.Loc, "ashr constexprs are no longer supported");
4601 case lltok::kw_shl:
4602 return error(ID.Loc, "shl constexprs are no longer supported");
4603 case lltok::kw_mul:
4604 return error(ID.Loc, "mul constexprs are no longer supported");
4605 case lltok::kw_fneg:
4606 return error(ID.Loc, "fneg constexprs are no longer supported");
4607 case lltok::kw_select:
4608 return error(ID.Loc, "select constexprs are no longer supported");
4609 case lltok::kw_zext:
4610 return error(ID.Loc, "zext constexprs are no longer supported");
4611 case lltok::kw_sext:
4612 return error(ID.Loc, "sext constexprs are no longer supported");
4613 case lltok::kw_fptrunc:
4614 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4615 case lltok::kw_fpext:
4616 return error(ID.Loc, "fpext constexprs are no longer supported");
4617 case lltok::kw_uitofp:
4618 return error(ID.Loc, "uitofp constexprs are no longer supported");
4619 case lltok::kw_sitofp:
4620 return error(ID.Loc, "sitofp constexprs are no longer supported");
4621 case lltok::kw_fptoui:
4622 return error(ID.Loc, "fptoui constexprs are no longer supported");
4623 case lltok::kw_fptosi:
4624 return error(ID.Loc, "fptosi constexprs are no longer supported");
4625 case lltok::kw_icmp:
4626 return error(ID.Loc, "icmp constexprs are no longer supported");
4627 case lltok::kw_fcmp:
4628 return error(ID.Loc, "fcmp constexprs are no longer supported");
4629
4630 // Binary Operators.
4631 case lltok::kw_add:
4632 case lltok::kw_sub:
4633 case lltok::kw_xor: {
4634 bool NUW = false;
4635 bool NSW = false;
4636 unsigned Opc = Lex.getUIntVal();
4637 Constant *Val0, *Val1;
4638 Lex.Lex();
4639 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4640 Opc == Instruction::Mul) {
4641 if (EatIfPresent(lltok::kw_nuw))
4642 NUW = true;
4643 if (EatIfPresent(lltok::kw_nsw)) {
4644 NSW = true;
4645 if (EatIfPresent(lltok::kw_nuw))
4646 NUW = true;
4647 }
4648 }
4649 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4650 parseGlobalTypeAndValue(Val0) ||
4651 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4652 parseGlobalTypeAndValue(Val1) ||
4653 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4654 return true;
4655 if (Val0->getType() != Val1->getType())
4656 return error(ID.Loc, "operands of constexpr must have same type");
4657 // Check that the type is valid for the operator.
4658 if (!Val0->getType()->isIntOrIntVectorTy())
4659 return error(ID.Loc,
4660 "constexpr requires integer or integer vector operands");
4661 unsigned Flags = 0;
4664 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4665 ID.Kind = ValID::t_Constant;
4666 return false;
4667 }
4668
4669 case lltok::kw_splat: {
4670 Lex.Lex();
4671 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4672 return true;
4673 Constant *C;
4674 if (parseGlobalTypeAndValue(C))
4675 return true;
4676 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4677 return true;
4678
4679 ID.ConstantVal = C;
4681 return false;
4682 }
4683
4688 unsigned Opc = Lex.getUIntVal();
4690 GEPNoWrapFlags NW;
4691 bool HasInRange = false;
4692 APSInt InRangeStart;
4693 APSInt InRangeEnd;
4694 Type *Ty;
4695 Lex.Lex();
4696
4697 if (Opc == Instruction::GetElementPtr) {
4698 while (true) {
4699 if (EatIfPresent(lltok::kw_inbounds))
4701 else if (EatIfPresent(lltok::kw_nusw))
4703 else if (EatIfPresent(lltok::kw_nuw))
4705 else
4706 break;
4707 }
4708
4709 if (EatIfPresent(lltok::kw_inrange)) {
4710 if (parseToken(lltok::lparen, "expected '('"))
4711 return true;
4712 if (Lex.getKind() != lltok::APSInt)
4713 return tokError("expected integer");
4714 InRangeStart = Lex.getAPSIntVal();
4715 Lex.Lex();
4716 if (parseToken(lltok::comma, "expected ','"))
4717 return true;
4718 if (Lex.getKind() != lltok::APSInt)
4719 return tokError("expected integer");
4720 InRangeEnd = Lex.getAPSIntVal();
4721 Lex.Lex();
4722 if (parseToken(lltok::rparen, "expected ')'"))
4723 return true;
4724 HasInRange = true;
4725 }
4726 }
4727
4728 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4729 return true;
4730
4731 if (Opc == Instruction::GetElementPtr) {
4732 if (parseType(Ty) ||
4733 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4734 return true;
4735 }
4736
4737 if (parseGlobalValueVector(Elts) ||
4738 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4739 return true;
4740
4741 if (Opc == Instruction::GetElementPtr) {
4742 if (Elts.size() == 0 ||
4743 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4744 return error(ID.Loc, "base of getelementptr must be a pointer");
4745
4746 Type *BaseType = Elts[0]->getType();
4747 std::optional<ConstantRange> InRange;
4748 if (HasInRange) {
4749 unsigned IndexWidth =
4750 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4751 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4752 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4753 if (InRangeStart.sge(InRangeEnd))
4754 return error(ID.Loc, "expected end to be larger than start");
4755 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4756 }
4757
4758 unsigned GEPWidth =
4759 BaseType->isVectorTy()
4760 ? cast<FixedVectorType>(BaseType)->getNumElements()
4761 : 0;
4762
4763 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4764 for (Constant *Val : Indices) {
4765 Type *ValTy = Val->getType();
4766 if (!ValTy->isIntOrIntVectorTy())
4767 return error(ID.Loc, "getelementptr index must be an integer");
4768 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4769 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4770 if (GEPWidth && (ValNumEl != GEPWidth))
4771 return error(
4772 ID.Loc,
4773 "getelementptr vector index has a wrong number of elements");
4774 // GEPWidth may have been unknown because the base is a scalar,
4775 // but it is known now.
4776 GEPWidth = ValNumEl;
4777 }
4778 }
4779
4780 SmallPtrSet<Type*, 4> Visited;
4781 if (!Indices.empty() && !Ty->isSized(&Visited))
4782 return error(ID.Loc, "base element of getelementptr must be sized");
4783
4785 return error(ID.Loc, "invalid base element for constant getelementptr");
4786
4787 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4788 return error(ID.Loc, "invalid getelementptr indices");
4789
4790 ID.ConstantVal =
4791 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4792 } else if (Opc == Instruction::ShuffleVector) {
4793 if (Elts.size() != 3)
4794 return error(ID.Loc, "expected three operands to shufflevector");
4795 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4796 return error(ID.Loc, "invalid operands to shufflevector");
4797 SmallVector<int, 16> Mask;
4799 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4800 } else if (Opc == Instruction::ExtractElement) {
4801 if (Elts.size() != 2)
4802 return error(ID.Loc, "expected two operands to extractelement");
4803 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4804 return error(ID.Loc, "invalid extractelement operands");
4805 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4806 } else {
4807 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4808 if (Elts.size() != 3)
4809 return error(ID.Loc, "expected three operands to insertelement");
4810 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4811 return error(ID.Loc, "invalid insertelement operands");
4812 ID.ConstantVal =
4813 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4814 }
4815
4816 ID.Kind = ValID::t_Constant;
4817 return false;
4818 }
4819 }
4820
4821 Lex.Lex();
4822 return false;
4823}
4824
4825/// parseGlobalValue - parse a global value with the specified type.
4826bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4827 C = nullptr;
4828 ValID ID;
4829 Value *V = nullptr;
4830 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4831 convertValIDToValue(Ty, ID, V, nullptr);
4832 if (V && !(C = dyn_cast<Constant>(V)))
4833 return error(ID.Loc, "global values must be constants");
4834 return Parsed;
4835}
4836
4837bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4838 Type *Ty = nullptr;
4839 return parseType(Ty) || parseGlobalValue(Ty, V);
4840}
4841
4842bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4843 C = nullptr;
4844
4845 LocTy KwLoc = Lex.getLoc();
4846 if (!EatIfPresent(lltok::kw_comdat))
4847 return false;
4848
4849 if (EatIfPresent(lltok::lparen)) {
4850 if (Lex.getKind() != lltok::ComdatVar)
4851 return tokError("expected comdat variable");
4852 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4853 Lex.Lex();
4854 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4855 return true;
4856 } else {
4857 if (GlobalName.empty())
4858 return tokError("comdat cannot be unnamed");
4859 C = getComdat(std::string(GlobalName), KwLoc);
4860 }
4861
4862 return false;
4863}
4864
4865/// parseGlobalValueVector
4866/// ::= /*empty*/
4867/// ::= TypeAndValue (',' TypeAndValue)*
4868bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4869 // Empty list.
4870 if (Lex.getKind() == lltok::rbrace ||
4871 Lex.getKind() == lltok::rsquare ||
4872 Lex.getKind() == lltok::greater ||
4873 Lex.getKind() == lltok::rparen)
4874 return false;
4875
4876 do {
4877 // Let the caller deal with inrange.
4878 if (Lex.getKind() == lltok::kw_inrange)
4879 return false;
4880
4881 Constant *C;
4882 if (parseGlobalTypeAndValue(C))
4883 return true;
4884 Elts.push_back(C);
4885 } while (EatIfPresent(lltok::comma));
4886
4887 return false;
4888}
4889
4890bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4892 if (parseMDNodeVector(Elts))
4893 return true;
4894
4895 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4896 return false;
4897}
4898
4899/// MDNode:
4900/// ::= !{ ... }
4901/// ::= !7
4902/// ::= !DILocation(...)
4903bool LLParser::parseMDNode(MDNode *&N) {
4904 if (Lex.getKind() == lltok::MetadataVar)
4905 return parseSpecializedMDNode(N);
4906
4907 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4908}
4909
4910bool LLParser::parseMDNodeTail(MDNode *&N) {
4911 // !{ ... }
4912 if (Lex.getKind() == lltok::lbrace)
4913 return parseMDTuple(N);
4914
4915 // !42
4916 return parseMDNodeID(N);
4917}
4918
4919namespace {
4920
4921/// Structure to represent an optional metadata field.
4922template <class FieldTy> struct MDFieldImpl {
4923 typedef MDFieldImpl ImplTy;
4924 FieldTy Val;
4925 bool Seen;
4926
4927 void assign(FieldTy Val) {
4928 Seen = true;
4929 this->Val = std::move(Val);
4930 }
4931
4932 explicit MDFieldImpl(FieldTy Default)
4933 : Val(std::move(Default)), Seen(false) {}
4934};
4935
4936/// Structure to represent an optional metadata field that
4937/// can be of either type (A or B) and encapsulates the
4938/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4939/// to reimplement the specifics for representing each Field.
4940template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4941 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4942 FieldTypeA A;
4943 FieldTypeB B;
4944 bool Seen;
4945
4946 enum {
4947 IsInvalid = 0,
4948 IsTypeA = 1,
4949 IsTypeB = 2
4950 } WhatIs;
4951
4952 void assign(FieldTypeA A) {
4953 Seen = true;
4954 this->A = std::move(A);
4955 WhatIs = IsTypeA;
4956 }
4957
4958 void assign(FieldTypeB B) {
4959 Seen = true;
4960 this->B = std::move(B);
4961 WhatIs = IsTypeB;
4962 }
4963
4964 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4965 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4966 WhatIs(IsInvalid) {}
4967};
4968
4969struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4970 uint64_t Max;
4971
4972 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4973 : ImplTy(Default), Max(Max) {}
4974};
4975
4976struct LineField : public MDUnsignedField {
4977 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4978};
4979
4980struct ColumnField : public MDUnsignedField {
4981 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4982};
4983
4984struct DwarfTagField : public MDUnsignedField {
4985 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4986 DwarfTagField(dwarf::Tag DefaultTag)
4987 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4988};
4989
4990struct DwarfMacinfoTypeField : public MDUnsignedField {
4991 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4992 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4993 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4994};
4995
4996struct DwarfAttEncodingField : public MDUnsignedField {
4997 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4998};
4999
5000struct DwarfVirtualityField : public MDUnsignedField {
5001 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
5002};
5003
5004struct DwarfLangField : public MDUnsignedField {
5005 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
5006};
5007
5008struct DwarfSourceLangNameField : public MDUnsignedField {
5009 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5010};
5011
5012struct DwarfCCField : public MDUnsignedField {
5013 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
5014};
5015
5016struct DwarfEnumKindField : public MDUnsignedField {
5017 DwarfEnumKindField()
5018 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
5019 dwarf::DW_APPLE_ENUM_KIND_max) {}
5020};
5021
5022struct EmissionKindField : public MDUnsignedField {
5023 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5024};
5025
5026struct FixedPointKindField : public MDUnsignedField {
5027 FixedPointKindField()
5028 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5029};
5030
5031struct NameTableKindField : public MDUnsignedField {
5032 NameTableKindField()
5033 : MDUnsignedField(
5034 0, (unsigned)
5035 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5036};
5037
5038struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
5039 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5040};
5041
5042struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
5043 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5044};
5045
5046struct MDAPSIntField : public MDFieldImpl<APSInt> {
5047 MDAPSIntField() : ImplTy(APSInt()) {}
5048};
5049
5050struct MDSignedField : public MDFieldImpl<int64_t> {
5051 int64_t Min = INT64_MIN;
5052 int64_t Max = INT64_MAX;
5053
5054 MDSignedField(int64_t Default = 0)
5055 : ImplTy(Default) {}
5056 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
5057 : ImplTy(Default), Min(Min), Max(Max) {}
5058};
5059
5060struct MDBoolField : public MDFieldImpl<bool> {
5061 MDBoolField(bool Default = false) : ImplTy(Default) {}
5062};
5063
5064struct MDField : public MDFieldImpl<Metadata *> {
5065 bool AllowNull;
5066
5067 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5068};
5069
5070struct MDStringField : public MDFieldImpl<MDString *> {
5071 enum class EmptyIs {
5072 Null, //< Allow empty input string, map to nullptr
5073 Empty, //< Allow empty input string, map to an empty MDString
5074 Error, //< Disallow empty string, map to an error
5075 } EmptyIs;
5076 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
5077 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5078};
5079
5080struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
5081 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
5082};
5083
5084struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
5085 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
5086};
5087
5088struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5089 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
5090 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
5091
5092 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
5093 bool AllowNull = true)
5094 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
5095
5096 bool isMDSignedField() const { return WhatIs == IsTypeA; }
5097 bool isMDField() const { return WhatIs == IsTypeB; }
5098 int64_t getMDSignedValue() const {
5099 assert(isMDSignedField() && "Wrong field type");
5100 return A.Val;
5101 }
5102 Metadata *getMDFieldValue() const {
5103 assert(isMDField() && "Wrong field type");
5104 return B.Val;
5105 }
5106};
5107
5108struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5109 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
5110 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
5111
5112 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
5113 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
5114
5115 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
5116 bool isMDField() const { return WhatIs == IsTypeB; }
5117 uint64_t getMDUnsignedValue() const {
5118 assert(isMDUnsignedField() && "Wrong field type");
5119 return A.Val;
5120 }
5121 Metadata *getMDFieldValue() const {
5122 assert(isMDField() && "Wrong field type");
5123 return B.Val;
5124 }
5125
5126 Metadata *getValueAsMetadata(LLVMContext &Context) const {
5127 if (isMDUnsignedField())
5129 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
5130 if (isMDField())
5131 return getMDFieldValue();
5132 return nullptr;
5133 }
5134};
5135
5136} // end anonymous namespace
5137
5138namespace llvm {
5139
5140template <>
5141bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
5142 if (Lex.getKind() != lltok::APSInt)
5143 return tokError("expected integer");
5144
5145 Result.assign(Lex.getAPSIntVal());
5146 Lex.Lex();
5147 return false;
5148}
5149
5150template <>
5151bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5152 MDUnsignedField &Result) {
5153 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5154 return tokError("expected unsigned integer");
5155
5156 auto &U = Lex.getAPSIntVal();
5157 if (U.ugt(Result.Max))
5158 return tokError("value for '" + Name + "' too large, limit is " +
5159 Twine(Result.Max));
5160 Result.assign(U.getZExtValue());
5161 assert(Result.Val <= Result.Max && "Expected value in range");
5162 Lex.Lex();
5163 return false;
5164}
5165
5166template <>
5167bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
5168 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5169}
5170template <>
5171bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
5172 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5173}
5174
5175template <>
5176bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
5177 if (Lex.getKind() == lltok::APSInt)
5178 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5179
5180 if (Lex.getKind() != lltok::DwarfTag)
5181 return tokError("expected DWARF tag");
5182
5183 unsigned Tag = dwarf::getTag(Lex.getStrVal());
5185 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
5186 assert(Tag <= Result.Max && "Expected valid DWARF tag");
5187
5188 Result.assign(Tag);
5189 Lex.Lex();
5190 return false;
5191}
5192
5193template <>
5194bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5195 DwarfMacinfoTypeField &Result) {
5196 if (Lex.getKind() == lltok::APSInt)
5197 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5198
5199 if (Lex.getKind() != lltok::DwarfMacinfo)
5200 return tokError("expected DWARF macinfo type");
5201
5202 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
5203 if (Macinfo == dwarf::DW_MACINFO_invalid)
5204 return tokError("invalid DWARF macinfo type" + Twine(" '") +
5205 Lex.getStrVal() + "'");
5206 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
5207
5208 Result.assign(Macinfo);
5209 Lex.Lex();
5210 return false;
5211}
5212
5213template <>
5214bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5215 DwarfVirtualityField &Result) {
5216 if (Lex.getKind() == lltok::APSInt)
5217 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5218
5219 if (Lex.getKind() != lltok::DwarfVirtuality)
5220 return tokError("expected DWARF virtuality code");
5221
5222 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
5223 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5224 return tokError("invalid DWARF virtuality code" + Twine(" '") +
5225 Lex.getStrVal() + "'");
5226 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5227 Result.assign(Virtuality);
5228 Lex.Lex();
5229 return false;
5230}
5231
5232template <>
5233bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5234 DwarfEnumKindField &Result) {
5235 if (Lex.getKind() == lltok::APSInt)
5236 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5237
5238 if (Lex.getKind() != lltok::DwarfEnumKind)
5239 return tokError("expected DWARF enum kind code");
5240
5241 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5242 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5243 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5244 Lex.getStrVal() + "'");
5245 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5246 Result.assign(EnumKind);
5247 Lex.Lex();
5248 return false;
5249}
5250
5251template <>
5252bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5253 if (Lex.getKind() == lltok::APSInt)
5254 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5255
5256 if (Lex.getKind() != lltok::DwarfLang)
5257 return tokError("expected DWARF language");
5258
5259 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5260 if (!Lang)
5261 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5262 "'");
5263 assert(Lang <= Result.Max && "Expected valid DWARF language");
5264 Result.assign(Lang);
5265 Lex.Lex();
5266 return false;
5267}
5268
5269template <>
5270bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5271 DwarfSourceLangNameField &Result) {
5272 if (Lex.getKind() == lltok::APSInt)
5273 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5274
5275 if (Lex.getKind() != lltok::DwarfSourceLangName)
5276 return tokError("expected DWARF source language name");
5277
5278 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5279 if (!Lang)
5280 return tokError("invalid DWARF source language name" + Twine(" '") +
5281 Lex.getStrVal() + "'");
5282 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5283 Result.assign(Lang);
5284 Lex.Lex();
5285 return false;
5286}
5287
5288template <>
5289bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5290 if (Lex.getKind() == lltok::APSInt)
5291 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5292
5293 if (Lex.getKind() != lltok::DwarfCC)
5294 return tokError("expected DWARF calling convention");
5295
5296 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5297 if (!CC)
5298 return tokError("invalid DWARF calling convention" + Twine(" '") +
5299 Lex.getStrVal() + "'");
5300 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5301 Result.assign(CC);
5302 Lex.Lex();
5303 return false;
5304}
5305
5306template <>
5307bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5308 EmissionKindField &Result) {
5309 if (Lex.getKind() == lltok::APSInt)
5310 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5311
5312 if (Lex.getKind() != lltok::EmissionKind)
5313 return tokError("expected emission kind");
5314
5315 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5316 if (!Kind)
5317 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5318 "'");
5319 assert(*Kind <= Result.Max && "Expected valid emission kind");
5320 Result.assign(*Kind);
5321 Lex.Lex();
5322 return false;
5323}
5324
5325template <>
5326bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5327 FixedPointKindField &Result) {
5328 if (Lex.getKind() == lltok::APSInt)
5329 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5330
5331 if (Lex.getKind() != lltok::FixedPointKind)
5332 return tokError("expected fixed-point kind");
5333
5334 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5335 if (!Kind)
5336 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5337 "'");
5338 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5339 Result.assign(*Kind);
5340 Lex.Lex();
5341 return false;
5342}
5343
5344template <>
5345bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5346 NameTableKindField &Result) {
5347 if (Lex.getKind() == lltok::APSInt)
5348 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5349
5350 if (Lex.getKind() != lltok::NameTableKind)
5351 return tokError("expected nameTable kind");
5352
5353 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5354 if (!Kind)
5355 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5356 "'");
5357 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5358 Result.assign((unsigned)*Kind);
5359 Lex.Lex();
5360 return false;
5361}
5362
5363template <>
5364bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5365 DwarfAttEncodingField &Result) {
5366 if (Lex.getKind() == lltok::APSInt)
5367 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5368
5369 if (Lex.getKind() != lltok::DwarfAttEncoding)
5370 return tokError("expected DWARF type attribute encoding");
5371
5372 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5373 if (!Encoding)
5374 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5375 Lex.getStrVal() + "'");
5376 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5377 Result.assign(Encoding);
5378 Lex.Lex();
5379 return false;
5380}
5381
5382/// DIFlagField
5383/// ::= uint32
5384/// ::= DIFlagVector
5385/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5386template <>
5387bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5388
5389 // parser for a single flag.
5390 auto parseFlag = [&](DINode::DIFlags &Val) {
5391 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5392 uint32_t TempVal = static_cast<uint32_t>(Val);
5393 bool Res = parseUInt32(TempVal);
5394 Val = static_cast<DINode::DIFlags>(TempVal);
5395 return Res;
5396 }
5397
5398 if (Lex.getKind() != lltok::DIFlag)
5399 return tokError("expected debug info flag");
5400
5401 Val = DINode::getFlag(Lex.getStrVal());
5402 if (!Val)
5403 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5404 "'");
5405 Lex.Lex();
5406 return false;
5407 };
5408
5409 // parse the flags and combine them together.
5410 DINode::DIFlags Combined = DINode::FlagZero;
5411 do {
5412 DINode::DIFlags Val;
5413 if (parseFlag(Val))
5414 return true;
5415 Combined |= Val;
5416 } while (EatIfPresent(lltok::bar));
5417
5418 Result.assign(Combined);
5419 return false;
5420}
5421
5422/// DISPFlagField
5423/// ::= uint32
5424/// ::= DISPFlagVector
5425/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5426template <>
5427bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5428
5429 // parser for a single flag.
5430 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5431 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5432 uint32_t TempVal = static_cast<uint32_t>(Val);
5433 bool Res = parseUInt32(TempVal);
5434 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5435 return Res;
5436 }
5437
5438 if (Lex.getKind() != lltok::DISPFlag)
5439 return tokError("expected debug info flag");
5440
5441 Val = DISubprogram::getFlag(Lex.getStrVal());
5442 if (!Val)
5443 return tokError(Twine("invalid subprogram debug info flag '") +
5444 Lex.getStrVal() + "'");
5445 Lex.Lex();
5446 return false;
5447 };
5448
5449 // parse the flags and combine them together.
5450 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5451 do {
5453 if (parseFlag(Val))
5454 return true;
5455 Combined |= Val;
5456 } while (EatIfPresent(lltok::bar));
5457
5458 Result.assign(Combined);
5459 return false;
5460}
5461
5462template <>
5463bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5464 if (Lex.getKind() != lltok::APSInt)
5465 return tokError("expected signed integer");
5466
5467 auto &S = Lex.getAPSIntVal();
5468 if (S < Result.Min)
5469 return tokError("value for '" + Name + "' too small, limit is " +
5470 Twine(Result.Min));
5471 if (S > Result.Max)
5472 return tokError("value for '" + Name + "' too large, limit is " +
5473 Twine(Result.Max));
5474 Result.assign(S.getExtValue());
5475 assert(Result.Val >= Result.Min && "Expected value in range");
5476 assert(Result.Val <= Result.Max && "Expected value in range");
5477 Lex.Lex();
5478 return false;
5479}
5480
5481template <>
5482bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5483 switch (Lex.getKind()) {
5484 default:
5485 return tokError("expected 'true' or 'false'");
5486 case lltok::kw_true:
5487 Result.assign(true);
5488 break;
5489 case lltok::kw_false:
5490 Result.assign(false);
5491 break;
5492 }
5493 Lex.Lex();
5494 return false;
5495}
5496
5497template <>
5498bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5499 if (Lex.getKind() == lltok::kw_null) {
5500 if (!Result.AllowNull)
5501 return tokError("'" + Name + "' cannot be null");
5502 Lex.Lex();
5503 Result.assign(nullptr);
5504 return false;
5505 }
5506
5507 Metadata *MD;
5508 if (parseMetadata(MD, nullptr))
5509 return true;
5510
5511 Result.assign(MD);
5512 return false;
5513}
5514
5515template <>
5516bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5517 MDSignedOrMDField &Result) {
5518 // Try to parse a signed int.
5519 if (Lex.getKind() == lltok::APSInt) {
5520 MDSignedField Res = Result.A;
5521 if (!parseMDField(Loc, Name, Res)) {
5522 Result.assign(Res);
5523 return false;
5524 }
5525 return true;
5526 }
5527
5528 // Otherwise, try to parse as an MDField.
5529 MDField Res = Result.B;
5530 if (!parseMDField(Loc, Name, Res)) {
5531 Result.assign(Res);
5532 return false;
5533 }
5534
5535 return true;
5536}
5537
5538template <>
5539bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5540 MDUnsignedOrMDField &Result) {
5541 // Try to parse an unsigned int.
5542 if (Lex.getKind() == lltok::APSInt) {
5543 MDUnsignedField Res = Result.A;
5544 if (!parseMDField(Loc, Name, Res)) {
5545 Result.assign(Res);
5546 return false;
5547 }
5548 return true;
5549 }
5550
5551 // Otherwise, try to parse as an MDField.
5552 MDField Res = Result.B;
5553 if (!parseMDField(Loc, Name, Res)) {
5554 Result.assign(Res);
5555 return false;
5556 }
5557
5558 return true;
5559}
5560
5561template <>
5562bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5563 LocTy ValueLoc = Lex.getLoc();
5564 std::string S;
5565 if (parseStringConstant(S))
5566 return true;
5567
5568 if (S.empty()) {
5569 switch (Result.EmptyIs) {
5570 case MDStringField::EmptyIs::Null:
5571 Result.assign(nullptr);
5572 return false;
5573 case MDStringField::EmptyIs::Empty:
5574 break;
5575 case MDStringField::EmptyIs::Error:
5576 return error(ValueLoc, "'" + Name + "' cannot be empty");
5577 }
5578 }
5579
5580 Result.assign(MDString::get(Context, S));
5581 return false;
5582}
5583
5584template <>
5585bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5587 if (parseMDNodeVector(MDs))
5588 return true;
5589
5590 Result.assign(std::move(MDs));
5591 return false;
5592}
5593
5594template <>
5595bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5596 ChecksumKindField &Result) {
5597 std::optional<DIFile::ChecksumKind> CSKind =
5598 DIFile::getChecksumKind(Lex.getStrVal());
5599
5600 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5601 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5602 "'");
5603
5604 Result.assign(*CSKind);
5605 Lex.Lex();
5606 return false;
5607}
5608
5609} // end namespace llvm
5610
5611template <class ParserTy>
5612bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5613 do {
5614 if (Lex.getKind() != lltok::LabelStr)
5615 return tokError("expected field label here");
5616
5617 if (ParseField())
5618 return true;
5619 } while (EatIfPresent(lltok::comma));
5620
5621 return false;
5622}
5623
5624template <class ParserTy>
5625bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5626 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5627 Lex.Lex();
5628
5629 if (parseToken(lltok::lparen, "expected '(' here"))
5630 return true;
5631 if (Lex.getKind() != lltok::rparen)
5632 if (parseMDFieldsImplBody(ParseField))
5633 return true;
5634
5635 ClosingLoc = Lex.getLoc();
5636 return parseToken(lltok::rparen, "expected ')' here");
5637}
5638
5639template <class FieldTy>
5640bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5641 if (Result.Seen)
5642 return tokError("field '" + Name + "' cannot be specified more than once");
5643
5644 LocTy Loc = Lex.getLoc();
5645 Lex.Lex();
5646 return parseMDField(Loc, Name, Result);
5647}
5648
5649bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5650 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5651
5652#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5653 if (Lex.getStrVal() == #CLASS) \
5654 return parse##CLASS(N, IsDistinct);
5655#include "llvm/IR/Metadata.def"
5656
5657 return tokError("expected metadata type");
5658}
5659
5660#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5661#define NOP_FIELD(NAME, TYPE, INIT)
5662#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5663 if (!NAME.Seen) \
5664 return error(ClosingLoc, "missing required field '" #NAME "'");
5665#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5666 if (Lex.getStrVal() == #NAME) \
5667 return parseMDField(#NAME, NAME);
5668#define PARSE_MD_FIELDS() \
5669 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5670 do { \
5671 LocTy ClosingLoc; \
5672 if (parseMDFieldsImpl( \
5673 [&]() -> bool { \
5674 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5675 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5676 "'"); \
5677 }, \
5678 ClosingLoc)) \
5679 return true; \
5680 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5681 } while (false)
5682#define GET_OR_DISTINCT(CLASS, ARGS) \
5683 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5684
5685/// parseDILocationFields:
5686/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5687/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5688bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5689#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5690 OPTIONAL(line, LineField, ); \
5691 OPTIONAL(column, ColumnField, ); \
5692 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5693 OPTIONAL(inlinedAt, MDField, ); \
5694 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5695 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5696 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5698#undef VISIT_MD_FIELDS
5699
5700 Result = GET_OR_DISTINCT(
5701 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5702 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5703 return false;
5704}
5705
5706/// parseDIAssignID:
5707/// ::= distinct !DIAssignID()
5708bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5709 if (!IsDistinct)
5710 return tokError("missing 'distinct', required for !DIAssignID()");
5711
5712 Lex.Lex();
5713
5714 // Now eat the parens.
5715 if (parseToken(lltok::lparen, "expected '(' here"))
5716 return true;
5717 if (parseToken(lltok::rparen, "expected ')' here"))
5718 return true;
5719
5721 return false;
5722}
5723
5724/// parseGenericDINode:
5725/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5726bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5727#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5728 REQUIRED(tag, DwarfTagField, ); \
5729 OPTIONAL(header, MDStringField, ); \
5730 OPTIONAL(operands, MDFieldList, );
5732#undef VISIT_MD_FIELDS
5733
5734 Result = GET_OR_DISTINCT(GenericDINode,
5735 (Context, tag.Val, header.Val, operands.Val));
5736 return false;
5737}
5738
5739/// parseDISubrangeType:
5740/// ::= !DISubrangeType(name: "whatever", file: !0,
5741/// line: 7, scope: !1, baseType: !2, size: 32,
5742/// align: 32, flags: 0, lowerBound: !3
5743/// upperBound: !4, stride: !5, bias: !6)
5744bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5745#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5746 OPTIONAL(name, MDStringField, ); \
5747 OPTIONAL(file, MDField, ); \
5748 OPTIONAL(line, LineField, ); \
5749 OPTIONAL(scope, MDField, ); \
5750 OPTIONAL(baseType, MDField, ); \
5751 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5752 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5753 OPTIONAL(flags, DIFlagField, ); \
5754 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5755 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5756 OPTIONAL(stride, MDSignedOrMDField, ); \
5757 OPTIONAL(bias, MDSignedOrMDField, );
5759#undef VISIT_MD_FIELDS
5760
5761 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5762 if (Bound.isMDSignedField())
5764 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5765 if (Bound.isMDField())
5766 return Bound.getMDFieldValue();
5767 return nullptr;
5768 };
5769
5770 Metadata *LowerBound = convToMetadata(lowerBound);
5771 Metadata *UpperBound = convToMetadata(upperBound);
5772 Metadata *Stride = convToMetadata(stride);
5773 Metadata *Bias = convToMetadata(bias);
5774
5776 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5777 size.getValueAsMetadata(Context), align.Val, flags.Val,
5778 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5779
5780 return false;
5781}
5782
5783/// parseDISubrange:
5784/// ::= !DISubrange(count: 30, lowerBound: 2)
5785/// ::= !DISubrange(count: !node, lowerBound: 2)
5786/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5787bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5788#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5789 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5790 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5791 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5792 OPTIONAL(stride, MDSignedOrMDField, );
5794#undef VISIT_MD_FIELDS
5795
5796 Metadata *Count = nullptr;
5797 Metadata *LowerBound = nullptr;
5798 Metadata *UpperBound = nullptr;
5799 Metadata *Stride = nullptr;
5800
5801 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5802 if (Bound.isMDSignedField())
5804 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5805 if (Bound.isMDField())
5806 return Bound.getMDFieldValue();
5807 return nullptr;
5808 };
5809
5810 Count = convToMetadata(count);
5811 LowerBound = convToMetadata(lowerBound);
5812 UpperBound = convToMetadata(upperBound);
5813 Stride = convToMetadata(stride);
5814
5815 Result = GET_OR_DISTINCT(DISubrange,
5816 (Context, Count, LowerBound, UpperBound, Stride));
5817
5818 return false;
5819}
5820
5821/// parseDIGenericSubrange:
5822/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5823/// !node3)
5824bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5825#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5826 OPTIONAL(count, MDSignedOrMDField, ); \
5827 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5828 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5829 OPTIONAL(stride, MDSignedOrMDField, );
5831#undef VISIT_MD_FIELDS
5832
5833 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5834 if (Bound.isMDSignedField())
5835 return DIExpression::get(
5836 Context, {dwarf::DW_OP_consts,
5837 static_cast<uint64_t>(Bound.getMDSignedValue())});
5838 if (Bound.isMDField())
5839 return Bound.getMDFieldValue();
5840 return nullptr;
5841 };
5842
5843 Metadata *Count = ConvToMetadata(count);
5844 Metadata *LowerBound = ConvToMetadata(lowerBound);
5845 Metadata *UpperBound = ConvToMetadata(upperBound);
5846 Metadata *Stride = ConvToMetadata(stride);
5847
5848 Result = GET_OR_DISTINCT(DIGenericSubrange,
5849 (Context, Count, LowerBound, UpperBound, Stride));
5850
5851 return false;
5852}
5853
5854/// parseDIEnumerator:
5855/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5856bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5857#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5858 REQUIRED(name, MDStringField, ); \
5859 REQUIRED(value, MDAPSIntField, ); \
5860 OPTIONAL(isUnsigned, MDBoolField, (false));
5862#undef VISIT_MD_FIELDS
5863
5864 if (isUnsigned.Val && value.Val.isNegative())
5865 return tokError("unsigned enumerator with negative value");
5866
5867 APSInt Value(value.Val);
5868 // Add a leading zero so that unsigned values with the msb set are not
5869 // mistaken for negative values when used for signed enumerators.
5870 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5871 Value = Value.zext(Value.getBitWidth() + 1);
5872
5873 Result =
5874 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5875
5876 return false;
5877}
5878
5879/// parseDIBasicType:
5880/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5881/// encoding: DW_ATE_encoding, flags: 0)
5882bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5883#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5884 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5885 OPTIONAL(name, MDStringField, ); \
5886 OPTIONAL(file, MDField, ); \
5887 OPTIONAL(line, LineField, ); \
5888 OPTIONAL(scope, MDField, ); \
5889 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5890 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5891 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5892 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5893 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5894 OPTIONAL(flags, DIFlagField, );
5896#undef VISIT_MD_FIELDS
5897
5899 DIBasicType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5900 size.getValueAsMetadata(Context), align.Val, encoding.Val,
5901 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5902 return false;
5903}
5904
5905/// parseDIFixedPointType:
5906/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5907/// align: 32, encoding: DW_ATE_signed_fixed,
5908/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5909/// denominator: 8)
5910bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5911#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5912 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5913 OPTIONAL(name, MDStringField, ); \
5914 OPTIONAL(file, MDField, ); \
5915 OPTIONAL(line, LineField, ); \
5916 OPTIONAL(scope, MDField, ); \
5917 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5918 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5919 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5920 OPTIONAL(flags, DIFlagField, ); \
5921 OPTIONAL(kind, FixedPointKindField, ); \
5922 OPTIONAL(factor, MDSignedField, ); \
5923 OPTIONAL(numerator, MDAPSIntField, ); \
5924 OPTIONAL(denominator, MDAPSIntField, );
5926#undef VISIT_MD_FIELDS
5927
5928 Result = GET_OR_DISTINCT(DIFixedPointType,
5929 (Context, tag.Val, name.Val, file.Val, line.Val,
5930 scope.Val, size.getValueAsMetadata(Context),
5931 align.Val, encoding.Val, flags.Val, kind.Val,
5932 factor.Val, numerator.Val, denominator.Val));
5933 return false;
5934}
5935
5936/// parseDIStringType:
5937/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5938bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5939#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5940 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5941 OPTIONAL(name, MDStringField, ); \
5942 OPTIONAL(stringLength, MDField, ); \
5943 OPTIONAL(stringLengthExpression, MDField, ); \
5944 OPTIONAL(stringLocationExpression, MDField, ); \
5945 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5946 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5947 OPTIONAL(encoding, DwarfAttEncodingField, );
5949#undef VISIT_MD_FIELDS
5950
5952 DIStringType,
5953 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5954 stringLocationExpression.Val, size.getValueAsMetadata(Context),
5955 align.Val, encoding.Val));
5956 return false;
5957}
5958
5959/// parseDIDerivedType:
5960/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5961/// line: 7, scope: !1, baseType: !2, size: 32,
5962/// align: 32, offset: 0, flags: 0, extraData: !3,
5963/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5964/// ptrAuthIsAddressDiscriminated: true,
5965/// ptrAuthExtraDiscriminator: 0x1234,
5966/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5967/// )
5968bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5969#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5970 REQUIRED(tag, DwarfTagField, ); \
5971 OPTIONAL(name, MDStringField, ); \
5972 OPTIONAL(file, MDField, ); \
5973 OPTIONAL(line, LineField, ); \
5974 OPTIONAL(scope, MDField, ); \
5975 REQUIRED(baseType, MDField, ); \
5976 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5977 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5978 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5979 OPTIONAL(flags, DIFlagField, ); \
5980 OPTIONAL(extraData, MDField, ); \
5981 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5982 OPTIONAL(annotations, MDField, ); \
5983 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5984 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5985 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5986 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5987 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5989#undef VISIT_MD_FIELDS
5990
5991 std::optional<unsigned> DWARFAddressSpace;
5992 if (dwarfAddressSpace.Val != UINT32_MAX)
5993 DWARFAddressSpace = dwarfAddressSpace.Val;
5994 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5995 if (ptrAuthKey.Val)
5996 PtrAuthData.emplace(
5997 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5998 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5999 ptrAuthAuthenticatesNullValues.Val);
6000
6002 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6003 baseType.Val, size.getValueAsMetadata(Context), align.Val,
6004 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6005 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6006 return false;
6007}
6008
6009bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
6010#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6011 REQUIRED(tag, DwarfTagField, ); \
6012 OPTIONAL(name, MDStringField, ); \
6013 OPTIONAL(file, MDField, ); \
6014 OPTIONAL(line, LineField, ); \
6015 OPTIONAL(scope, MDField, ); \
6016 OPTIONAL(baseType, MDField, ); \
6017 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6018 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6019 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6020 OPTIONAL(flags, DIFlagField, ); \
6021 OPTIONAL(elements, MDField, ); \
6022 OPTIONAL(runtimeLang, DwarfLangField, ); \
6023 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6024 OPTIONAL(vtableHolder, MDField, ); \
6025 OPTIONAL(templateParams, MDField, ); \
6026 OPTIONAL(identifier, MDStringField, ); \
6027 OPTIONAL(discriminator, MDField, ); \
6028 OPTIONAL(dataLocation, MDField, ); \
6029 OPTIONAL(associated, MDField, ); \
6030 OPTIONAL(allocated, MDField, ); \
6031 OPTIONAL(rank, MDSignedOrMDField, ); \
6032 OPTIONAL(annotations, MDField, ); \
6033 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6034 OPTIONAL(specification, MDField, ); \
6035 OPTIONAL(bitStride, MDField, );
6037#undef VISIT_MD_FIELDS
6038
6039 Metadata *Rank = nullptr;
6040 if (rank.isMDSignedField())
6042 Type::getInt64Ty(Context), rank.getMDSignedValue()));
6043 else if (rank.isMDField())
6044 Rank = rank.getMDFieldValue();
6045
6046 std::optional<unsigned> EnumKind;
6047 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
6048 EnumKind = enumKind.Val;
6049
6050 // If this has an identifier try to build an ODR type.
6051 if (identifier.Val)
6052 if (auto *CT = DICompositeType::buildODRType(
6053 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
6054 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
6055 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6056 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6057 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6058 dataLocation.Val, associated.Val, allocated.Val, Rank,
6059 annotations.Val, bitStride.Val)) {
6060 Result = CT;
6061 return false;
6062 }
6063
6064 // Create a new node, and save it in the context if it belongs in the type
6065 // map.
6067 DICompositeType,
6068 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
6069 size.getValueAsMetadata(Context), align.Val,
6070 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6071 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6072 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6073 allocated.Val, Rank, annotations.Val, specification.Val,
6074 num_extra_inhabitants.Val, bitStride.Val));
6075 return false;
6076}
6077
6078bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
6079#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6080 OPTIONAL(flags, DIFlagField, ); \
6081 OPTIONAL(cc, DwarfCCField, ); \
6082 REQUIRED(types, MDField, );
6084#undef VISIT_MD_FIELDS
6085
6086 Result = GET_OR_DISTINCT(DISubroutineType,
6087 (Context, flags.Val, cc.Val, types.Val));
6088 return false;
6089}
6090
6091/// parseDIFileType:
6092/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
6093/// checksumkind: CSK_MD5,
6094/// checksum: "000102030405060708090a0b0c0d0e0f",
6095/// source: "source file contents")
6096bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
6097 // The default constructed value for checksumkind is required, but will never
6098 // be used, as the parser checks if the field was actually Seen before using
6099 // the Val.
6100#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6101 REQUIRED(filename, MDStringField, ); \
6102 REQUIRED(directory, MDStringField, ); \
6103 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6104 OPTIONAL(checksum, MDStringField, ); \
6105 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6107#undef VISIT_MD_FIELDS
6108
6109 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6110 if (checksumkind.Seen && checksum.Seen)
6111 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6112 else if (checksumkind.Seen || checksum.Seen)
6113 return tokError("'checksumkind' and 'checksum' must be provided together");
6114
6115 MDString *Source = nullptr;
6116 if (source.Seen)
6117 Source = source.Val;
6119 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
6120 return false;
6121}
6122
6123/// parseDICompileUnit:
6124/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
6125/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
6126/// splitDebugFilename: "abc.debug",
6127/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
6128/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
6129/// sysroot: "/", sdk: "MacOSX.sdk")
6130bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
6131 if (!IsDistinct)
6132 return tokError("missing 'distinct', required for !DICompileUnit");
6133
6134 LocTy Loc = Lex.getLoc();
6135
6136#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6137 REQUIRED(file, MDField, (/* AllowNull */ false)); \
6138 OPTIONAL(language, DwarfLangField, ); \
6139 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6140 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6141 OPTIONAL(producer, MDStringField, ); \
6142 OPTIONAL(isOptimized, MDBoolField, ); \
6143 OPTIONAL(flags, MDStringField, ); \
6144 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6145 OPTIONAL(splitDebugFilename, MDStringField, ); \
6146 OPTIONAL(emissionKind, EmissionKindField, ); \
6147 OPTIONAL(enums, MDField, ); \
6148 OPTIONAL(retainedTypes, MDField, ); \
6149 OPTIONAL(globals, MDField, ); \
6150 OPTIONAL(imports, MDField, ); \
6151 OPTIONAL(macros, MDField, ); \
6152 OPTIONAL(dwoId, MDUnsignedField, ); \
6153 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6154 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6155 OPTIONAL(nameTableKind, NameTableKindField, ); \
6156 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6157 OPTIONAL(sysroot, MDStringField, ); \
6158 OPTIONAL(sdk, MDStringField, );
6160#undef VISIT_MD_FIELDS
6161
6162 if (!language.Seen && !sourceLanguageName.Seen)
6163 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
6164 "required for !DICompileUnit");
6165
6166 if (language.Seen && sourceLanguageName.Seen)
6167 return error(Loc, "can only specify one of 'language' and "
6168 "'sourceLanguageName' on !DICompileUnit");
6169
6170 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6171 return error(Loc, "'sourceLanguageVersion' requires an associated "
6172 "'sourceLanguageName' on !DICompileUnit");
6173
6175 Context,
6176 language.Seen ? DISourceLanguageName(language.Val)
6177 : DISourceLanguageName(sourceLanguageName.Val,
6178 sourceLanguageVersion.Val),
6179 file.Val, producer.Val, isOptimized.Val, flags.Val, runtimeVersion.Val,
6180 splitDebugFilename.Val, emissionKind.Val, enums.Val, retainedTypes.Val,
6181 globals.Val, imports.Val, macros.Val, dwoId.Val, splitDebugInlining.Val,
6182 debugInfoForProfiling.Val, nameTableKind.Val, rangesBaseAddress.Val,
6183 sysroot.Val, sdk.Val);
6184 return false;
6185}
6186
6187/// parseDISubprogram:
6188/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
6189/// file: !1, line: 7, type: !2, isLocal: false,
6190/// isDefinition: true, scopeLine: 8, containingType: !3,
6191/// virtuality: DW_VIRTUALTIY_pure_virtual,
6192/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
6193/// spFlags: 10, isOptimized: false, templateParams: !4,
6194/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
6195/// annotations: !8)
6196bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
6197 auto Loc = Lex.getLoc();
6198#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6199 OPTIONAL(scope, MDField, ); \
6200 OPTIONAL(name, MDStringField, ); \
6201 OPTIONAL(linkageName, MDStringField, ); \
6202 OPTIONAL(file, MDField, ); \
6203 OPTIONAL(line, LineField, ); \
6204 OPTIONAL(type, MDField, ); \
6205 OPTIONAL(isLocal, MDBoolField, ); \
6206 OPTIONAL(isDefinition, MDBoolField, (true)); \
6207 OPTIONAL(scopeLine, LineField, ); \
6208 OPTIONAL(containingType, MDField, ); \
6209 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6210 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6211 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6212 OPTIONAL(flags, DIFlagField, ); \
6213 OPTIONAL(spFlags, DISPFlagField, ); \
6214 OPTIONAL(isOptimized, MDBoolField, ); \
6215 OPTIONAL(unit, MDField, ); \
6216 OPTIONAL(templateParams, MDField, ); \
6217 OPTIONAL(declaration, MDField, ); \
6218 OPTIONAL(retainedNodes, MDField, ); \
6219 OPTIONAL(thrownTypes, MDField, ); \
6220 OPTIONAL(annotations, MDField, ); \
6221 OPTIONAL(targetFuncName, MDStringField, ); \
6222 OPTIONAL(keyInstructions, MDBoolField, );
6224#undef VISIT_MD_FIELDS
6225
6226 // An explicit spFlags field takes precedence over individual fields in
6227 // older IR versions.
6228 DISubprogram::DISPFlags SPFlags =
6229 spFlags.Seen ? spFlags.Val
6230 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
6231 isOptimized.Val, virtuality.Val);
6232 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6233 return error(
6234 Loc,
6235 "missing 'distinct', required for !DISubprogram that is a Definition");
6237 DISubprogram,
6238 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6239 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6240 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6241 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6242 targetFuncName.Val, keyInstructions.Val));
6243
6244 if (IsDistinct)
6245 NewDistinctSPs.push_back(cast<DISubprogram>(Result));
6246
6247 return false;
6248}
6249
6250/// parseDILexicalBlock:
6251/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6252bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6253#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6254 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6255 OPTIONAL(file, MDField, ); \
6256 OPTIONAL(line, LineField, ); \
6257 OPTIONAL(column, ColumnField, );
6259#undef VISIT_MD_FIELDS
6260
6262 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6263 return false;
6264}
6265
6266/// parseDILexicalBlockFile:
6267/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6268bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6269#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6270 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6271 OPTIONAL(file, MDField, ); \
6272 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6274#undef VISIT_MD_FIELDS
6275
6276 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6277 (Context, scope.Val, file.Val, discriminator.Val));
6278 return false;
6279}
6280
6281/// parseDICommonBlock:
6282/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6283bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6284#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6285 REQUIRED(scope, MDField, ); \
6286 OPTIONAL(declaration, MDField, ); \
6287 OPTIONAL(name, MDStringField, ); \
6288 OPTIONAL(file, MDField, ); \
6289 OPTIONAL(line, LineField, );
6291#undef VISIT_MD_FIELDS
6292
6293 Result = GET_OR_DISTINCT(DICommonBlock,
6294 (Context, scope.Val, declaration.Val, name.Val,
6295 file.Val, line.Val));
6296 return false;
6297}
6298
6299/// parseDINamespace:
6300/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6301bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6302#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6303 REQUIRED(scope, MDField, ); \
6304 OPTIONAL(name, MDStringField, ); \
6305 OPTIONAL(exportSymbols, MDBoolField, );
6307#undef VISIT_MD_FIELDS
6308
6309 Result = GET_OR_DISTINCT(DINamespace,
6310 (Context, scope.Val, name.Val, exportSymbols.Val));
6311 return false;
6312}
6313
6314/// parseDIMacro:
6315/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6316/// "SomeValue")
6317bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6318#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6319 REQUIRED(type, DwarfMacinfoTypeField, ); \
6320 OPTIONAL(line, LineField, ); \
6321 REQUIRED(name, MDStringField, ); \
6322 OPTIONAL(value, MDStringField, );
6324#undef VISIT_MD_FIELDS
6325
6326 Result = GET_OR_DISTINCT(DIMacro,
6327 (Context, type.Val, line.Val, name.Val, value.Val));
6328 return false;
6329}
6330
6331/// parseDIMacroFile:
6332/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6333bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6334#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6335 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6336 OPTIONAL(line, LineField, ); \
6337 REQUIRED(file, MDField, ); \
6338 OPTIONAL(nodes, MDField, );
6340#undef VISIT_MD_FIELDS
6341
6342 Result = GET_OR_DISTINCT(DIMacroFile,
6343 (Context, type.Val, line.Val, file.Val, nodes.Val));
6344 return false;
6345}
6346
6347/// parseDIModule:
6348/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6349/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6350/// file: !1, line: 4, isDecl: false)
6351bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6352#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6353 REQUIRED(scope, MDField, ); \
6354 REQUIRED(name, MDStringField, ); \
6355 OPTIONAL(configMacros, MDStringField, ); \
6356 OPTIONAL(includePath, MDStringField, ); \
6357 OPTIONAL(apinotes, MDStringField, ); \
6358 OPTIONAL(file, MDField, ); \
6359 OPTIONAL(line, LineField, ); \
6360 OPTIONAL(isDecl, MDBoolField, );
6362#undef VISIT_MD_FIELDS
6363
6364 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6365 configMacros.Val, includePath.Val,
6366 apinotes.Val, line.Val, isDecl.Val));
6367 return false;
6368}
6369
6370/// parseDITemplateTypeParameter:
6371/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6372bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6373#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6374 OPTIONAL(name, MDStringField, ); \
6375 REQUIRED(type, MDField, ); \
6376 OPTIONAL(defaulted, MDBoolField, );
6378#undef VISIT_MD_FIELDS
6379
6380 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6381 (Context, name.Val, type.Val, defaulted.Val));
6382 return false;
6383}
6384
6385/// parseDITemplateValueParameter:
6386/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6387/// name: "V", type: !1, defaulted: false,
6388/// value: i32 7)
6389bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6390#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6391 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6392 OPTIONAL(name, MDStringField, ); \
6393 OPTIONAL(type, MDField, ); \
6394 OPTIONAL(defaulted, MDBoolField, ); \
6395 REQUIRED(value, MDField, );
6396
6398#undef VISIT_MD_FIELDS
6399
6401 DITemplateValueParameter,
6402 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6403 return false;
6404}
6405
6406/// parseDIGlobalVariable:
6407/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6408/// file: !1, line: 7, type: !2, isLocal: false,
6409/// isDefinition: true, templateParams: !3,
6410/// declaration: !4, align: 8)
6411bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6412#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6413 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6414 OPTIONAL(scope, MDField, ); \
6415 OPTIONAL(linkageName, MDStringField, ); \
6416 OPTIONAL(file, MDField, ); \
6417 OPTIONAL(line, LineField, ); \
6418 OPTIONAL(type, MDField, ); \
6419 OPTIONAL(isLocal, MDBoolField, ); \
6420 OPTIONAL(isDefinition, MDBoolField, (true)); \
6421 OPTIONAL(templateParams, MDField, ); \
6422 OPTIONAL(declaration, MDField, ); \
6423 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6424 OPTIONAL(annotations, MDField, );
6426#undef VISIT_MD_FIELDS
6427
6428 Result =
6429 GET_OR_DISTINCT(DIGlobalVariable,
6430 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6431 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6432 declaration.Val, templateParams.Val, align.Val,
6433 annotations.Val));
6434 return false;
6435}
6436
6437/// parseDILocalVariable:
6438/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6439/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6440/// align: 8)
6441/// ::= !DILocalVariable(scope: !0, name: "foo",
6442/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6443/// align: 8)
6444bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6445#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6446 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6447 OPTIONAL(name, MDStringField, ); \
6448 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6449 OPTIONAL(file, MDField, ); \
6450 OPTIONAL(line, LineField, ); \
6451 OPTIONAL(type, MDField, ); \
6452 OPTIONAL(flags, DIFlagField, ); \
6453 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6454 OPTIONAL(annotations, MDField, );
6456#undef VISIT_MD_FIELDS
6457
6458 Result = GET_OR_DISTINCT(DILocalVariable,
6459 (Context, scope.Val, name.Val, file.Val, line.Val,
6460 type.Val, arg.Val, flags.Val, align.Val,
6461 annotations.Val));
6462 return false;
6463}
6464
6465/// parseDILabel:
6466/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6467bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6468#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6469 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6470 REQUIRED(name, MDStringField, ); \
6471 REQUIRED(file, MDField, ); \
6472 REQUIRED(line, LineField, ); \
6473 OPTIONAL(column, ColumnField, ); \
6474 OPTIONAL(isArtificial, MDBoolField, ); \
6475 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6477#undef VISIT_MD_FIELDS
6478
6479 std::optional<unsigned> CoroSuspendIdx =
6480 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6481 : std::nullopt;
6482
6483 Result = GET_OR_DISTINCT(DILabel,
6484 (Context, scope.Val, name.Val, file.Val, line.Val,
6485 column.Val, isArtificial.Val, CoroSuspendIdx));
6486 return false;
6487}
6488
6489/// parseDIExpressionBody:
6490/// ::= (0, 7, -1)
6491bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6492 if (parseToken(lltok::lparen, "expected '(' here"))
6493 return true;
6494
6495 SmallVector<uint64_t, 8> Elements;
6496 if (Lex.getKind() != lltok::rparen)
6497 do {
6498 if (Lex.getKind() == lltok::DwarfOp) {
6499 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6500 Lex.Lex();
6501 Elements.push_back(Op);
6502 continue;
6503 }
6504 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6505 }
6506
6507 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6508 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6509 Lex.Lex();
6510 Elements.push_back(Op);
6511 continue;
6512 }
6513 return tokError(Twine("invalid DWARF attribute encoding '") +
6514 Lex.getStrVal() + "'");
6515 }
6516
6517 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6518 return tokError("expected unsigned integer");
6519
6520 auto &U = Lex.getAPSIntVal();
6521 if (U.ugt(UINT64_MAX))
6522 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6523 Elements.push_back(U.getZExtValue());
6524 Lex.Lex();
6525 } while (EatIfPresent(lltok::comma));
6526
6527 if (parseToken(lltok::rparen, "expected ')' here"))
6528 return true;
6529
6530 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6531 return false;
6532}
6533
6534/// parseDIExpression:
6535/// ::= !DIExpression(0, 7, -1)
6536bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6537 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6538 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6539 Lex.Lex();
6540
6541 return parseDIExpressionBody(Result, IsDistinct);
6542}
6543
6544/// ParseDIArgList:
6545/// ::= !DIArgList(i32 7, i64 %0)
6546bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6547 assert(PFS && "Expected valid function state");
6548 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6549 Lex.Lex();
6550
6551 if (parseToken(lltok::lparen, "expected '(' here"))
6552 return true;
6553
6555 if (Lex.getKind() != lltok::rparen)
6556 do {
6557 Metadata *MD;
6558 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6559 return true;
6560 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6561 } while (EatIfPresent(lltok::comma));
6562
6563 if (parseToken(lltok::rparen, "expected ')' here"))
6564 return true;
6565
6566 MD = DIArgList::get(Context, Args);
6567 return false;
6568}
6569
6570/// parseDIGlobalVariableExpression:
6571/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6572bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6573 bool IsDistinct) {
6574#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6575 REQUIRED(var, MDField, ); \
6576 REQUIRED(expr, MDField, );
6578#undef VISIT_MD_FIELDS
6579
6580 Result =
6581 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6582 return false;
6583}
6584
6585/// parseDIObjCProperty:
6586/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6587/// getter: "getFoo", attributes: 7, type: !2)
6588bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6589#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6590 OPTIONAL(name, MDStringField, ); \
6591 OPTIONAL(file, MDField, ); \
6592 OPTIONAL(line, LineField, ); \
6593 OPTIONAL(setter, MDStringField, ); \
6594 OPTIONAL(getter, MDStringField, ); \
6595 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6596 OPTIONAL(type, MDField, );
6598#undef VISIT_MD_FIELDS
6599
6600 Result = GET_OR_DISTINCT(DIObjCProperty,
6601 (Context, name.Val, file.Val, line.Val, getter.Val,
6602 setter.Val, attributes.Val, type.Val));
6603 return false;
6604}
6605
6606/// parseDIImportedEntity:
6607/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6608/// line: 7, name: "foo", elements: !2)
6609bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6610#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6611 REQUIRED(tag, DwarfTagField, ); \
6612 REQUIRED(scope, MDField, ); \
6613 OPTIONAL(entity, MDField, ); \
6614 OPTIONAL(file, MDField, ); \
6615 OPTIONAL(line, LineField, ); \
6616 OPTIONAL(name, MDStringField, ); \
6617 OPTIONAL(elements, MDField, );
6619#undef VISIT_MD_FIELDS
6620
6621 Result = GET_OR_DISTINCT(DIImportedEntity,
6622 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6623 line.Val, name.Val, elements.Val));
6624 return false;
6625}
6626
6627#undef PARSE_MD_FIELD
6628#undef NOP_FIELD
6629#undef REQUIRE_FIELD
6630#undef DECLARE_FIELD
6631
6632/// parseMetadataAsValue
6633/// ::= metadata i32 %local
6634/// ::= metadata i32 @global
6635/// ::= metadata i32 7
6636/// ::= metadata !0
6637/// ::= metadata !{...}
6638/// ::= metadata !"string"
6639bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6640 // Note: the type 'metadata' has already been parsed.
6641 Metadata *MD;
6642 if (parseMetadata(MD, &PFS))
6643 return true;
6644
6645 V = MetadataAsValue::get(Context, MD);
6646 return false;
6647}
6648
6649/// parseValueAsMetadata
6650/// ::= i32 %local
6651/// ::= i32 @global
6652/// ::= i32 7
6653bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6654 PerFunctionState *PFS) {
6655 Type *Ty;
6656 LocTy Loc;
6657 if (parseType(Ty, TypeMsg, Loc))
6658 return true;
6659 if (Ty->isMetadataTy())
6660 return error(Loc, "invalid metadata-value-metadata roundtrip");
6661
6662 Value *V;
6663 if (parseValue(Ty, V, PFS))
6664 return true;
6665
6666 MD = ValueAsMetadata::get(V);
6667 return false;
6668}
6669
6670/// parseMetadata
6671/// ::= i32 %local
6672/// ::= i32 @global
6673/// ::= i32 7
6674/// ::= !42
6675/// ::= !{...}
6676/// ::= !"string"
6677/// ::= !DILocation(...)
6678bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6679 if (Lex.getKind() == lltok::MetadataVar) {
6680 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6681 // so parsing this requires a Function State.
6682 if (Lex.getStrVal() == "DIArgList") {
6683 Metadata *AL;
6684 if (parseDIArgList(AL, PFS))
6685 return true;
6686 MD = AL;
6687 return false;
6688 }
6689 MDNode *N;
6690 if (parseSpecializedMDNode(N)) {
6691 return true;
6692 }
6693 MD = N;
6694 return false;
6695 }
6696
6697 // ValueAsMetadata:
6698 // <type> <value>
6699 if (Lex.getKind() != lltok::exclaim)
6700 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6701
6702 // '!'.
6703 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6704 Lex.Lex();
6705
6706 // MDString:
6707 // ::= '!' STRINGCONSTANT
6708 if (Lex.getKind() == lltok::StringConstant) {
6709 MDString *S;
6710 if (parseMDString(S))
6711 return true;
6712 MD = S;
6713 return false;
6714 }
6715
6716 // MDNode:
6717 // !{ ... }
6718 // !7
6719 MDNode *N;
6720 if (parseMDNodeTail(N))
6721 return true;
6722 MD = N;
6723 return false;
6724}
6725
6726//===----------------------------------------------------------------------===//
6727// Function Parsing.
6728//===----------------------------------------------------------------------===//
6729
6730bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6731 PerFunctionState *PFS) {
6732 if (Ty->isFunctionTy())
6733 return error(ID.Loc, "functions are not values, refer to them as pointers");
6734
6735 switch (ID.Kind) {
6736 case ValID::t_LocalID:
6737 if (!PFS)
6738 return error(ID.Loc, "invalid use of function-local name");
6739 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6740 return V == nullptr;
6741 case ValID::t_LocalName:
6742 if (!PFS)
6743 return error(ID.Loc, "invalid use of function-local name");
6744 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6745 return V == nullptr;
6746 case ValID::t_InlineAsm: {
6747 if (!ID.FTy)
6748 return error(ID.Loc, "invalid type for inline asm constraint string");
6749 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6750 return error(ID.Loc, toString(std::move(Err)));
6751 V = InlineAsm::get(
6752 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6753 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6754 return false;
6755 }
6757 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6758 if (V && ID.NoCFI)
6760 return V == nullptr;
6761 case ValID::t_GlobalID:
6762 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6763 if (V && ID.NoCFI)
6765 return V == nullptr;
6766 case ValID::t_APSInt:
6767 if (!Ty->isIntegerTy() && !Ty->isByteTy())
6768 return error(ID.Loc, "integer/byte constant must have integer/byte type");
6769 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6770 Ty->isIntegerTy() ? V = ConstantInt::get(Context, ID.APSIntVal)
6771 : V = ConstantByte::get(Context, ID.APSIntVal);
6772 return false;
6773 case ValID::t_APFloat:
6774 if (!Ty->isFloatingPointTy() ||
6775 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6776 return error(ID.Loc, "floating point constant invalid for type");
6777
6778 // The lexer has no type info, so builds all half, bfloat, float, and double
6779 // FP constants as double. Fix this here. Long double does not need this.
6780 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6781 // Check for signaling before potentially converting and losing that info.
6782 bool IsSNAN = ID.APFloatVal.isSignaling();
6783 bool Ignored;
6784 if (Ty->isHalfTy())
6785 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6786 &Ignored);
6787 else if (Ty->isBFloatTy())
6788 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6789 &Ignored);
6790 else if (Ty->isFloatTy())
6791 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6792 &Ignored);
6793 if (IsSNAN) {
6794 // The convert call above may quiet an SNaN, so manufacture another
6795 // SNaN. The bitcast works because the payload (significand) parameter
6796 // is truncated to fit.
6797 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6798 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6799 ID.APFloatVal.isNegative(), &Payload);
6800 }
6801 }
6802 V = ConstantFP::get(Context, ID.APFloatVal);
6803
6804 if (V->getType() != Ty)
6805 return error(ID.Loc, "floating point constant does not have type '" +
6806 getTypeString(Ty) + "'");
6807
6808 return false;
6809 case ValID::t_Null:
6810 if (!Ty->isPointerTy())
6811 return error(ID.Loc, "null must be a pointer type");
6813 return false;
6814 case ValID::t_Undef:
6815 // FIXME: LabelTy should not be a first-class type.
6816 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6817 return error(ID.Loc, "invalid type for undef constant");
6818 V = UndefValue::get(Ty);
6819 return false;
6821 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6822 return error(ID.Loc, "invalid empty array initializer");
6823 V = PoisonValue::get(Ty);
6824 return false;
6825 case ValID::t_Zero:
6826 // FIXME: LabelTy should not be a first-class type.
6827 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6828 return error(ID.Loc, "invalid type for null constant");
6829 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6830 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6831 return error(ID.Loc, "invalid type for null constant");
6833 return false;
6834 case ValID::t_None:
6835 if (!Ty->isTokenTy())
6836 return error(ID.Loc, "invalid type for none constant");
6838 return false;
6839 case ValID::t_Poison:
6840 // FIXME: LabelTy should not be a first-class type.
6841 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6842 return error(ID.Loc, "invalid type for poison constant");
6843 V = PoisonValue::get(Ty);
6844 return false;
6845 case ValID::t_Constant:
6846 if (ID.ConstantVal->getType() != Ty)
6847 return error(ID.Loc, "constant expression type mismatch: got type '" +
6848 getTypeString(ID.ConstantVal->getType()) +
6849 "' but expected '" + getTypeString(Ty) + "'");
6850 V = ID.ConstantVal;
6851 return false;
6853 if (!Ty->isVectorTy())
6854 return error(ID.Loc, "vector constant must have vector type");
6855 if (ID.ConstantVal->getType() != Ty->getScalarType())
6856 return error(ID.Loc, "constant expression type mismatch: got type '" +
6857 getTypeString(ID.ConstantVal->getType()) +
6858 "' but expected '" +
6859 getTypeString(Ty->getScalarType()) + "'");
6860 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6861 ID.ConstantVal);
6862 return false;
6865 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6866 if (ST->getNumElements() != ID.UIntVal)
6867 return error(ID.Loc,
6868 "initializer with struct type has wrong # elements");
6869 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6870 return error(ID.Loc, "packed'ness of initializer and type don't match");
6871
6872 // Verify that the elements are compatible with the structtype.
6873 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6874 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6875 return error(
6876 ID.Loc,
6877 "element " + Twine(i) +
6878 " of struct initializer doesn't match struct element type");
6879
6881 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6882 } else
6883 return error(ID.Loc, "constant expression type mismatch");
6884 return false;
6885 }
6886 llvm_unreachable("Invalid ValID");
6887}
6888
6889bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6890 C = nullptr;
6891 ValID ID;
6892 auto Loc = Lex.getLoc();
6893 if (parseValID(ID, /*PFS=*/nullptr, /*ExpectedTy=*/Ty))
6894 return true;
6895 switch (ID.Kind) {
6896 case ValID::t_APSInt:
6897 case ValID::t_APFloat:
6898 case ValID::t_Undef:
6899 case ValID::t_Poison:
6900 case ValID::t_Zero:
6901 case ValID::t_Constant:
6905 Value *V;
6906 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6907 return true;
6908 assert(isa<Constant>(V) && "Expected a constant value");
6909 C = cast<Constant>(V);
6910 return false;
6911 }
6912 case ValID::t_Null:
6914 return false;
6915 default:
6916 return error(Loc, "expected a constant value");
6917 }
6918}
6919
6920bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6921 V = nullptr;
6922 ValID ID;
6923
6924 FileLoc Start = getTokLineColumnPos();
6925 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
6926 if (!Ret && ParserContext) {
6927 FileLoc End = getPrevTokEndLineColumnPos();
6928 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
6929 }
6930 return Ret;
6931}
6932
6933bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6934 Type *Ty = nullptr;
6935 return parseType(Ty) || parseValue(Ty, V, PFS);
6936}
6937
6938bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6939 PerFunctionState &PFS) {
6940 Value *V;
6941 Loc = Lex.getLoc();
6942 if (parseTypeAndValue(V, PFS))
6943 return true;
6944 if (!isa<BasicBlock>(V))
6945 return error(Loc, "expected a basic block");
6946 BB = cast<BasicBlock>(V);
6947 return false;
6948}
6949
6951 // Exit early for the common (non-debug-intrinsic) case.
6952 // We can make this the only check when we begin supporting all "llvm.dbg"
6953 // intrinsics in the new debug info format.
6954 if (!Name.starts_with("llvm.dbg."))
6955 return false;
6957 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6958 FnID == Intrinsic::dbg_assign;
6959}
6960
6961/// FunctionHeader
6962/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6963/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6964/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6965/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6966bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6967 unsigned &FunctionNumber,
6968 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6969 // parse the linkage.
6970 LocTy LinkageLoc = Lex.getLoc();
6971 unsigned Linkage;
6972 unsigned Visibility;
6973 unsigned DLLStorageClass;
6974 bool DSOLocal;
6975 AttrBuilder RetAttrs(M->getContext());
6976 unsigned CC;
6977 bool HasLinkage;
6978 Type *RetType = nullptr;
6979 LocTy RetTypeLoc = Lex.getLoc();
6980 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6981 DSOLocal) ||
6982 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6983 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6984 return true;
6985
6986 // Verify that the linkage is ok.
6989 break; // always ok.
6991 if (IsDefine)
6992 return error(LinkageLoc, "invalid linkage for function definition");
6993 break;
7001 if (!IsDefine)
7002 return error(LinkageLoc, "invalid linkage for function declaration");
7003 break;
7006 return error(LinkageLoc, "invalid function linkage type");
7007 }
7008
7009 if (!isValidVisibilityForLinkage(Visibility, Linkage))
7010 return error(LinkageLoc,
7011 "symbol with local linkage must have default visibility");
7012
7013 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
7014 return error(LinkageLoc,
7015 "symbol with local linkage cannot have a DLL storage class");
7016
7017 if (!FunctionType::isValidReturnType(RetType))
7018 return error(RetTypeLoc, "invalid function return type");
7019
7020 LocTy NameLoc = Lex.getLoc();
7021
7022 std::string FunctionName;
7023 if (Lex.getKind() == lltok::GlobalVar) {
7024 FunctionName = Lex.getStrVal();
7025 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
7026 FunctionNumber = Lex.getUIntVal();
7027 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
7028 FunctionNumber))
7029 return true;
7030 } else {
7031 return tokError("expected function name");
7032 }
7033
7034 Lex.Lex();
7035
7036 if (Lex.getKind() != lltok::lparen)
7037 return tokError("expected '(' in function argument list");
7038
7040 bool IsVarArg;
7041 AttrBuilder FuncAttrs(M->getContext());
7042 std::vector<unsigned> FwdRefAttrGrps;
7043 LocTy BuiltinLoc;
7044 std::string Section;
7045 std::string Partition;
7046 MaybeAlign Alignment, PrefAlignment;
7047 std::string GC;
7049 unsigned AddrSpace = 0;
7050 Constant *Prefix = nullptr;
7051 Constant *Prologue = nullptr;
7052 Constant *PersonalityFn = nullptr;
7053 Comdat *C;
7054
7055 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7056 parseOptionalUnnamedAddr(UnnamedAddr) ||
7057 parseOptionalProgramAddrSpace(AddrSpace) ||
7058 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
7059 BuiltinLoc) ||
7060 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
7061 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
7062 parseOptionalComdat(FunctionName, C) ||
7063 parseOptionalAlignment(Alignment) ||
7064 parseOptionalPrefAlignment(PrefAlignment) ||
7065 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
7066 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
7067 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
7068 (EatIfPresent(lltok::kw_personality) &&
7069 parseGlobalTypeAndValue(PersonalityFn)))
7070 return true;
7071
7072 if (FuncAttrs.contains(Attribute::Builtin))
7073 return error(BuiltinLoc, "'builtin' attribute not valid on function");
7074
7075 // If the alignment was parsed as an attribute, move to the alignment field.
7076 if (MaybeAlign A = FuncAttrs.getAlignment()) {
7077 Alignment = A;
7078 FuncAttrs.removeAttribute(Attribute::Alignment);
7079 }
7080
7081 // Okay, if we got here, the function is syntactically valid. Convert types
7082 // and do semantic checks.
7083 std::vector<Type*> ParamTypeList;
7085
7086 for (const ArgInfo &Arg : ArgList) {
7087 ParamTypeList.push_back(Arg.Ty);
7088 Attrs.push_back(Arg.Attrs);
7089 }
7090
7091 AttributeList PAL =
7092 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
7093 AttributeSet::get(Context, RetAttrs), Attrs);
7094
7095 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
7096 return error(RetTypeLoc, "functions with 'sret' argument must return void");
7097
7098 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
7099 PointerType *PFT = PointerType::get(Context, AddrSpace);
7100
7101 Fn = nullptr;
7102 GlobalValue *FwdFn = nullptr;
7103 if (!FunctionName.empty()) {
7104 // If this was a definition of a forward reference, remove the definition
7105 // from the forward reference table and fill in the forward ref.
7106 auto FRVI = ForwardRefVals.find(FunctionName);
7107 if (FRVI != ForwardRefVals.end()) {
7108 FwdFn = FRVI->second.first;
7109 if (FwdFn->getType() != PFT)
7110 return error(FRVI->second.second,
7111 "invalid forward reference to "
7112 "function '" +
7113 FunctionName +
7114 "' with wrong type: "
7115 "expected '" +
7116 getTypeString(PFT) + "' but was '" +
7117 getTypeString(FwdFn->getType()) + "'");
7118 ForwardRefVals.erase(FRVI);
7119 } else if ((Fn = M->getFunction(FunctionName))) {
7120 // Reject redefinitions.
7121 return error(NameLoc,
7122 "invalid redefinition of function '" + FunctionName + "'");
7123 } else if (M->getNamedValue(FunctionName)) {
7124 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
7125 }
7126
7127 } else {
7128 // Handle @"", where a name is syntactically specified, but semantically
7129 // missing.
7130 if (FunctionNumber == (unsigned)-1)
7131 FunctionNumber = NumberedVals.getNext();
7132
7133 // If this is a definition of a forward referenced function, make sure the
7134 // types agree.
7135 auto I = ForwardRefValIDs.find(FunctionNumber);
7136 if (I != ForwardRefValIDs.end()) {
7137 FwdFn = I->second.first;
7138 if (FwdFn->getType() != PFT)
7139 return error(NameLoc, "type of definition and forward reference of '@" +
7140 Twine(FunctionNumber) +
7141 "' disagree: "
7142 "expected '" +
7143 getTypeString(PFT) + "' but was '" +
7144 getTypeString(FwdFn->getType()) + "'");
7145 ForwardRefValIDs.erase(I);
7146 }
7147 }
7148
7150 FunctionName, M);
7151
7152 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
7153
7154 if (FunctionName.empty())
7155 NumberedVals.add(FunctionNumber, Fn);
7156
7158 maybeSetDSOLocal(DSOLocal, *Fn);
7161 Fn->setCallingConv(CC);
7162 Fn->setAttributes(PAL);
7163 Fn->setUnnamedAddr(UnnamedAddr);
7164 if (Alignment)
7165 Fn->setAlignment(*Alignment);
7166 Fn->setPreferredAlignment(PrefAlignment);
7167 Fn->setSection(Section);
7168 Fn->setPartition(Partition);
7169 Fn->setComdat(C);
7170 Fn->setPersonalityFn(PersonalityFn);
7171 if (!GC.empty()) Fn->setGC(GC);
7172 Fn->setPrefixData(Prefix);
7173 Fn->setPrologueData(Prologue);
7174 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7175
7176 // Add all of the arguments we parsed to the function.
7177 Function::arg_iterator ArgIt = Fn->arg_begin();
7178 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7179 if (ParserContext && ArgList[i].IdentLoc)
7180 ParserContext->addInstructionOrArgumentLocation(
7181 &*ArgIt, ArgList[i].IdentLoc.value());
7182 // If the argument has a name, insert it into the argument symbol table.
7183 if (ArgList[i].Name.empty()) continue;
7184
7185 // Set the name, if it conflicted, it will be auto-renamed.
7186 ArgIt->setName(ArgList[i].Name);
7187
7188 if (ArgIt->getName() != ArgList[i].Name)
7189 return error(ArgList[i].Loc,
7190 "redefinition of argument '%" + ArgList[i].Name + "'");
7191 }
7192
7193 if (FwdFn) {
7194 FwdFn->replaceAllUsesWith(Fn);
7195 FwdFn->eraseFromParent();
7196 }
7197
7198 if (IsDefine)
7199 return false;
7200
7201 // Check the declaration has no block address forward references.
7202 ValID ID;
7203 if (FunctionName.empty()) {
7204 ID.Kind = ValID::t_GlobalID;
7205 ID.UIntVal = FunctionNumber;
7206 } else {
7207 ID.Kind = ValID::t_GlobalName;
7208 ID.StrVal = FunctionName;
7209 }
7210 auto Blocks = ForwardRefBlockAddresses.find(ID);
7211 if (Blocks != ForwardRefBlockAddresses.end())
7212 return error(Blocks->first.Loc,
7213 "cannot take blockaddress inside a declaration");
7214 return false;
7215}
7216
7217bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7218 ValID ID;
7219 if (FunctionNumber == -1) {
7220 ID.Kind = ValID::t_GlobalName;
7221 ID.StrVal = std::string(F.getName());
7222 } else {
7223 ID.Kind = ValID::t_GlobalID;
7224 ID.UIntVal = FunctionNumber;
7225 }
7226
7227 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7228 if (Blocks == P.ForwardRefBlockAddresses.end())
7229 return false;
7230
7231 for (const auto &I : Blocks->second) {
7232 const ValID &BBID = I.first;
7233 GlobalValue *GV = I.second;
7234
7235 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7236 "Expected local id or name");
7237 BasicBlock *BB;
7238 if (BBID.Kind == ValID::t_LocalName)
7239 BB = getBB(BBID.StrVal, BBID.Loc);
7240 else
7241 BB = getBB(BBID.UIntVal, BBID.Loc);
7242 if (!BB)
7243 return P.error(BBID.Loc, "referenced value is not a basic block");
7244
7245 Value *ResolvedVal = BlockAddress::get(&F, BB);
7246 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7247 ResolvedVal);
7248 if (!ResolvedVal)
7249 return true;
7250 GV->replaceAllUsesWith(ResolvedVal);
7251 GV->eraseFromParent();
7252 }
7253
7254 P.ForwardRefBlockAddresses.erase(Blocks);
7255 return false;
7256}
7257
7258/// parseFunctionBody
7259/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7260bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7261 ArrayRef<unsigned> UnnamedArgNums) {
7262 if (Lex.getKind() != lltok::lbrace)
7263 return tokError("expected '{' in function body");
7264 Lex.Lex(); // eat the {.
7265
7266 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7267
7268 // Resolve block addresses and allow basic blocks to be forward-declared
7269 // within this function.
7270 if (PFS.resolveForwardRefBlockAddresses())
7271 return true;
7272 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7273
7274 // We need at least one basic block.
7275 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7276 return tokError("function body requires at least one basic block");
7277
7278 while (Lex.getKind() != lltok::rbrace &&
7279 Lex.getKind() != lltok::kw_uselistorder)
7280 if (parseBasicBlock(PFS))
7281 return true;
7282
7283 while (Lex.getKind() != lltok::rbrace)
7284 if (parseUseListOrder(&PFS))
7285 return true;
7286
7287 // Eat the }.
7288 Lex.Lex();
7289
7290 // Verify function is ok.
7291 return PFS.finishFunction();
7292}
7293
7294/// parseBasicBlock
7295/// ::= (LabelStr|LabelID)? Instruction*
7296bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7297 FileLoc BBStart = getTokLineColumnPos();
7298
7299 // If this basic block starts out with a name, remember it.
7300 std::string Name;
7301 int NameID = -1;
7302 LocTy NameLoc = Lex.getLoc();
7303 if (Lex.getKind() == lltok::LabelStr) {
7304 Name = Lex.getStrVal();
7305 Lex.Lex();
7306 } else if (Lex.getKind() == lltok::LabelID) {
7307 NameID = Lex.getUIntVal();
7308 Lex.Lex();
7309 }
7310
7311 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7312 if (!BB)
7313 return true;
7314
7315 std::string NameStr;
7316
7317 // Parse the instructions and debug values in this block until we get a
7318 // terminator.
7319 Instruction *Inst;
7320 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7321 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7322 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7323 do {
7324 // Handle debug records first - there should always be an instruction
7325 // following the debug records, i.e. they cannot appear after the block
7326 // terminator.
7327 while (Lex.getKind() == lltok::hash) {
7328 if (SeenOldDbgInfoFormat)
7329 return error(Lex.getLoc(), "debug record should not appear in a module "
7330 "containing debug info intrinsics");
7331 SeenNewDbgInfoFormat = true;
7332 Lex.Lex();
7333
7334 DbgRecord *DR;
7335 if (parseDebugRecord(DR, PFS))
7336 return true;
7337 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7338 }
7339
7340 FileLoc InstStart = getTokLineColumnPos();
7341 // This instruction may have three possibilities for a name: a) none
7342 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7343 LocTy NameLoc = Lex.getLoc();
7344 int NameID = -1;
7345 NameStr = "";
7346
7347 if (Lex.getKind() == lltok::LocalVarID) {
7348 NameID = Lex.getUIntVal();
7349 Lex.Lex();
7350 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7351 return true;
7352 } else if (Lex.getKind() == lltok::LocalVar) {
7353 NameStr = Lex.getStrVal();
7354 Lex.Lex();
7355 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7356 return true;
7357 }
7358
7359 switch (parseInstruction(Inst, BB, PFS)) {
7360 default:
7361 llvm_unreachable("Unknown parseInstruction result!");
7362 case InstError: return true;
7363 case InstNormal:
7364 Inst->insertInto(BB, BB->end());
7365
7366 // With a normal result, we check to see if the instruction is followed by
7367 // a comma and metadata.
7368 if (EatIfPresent(lltok::comma))
7369 if (parseInstructionMetadata(*Inst))
7370 return true;
7371 break;
7372 case InstExtraComma:
7373 Inst->insertInto(BB, BB->end());
7374
7375 // If the instruction parser ate an extra comma at the end of it, it
7376 // *must* be followed by metadata.
7377 if (parseInstructionMetadata(*Inst))
7378 return true;
7379 break;
7380 }
7381
7382 // Set the name on the instruction.
7383 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7384 return true;
7385
7386 // Attach any preceding debug values to this instruction.
7387 for (DbgRecordPtr &DR : TrailingDbgRecord)
7388 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7389 TrailingDbgRecord.clear();
7390 if (ParserContext) {
7391 ParserContext->addInstructionOrArgumentLocation(
7392 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7393 }
7394 } while (!Inst->isTerminator());
7395
7396 if (ParserContext)
7397 ParserContext->addBlockLocation(
7398 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7399
7400 assert(TrailingDbgRecord.empty() &&
7401 "All debug values should have been attached to an instruction.");
7402
7403 return false;
7404}
7405
7406/// parseDebugRecord
7407/// ::= #dbg_label '(' MDNode ')'
7408/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7409/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7410bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7411 using RecordKind = DbgRecord::Kind;
7412 using LocType = DbgVariableRecord::LocationType;
7413 LocTy DVRLoc = Lex.getLoc();
7414 if (Lex.getKind() != lltok::DbgRecordType)
7415 return error(DVRLoc, "expected debug record type here");
7416 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7417 .Case("declare", RecordKind::ValueKind)
7418 .Case("value", RecordKind::ValueKind)
7419 .Case("assign", RecordKind::ValueKind)
7420 .Case("label", RecordKind::LabelKind)
7421 .Case("declare_value", RecordKind::ValueKind);
7422
7423 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7424 // full DbgVariableRecord processing stage.
7425 if (RecordType == RecordKind::LabelKind) {
7426 Lex.Lex();
7427 if (parseToken(lltok::lparen, "Expected '(' here"))
7428 return true;
7429 MDNode *Label;
7430 if (parseMDNode(Label))
7431 return true;
7432 if (parseToken(lltok::comma, "Expected ',' here"))
7433 return true;
7434 MDNode *DbgLoc;
7435 if (parseMDNode(DbgLoc))
7436 return true;
7437 if (parseToken(lltok::rparen, "Expected ')' here"))
7438 return true;
7440 return false;
7441 }
7442
7443 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7444 .Case("declare", LocType::Declare)
7445 .Case("value", LocType::Value)
7446 .Case("assign", LocType::Assign)
7447 .Case("declare_value", LocType::DeclareValue);
7448
7449 Lex.Lex();
7450 if (parseToken(lltok::lparen, "Expected '(' here"))
7451 return true;
7452
7453 // Parse Value field.
7454 Metadata *ValLocMD;
7455 if (parseMetadata(ValLocMD, &PFS))
7456 return true;
7457 if (parseToken(lltok::comma, "Expected ',' here"))
7458 return true;
7459
7460 // Parse Variable field.
7461 MDNode *Variable;
7462 if (parseMDNode(Variable))
7463 return true;
7464 if (parseToken(lltok::comma, "Expected ',' here"))
7465 return true;
7466
7467 // Parse Expression field.
7468 MDNode *Expression;
7469 if (parseMDNode(Expression))
7470 return true;
7471 if (parseToken(lltok::comma, "Expected ',' here"))
7472 return true;
7473
7474 // Parse additional fields for #dbg_assign.
7475 MDNode *AssignID = nullptr;
7476 Metadata *AddressLocation = nullptr;
7477 MDNode *AddressExpression = nullptr;
7478 if (ValueType == LocType::Assign) {
7479 // Parse DIAssignID.
7480 if (parseMDNode(AssignID))
7481 return true;
7482 if (parseToken(lltok::comma, "Expected ',' here"))
7483 return true;
7484
7485 // Parse address ValueAsMetadata.
7486 if (parseMetadata(AddressLocation, &PFS))
7487 return true;
7488 if (parseToken(lltok::comma, "Expected ',' here"))
7489 return true;
7490
7491 // Parse address DIExpression.
7492 if (parseMDNode(AddressExpression))
7493 return true;
7494 if (parseToken(lltok::comma, "Expected ',' here"))
7495 return true;
7496 }
7497
7498 /// Parse DILocation.
7499 MDNode *DebugLoc;
7500 if (parseMDNode(DebugLoc))
7501 return true;
7502
7503 if (parseToken(lltok::rparen, "Expected ')' here"))
7504 return true;
7506 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7507 AddressExpression, DebugLoc);
7508 return false;
7509}
7510//===----------------------------------------------------------------------===//
7511// Instruction Parsing.
7512//===----------------------------------------------------------------------===//
7513
7514/// parseInstruction - parse one of the many different instructions.
7515///
7516int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7517 PerFunctionState &PFS) {
7518 lltok::Kind Token = Lex.getKind();
7519 if (Token == lltok::Eof)
7520 return tokError("found end of file when expecting more instructions");
7521 LocTy Loc = Lex.getLoc();
7522 unsigned KeywordVal = Lex.getUIntVal();
7523 Lex.Lex(); // Eat the keyword.
7524
7525 switch (Token) {
7526 default:
7527 return error(Loc, "expected instruction opcode");
7528 // Terminator Instructions.
7529 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7530 case lltok::kw_ret:
7531 return parseRet(Inst, BB, PFS);
7532 case lltok::kw_br:
7533 return parseBr(Inst, PFS);
7534 case lltok::kw_switch:
7535 return parseSwitch(Inst, PFS);
7537 return parseIndirectBr(Inst, PFS);
7538 case lltok::kw_invoke:
7539 return parseInvoke(Inst, PFS);
7540 case lltok::kw_resume:
7541 return parseResume(Inst, PFS);
7543 return parseCleanupRet(Inst, PFS);
7544 case lltok::kw_catchret:
7545 return parseCatchRet(Inst, PFS);
7547 return parseCatchSwitch(Inst, PFS);
7548 case lltok::kw_catchpad:
7549 return parseCatchPad(Inst, PFS);
7551 return parseCleanupPad(Inst, PFS);
7552 case lltok::kw_callbr:
7553 return parseCallBr(Inst, PFS);
7554 // Unary Operators.
7555 case lltok::kw_fneg: {
7556 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7557 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7558 if (Res != 0)
7559 return Res;
7560 if (FMF.any())
7561 Inst->setFastMathFlags(FMF);
7562 return false;
7563 }
7564 // Binary Operators.
7565 case lltok::kw_add:
7566 case lltok::kw_sub:
7567 case lltok::kw_mul:
7568 case lltok::kw_shl: {
7569 bool NUW = EatIfPresent(lltok::kw_nuw);
7570 bool NSW = EatIfPresent(lltok::kw_nsw);
7571 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7572
7573 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7574 return true;
7575
7576 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7577 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7578 return false;
7579 }
7580 case lltok::kw_fadd:
7581 case lltok::kw_fsub:
7582 case lltok::kw_fmul:
7583 case lltok::kw_fdiv:
7584 case lltok::kw_frem: {
7585 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7586 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7587 if (Res != 0)
7588 return Res;
7589 if (FMF.any())
7590 Inst->setFastMathFlags(FMF);
7591 return 0;
7592 }
7593
7594 case lltok::kw_sdiv:
7595 case lltok::kw_udiv:
7596 case lltok::kw_lshr:
7597 case lltok::kw_ashr: {
7598 bool Exact = EatIfPresent(lltok::kw_exact);
7599
7600 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7601 return true;
7602 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7603 return false;
7604 }
7605
7606 case lltok::kw_urem:
7607 case lltok::kw_srem:
7608 return parseArithmetic(Inst, PFS, KeywordVal,
7609 /*IsFP*/ false);
7610 case lltok::kw_or: {
7611 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7612 if (parseLogical(Inst, PFS, KeywordVal))
7613 return true;
7614 if (Disjoint)
7615 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7616 return false;
7617 }
7618 case lltok::kw_and:
7619 case lltok::kw_xor:
7620 return parseLogical(Inst, PFS, KeywordVal);
7621 case lltok::kw_icmp: {
7622 bool SameSign = EatIfPresent(lltok::kw_samesign);
7623 if (parseCompare(Inst, PFS, KeywordVal))
7624 return true;
7625 if (SameSign)
7626 cast<ICmpInst>(Inst)->setSameSign();
7627 return false;
7628 }
7629 case lltok::kw_fcmp: {
7630 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7631 int Res = parseCompare(Inst, PFS, KeywordVal);
7632 if (Res != 0)
7633 return Res;
7634 if (FMF.any())
7635 Inst->setFastMathFlags(FMF);
7636 return 0;
7637 }
7638
7639 // Casts.
7640 case lltok::kw_uitofp:
7641 case lltok::kw_zext: {
7642 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7643 bool Res = parseCast(Inst, PFS, KeywordVal);
7644 if (Res != 0)
7645 return Res;
7646 if (NonNeg)
7647 Inst->setNonNeg();
7648 return 0;
7649 }
7650 case lltok::kw_trunc: {
7651 bool NUW = EatIfPresent(lltok::kw_nuw);
7652 bool NSW = EatIfPresent(lltok::kw_nsw);
7653 if (!NUW)
7654 NUW = EatIfPresent(lltok::kw_nuw);
7655 if (parseCast(Inst, PFS, KeywordVal))
7656 return true;
7657 if (NUW)
7658 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7659 if (NSW)
7660 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7661 return false;
7662 }
7663 case lltok::kw_sext:
7664 case lltok::kw_bitcast:
7666 case lltok::kw_sitofp:
7667 case lltok::kw_fptoui:
7668 case lltok::kw_fptosi:
7669 case lltok::kw_inttoptr:
7671 case lltok::kw_ptrtoint:
7672 return parseCast(Inst, PFS, KeywordVal);
7673 case lltok::kw_fptrunc:
7674 case lltok::kw_fpext: {
7675 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7676 if (parseCast(Inst, PFS, KeywordVal))
7677 return true;
7678 if (FMF.any())
7679 Inst->setFastMathFlags(FMF);
7680 return false;
7681 }
7682
7683 // Other.
7684 case lltok::kw_select: {
7685 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7686 int Res = parseSelect(Inst, PFS);
7687 if (Res != 0)
7688 return Res;
7689 if (FMF.any()) {
7690 if (!isa<FPMathOperator>(Inst))
7691 return error(Loc, "fast-math-flags specified for select without "
7692 "floating-point scalar or vector return type");
7693 Inst->setFastMathFlags(FMF);
7694 }
7695 return 0;
7696 }
7697 case lltok::kw_va_arg:
7698 return parseVAArg(Inst, PFS);
7700 return parseExtractElement(Inst, PFS);
7702 return parseInsertElement(Inst, PFS);
7704 return parseShuffleVector(Inst, PFS);
7705 case lltok::kw_phi: {
7706 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7707 int Res = parsePHI(Inst, PFS);
7708 if (Res != 0)
7709 return Res;
7710 if (FMF.any()) {
7711 if (!isa<FPMathOperator>(Inst))
7712 return error(Loc, "fast-math-flags specified for phi without "
7713 "floating-point scalar or vector return type");
7714 Inst->setFastMathFlags(FMF);
7715 }
7716 return 0;
7717 }
7719 return parseLandingPad(Inst, PFS);
7720 case lltok::kw_freeze:
7721 return parseFreeze(Inst, PFS);
7722 // Call.
7723 case lltok::kw_call:
7724 return parseCall(Inst, PFS, CallInst::TCK_None);
7725 case lltok::kw_tail:
7726 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7727 case lltok::kw_musttail:
7728 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7729 case lltok::kw_notail:
7730 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7731 // Memory.
7732 case lltok::kw_alloca:
7733 return parseAlloc(Inst, PFS);
7734 case lltok::kw_load:
7735 return parseLoad(Inst, PFS);
7736 case lltok::kw_store:
7737 return parseStore(Inst, PFS);
7738 case lltok::kw_cmpxchg:
7739 return parseCmpXchg(Inst, PFS);
7741 return parseAtomicRMW(Inst, PFS);
7742 case lltok::kw_fence:
7743 return parseFence(Inst, PFS);
7745 return parseGetElementPtr(Inst, PFS);
7747 return parseExtractValue(Inst, PFS);
7749 return parseInsertValue(Inst, PFS);
7750 }
7751}
7752
7753/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7754bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7755 if (Opc == Instruction::FCmp) {
7756 switch (Lex.getKind()) {
7757 default:
7758 return tokError("expected fcmp predicate (e.g. 'oeq')");
7759 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7760 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7761 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7762 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7763 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7764 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7765 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7766 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7767 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7768 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7769 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7770 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7771 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7772 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7773 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7774 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7775 }
7776 } else {
7777 switch (Lex.getKind()) {
7778 default:
7779 return tokError("expected icmp predicate (e.g. 'eq')");
7780 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7781 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7782 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7783 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7784 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7785 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7786 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7787 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7788 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7789 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7790 }
7791 }
7792 Lex.Lex();
7793 return false;
7794}
7795
7796//===----------------------------------------------------------------------===//
7797// Terminator Instructions.
7798//===----------------------------------------------------------------------===//
7799
7800/// parseRet - parse a return instruction.
7801/// ::= 'ret' void (',' !dbg, !1)*
7802/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7803bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7804 PerFunctionState &PFS) {
7805 SMLoc TypeLoc = Lex.getLoc();
7806 Type *Ty = nullptr;
7807 if (parseType(Ty, true /*void allowed*/))
7808 return true;
7809
7810 Type *ResType = PFS.getFunction().getReturnType();
7811
7812 if (Ty->isVoidTy()) {
7813 if (!ResType->isVoidTy())
7814 return error(TypeLoc, "value doesn't match function result type '" +
7815 getTypeString(ResType) + "'");
7816
7817 Inst = ReturnInst::Create(Context);
7818 return false;
7819 }
7820
7821 Value *RV;
7822 if (parseValue(Ty, RV, PFS))
7823 return true;
7824
7825 if (ResType != RV->getType())
7826 return error(TypeLoc, "value doesn't match function result type '" +
7827 getTypeString(ResType) + "'");
7828
7829 Inst = ReturnInst::Create(Context, RV);
7830 return false;
7831}
7832
7833/// parseBr
7834/// ::= 'br' TypeAndValue
7835/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7836bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7837 LocTy Loc, Loc2;
7838 Value *Op0;
7839 BasicBlock *Op1, *Op2;
7840 if (parseTypeAndValue(Op0, Loc, PFS))
7841 return true;
7842
7843 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7844 Inst = UncondBrInst::Create(BB);
7845 return false;
7846 }
7847
7848 if (Op0->getType() != Type::getInt1Ty(Context))
7849 return error(Loc, "branch condition must have 'i1' type");
7850
7851 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7852 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7853 parseToken(lltok::comma, "expected ',' after true destination") ||
7854 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7855 return true;
7856
7857 Inst = CondBrInst::Create(Op0, Op1, Op2);
7858 return false;
7859}
7860
7861/// parseSwitch
7862/// Instruction
7863/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7864/// JumpTable
7865/// ::= (TypeAndValue ',' TypeAndValue)*
7866bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7867 LocTy CondLoc, BBLoc;
7868 Value *Cond;
7869 BasicBlock *DefaultBB;
7870 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7871 parseToken(lltok::comma, "expected ',' after switch condition") ||
7872 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7873 parseToken(lltok::lsquare, "expected '[' with switch table"))
7874 return true;
7875
7876 if (!Cond->getType()->isIntegerTy())
7877 return error(CondLoc, "switch condition must have integer type");
7878
7879 // parse the jump table pairs.
7880 SmallPtrSet<Value*, 32> SeenCases;
7882 while (Lex.getKind() != lltok::rsquare) {
7883 Value *Constant;
7884 BasicBlock *DestBB;
7885
7886 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7887 parseToken(lltok::comma, "expected ',' after case value") ||
7888 parseTypeAndBasicBlock(DestBB, PFS))
7889 return true;
7890
7891 if (!SeenCases.insert(Constant).second)
7892 return error(CondLoc, "duplicate case value in switch");
7893 if (!isa<ConstantInt>(Constant))
7894 return error(CondLoc, "case value is not a constant integer");
7895
7896 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7897 }
7898
7899 Lex.Lex(); // Eat the ']'.
7900
7901 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7902 for (const auto &[OnVal, Dest] : Table)
7903 SI->addCase(OnVal, Dest);
7904 Inst = SI;
7905 return false;
7906}
7907
7908/// parseIndirectBr
7909/// Instruction
7910/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7911bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7912 LocTy AddrLoc;
7913 Value *Address;
7914 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7915 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7916 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7917 return true;
7918
7919 if (!Address->getType()->isPointerTy())
7920 return error(AddrLoc, "indirectbr address must have pointer type");
7921
7922 // parse the destination list.
7923 SmallVector<BasicBlock*, 16> DestList;
7924
7925 if (Lex.getKind() != lltok::rsquare) {
7926 BasicBlock *DestBB;
7927 if (parseTypeAndBasicBlock(DestBB, PFS))
7928 return true;
7929 DestList.push_back(DestBB);
7930
7931 while (EatIfPresent(lltok::comma)) {
7932 if (parseTypeAndBasicBlock(DestBB, PFS))
7933 return true;
7934 DestList.push_back(DestBB);
7935 }
7936 }
7937
7938 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7939 return true;
7940
7941 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
7942 for (BasicBlock *Dest : DestList)
7943 IBI->addDestination(Dest);
7944 Inst = IBI;
7945 return false;
7946}
7947
7948// If RetType is a non-function pointer type, then this is the short syntax
7949// for the call, which means that RetType is just the return type. Infer the
7950// rest of the function argument types from the arguments that are present.
7951bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7952 FunctionType *&FuncTy) {
7953 FuncTy = dyn_cast<FunctionType>(RetType);
7954 if (!FuncTy) {
7955 // Pull out the types of all of the arguments...
7956 SmallVector<Type *, 8> ParamTypes;
7957 ParamTypes.reserve(ArgList.size());
7958 for (const ParamInfo &Arg : ArgList)
7959 ParamTypes.push_back(Arg.V->getType());
7960
7961 if (!FunctionType::isValidReturnType(RetType))
7962 return true;
7963
7964 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7965 }
7966 return false;
7967}
7968
7969/// parseInvoke
7970/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7971/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7972bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7973 LocTy CallLoc = Lex.getLoc();
7974 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7975 std::vector<unsigned> FwdRefAttrGrps;
7976 LocTy NoBuiltinLoc;
7977 unsigned CC;
7978 unsigned InvokeAddrSpace;
7979 Type *RetType = nullptr;
7980 LocTy RetTypeLoc;
7981 ValID CalleeID;
7984
7985 BasicBlock *NormalBB, *UnwindBB;
7986 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7987 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7988 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7989 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7990 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7991 NoBuiltinLoc) ||
7992 parseOptionalOperandBundles(BundleList, PFS) ||
7993 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7994 parseTypeAndBasicBlock(NormalBB, PFS) ||
7995 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7996 parseTypeAndBasicBlock(UnwindBB, PFS))
7997 return true;
7998
7999 // If RetType is a non-function pointer type, then this is the short syntax
8000 // for the call, which means that RetType is just the return type. Infer the
8001 // rest of the function argument types from the arguments that are present.
8002 FunctionType *Ty;
8003 if (resolveFunctionType(RetType, ArgList, Ty))
8004 return error(RetTypeLoc, "Invalid result type for LLVM function");
8005
8006 CalleeID.FTy = Ty;
8007
8008 // Look up the callee.
8009 Value *Callee;
8010 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
8011 Callee, &PFS))
8012 return true;
8013
8014 // Set up the Attribute for the function.
8015 SmallVector<Value *, 8> Args;
8017
8018 // Loop through FunctionType's arguments and ensure they are specified
8019 // correctly. Also, gather any parameter attributes.
8020 FunctionType::param_iterator I = Ty->param_begin();
8021 FunctionType::param_iterator E = Ty->param_end();
8022 for (const ParamInfo &Arg : ArgList) {
8023 Type *ExpectedTy = nullptr;
8024 if (I != E) {
8025 ExpectedTy = *I++;
8026 } else if (!Ty->isVarArg()) {
8027 return error(Arg.Loc, "too many arguments specified");
8028 }
8029
8030 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8031 return error(Arg.Loc, "argument is not of expected type '" +
8032 getTypeString(ExpectedTy) + "'");
8033 Args.push_back(Arg.V);
8034 ArgAttrs.push_back(Arg.Attrs);
8035 }
8036
8037 if (I != E)
8038 return error(CallLoc, "not enough parameters specified for call");
8039
8040 // Finish off the Attribute and check them
8041 AttributeList PAL =
8042 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8043 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8044
8045 InvokeInst *II =
8046 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
8047 II->setCallingConv(CC);
8048 II->setAttributes(PAL);
8049 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
8050 Inst = II;
8051 return false;
8052}
8053
8054/// parseResume
8055/// ::= 'resume' TypeAndValue
8056bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8057 Value *Exn; LocTy ExnLoc;
8058 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8059 return true;
8060
8061 ResumeInst *RI = ResumeInst::Create(Exn);
8062 Inst = RI;
8063 return false;
8064}
8065
8066bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8067 PerFunctionState &PFS) {
8068 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
8069 return true;
8070
8071 while (Lex.getKind() != lltok::rsquare) {
8072 // If this isn't the first argument, we need a comma.
8073 if (!Args.empty() &&
8074 parseToken(lltok::comma, "expected ',' in argument list"))
8075 return true;
8076
8077 // parse the argument.
8078 LocTy ArgLoc;
8079 Type *ArgTy = nullptr;
8080 if (parseType(ArgTy, ArgLoc))
8081 return true;
8082
8083 Value *V;
8084 if (ArgTy->isMetadataTy()) {
8085 if (parseMetadataAsValue(V, PFS))
8086 return true;
8087 } else {
8088 if (parseValue(ArgTy, V, PFS))
8089 return true;
8090 }
8091 Args.push_back(V);
8092 }
8093
8094 Lex.Lex(); // Lex the ']'.
8095 return false;
8096}
8097
8098/// parseCleanupRet
8099/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
8100bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8101 Value *CleanupPad = nullptr;
8102
8103 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
8104 return true;
8105
8106 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
8107 return true;
8108
8109 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
8110 return true;
8111
8112 BasicBlock *UnwindBB = nullptr;
8113 if (Lex.getKind() == lltok::kw_to) {
8114 Lex.Lex();
8115 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
8116 return true;
8117 } else {
8118 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8119 return true;
8120 }
8121 }
8122
8123 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
8124 return false;
8125}
8126
8127/// parseCatchRet
8128/// ::= 'catchret' from Parent Value 'to' TypeAndValue
8129bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8130 Value *CatchPad = nullptr;
8131
8132 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
8133 return true;
8134
8135 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
8136 return true;
8137
8138 BasicBlock *BB;
8139 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
8140 parseTypeAndBasicBlock(BB, PFS))
8141 return true;
8142
8143 Inst = CatchReturnInst::Create(CatchPad, BB);
8144 return false;
8145}
8146
8147/// parseCatchSwitch
8148/// ::= 'catchswitch' within Parent
8149bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8150 Value *ParentPad;
8151
8152 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
8153 return true;
8154
8155 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8156 Lex.getKind() != lltok::LocalVarID)
8157 return tokError("expected scope value for catchswitch");
8158
8159 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8160 return true;
8161
8162 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
8163 return true;
8164
8166 do {
8167 BasicBlock *DestBB;
8168 if (parseTypeAndBasicBlock(DestBB, PFS))
8169 return true;
8170 Table.push_back(DestBB);
8171 } while (EatIfPresent(lltok::comma));
8172
8173 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
8174 return true;
8175
8176 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
8177 return true;
8178
8179 BasicBlock *UnwindBB = nullptr;
8180 if (EatIfPresent(lltok::kw_to)) {
8181 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
8182 return true;
8183 } else {
8184 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8185 return true;
8186 }
8187
8188 auto *CatchSwitch =
8189 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
8190 for (BasicBlock *DestBB : Table)
8191 CatchSwitch->addHandler(DestBB);
8192 Inst = CatchSwitch;
8193 return false;
8194}
8195
8196/// parseCatchPad
8197/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
8198bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8199 Value *CatchSwitch = nullptr;
8200
8201 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
8202 return true;
8203
8204 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
8205 return tokError("expected scope value for catchpad");
8206
8207 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
8208 return true;
8209
8210 SmallVector<Value *, 8> Args;
8211 if (parseExceptionArgs(Args, PFS))
8212 return true;
8213
8214 Inst = CatchPadInst::Create(CatchSwitch, Args);
8215 return false;
8216}
8217
8218/// parseCleanupPad
8219/// ::= 'cleanuppad' within Parent ParamList
8220bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8221 Value *ParentPad = nullptr;
8222
8223 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
8224 return true;
8225
8226 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8227 Lex.getKind() != lltok::LocalVarID)
8228 return tokError("expected scope value for cleanuppad");
8229
8230 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8231 return true;
8232
8233 SmallVector<Value *, 8> Args;
8234 if (parseExceptionArgs(Args, PFS))
8235 return true;
8236
8237 Inst = CleanupPadInst::Create(ParentPad, Args);
8238 return false;
8239}
8240
8241//===----------------------------------------------------------------------===//
8242// Unary Operators.
8243//===----------------------------------------------------------------------===//
8244
8245/// parseUnaryOp
8246/// ::= UnaryOp TypeAndValue ',' Value
8247///
8248/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8249/// operand is allowed.
8250bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8251 unsigned Opc, bool IsFP) {
8252 LocTy Loc; Value *LHS;
8253 if (parseTypeAndValue(LHS, Loc, PFS))
8254 return true;
8255
8256 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8258
8259 if (!Valid)
8260 return error(Loc, "invalid operand type for instruction");
8261
8263 return false;
8264}
8265
8266/// parseCallBr
8267/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8268/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8269/// '[' LabelList ']'
8270bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8271 LocTy CallLoc = Lex.getLoc();
8272 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8273 std::vector<unsigned> FwdRefAttrGrps;
8274 LocTy NoBuiltinLoc;
8275 unsigned CC;
8276 Type *RetType = nullptr;
8277 LocTy RetTypeLoc;
8278 ValID CalleeID;
8281
8282 BasicBlock *DefaultDest;
8283 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8284 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8285 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8286 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8287 NoBuiltinLoc) ||
8288 parseOptionalOperandBundles(BundleList, PFS) ||
8289 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8290 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8291 parseToken(lltok::lsquare, "expected '[' in callbr"))
8292 return true;
8293
8294 // parse the destination list.
8295 SmallVector<BasicBlock *, 16> IndirectDests;
8296
8297 if (Lex.getKind() != lltok::rsquare) {
8298 BasicBlock *DestBB;
8299 if (parseTypeAndBasicBlock(DestBB, PFS))
8300 return true;
8301 IndirectDests.push_back(DestBB);
8302
8303 while (EatIfPresent(lltok::comma)) {
8304 if (parseTypeAndBasicBlock(DestBB, PFS))
8305 return true;
8306 IndirectDests.push_back(DestBB);
8307 }
8308 }
8309
8310 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8311 return true;
8312
8313 // If RetType is a non-function pointer type, then this is the short syntax
8314 // for the call, which means that RetType is just the return type. Infer the
8315 // rest of the function argument types from the arguments that are present.
8316 FunctionType *Ty;
8317 if (resolveFunctionType(RetType, ArgList, Ty))
8318 return error(RetTypeLoc, "Invalid result type for LLVM function");
8319
8320 CalleeID.FTy = Ty;
8321
8322 // Look up the callee.
8323 Value *Callee;
8324 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8325 &PFS))
8326 return true;
8327
8328 // Set up the Attribute for the function.
8329 SmallVector<Value *, 8> Args;
8331
8332 // Loop through FunctionType's arguments and ensure they are specified
8333 // correctly. Also, gather any parameter attributes.
8334 FunctionType::param_iterator I = Ty->param_begin();
8335 FunctionType::param_iterator E = Ty->param_end();
8336 for (const ParamInfo &Arg : ArgList) {
8337 Type *ExpectedTy = nullptr;
8338 if (I != E) {
8339 ExpectedTy = *I++;
8340 } else if (!Ty->isVarArg()) {
8341 return error(Arg.Loc, "too many arguments specified");
8342 }
8343
8344 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8345 return error(Arg.Loc, "argument is not of expected type '" +
8346 getTypeString(ExpectedTy) + "'");
8347 Args.push_back(Arg.V);
8348 ArgAttrs.push_back(Arg.Attrs);
8349 }
8350
8351 if (I != E)
8352 return error(CallLoc, "not enough parameters specified for call");
8353
8354 // Finish off the Attribute and check them
8355 AttributeList PAL =
8356 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8357 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8358
8359 CallBrInst *CBI =
8360 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8361 BundleList);
8362 CBI->setCallingConv(CC);
8363 CBI->setAttributes(PAL);
8364 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8365 Inst = CBI;
8366 return false;
8367}
8368
8369//===----------------------------------------------------------------------===//
8370// Binary Operators.
8371//===----------------------------------------------------------------------===//
8372
8373/// parseArithmetic
8374/// ::= ArithmeticOps TypeAndValue ',' Value
8375///
8376/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8377/// operand is allowed.
8378bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8379 unsigned Opc, bool IsFP) {
8380 LocTy Loc; Value *LHS, *RHS;
8381 if (parseTypeAndValue(LHS, Loc, PFS) ||
8382 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8383 parseValue(LHS->getType(), RHS, PFS))
8384 return true;
8385
8386 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8388
8389 if (!Valid)
8390 return error(Loc, "invalid operand type for instruction");
8391
8393 return false;
8394}
8395
8396/// parseLogical
8397/// ::= ArithmeticOps TypeAndValue ',' Value {
8398bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8399 unsigned Opc) {
8400 LocTy Loc; Value *LHS, *RHS;
8401 if (parseTypeAndValue(LHS, Loc, PFS) ||
8402 parseToken(lltok::comma, "expected ',' in logical operation") ||
8403 parseValue(LHS->getType(), RHS, PFS))
8404 return true;
8405
8406 if (!LHS->getType()->isIntOrIntVectorTy())
8407 return error(Loc,
8408 "instruction requires integer or integer vector operands");
8409
8411 return false;
8412}
8413
8414/// parseCompare
8415/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8416/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8417bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8418 unsigned Opc) {
8419 // parse the integer/fp comparison predicate.
8420 LocTy Loc;
8421 unsigned Pred;
8422 Value *LHS, *RHS;
8423 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8424 parseToken(lltok::comma, "expected ',' after compare value") ||
8425 parseValue(LHS->getType(), RHS, PFS))
8426 return true;
8427
8428 if (Opc == Instruction::FCmp) {
8429 if (!LHS->getType()->isFPOrFPVectorTy())
8430 return error(Loc, "fcmp requires floating point operands");
8431 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8432 } else {
8433 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8434 if (!LHS->getType()->isIntOrIntVectorTy() &&
8436 return error(Loc, "icmp requires integer operands");
8437 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8438 }
8439 return false;
8440}
8441
8442//===----------------------------------------------------------------------===//
8443// Other Instructions.
8444//===----------------------------------------------------------------------===//
8445
8446/// parseCast
8447/// ::= CastOpc TypeAndValue 'to' Type
8448bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8449 unsigned Opc) {
8450 LocTy Loc;
8451 Value *Op;
8452 Type *DestTy = nullptr;
8453 if (parseTypeAndValue(Op, Loc, PFS) ||
8454 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8455 parseType(DestTy))
8456 return true;
8457
8459 return error(Loc, "invalid cast opcode for cast from '" +
8460 getTypeString(Op->getType()) + "' to '" +
8461 getTypeString(DestTy) + "'");
8462 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8463 return false;
8464}
8465
8466/// parseSelect
8467/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8468bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8469 LocTy Loc;
8470 Value *Op0, *Op1, *Op2;
8471 if (parseTypeAndValue(Op0, Loc, PFS) ||
8472 parseToken(lltok::comma, "expected ',' after select condition") ||
8473 parseTypeAndValue(Op1, PFS) ||
8474 parseToken(lltok::comma, "expected ',' after select value") ||
8475 parseTypeAndValue(Op2, PFS))
8476 return true;
8477
8478 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8479 return error(Loc, Reason);
8480
8481 Inst = SelectInst::Create(Op0, Op1, Op2);
8482 return false;
8483}
8484
8485/// parseVAArg
8486/// ::= 'va_arg' TypeAndValue ',' Type
8487bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8488 Value *Op;
8489 Type *EltTy = nullptr;
8490 LocTy TypeLoc;
8491 if (parseTypeAndValue(Op, PFS) ||
8492 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8493 parseType(EltTy, TypeLoc))
8494 return true;
8495
8496 if (!EltTy->isFirstClassType())
8497 return error(TypeLoc, "va_arg requires operand with first class type");
8498
8499 Inst = new VAArgInst(Op, EltTy);
8500 return false;
8501}
8502
8503/// parseExtractElement
8504/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8505bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8506 LocTy Loc;
8507 Value *Op0, *Op1;
8508 if (parseTypeAndValue(Op0, Loc, PFS) ||
8509 parseToken(lltok::comma, "expected ',' after extract value") ||
8510 parseTypeAndValue(Op1, PFS))
8511 return true;
8512
8514 return error(Loc, "invalid extractelement operands");
8515
8516 Inst = ExtractElementInst::Create(Op0, Op1);
8517 return false;
8518}
8519
8520/// parseInsertElement
8521/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8522bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8523 LocTy Loc;
8524 Value *Op0, *Op1, *Op2;
8525 if (parseTypeAndValue(Op0, Loc, PFS) ||
8526 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8527 parseTypeAndValue(Op1, PFS) ||
8528 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8529 parseTypeAndValue(Op2, PFS))
8530 return true;
8531
8532 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8533 return error(Loc, "invalid insertelement operands");
8534
8535 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8536 return false;
8537}
8538
8539/// parseShuffleVector
8540/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8541bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8542 LocTy Loc;
8543 Value *Op0, *Op1, *Op2;
8544 if (parseTypeAndValue(Op0, Loc, PFS) ||
8545 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8546 parseTypeAndValue(Op1, PFS) ||
8547 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8548 parseTypeAndValue(Op2, PFS))
8549 return true;
8550
8551 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8552 return error(Loc, "invalid shufflevector operands");
8553
8554 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8555 return false;
8556}
8557
8558/// parsePHI
8559/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8560int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8561 Type *Ty = nullptr; LocTy TypeLoc;
8562 Value *Op0, *Op1;
8563
8564 if (parseType(Ty, TypeLoc))
8565 return true;
8566
8567 if (!Ty->isFirstClassType())
8568 return error(TypeLoc, "phi node must have first class type");
8569
8570 bool First = true;
8571 bool AteExtraComma = false;
8573
8574 while (true) {
8575 if (First) {
8576 if (Lex.getKind() != lltok::lsquare)
8577 break;
8578 First = false;
8579 } else if (!EatIfPresent(lltok::comma))
8580 break;
8581
8582 if (Lex.getKind() == lltok::MetadataVar) {
8583 AteExtraComma = true;
8584 break;
8585 }
8586
8587 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8588 parseValue(Ty, Op0, PFS) ||
8589 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8590 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8591 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8592 return true;
8593
8594 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8595 }
8596
8597 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8598 for (const auto &[Val, BB] : PHIVals)
8599 PN->addIncoming(Val, BB);
8600 Inst = PN;
8601 return AteExtraComma ? InstExtraComma : InstNormal;
8602}
8603
8604/// parseLandingPad
8605/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8606/// Clause
8607/// ::= 'catch' TypeAndValue
8608/// ::= 'filter'
8609/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8610bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8611 Type *Ty = nullptr; LocTy TyLoc;
8612
8613 if (parseType(Ty, TyLoc))
8614 return true;
8615
8616 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8617 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8618
8619 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8621 if (EatIfPresent(lltok::kw_catch))
8623 else if (EatIfPresent(lltok::kw_filter))
8625 else
8626 return tokError("expected 'catch' or 'filter' clause type");
8627
8628 Value *V;
8629 LocTy VLoc;
8630 if (parseTypeAndValue(V, VLoc, PFS))
8631 return true;
8632
8633 // A 'catch' type expects a non-array constant. A filter clause expects an
8634 // array constant.
8635 if (CT == LandingPadInst::Catch) {
8636 if (isa<ArrayType>(V->getType()))
8637 return error(VLoc, "'catch' clause has an invalid type");
8638 } else {
8639 if (!isa<ArrayType>(V->getType()))
8640 return error(VLoc, "'filter' clause has an invalid type");
8641 }
8642
8644 if (!CV)
8645 return error(VLoc, "clause argument must be a constant");
8646 LP->addClause(CV);
8647 }
8648
8649 Inst = LP.release();
8650 return false;
8651}
8652
8653/// parseFreeze
8654/// ::= 'freeze' Type Value
8655bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8656 LocTy Loc;
8657 Value *Op;
8658 if (parseTypeAndValue(Op, Loc, PFS))
8659 return true;
8660
8661 Inst = new FreezeInst(Op);
8662 return false;
8663}
8664
8665/// parseCall
8666/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8667/// OptionalAttrs Type Value ParameterList OptionalAttrs
8668/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8669/// OptionalAttrs Type Value ParameterList OptionalAttrs
8670/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8671/// OptionalAttrs Type Value ParameterList OptionalAttrs
8672/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8673/// OptionalAttrs Type Value ParameterList OptionalAttrs
8674bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8676 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8677 std::vector<unsigned> FwdRefAttrGrps;
8678 LocTy BuiltinLoc;
8679 unsigned CallAddrSpace;
8680 unsigned CC;
8681 Type *RetType = nullptr;
8682 LocTy RetTypeLoc;
8683 ValID CalleeID;
8686 LocTy CallLoc = Lex.getLoc();
8687
8688 if (TCK != CallInst::TCK_None &&
8689 parseToken(lltok::kw_call,
8690 "expected 'tail call', 'musttail call', or 'notail call'"))
8691 return true;
8692
8693 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8694
8695 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8696 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8697 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8698 parseValID(CalleeID, &PFS) ||
8699 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8700 PFS.getFunction().isVarArg()) ||
8701 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8702 parseOptionalOperandBundles(BundleList, PFS))
8703 return true;
8704
8705 // If RetType is a non-function pointer type, then this is the short syntax
8706 // for the call, which means that RetType is just the return type. Infer the
8707 // rest of the function argument types from the arguments that are present.
8708 FunctionType *Ty;
8709 if (resolveFunctionType(RetType, ArgList, Ty))
8710 return error(RetTypeLoc, "Invalid result type for LLVM function");
8711
8712 CalleeID.FTy = Ty;
8713
8714 // Look up the callee.
8715 Value *Callee;
8716 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8717 Callee, &PFS))
8718 return true;
8719
8720 // Set up the Attribute for the function.
8722
8723 SmallVector<Value*, 8> Args;
8724
8725 // Loop through FunctionType's arguments and ensure they are specified
8726 // correctly. Also, gather any parameter attributes.
8727 FunctionType::param_iterator I = Ty->param_begin();
8728 FunctionType::param_iterator E = Ty->param_end();
8729 for (const ParamInfo &Arg : ArgList) {
8730 Type *ExpectedTy = nullptr;
8731 if (I != E) {
8732 ExpectedTy = *I++;
8733 } else if (!Ty->isVarArg()) {
8734 return error(Arg.Loc, "too many arguments specified");
8735 }
8736
8737 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8738 return error(Arg.Loc, "argument is not of expected type '" +
8739 getTypeString(ExpectedTy) + "'");
8740 Args.push_back(Arg.V);
8741 Attrs.push_back(Arg.Attrs);
8742 }
8743
8744 if (I != E)
8745 return error(CallLoc, "not enough parameters specified for call");
8746
8747 // Finish off the Attribute and check them
8748 AttributeList PAL =
8749 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8750 AttributeSet::get(Context, RetAttrs), Attrs);
8751
8752 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8753 CI->setTailCallKind(TCK);
8754 CI->setCallingConv(CC);
8755 if (FMF.any()) {
8756 if (!isa<FPMathOperator>(CI)) {
8757 CI->deleteValue();
8758 return error(CallLoc, "fast-math-flags specified for call without "
8759 "floating-point scalar or vector return type");
8760 }
8761 CI->setFastMathFlags(FMF);
8762 }
8763
8764 if (CalleeID.Kind == ValID::t_GlobalName &&
8765 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8766 if (SeenNewDbgInfoFormat) {
8767 CI->deleteValue();
8768 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8769 "using non-intrinsic debug info");
8770 }
8771 SeenOldDbgInfoFormat = true;
8772 }
8773 CI->setAttributes(PAL);
8774 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8775 Inst = CI;
8776 return false;
8777}
8778
8779//===----------------------------------------------------------------------===//
8780// Memory Instructions.
8781//===----------------------------------------------------------------------===//
8782
8783/// parseAlloc
8784/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8785/// (',' 'align' i32)? (',', 'addrspace(n))?
8786int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8787 Value *Size = nullptr;
8788 LocTy SizeLoc, TyLoc, ASLoc;
8789 MaybeAlign Alignment;
8790 unsigned AddrSpace = 0;
8791 Type *Ty = nullptr;
8792
8793 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8794 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8795
8796 if (parseType(Ty, TyLoc))
8797 return true;
8798
8800 return error(TyLoc, "invalid type for alloca");
8801
8802 bool AteExtraComma = false;
8803 if (EatIfPresent(lltok::comma)) {
8804 if (Lex.getKind() == lltok::kw_align) {
8805 if (parseOptionalAlignment(Alignment))
8806 return true;
8807 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8808 return true;
8809 } else if (Lex.getKind() == lltok::kw_addrspace) {
8810 ASLoc = Lex.getLoc();
8811 if (parseOptionalAddrSpace(AddrSpace))
8812 return true;
8813 } else if (Lex.getKind() == lltok::MetadataVar) {
8814 AteExtraComma = true;
8815 } else {
8816 if (parseTypeAndValue(Size, SizeLoc, PFS))
8817 return true;
8818 if (EatIfPresent(lltok::comma)) {
8819 if (Lex.getKind() == lltok::kw_align) {
8820 if (parseOptionalAlignment(Alignment))
8821 return true;
8822 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8823 return true;
8824 } else if (Lex.getKind() == lltok::kw_addrspace) {
8825 ASLoc = Lex.getLoc();
8826 if (parseOptionalAddrSpace(AddrSpace))
8827 return true;
8828 } else if (Lex.getKind() == lltok::MetadataVar) {
8829 AteExtraComma = true;
8830 }
8831 }
8832 }
8833 }
8834
8835 if (Size && !Size->getType()->isIntegerTy())
8836 return error(SizeLoc, "element count must have integer type");
8837
8838 SmallPtrSet<Type *, 4> Visited;
8839 if (!Alignment && !Ty->isSized(&Visited))
8840 return error(TyLoc, "Cannot allocate unsized type");
8841 if (!Alignment)
8842 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8843 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8844 AI->setUsedWithInAlloca(IsInAlloca);
8845 AI->setSwiftError(IsSwiftError);
8846 Inst = AI;
8847 return AteExtraComma ? InstExtraComma : InstNormal;
8848}
8849
8850/// parseLoad
8851/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8852/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8853/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8854int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8855 Value *Val; LocTy Loc;
8856 MaybeAlign Alignment;
8857 bool AteExtraComma = false;
8858 bool isAtomic = false;
8861
8862 if (Lex.getKind() == lltok::kw_atomic) {
8863 isAtomic = true;
8864 Lex.Lex();
8865 }
8866
8867 bool isVolatile = false;
8868 if (Lex.getKind() == lltok::kw_volatile) {
8869 isVolatile = true;
8870 Lex.Lex();
8871 }
8872
8873 Type *Ty;
8874 LocTy ExplicitTypeLoc = Lex.getLoc();
8875 if (parseType(Ty) ||
8876 parseToken(lltok::comma, "expected comma after load's type") ||
8877 parseTypeAndValue(Val, Loc, PFS) ||
8878 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8879 parseOptionalCommaAlign(Alignment, AteExtraComma))
8880 return true;
8881
8882 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8883 return error(Loc, "load operand must be a pointer to a first class type");
8884 if (isAtomic && !Alignment)
8885 return error(Loc, "atomic load must have explicit non-zero alignment");
8886 if (Ordering == AtomicOrdering::Release ||
8888 return error(Loc, "atomic load cannot use Release ordering");
8889
8890 SmallPtrSet<Type *, 4> Visited;
8891 if (!Alignment && !Ty->isSized(&Visited))
8892 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8893 if (!Alignment)
8894 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8895 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8896 return AteExtraComma ? InstExtraComma : InstNormal;
8897}
8898
8899/// parseStore
8900
8901/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8902/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8903/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8904int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8905 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8906 MaybeAlign Alignment;
8907 bool AteExtraComma = false;
8908 bool isAtomic = false;
8911
8912 if (Lex.getKind() == lltok::kw_atomic) {
8913 isAtomic = true;
8914 Lex.Lex();
8915 }
8916
8917 bool isVolatile = false;
8918 if (Lex.getKind() == lltok::kw_volatile) {
8919 isVolatile = true;
8920 Lex.Lex();
8921 }
8922
8923 if (parseTypeAndValue(Val, Loc, PFS) ||
8924 parseToken(lltok::comma, "expected ',' after store operand") ||
8925 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8926 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8927 parseOptionalCommaAlign(Alignment, AteExtraComma))
8928 return true;
8929
8930 if (!Ptr->getType()->isPointerTy())
8931 return error(PtrLoc, "store operand must be a pointer");
8932 if (!Val->getType()->isFirstClassType())
8933 return error(Loc, "store operand must be a first class value");
8934 if (isAtomic && !Alignment)
8935 return error(Loc, "atomic store must have explicit non-zero alignment");
8936 if (Ordering == AtomicOrdering::Acquire ||
8938 return error(Loc, "atomic store cannot use Acquire ordering");
8939 SmallPtrSet<Type *, 4> Visited;
8940 if (!Alignment && !Val->getType()->isSized(&Visited))
8941 return error(Loc, "storing unsized types is not allowed");
8942 if (!Alignment)
8943 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8944
8945 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8946 return AteExtraComma ? InstExtraComma : InstNormal;
8947}
8948
8949/// parseCmpXchg
8950/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8951/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8952/// 'Align'?
8953int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8954 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8955 bool AteExtraComma = false;
8956 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8957 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8959 bool isVolatile = false;
8960 bool isWeak = false;
8961 MaybeAlign Alignment;
8962
8963 if (EatIfPresent(lltok::kw_weak))
8964 isWeak = true;
8965
8966 if (EatIfPresent(lltok::kw_volatile))
8967 isVolatile = true;
8968
8969 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8970 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8971 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8972 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8973 parseTypeAndValue(New, NewLoc, PFS) ||
8974 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8975 parseOrdering(FailureOrdering) ||
8976 parseOptionalCommaAlign(Alignment, AteExtraComma))
8977 return true;
8978
8979 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8980 return tokError("invalid cmpxchg success ordering");
8981 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8982 return tokError("invalid cmpxchg failure ordering");
8983 if (!Ptr->getType()->isPointerTy())
8984 return error(PtrLoc, "cmpxchg operand must be a pointer");
8985 if (Cmp->getType() != New->getType())
8986 return error(NewLoc, "compare value and new value type do not match");
8987 if (!New->getType()->isFirstClassType())
8988 return error(NewLoc, "cmpxchg operand must be a first class value");
8989
8990 const Align DefaultAlignment(
8991 PFS.getFunction().getDataLayout().getTypeStoreSize(
8992 Cmp->getType()));
8993
8994 AtomicCmpXchgInst *CXI =
8995 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8996 SuccessOrdering, FailureOrdering, SSID);
8997 CXI->setVolatile(isVolatile);
8998 CXI->setWeak(isWeak);
8999
9000 Inst = CXI;
9001 return AteExtraComma ? InstExtraComma : InstNormal;
9002}
9003
9004/// parseAtomicRMW
9005/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
9006/// 'singlethread'? AtomicOrdering
9007int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9008 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
9009 bool AteExtraComma = false;
9012 bool isVolatile = false;
9013 bool IsFP = false;
9015 MaybeAlign Alignment;
9016
9017 if (EatIfPresent(lltok::kw_volatile))
9018 isVolatile = true;
9019
9020 switch (Lex.getKind()) {
9021 default:
9022 return tokError("expected binary operation in atomicrmw");
9036 break;
9039 break;
9042 break;
9043 case lltok::kw_usub_sat:
9045 break;
9046 case lltok::kw_fadd:
9048 IsFP = true;
9049 break;
9050 case lltok::kw_fsub:
9052 IsFP = true;
9053 break;
9054 case lltok::kw_fmax:
9056 IsFP = true;
9057 break;
9058 case lltok::kw_fmin:
9060 IsFP = true;
9061 break;
9062 case lltok::kw_fmaximum:
9064 IsFP = true;
9065 break;
9066 case lltok::kw_fminimum:
9068 IsFP = true;
9069 break;
9072 IsFP = true;
9073 break;
9076 IsFP = true;
9077 break;
9078 }
9079 Lex.Lex(); // Eat the operation.
9080
9081 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9082 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
9083 parseTypeAndValue(Val, ValLoc, PFS) ||
9084 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
9085 parseOptionalCommaAlign(Alignment, AteExtraComma))
9086 return true;
9087
9088 if (Ordering == AtomicOrdering::Unordered)
9089 return tokError("atomicrmw cannot be unordered");
9090 if (!Ptr->getType()->isPointerTy())
9091 return error(PtrLoc, "atomicrmw operand must be a pointer");
9092 if (Val->getType()->isScalableTy())
9093 return error(ValLoc, "atomicrmw operand may not be scalable");
9094
9096 if (!Val->getType()->isIntegerTy() &&
9097 !Val->getType()->isFloatingPointTy() &&
9098 !Val->getType()->isPointerTy()) {
9099 return error(
9100 ValLoc,
9102 " operand must be an integer, floating point, or pointer type");
9103 }
9104 } else if (IsFP) {
9105 if (!Val->getType()->isFPOrFPVectorTy()) {
9106 return error(ValLoc, "atomicrmw " +
9108 " operand must be a floating point type");
9109 }
9110 } else {
9111 if (!Val->getType()->isIntegerTy()) {
9112 return error(ValLoc, "atomicrmw " +
9114 " operand must be an integer");
9115 }
9116 }
9117
9118 unsigned Size =
9119 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
9120 Val->getType());
9121 if (Size < 8 || (Size & (Size - 1)))
9122 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
9123 " integer");
9124 const Align DefaultAlignment(
9125 PFS.getFunction().getDataLayout().getTypeStoreSize(
9126 Val->getType()));
9127 AtomicRMWInst *RMWI =
9128 new AtomicRMWInst(Operation, Ptr, Val,
9129 Alignment.value_or(DefaultAlignment), Ordering, SSID);
9130 RMWI->setVolatile(isVolatile);
9131 Inst = RMWI;
9132 return AteExtraComma ? InstExtraComma : InstNormal;
9133}
9134
9135/// parseFence
9136/// ::= 'fence' 'singlethread'? AtomicOrdering
9137int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9140 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
9141 return true;
9142
9143 if (Ordering == AtomicOrdering::Unordered)
9144 return tokError("fence cannot be unordered");
9145 if (Ordering == AtomicOrdering::Monotonic)
9146 return tokError("fence cannot be monotonic");
9147
9148 Inst = new FenceInst(Context, Ordering, SSID);
9149 return InstNormal;
9150}
9151
9152/// parseGetElementPtr
9153/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9154int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9155 Value *Ptr = nullptr;
9156 Value *Val = nullptr;
9157 LocTy Loc, EltLoc;
9158 GEPNoWrapFlags NW;
9159
9160 while (true) {
9161 if (EatIfPresent(lltok::kw_inbounds))
9163 else if (EatIfPresent(lltok::kw_nusw))
9165 else if (EatIfPresent(lltok::kw_nuw))
9167 else
9168 break;
9169 }
9170
9171 Type *Ty = nullptr;
9172 if (parseType(Ty) ||
9173 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
9174 parseTypeAndValue(Ptr, Loc, PFS))
9175 return true;
9176
9177 Type *BaseType = Ptr->getType();
9178 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
9179 if (!BasePointerType)
9180 return error(Loc, "base of getelementptr must be a pointer");
9181
9182 SmallVector<Value*, 16> Indices;
9183 bool AteExtraComma = false;
9184 // GEP returns a vector of pointers if at least one of parameters is a vector.
9185 // All vector parameters should have the same vector width.
9186 ElementCount GEPWidth = BaseType->isVectorTy()
9187 ? cast<VectorType>(BaseType)->getElementCount()
9189
9190 while (EatIfPresent(lltok::comma)) {
9191 if (Lex.getKind() == lltok::MetadataVar) {
9192 AteExtraComma = true;
9193 break;
9194 }
9195 if (parseTypeAndValue(Val, EltLoc, PFS))
9196 return true;
9197 if (!Val->getType()->isIntOrIntVectorTy())
9198 return error(EltLoc, "getelementptr index must be an integer");
9199
9200 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
9201 ElementCount ValNumEl = ValVTy->getElementCount();
9202 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
9203 return error(
9204 EltLoc,
9205 "getelementptr vector index has a wrong number of elements");
9206 GEPWidth = ValNumEl;
9207 }
9208 Indices.push_back(Val);
9209 }
9210
9211 SmallPtrSet<Type*, 4> Visited;
9212 if (!Indices.empty() && !Ty->isSized(&Visited))
9213 return error(Loc, "base element of getelementptr must be sized");
9214
9215 auto *STy = dyn_cast<StructType>(Ty);
9216 if (STy && STy->isScalableTy())
9217 return error(Loc, "getelementptr cannot target structure that contains "
9218 "scalable vector type");
9219
9220 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
9221 return error(Loc, "invalid getelementptr indices");
9222 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
9223 Inst = GEP;
9224 GEP->setNoWrapFlags(NW);
9225 return AteExtraComma ? InstExtraComma : InstNormal;
9226}
9227
9228/// parseExtractValue
9229/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9230int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9231 Value *Val; LocTy Loc;
9232 SmallVector<unsigned, 4> Indices;
9233 bool AteExtraComma;
9234 if (parseTypeAndValue(Val, Loc, PFS) ||
9235 parseIndexList(Indices, AteExtraComma))
9236 return true;
9237
9238 if (!Val->getType()->isAggregateType())
9239 return error(Loc, "extractvalue operand must be aggregate type");
9240
9241 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9242 return error(Loc, "invalid indices for extractvalue");
9243 Inst = ExtractValueInst::Create(Val, Indices);
9244 return AteExtraComma ? InstExtraComma : InstNormal;
9245}
9246
9247/// parseInsertValue
9248/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9249int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9250 Value *Val0, *Val1; LocTy Loc0, Loc1;
9251 SmallVector<unsigned, 4> Indices;
9252 bool AteExtraComma;
9253 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9254 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9255 parseTypeAndValue(Val1, Loc1, PFS) ||
9256 parseIndexList(Indices, AteExtraComma))
9257 return true;
9258
9259 if (!Val0->getType()->isAggregateType())
9260 return error(Loc0, "insertvalue operand must be aggregate type");
9261
9262 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9263 if (!IndexedType)
9264 return error(Loc0, "invalid indices for insertvalue");
9265 if (IndexedType != Val1->getType())
9266 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9267 getTypeString(Val1->getType()) + "' instead of '" +
9268 getTypeString(IndexedType) + "'");
9269 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9270 return AteExtraComma ? InstExtraComma : InstNormal;
9271}
9272
9273//===----------------------------------------------------------------------===//
9274// Embedded metadata.
9275//===----------------------------------------------------------------------===//
9276
9277/// parseMDNodeVector
9278/// ::= { Element (',' Element)* }
9279/// Element
9280/// ::= 'null' | Metadata
9281bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9282 if (parseToken(lltok::lbrace, "expected '{' here"))
9283 return true;
9284
9285 // Check for an empty list.
9286 if (EatIfPresent(lltok::rbrace))
9287 return false;
9288
9289 do {
9290 if (EatIfPresent(lltok::kw_null)) {
9291 Elts.push_back(nullptr);
9292 continue;
9293 }
9294
9295 Metadata *MD;
9296 if (parseMetadata(MD, nullptr))
9297 return true;
9298 Elts.push_back(MD);
9299 } while (EatIfPresent(lltok::comma));
9300
9301 return parseToken(lltok::rbrace, "expected end of metadata node");
9302}
9303
9304//===----------------------------------------------------------------------===//
9305// Use-list order directives.
9306//===----------------------------------------------------------------------===//
9307bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9308 SMLoc Loc) {
9309 if (!V->hasUseList())
9310 return false;
9311 if (V->use_empty())
9312 return error(Loc, "value has no uses");
9313
9314 unsigned NumUses = 0;
9315 SmallDenseMap<const Use *, unsigned, 16> Order;
9316 for (const Use &U : V->uses()) {
9317 if (++NumUses > Indexes.size())
9318 break;
9319 Order[&U] = Indexes[NumUses - 1];
9320 }
9321 if (NumUses < 2)
9322 return error(Loc, "value only has one use");
9323 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9324 return error(Loc,
9325 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9326
9327 V->sortUseList([&](const Use &L, const Use &R) {
9328 return Order.lookup(&L) < Order.lookup(&R);
9329 });
9330 return false;
9331}
9332
9333/// parseUseListOrderIndexes
9334/// ::= '{' uint32 (',' uint32)+ '}'
9335bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9336 SMLoc Loc = Lex.getLoc();
9337 if (parseToken(lltok::lbrace, "expected '{' here"))
9338 return true;
9339 if (Lex.getKind() == lltok::rbrace)
9340 return tokError("expected non-empty list of uselistorder indexes");
9341
9342 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9343 // indexes should be distinct numbers in the range [0, size-1], and should
9344 // not be in order.
9345 unsigned Offset = 0;
9346 unsigned Max = 0;
9347 bool IsOrdered = true;
9348 assert(Indexes.empty() && "Expected empty order vector");
9349 do {
9350 unsigned Index;
9351 if (parseUInt32(Index))
9352 return true;
9353
9354 // Update consistency checks.
9355 Offset += Index - Indexes.size();
9356 Max = std::max(Max, Index);
9357 IsOrdered &= Index == Indexes.size();
9358
9359 Indexes.push_back(Index);
9360 } while (EatIfPresent(lltok::comma));
9361
9362 if (parseToken(lltok::rbrace, "expected '}' here"))
9363 return true;
9364
9365 if (Indexes.size() < 2)
9366 return error(Loc, "expected >= 2 uselistorder indexes");
9367 if (Offset != 0 || Max >= Indexes.size())
9368 return error(Loc,
9369 "expected distinct uselistorder indexes in range [0, size)");
9370 if (IsOrdered)
9371 return error(Loc, "expected uselistorder indexes to change the order");
9372
9373 return false;
9374}
9375
9376/// parseUseListOrder
9377/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9378bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9379 SMLoc Loc = Lex.getLoc();
9380 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9381 return true;
9382
9383 Value *V;
9384 SmallVector<unsigned, 16> Indexes;
9385 if (parseTypeAndValue(V, PFS) ||
9386 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9387 parseUseListOrderIndexes(Indexes))
9388 return true;
9389
9390 return sortUseListOrder(V, Indexes, Loc);
9391}
9392
9393/// parseUseListOrderBB
9394/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
9395bool LLParser::parseUseListOrderBB() {
9396 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
9397 SMLoc Loc = Lex.getLoc();
9398 Lex.Lex();
9399
9400 ValID Fn, Label;
9401 SmallVector<unsigned, 16> Indexes;
9402 if (parseValID(Fn, /*PFS=*/nullptr) ||
9403 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9404 parseValID(Label, /*PFS=*/nullptr) ||
9405 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9406 parseUseListOrderIndexes(Indexes))
9407 return true;
9408
9409 // Check the function.
9410 GlobalValue *GV;
9411 if (Fn.Kind == ValID::t_GlobalName)
9412 GV = M->getNamedValue(Fn.StrVal);
9413 else if (Fn.Kind == ValID::t_GlobalID)
9414 GV = NumberedVals.get(Fn.UIntVal);
9415 else
9416 return error(Fn.Loc, "expected function name in uselistorder_bb");
9417 if (!GV)
9418 return error(Fn.Loc,
9419 "invalid function forward reference in uselistorder_bb");
9420 auto *F = dyn_cast<Function>(GV);
9421 if (!F)
9422 return error(Fn.Loc, "expected function name in uselistorder_bb");
9423 if (F->isDeclaration())
9424 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
9425
9426 // Check the basic block.
9427 if (Label.Kind == ValID::t_LocalID)
9428 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
9429 if (Label.Kind != ValID::t_LocalName)
9430 return error(Label.Loc, "expected basic block name in uselistorder_bb");
9431 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
9432 if (!V)
9433 return error(Label.Loc, "invalid basic block in uselistorder_bb");
9434 if (!isa<BasicBlock>(V))
9435 return error(Label.Loc, "expected basic block in uselistorder_bb");
9436
9437 return sortUseListOrder(V, Indexes, Loc);
9438}
9439
9440/// ModuleEntry
9441/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9442/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9443bool LLParser::parseModuleEntry(unsigned ID) {
9444 assert(Lex.getKind() == lltok::kw_module);
9445 Lex.Lex();
9446
9447 std::string Path;
9448 if (parseToken(lltok::colon, "expected ':' here") ||
9449 parseToken(lltok::lparen, "expected '(' here") ||
9450 parseToken(lltok::kw_path, "expected 'path' here") ||
9451 parseToken(lltok::colon, "expected ':' here") ||
9452 parseStringConstant(Path) ||
9453 parseToken(lltok::comma, "expected ',' here") ||
9454 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9455 parseToken(lltok::colon, "expected ':' here") ||
9456 parseToken(lltok::lparen, "expected '(' here"))
9457 return true;
9458
9459 ModuleHash Hash;
9460 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9461 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9462 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9463 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9464 parseUInt32(Hash[4]))
9465 return true;
9466
9467 if (parseToken(lltok::rparen, "expected ')' here") ||
9468 parseToken(lltok::rparen, "expected ')' here"))
9469 return true;
9470
9471 auto ModuleEntry = Index->addModule(Path, Hash);
9472 ModuleIdMap[ID] = ModuleEntry->first();
9473
9474 return false;
9475}
9476
9477/// TypeIdEntry
9478/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9479bool LLParser::parseTypeIdEntry(unsigned ID) {
9480 assert(Lex.getKind() == lltok::kw_typeid);
9481 Lex.Lex();
9482
9483 std::string Name;
9484 if (parseToken(lltok::colon, "expected ':' here") ||
9485 parseToken(lltok::lparen, "expected '(' here") ||
9486 parseToken(lltok::kw_name, "expected 'name' here") ||
9487 parseToken(lltok::colon, "expected ':' here") ||
9488 parseStringConstant(Name))
9489 return true;
9490
9491 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9492 if (parseToken(lltok::comma, "expected ',' here") ||
9493 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9494 return true;
9495
9496 // Check if this ID was forward referenced, and if so, update the
9497 // corresponding GUIDs.
9498 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9499 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9500 for (auto TIDRef : FwdRefTIDs->second) {
9501 assert(!*TIDRef.first &&
9502 "Forward referenced type id GUID expected to be 0");
9503 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9504 }
9505 ForwardRefTypeIds.erase(FwdRefTIDs);
9506 }
9507
9508 return false;
9509}
9510
9511/// TypeIdSummary
9512/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9513bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9514 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9515 parseToken(lltok::colon, "expected ':' here") ||
9516 parseToken(lltok::lparen, "expected '(' here") ||
9517 parseTypeTestResolution(TIS.TTRes))
9518 return true;
9519
9520 if (EatIfPresent(lltok::comma)) {
9521 // Expect optional wpdResolutions field
9522 if (parseOptionalWpdResolutions(TIS.WPDRes))
9523 return true;
9524 }
9525
9526 if (parseToken(lltok::rparen, "expected ')' here"))
9527 return true;
9528
9529 return false;
9530}
9531
9533 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9534
9535/// TypeIdCompatibleVtableEntry
9536/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9537/// TypeIdCompatibleVtableInfo
9538/// ')'
9539bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9541 Lex.Lex();
9542
9543 std::string Name;
9544 if (parseToken(lltok::colon, "expected ':' here") ||
9545 parseToken(lltok::lparen, "expected '(' here") ||
9546 parseToken(lltok::kw_name, "expected 'name' here") ||
9547 parseToken(lltok::colon, "expected ':' here") ||
9548 parseStringConstant(Name))
9549 return true;
9550
9552 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9553 if (parseToken(lltok::comma, "expected ',' here") ||
9554 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9555 parseToken(lltok::colon, "expected ':' here") ||
9556 parseToken(lltok::lparen, "expected '(' here"))
9557 return true;
9558
9559 IdToIndexMapType IdToIndexMap;
9560 // parse each call edge
9561 do {
9563 if (parseToken(lltok::lparen, "expected '(' here") ||
9564 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9565 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9566 parseToken(lltok::comma, "expected ',' here"))
9567 return true;
9568
9569 LocTy Loc = Lex.getLoc();
9570 unsigned GVId;
9571 ValueInfo VI;
9572 if (parseGVReference(VI, GVId))
9573 return true;
9574
9575 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9576 // forward reference. We will save the location of the ValueInfo needing an
9577 // update, but can only do so once the std::vector is finalized.
9578 if (VI == EmptyVI)
9579 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9580 TI.push_back({Offset, VI});
9581
9582 if (parseToken(lltok::rparen, "expected ')' in call"))
9583 return true;
9584 } while (EatIfPresent(lltok::comma));
9585
9586 // Now that the TI vector is finalized, it is safe to save the locations
9587 // of any forward GV references that need updating later.
9588 for (auto I : IdToIndexMap) {
9589 auto &Infos = ForwardRefValueInfos[I.first];
9590 for (auto P : I.second) {
9591 assert(TI[P.first].VTableVI == EmptyVI &&
9592 "Forward referenced ValueInfo expected to be empty");
9593 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9594 }
9595 }
9596
9597 if (parseToken(lltok::rparen, "expected ')' here") ||
9598 parseToken(lltok::rparen, "expected ')' here"))
9599 return true;
9600
9601 // Check if this ID was forward referenced, and if so, update the
9602 // corresponding GUIDs.
9603 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9604 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9605 for (auto TIDRef : FwdRefTIDs->second) {
9606 assert(!*TIDRef.first &&
9607 "Forward referenced type id GUID expected to be 0");
9608 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9609 }
9610 ForwardRefTypeIds.erase(FwdRefTIDs);
9611 }
9612
9613 return false;
9614}
9615
9616/// TypeTestResolution
9617/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9618/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9619/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9620/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9621/// [',' 'inlinesBits' ':' UInt64]? ')'
9622bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9623 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9624 parseToken(lltok::colon, "expected ':' here") ||
9625 parseToken(lltok::lparen, "expected '(' here") ||
9626 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9627 parseToken(lltok::colon, "expected ':' here"))
9628 return true;
9629
9630 switch (Lex.getKind()) {
9631 case lltok::kw_unknown:
9633 break;
9634 case lltok::kw_unsat:
9636 break;
9639 break;
9640 case lltok::kw_inline:
9642 break;
9643 case lltok::kw_single:
9645 break;
9646 case lltok::kw_allOnes:
9648 break;
9649 default:
9650 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9651 }
9652 Lex.Lex();
9653
9654 if (parseToken(lltok::comma, "expected ',' here") ||
9655 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9656 parseToken(lltok::colon, "expected ':' here") ||
9657 parseUInt32(TTRes.SizeM1BitWidth))
9658 return true;
9659
9660 // parse optional fields
9661 while (EatIfPresent(lltok::comma)) {
9662 switch (Lex.getKind()) {
9664 Lex.Lex();
9665 if (parseToken(lltok::colon, "expected ':'") ||
9666 parseUInt64(TTRes.AlignLog2))
9667 return true;
9668 break;
9669 case lltok::kw_sizeM1:
9670 Lex.Lex();
9671 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9672 return true;
9673 break;
9674 case lltok::kw_bitMask: {
9675 unsigned Val;
9676 Lex.Lex();
9677 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9678 return true;
9679 assert(Val <= 0xff);
9680 TTRes.BitMask = (uint8_t)Val;
9681 break;
9682 }
9684 Lex.Lex();
9685 if (parseToken(lltok::colon, "expected ':'") ||
9686 parseUInt64(TTRes.InlineBits))
9687 return true;
9688 break;
9689 default:
9690 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9691 }
9692 }
9693
9694 if (parseToken(lltok::rparen, "expected ')' here"))
9695 return true;
9696
9697 return false;
9698}
9699
9700/// OptionalWpdResolutions
9701/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9702/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9703bool LLParser::parseOptionalWpdResolutions(
9704 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9705 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9706 parseToken(lltok::colon, "expected ':' here") ||
9707 parseToken(lltok::lparen, "expected '(' here"))
9708 return true;
9709
9710 do {
9711 uint64_t Offset;
9712 WholeProgramDevirtResolution WPDRes;
9713 if (parseToken(lltok::lparen, "expected '(' here") ||
9714 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9715 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9716 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9717 parseToken(lltok::rparen, "expected ')' here"))
9718 return true;
9719 WPDResMap[Offset] = WPDRes;
9720 } while (EatIfPresent(lltok::comma));
9721
9722 if (parseToken(lltok::rparen, "expected ')' here"))
9723 return true;
9724
9725 return false;
9726}
9727
9728/// WpdRes
9729/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9730/// [',' OptionalResByArg]? ')'
9731/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9732/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9733/// [',' OptionalResByArg]? ')'
9734/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9735/// [',' OptionalResByArg]? ')'
9736bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9737 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9738 parseToken(lltok::colon, "expected ':' here") ||
9739 parseToken(lltok::lparen, "expected '(' here") ||
9740 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9741 parseToken(lltok::colon, "expected ':' here"))
9742 return true;
9743
9744 switch (Lex.getKind()) {
9745 case lltok::kw_indir:
9747 break;
9750 break;
9753 break;
9754 default:
9755 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9756 }
9757 Lex.Lex();
9758
9759 // parse optional fields
9760 while (EatIfPresent(lltok::comma)) {
9761 switch (Lex.getKind()) {
9763 Lex.Lex();
9764 if (parseToken(lltok::colon, "expected ':' here") ||
9765 parseStringConstant(WPDRes.SingleImplName))
9766 return true;
9767 break;
9768 case lltok::kw_resByArg:
9769 if (parseOptionalResByArg(WPDRes.ResByArg))
9770 return true;
9771 break;
9772 default:
9773 return error(Lex.getLoc(),
9774 "expected optional WholeProgramDevirtResolution field");
9775 }
9776 }
9777
9778 if (parseToken(lltok::rparen, "expected ')' here"))
9779 return true;
9780
9781 return false;
9782}
9783
9784/// OptionalResByArg
9785/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9786/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9787/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9788/// 'virtualConstProp' )
9789/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9790/// [',' 'bit' ':' UInt32]? ')'
9791bool LLParser::parseOptionalResByArg(
9792 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9793 &ResByArg) {
9794 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9795 parseToken(lltok::colon, "expected ':' here") ||
9796 parseToken(lltok::lparen, "expected '(' here"))
9797 return true;
9798
9799 do {
9800 std::vector<uint64_t> Args;
9801 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9802 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9803 parseToken(lltok::colon, "expected ':' here") ||
9804 parseToken(lltok::lparen, "expected '(' here") ||
9805 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9806 parseToken(lltok::colon, "expected ':' here"))
9807 return true;
9808
9809 WholeProgramDevirtResolution::ByArg ByArg;
9810 switch (Lex.getKind()) {
9811 case lltok::kw_indir:
9813 break;
9816 break;
9819 break;
9822 break;
9823 default:
9824 return error(Lex.getLoc(),
9825 "unexpected WholeProgramDevirtResolution::ByArg kind");
9826 }
9827 Lex.Lex();
9828
9829 // parse optional fields
9830 while (EatIfPresent(lltok::comma)) {
9831 switch (Lex.getKind()) {
9832 case lltok::kw_info:
9833 Lex.Lex();
9834 if (parseToken(lltok::colon, "expected ':' here") ||
9835 parseUInt64(ByArg.Info))
9836 return true;
9837 break;
9838 case lltok::kw_byte:
9839 Lex.Lex();
9840 if (parseToken(lltok::colon, "expected ':' here") ||
9841 parseUInt32(ByArg.Byte))
9842 return true;
9843 break;
9844 case lltok::kw_bit:
9845 Lex.Lex();
9846 if (parseToken(lltok::colon, "expected ':' here") ||
9847 parseUInt32(ByArg.Bit))
9848 return true;
9849 break;
9850 default:
9851 return error(Lex.getLoc(),
9852 "expected optional whole program devirt field");
9853 }
9854 }
9855
9856 if (parseToken(lltok::rparen, "expected ')' here"))
9857 return true;
9858
9859 ResByArg[Args] = ByArg;
9860 } while (EatIfPresent(lltok::comma));
9861
9862 if (parseToken(lltok::rparen, "expected ')' here"))
9863 return true;
9864
9865 return false;
9866}
9867
9868/// OptionalResByArg
9869/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9870bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9871 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9872 parseToken(lltok::colon, "expected ':' here") ||
9873 parseToken(lltok::lparen, "expected '(' here"))
9874 return true;
9875
9876 do {
9877 uint64_t Val;
9878 if (parseUInt64(Val))
9879 return true;
9880 Args.push_back(Val);
9881 } while (EatIfPresent(lltok::comma));
9882
9883 if (parseToken(lltok::rparen, "expected ')' here"))
9884 return true;
9885
9886 return false;
9887}
9888
9889static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9890
9891static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9892 bool ReadOnly = Fwd->isReadOnly();
9893 bool WriteOnly = Fwd->isWriteOnly();
9894 assert(!(ReadOnly && WriteOnly));
9895 *Fwd = Resolved;
9896 if (ReadOnly)
9897 Fwd->setReadOnly();
9898 if (WriteOnly)
9899 Fwd->setWriteOnly();
9900}
9901
9902/// Stores the given Name/GUID and associated summary into the Index.
9903/// Also updates any forward references to the associated entry ID.
9904bool LLParser::addGlobalValueToIndex(
9905 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9906 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9907 // First create the ValueInfo utilizing the Name or GUID.
9908 ValueInfo VI;
9909 if (GUID != 0) {
9910 assert(Name.empty());
9911 VI = Index->getOrInsertValueInfo(GUID);
9912 } else {
9913 assert(!Name.empty());
9914 if (M) {
9915 auto *GV = M->getNamedValue(Name);
9916 if (!GV)
9917 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9918
9919 VI = Index->getOrInsertValueInfo(GV);
9920 } else {
9921 assert(
9922 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9923 "Need a source_filename to compute GUID for local");
9925 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9926 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9927 }
9928 }
9929
9930 // Resolve forward references from calls/refs
9931 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9932 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9933 for (auto VIRef : FwdRefVIs->second) {
9934 assert(VIRef.first->getRef() == FwdVIRef &&
9935 "Forward referenced ValueInfo expected to be empty");
9936 resolveFwdRef(VIRef.first, VI);
9937 }
9938 ForwardRefValueInfos.erase(FwdRefVIs);
9939 }
9940
9941 // Resolve forward references from aliases
9942 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9943 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9944 for (auto AliaseeRef : FwdRefAliasees->second) {
9945 assert(!AliaseeRef.first->hasAliasee() &&
9946 "Forward referencing alias already has aliasee");
9947 assert(Summary && "Aliasee must be a definition");
9948 AliaseeRef.first->setAliasee(VI, Summary.get());
9949 }
9950 ForwardRefAliasees.erase(FwdRefAliasees);
9951 }
9952
9953 // Add the summary if one was provided.
9954 if (Summary)
9955 Index->addGlobalValueSummary(VI, std::move(Summary));
9956
9957 // Save the associated ValueInfo for use in later references by ID.
9958 if (ID == NumberedValueInfos.size())
9959 NumberedValueInfos.push_back(VI);
9960 else {
9961 // Handle non-continuous numbers (to make test simplification easier).
9962 if (ID > NumberedValueInfos.size())
9963 NumberedValueInfos.resize(ID + 1);
9964 NumberedValueInfos[ID] = VI;
9965 }
9966
9967 return false;
9968}
9969
9970/// parseSummaryIndexFlags
9971/// ::= 'flags' ':' UInt64
9972bool LLParser::parseSummaryIndexFlags() {
9973 assert(Lex.getKind() == lltok::kw_flags);
9974 Lex.Lex();
9975
9976 if (parseToken(lltok::colon, "expected ':' here"))
9977 return true;
9978 uint64_t Flags;
9979 if (parseUInt64(Flags))
9980 return true;
9981 if (Index)
9982 Index->setFlags(Flags);
9983 return false;
9984}
9985
9986/// parseBlockCount
9987/// ::= 'blockcount' ':' UInt64
9988bool LLParser::parseBlockCount() {
9989 assert(Lex.getKind() == lltok::kw_blockcount);
9990 Lex.Lex();
9991
9992 if (parseToken(lltok::colon, "expected ':' here"))
9993 return true;
9994 uint64_t BlockCount;
9995 if (parseUInt64(BlockCount))
9996 return true;
9997 if (Index)
9998 Index->setBlockCount(BlockCount);
9999 return false;
10000}
10001
10002/// parseGVEntry
10003/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
10004/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
10005/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
10006bool LLParser::parseGVEntry(unsigned ID) {
10007 assert(Lex.getKind() == lltok::kw_gv);
10008 Lex.Lex();
10009
10010 if (parseToken(lltok::colon, "expected ':' here") ||
10011 parseToken(lltok::lparen, "expected '(' here"))
10012 return true;
10013
10014 LocTy Loc = Lex.getLoc();
10015 std::string Name;
10017 switch (Lex.getKind()) {
10018 case lltok::kw_name:
10019 Lex.Lex();
10020 if (parseToken(lltok::colon, "expected ':' here") ||
10021 parseStringConstant(Name))
10022 return true;
10023 // Can't create GUID/ValueInfo until we have the linkage.
10024 break;
10025 case lltok::kw_guid:
10026 Lex.Lex();
10027 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
10028 return true;
10029 break;
10030 default:
10031 return error(Lex.getLoc(), "expected name or guid tag");
10032 }
10033
10034 if (!EatIfPresent(lltok::comma)) {
10035 // No summaries. Wrap up.
10036 if (parseToken(lltok::rparen, "expected ')' here"))
10037 return true;
10038 // This was created for a call to an external or indirect target.
10039 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
10040 // created for indirect calls with VP. A Name with no GUID came from
10041 // an external definition. We pass ExternalLinkage since that is only
10042 // used when the GUID must be computed from Name, and in that case
10043 // the symbol must have external linkage.
10044 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
10045 nullptr, Loc);
10046 }
10047
10048 // Have a list of summaries
10049 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
10050 parseToken(lltok::colon, "expected ':' here") ||
10051 parseToken(lltok::lparen, "expected '(' here"))
10052 return true;
10053 do {
10054 switch (Lex.getKind()) {
10055 case lltok::kw_function:
10056 if (parseFunctionSummary(Name, GUID, ID))
10057 return true;
10058 break;
10059 case lltok::kw_variable:
10060 if (parseVariableSummary(Name, GUID, ID))
10061 return true;
10062 break;
10063 case lltok::kw_alias:
10064 if (parseAliasSummary(Name, GUID, ID))
10065 return true;
10066 break;
10067 default:
10068 return error(Lex.getLoc(), "expected summary type");
10069 }
10070 } while (EatIfPresent(lltok::comma));
10071
10072 if (parseToken(lltok::rparen, "expected ')' here") ||
10073 parseToken(lltok::rparen, "expected ')' here"))
10074 return true;
10075
10076 return false;
10077}
10078
10079/// FunctionSummary
10080/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10081/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10082/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10083/// [',' OptionalRefs]? ')'
10084bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10085 unsigned ID) {
10086 LocTy Loc = Lex.getLoc();
10087 assert(Lex.getKind() == lltok::kw_function);
10088 Lex.Lex();
10089
10090 StringRef ModulePath;
10091 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10093 /*NotEligibleToImport=*/false,
10094 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10095 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10096 unsigned InstCount;
10098 FunctionSummary::TypeIdInfo TypeIdInfo;
10099 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10101 std::vector<CallsiteInfo> Callsites;
10102 std::vector<AllocInfo> Allocs;
10103 // Default is all-zeros (conservative values).
10104 FunctionSummary::FFlags FFlags = {};
10105 if (parseToken(lltok::colon, "expected ':' here") ||
10106 parseToken(lltok::lparen, "expected '(' here") ||
10107 parseModuleReference(ModulePath) ||
10108 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10109 parseToken(lltok::comma, "expected ',' here") ||
10110 parseToken(lltok::kw_insts, "expected 'insts' here") ||
10111 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
10112 return true;
10113
10114 // parse optional fields
10115 while (EatIfPresent(lltok::comma)) {
10116 switch (Lex.getKind()) {
10118 if (parseOptionalFFlags(FFlags))
10119 return true;
10120 break;
10121 case lltok::kw_calls:
10122 if (parseOptionalCalls(Calls))
10123 return true;
10124 break;
10126 if (parseOptionalTypeIdInfo(TypeIdInfo))
10127 return true;
10128 break;
10129 case lltok::kw_refs:
10130 if (parseOptionalRefs(Refs))
10131 return true;
10132 break;
10133 case lltok::kw_params:
10134 if (parseOptionalParamAccesses(ParamAccesses))
10135 return true;
10136 break;
10137 case lltok::kw_allocs:
10138 if (parseOptionalAllocs(Allocs))
10139 return true;
10140 break;
10142 if (parseOptionalCallsites(Callsites))
10143 return true;
10144 break;
10145 default:
10146 return error(Lex.getLoc(), "expected optional function summary field");
10147 }
10148 }
10149
10150 if (parseToken(lltok::rparen, "expected ')' here"))
10151 return true;
10152
10153 auto FS = std::make_unique<FunctionSummary>(
10154 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10155 std::move(TypeIdInfo.TypeTests),
10156 std::move(TypeIdInfo.TypeTestAssumeVCalls),
10157 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10158 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10159 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10160 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10161
10162 FS->setModulePath(ModulePath);
10163
10164 return addGlobalValueToIndex(Name, GUID,
10166 std::move(FS), Loc);
10167}
10168
10169/// VariableSummary
10170/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10171/// [',' OptionalRefs]? ')'
10172bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10173 unsigned ID) {
10174 LocTy Loc = Lex.getLoc();
10175 assert(Lex.getKind() == lltok::kw_variable);
10176 Lex.Lex();
10177
10178 StringRef ModulePath;
10179 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10181 /*NotEligibleToImport=*/false,
10182 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10183 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10184 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10185 /* WriteOnly */ false,
10186 /* Constant */ false,
10189 VTableFuncList VTableFuncs;
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 parseGVarFlags(GVarFlags))
10196 return true;
10197
10198 // parse optional fields
10199 while (EatIfPresent(lltok::comma)) {
10200 switch (Lex.getKind()) {
10202 if (parseOptionalVTableFuncs(VTableFuncs))
10203 return true;
10204 break;
10205 case lltok::kw_refs:
10206 if (parseOptionalRefs(Refs))
10207 return true;
10208 break;
10209 default:
10210 return error(Lex.getLoc(), "expected optional variable summary field");
10211 }
10212 }
10213
10214 if (parseToken(lltok::rparen, "expected ')' here"))
10215 return true;
10216
10217 auto GS =
10218 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10219
10220 GS->setModulePath(ModulePath);
10221 GS->setVTableFuncs(std::move(VTableFuncs));
10222
10223 return addGlobalValueToIndex(Name, GUID,
10225 std::move(GS), Loc);
10226}
10227
10228/// AliasSummary
10229/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10230/// 'aliasee' ':' GVReference ')'
10231bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10232 unsigned ID) {
10233 assert(Lex.getKind() == lltok::kw_alias);
10234 LocTy Loc = Lex.getLoc();
10235 Lex.Lex();
10236
10237 StringRef ModulePath;
10238 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10240 /*NotEligibleToImport=*/false,
10241 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10242 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10243 if (parseToken(lltok::colon, "expected ':' here") ||
10244 parseToken(lltok::lparen, "expected '(' here") ||
10245 parseModuleReference(ModulePath) ||
10246 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10247 parseToken(lltok::comma, "expected ',' here") ||
10248 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10249 parseToken(lltok::colon, "expected ':' here"))
10250 return true;
10251
10252 ValueInfo AliaseeVI;
10253 unsigned GVId;
10254 auto AS = std::make_unique<AliasSummary>(GVFlags);
10255 AS->setModulePath(ModulePath);
10256
10257 if (!EatIfPresent(lltok::kw_null)) {
10258 if (parseGVReference(AliaseeVI, GVId))
10259 return true;
10260
10261 // Record forward reference if the aliasee is not parsed yet.
10262 if (AliaseeVI.getRef() == FwdVIRef) {
10263 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10264 } else {
10265 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10266 assert(Summary && "Aliasee must be a definition");
10267 AS->setAliasee(AliaseeVI, Summary);
10268 }
10269 }
10270
10271 if (parseToken(lltok::rparen, "expected ')' here"))
10272 return true;
10273
10274 return addGlobalValueToIndex(Name, GUID,
10276 std::move(AS), Loc);
10277}
10278
10279/// Flag
10280/// ::= [0|1]
10281bool LLParser::parseFlag(unsigned &Val) {
10282 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10283 return tokError("expected integer");
10284 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10285 Lex.Lex();
10286 return false;
10287}
10288
10289/// OptionalFFlags
10290/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10291/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10292/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10293/// [',' 'noInline' ':' Flag]? ')'
10294/// [',' 'alwaysInline' ':' Flag]? ')'
10295/// [',' 'noUnwind' ':' Flag]? ')'
10296/// [',' 'mayThrow' ':' Flag]? ')'
10297/// [',' 'hasUnknownCall' ':' Flag]? ')'
10298/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10299
10300bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10301 assert(Lex.getKind() == lltok::kw_funcFlags);
10302 Lex.Lex();
10303
10304 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10305 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10306 return true;
10307
10308 do {
10309 unsigned Val = 0;
10310 switch (Lex.getKind()) {
10311 case lltok::kw_readNone:
10312 Lex.Lex();
10313 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10314 return true;
10315 FFlags.ReadNone = Val;
10316 break;
10317 case lltok::kw_readOnly:
10318 Lex.Lex();
10319 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10320 return true;
10321 FFlags.ReadOnly = Val;
10322 break;
10324 Lex.Lex();
10325 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10326 return true;
10327 FFlags.NoRecurse = Val;
10328 break;
10330 Lex.Lex();
10331 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10332 return true;
10333 FFlags.ReturnDoesNotAlias = Val;
10334 break;
10335 case lltok::kw_noInline:
10336 Lex.Lex();
10337 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10338 return true;
10339 FFlags.NoInline = Val;
10340 break;
10342 Lex.Lex();
10343 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10344 return true;
10345 FFlags.AlwaysInline = Val;
10346 break;
10347 case lltok::kw_noUnwind:
10348 Lex.Lex();
10349 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10350 return true;
10351 FFlags.NoUnwind = Val;
10352 break;
10353 case lltok::kw_mayThrow:
10354 Lex.Lex();
10355 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10356 return true;
10357 FFlags.MayThrow = Val;
10358 break;
10360 Lex.Lex();
10361 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10362 return true;
10363 FFlags.HasUnknownCall = Val;
10364 break;
10366 Lex.Lex();
10367 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10368 return true;
10369 FFlags.MustBeUnreachable = Val;
10370 break;
10371 default:
10372 return error(Lex.getLoc(), "expected function flag type");
10373 }
10374 } while (EatIfPresent(lltok::comma));
10375
10376 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10377 return true;
10378
10379 return false;
10380}
10381
10382/// OptionalCalls
10383/// := 'calls' ':' '(' Call [',' Call]* ')'
10384/// Call ::= '(' 'callee' ':' GVReference
10385/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10386/// [ ',' 'tail' ]? ')'
10387bool LLParser::parseOptionalCalls(
10388 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10389 assert(Lex.getKind() == lltok::kw_calls);
10390 Lex.Lex();
10391
10392 if (parseToken(lltok::colon, "expected ':' in calls") ||
10393 parseToken(lltok::lparen, "expected '(' in calls"))
10394 return true;
10395
10396 IdToIndexMapType IdToIndexMap;
10397 // parse each call edge
10398 do {
10399 ValueInfo VI;
10400 if (parseToken(lltok::lparen, "expected '(' in call") ||
10401 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10402 parseToken(lltok::colon, "expected ':'"))
10403 return true;
10404
10405 LocTy Loc = Lex.getLoc();
10406 unsigned GVId;
10407 if (parseGVReference(VI, GVId))
10408 return true;
10409
10411 unsigned RelBF = 0;
10412 unsigned HasTailCall = false;
10413
10414 // parse optional fields
10415 while (EatIfPresent(lltok::comma)) {
10416 switch (Lex.getKind()) {
10417 case lltok::kw_hotness:
10418 Lex.Lex();
10419 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10420 return true;
10421 break;
10422 // Deprecated, keep in order to support old files.
10423 case lltok::kw_relbf:
10424 Lex.Lex();
10425 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10426 return true;
10427 break;
10428 case lltok::kw_tail:
10429 Lex.Lex();
10430 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10431 return true;
10432 break;
10433 default:
10434 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10435 }
10436 }
10437 // Keep track of the Call array index needing a forward reference.
10438 // We will save the location of the ValueInfo needing an update, but
10439 // can only do so once the std::vector is finalized.
10440 if (VI.getRef() == FwdVIRef)
10441 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10442 Calls.push_back(
10443 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall)});
10444
10445 if (parseToken(lltok::rparen, "expected ')' in call"))
10446 return true;
10447 } while (EatIfPresent(lltok::comma));
10448
10449 // Now that the Calls vector is finalized, it is safe to save the locations
10450 // of any forward GV references that need updating later.
10451 for (auto I : IdToIndexMap) {
10452 auto &Infos = ForwardRefValueInfos[I.first];
10453 for (auto P : I.second) {
10454 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10455 "Forward referenced ValueInfo expected to be empty");
10456 Infos.emplace_back(&Calls[P.first].first, P.second);
10457 }
10458 }
10459
10460 if (parseToken(lltok::rparen, "expected ')' in calls"))
10461 return true;
10462
10463 return false;
10464}
10465
10466/// Hotness
10467/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10468bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10469 switch (Lex.getKind()) {
10470 case lltok::kw_unknown:
10472 break;
10473 case lltok::kw_cold:
10475 break;
10476 case lltok::kw_none:
10478 break;
10479 case lltok::kw_hot:
10481 break;
10482 case lltok::kw_critical:
10484 break;
10485 default:
10486 return error(Lex.getLoc(), "invalid call edge hotness");
10487 }
10488 Lex.Lex();
10489 return false;
10490}
10491
10492/// OptionalVTableFuncs
10493/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10494/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10495bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10496 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10497 Lex.Lex();
10498
10499 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10500 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10501 return true;
10502
10503 IdToIndexMapType IdToIndexMap;
10504 // parse each virtual function pair
10505 do {
10506 ValueInfo VI;
10507 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10508 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10509 parseToken(lltok::colon, "expected ':'"))
10510 return true;
10511
10512 LocTy Loc = Lex.getLoc();
10513 unsigned GVId;
10514 if (parseGVReference(VI, GVId))
10515 return true;
10516
10517 uint64_t Offset;
10518 if (parseToken(lltok::comma, "expected comma") ||
10519 parseToken(lltok::kw_offset, "expected offset") ||
10520 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10521 return true;
10522
10523 // Keep track of the VTableFuncs array index needing a forward reference.
10524 // We will save the location of the ValueInfo needing an update, but
10525 // can only do so once the std::vector is finalized.
10526 if (VI == EmptyVI)
10527 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10528 VTableFuncs.push_back({VI, Offset});
10529
10530 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10531 return true;
10532 } while (EatIfPresent(lltok::comma));
10533
10534 // Now that the VTableFuncs vector is finalized, it is safe to save the
10535 // locations 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(VTableFuncs[P.first].FuncVI == EmptyVI &&
10540 "Forward referenced ValueInfo expected to be empty");
10541 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10542 }
10543 }
10544
10545 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10546 return true;
10547
10548 return false;
10549}
10550
10551/// ParamNo := 'param' ':' UInt64
10552bool LLParser::parseParamNo(uint64_t &ParamNo) {
10553 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10554 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10555 return true;
10556 return false;
10557}
10558
10559/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10560bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10561 APSInt Lower;
10562 APSInt Upper;
10563 auto ParseAPSInt = [&](APSInt &Val) {
10564 if (Lex.getKind() != lltok::APSInt)
10565 return tokError("expected integer");
10566 Val = Lex.getAPSIntVal();
10567 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10568 Val.setIsSigned(true);
10569 Lex.Lex();
10570 return false;
10571 };
10572 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10573 parseToken(lltok::colon, "expected ':' here") ||
10574 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10575 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10576 parseToken(lltok::rsquare, "expected ']' here"))
10577 return true;
10578
10579 ++Upper;
10580 Range =
10581 (Lower == Upper && !Lower.isMaxValue())
10582 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10583 : ConstantRange(Lower, Upper);
10584
10585 return false;
10586}
10587
10588/// ParamAccessCall
10589/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10590bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10591 IdLocListType &IdLocList) {
10592 if (parseToken(lltok::lparen, "expected '(' here") ||
10593 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10594 parseToken(lltok::colon, "expected ':' here"))
10595 return true;
10596
10597 unsigned GVId;
10598 ValueInfo VI;
10599 LocTy Loc = Lex.getLoc();
10600 if (parseGVReference(VI, GVId))
10601 return true;
10602
10603 Call.Callee = VI;
10604 IdLocList.emplace_back(GVId, Loc);
10605
10606 if (parseToken(lltok::comma, "expected ',' here") ||
10607 parseParamNo(Call.ParamNo) ||
10608 parseToken(lltok::comma, "expected ',' here") ||
10609 parseParamAccessOffset(Call.Offsets))
10610 return true;
10611
10612 if (parseToken(lltok::rparen, "expected ')' here"))
10613 return true;
10614
10615 return false;
10616}
10617
10618/// ParamAccess
10619/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10620/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10621bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10622 IdLocListType &IdLocList) {
10623 if (parseToken(lltok::lparen, "expected '(' here") ||
10624 parseParamNo(Param.ParamNo) ||
10625 parseToken(lltok::comma, "expected ',' here") ||
10626 parseParamAccessOffset(Param.Use))
10627 return true;
10628
10629 if (EatIfPresent(lltok::comma)) {
10630 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10631 parseToken(lltok::colon, "expected ':' here") ||
10632 parseToken(lltok::lparen, "expected '(' here"))
10633 return true;
10634 do {
10635 FunctionSummary::ParamAccess::Call Call;
10636 if (parseParamAccessCall(Call, IdLocList))
10637 return true;
10638 Param.Calls.push_back(Call);
10639 } while (EatIfPresent(lltok::comma));
10640
10641 if (parseToken(lltok::rparen, "expected ')' here"))
10642 return true;
10643 }
10644
10645 if (parseToken(lltok::rparen, "expected ')' here"))
10646 return true;
10647
10648 return false;
10649}
10650
10651/// OptionalParamAccesses
10652/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10653bool LLParser::parseOptionalParamAccesses(
10654 std::vector<FunctionSummary::ParamAccess> &Params) {
10655 assert(Lex.getKind() == lltok::kw_params);
10656 Lex.Lex();
10657
10658 if (parseToken(lltok::colon, "expected ':' here") ||
10659 parseToken(lltok::lparen, "expected '(' here"))
10660 return true;
10661
10662 IdLocListType VContexts;
10663 size_t CallsNum = 0;
10664 do {
10665 FunctionSummary::ParamAccess ParamAccess;
10666 if (parseParamAccess(ParamAccess, VContexts))
10667 return true;
10668 CallsNum += ParamAccess.Calls.size();
10669 assert(VContexts.size() == CallsNum);
10670 (void)CallsNum;
10671 Params.emplace_back(std::move(ParamAccess));
10672 } while (EatIfPresent(lltok::comma));
10673
10674 if (parseToken(lltok::rparen, "expected ')' here"))
10675 return true;
10676
10677 // Now that the Params is finalized, it is safe to save the locations
10678 // of any forward GV references that need updating later.
10679 IdLocListType::const_iterator ItContext = VContexts.begin();
10680 for (auto &PA : Params) {
10681 for (auto &C : PA.Calls) {
10682 if (C.Callee.getRef() == FwdVIRef)
10683 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10684 ItContext->second);
10685 ++ItContext;
10686 }
10687 }
10688 assert(ItContext == VContexts.end());
10689
10690 return false;
10691}
10692
10693/// OptionalRefs
10694/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10695bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10696 assert(Lex.getKind() == lltok::kw_refs);
10697 Lex.Lex();
10698
10699 if (parseToken(lltok::colon, "expected ':' in refs") ||
10700 parseToken(lltok::lparen, "expected '(' in refs"))
10701 return true;
10702
10703 struct ValueContext {
10704 ValueInfo VI;
10705 unsigned GVId;
10706 LocTy Loc;
10707 };
10708 std::vector<ValueContext> VContexts;
10709 // parse each ref edge
10710 do {
10711 ValueContext VC;
10712 VC.Loc = Lex.getLoc();
10713 if (parseGVReference(VC.VI, VC.GVId))
10714 return true;
10715 VContexts.push_back(VC);
10716 } while (EatIfPresent(lltok::comma));
10717
10718 // Sort value contexts so that ones with writeonly
10719 // and readonly ValueInfo are at the end of VContexts vector.
10720 // See FunctionSummary::specialRefCounts()
10721 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10722 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10723 });
10724
10725 IdToIndexMapType IdToIndexMap;
10726 for (auto &VC : VContexts) {
10727 // Keep track of the Refs array index needing a forward reference.
10728 // We will save the location of the ValueInfo needing an update, but
10729 // can only do so once the std::vector is finalized.
10730 if (VC.VI.getRef() == FwdVIRef)
10731 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10732 Refs.push_back(VC.VI);
10733 }
10734
10735 // Now that the Refs vector is finalized, it is safe to save the locations
10736 // of any forward GV references that need updating later.
10737 for (auto I : IdToIndexMap) {
10738 auto &Infos = ForwardRefValueInfos[I.first];
10739 for (auto P : I.second) {
10740 assert(Refs[P.first].getRef() == FwdVIRef &&
10741 "Forward referenced ValueInfo expected to be empty");
10742 Infos.emplace_back(&Refs[P.first], P.second);
10743 }
10744 }
10745
10746 if (parseToken(lltok::rparen, "expected ')' in refs"))
10747 return true;
10748
10749 return false;
10750}
10751
10752/// OptionalTypeIdInfo
10753/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10754/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10755/// [',' TypeCheckedLoadConstVCalls]? ')'
10756bool LLParser::parseOptionalTypeIdInfo(
10757 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10758 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10759 Lex.Lex();
10760
10761 if (parseToken(lltok::colon, "expected ':' here") ||
10762 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10763 return true;
10764
10765 do {
10766 switch (Lex.getKind()) {
10768 if (parseTypeTests(TypeIdInfo.TypeTests))
10769 return true;
10770 break;
10772 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10773 TypeIdInfo.TypeTestAssumeVCalls))
10774 return true;
10775 break;
10777 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10778 TypeIdInfo.TypeCheckedLoadVCalls))
10779 return true;
10780 break;
10782 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10783 TypeIdInfo.TypeTestAssumeConstVCalls))
10784 return true;
10785 break;
10787 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10788 TypeIdInfo.TypeCheckedLoadConstVCalls))
10789 return true;
10790 break;
10791 default:
10792 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10793 }
10794 } while (EatIfPresent(lltok::comma));
10795
10796 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10797 return true;
10798
10799 return false;
10800}
10801
10802/// TypeTests
10803/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10804/// [',' (SummaryID | UInt64)]* ')'
10805bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10806 assert(Lex.getKind() == lltok::kw_typeTests);
10807 Lex.Lex();
10808
10809 if (parseToken(lltok::colon, "expected ':' here") ||
10810 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10811 return true;
10812
10813 IdToIndexMapType IdToIndexMap;
10814 do {
10816 if (Lex.getKind() == lltok::SummaryID) {
10817 unsigned ID = Lex.getUIntVal();
10818 LocTy Loc = Lex.getLoc();
10819 // Keep track of the TypeTests array index needing a forward reference.
10820 // We will save the location of the GUID needing an update, but
10821 // can only do so once the std::vector is finalized.
10822 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10823 Lex.Lex();
10824 } else if (parseUInt64(GUID))
10825 return true;
10826 TypeTests.push_back(GUID);
10827 } while (EatIfPresent(lltok::comma));
10828
10829 // Now that the TypeTests vector is finalized, it is safe to save the
10830 // locations of any forward GV references that need updating later.
10831 for (auto I : IdToIndexMap) {
10832 auto &Ids = ForwardRefTypeIds[I.first];
10833 for (auto P : I.second) {
10834 assert(TypeTests[P.first] == 0 &&
10835 "Forward referenced type id GUID expected to be 0");
10836 Ids.emplace_back(&TypeTests[P.first], P.second);
10837 }
10838 }
10839
10840 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10841 return true;
10842
10843 return false;
10844}
10845
10846/// VFuncIdList
10847/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10848bool LLParser::parseVFuncIdList(
10849 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10850 assert(Lex.getKind() == Kind);
10851 Lex.Lex();
10852
10853 if (parseToken(lltok::colon, "expected ':' here") ||
10854 parseToken(lltok::lparen, "expected '(' here"))
10855 return true;
10856
10857 IdToIndexMapType IdToIndexMap;
10858 do {
10859 FunctionSummary::VFuncId VFuncId;
10860 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10861 return true;
10862 VFuncIdList.push_back(VFuncId);
10863 } while (EatIfPresent(lltok::comma));
10864
10865 if (parseToken(lltok::rparen, "expected ')' here"))
10866 return true;
10867
10868 // Now that the VFuncIdList vector is finalized, it is safe to save the
10869 // locations of any forward GV references that need updating later.
10870 for (auto I : IdToIndexMap) {
10871 auto &Ids = ForwardRefTypeIds[I.first];
10872 for (auto P : I.second) {
10873 assert(VFuncIdList[P.first].GUID == 0 &&
10874 "Forward referenced type id GUID expected to be 0");
10875 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10876 }
10877 }
10878
10879 return false;
10880}
10881
10882/// ConstVCallList
10883/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10884bool LLParser::parseConstVCallList(
10885 lltok::Kind Kind,
10886 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10887 assert(Lex.getKind() == Kind);
10888 Lex.Lex();
10889
10890 if (parseToken(lltok::colon, "expected ':' here") ||
10891 parseToken(lltok::lparen, "expected '(' here"))
10892 return true;
10893
10894 IdToIndexMapType IdToIndexMap;
10895 do {
10896 FunctionSummary::ConstVCall ConstVCall;
10897 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10898 return true;
10899 ConstVCallList.push_back(ConstVCall);
10900 } while (EatIfPresent(lltok::comma));
10901
10902 if (parseToken(lltok::rparen, "expected ')' here"))
10903 return true;
10904
10905 // Now that the ConstVCallList vector is finalized, it is safe to save the
10906 // locations of any forward GV references that need updating later.
10907 for (auto I : IdToIndexMap) {
10908 auto &Ids = ForwardRefTypeIds[I.first];
10909 for (auto P : I.second) {
10910 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10911 "Forward referenced type id GUID expected to be 0");
10912 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10913 }
10914 }
10915
10916 return false;
10917}
10918
10919/// ConstVCall
10920/// ::= '(' VFuncId ',' Args ')'
10921bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10922 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10923 if (parseToken(lltok::lparen, "expected '(' here") ||
10924 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10925 return true;
10926
10927 if (EatIfPresent(lltok::comma))
10928 if (parseArgs(ConstVCall.Args))
10929 return true;
10930
10931 if (parseToken(lltok::rparen, "expected ')' here"))
10932 return true;
10933
10934 return false;
10935}
10936
10937/// VFuncId
10938/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10939/// 'offset' ':' UInt64 ')'
10940bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10941 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10942 assert(Lex.getKind() == lltok::kw_vFuncId);
10943 Lex.Lex();
10944
10945 if (parseToken(lltok::colon, "expected ':' here") ||
10946 parseToken(lltok::lparen, "expected '(' here"))
10947 return true;
10948
10949 if (Lex.getKind() == lltok::SummaryID) {
10950 VFuncId.GUID = 0;
10951 unsigned ID = Lex.getUIntVal();
10952 LocTy Loc = Lex.getLoc();
10953 // Keep track of the array index needing a forward reference.
10954 // We will save the location of the GUID needing an update, but
10955 // can only do so once the caller's std::vector is finalized.
10956 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10957 Lex.Lex();
10958 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10959 parseToken(lltok::colon, "expected ':' here") ||
10960 parseUInt64(VFuncId.GUID))
10961 return true;
10962
10963 if (parseToken(lltok::comma, "expected ',' here") ||
10964 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10965 parseToken(lltok::colon, "expected ':' here") ||
10966 parseUInt64(VFuncId.Offset) ||
10967 parseToken(lltok::rparen, "expected ')' here"))
10968 return true;
10969
10970 return false;
10971}
10972
10973/// GVFlags
10974/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10975/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10976/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10977/// 'canAutoHide' ':' Flag ',' ')'
10978bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10979 assert(Lex.getKind() == lltok::kw_flags);
10980 Lex.Lex();
10981
10982 if (parseToken(lltok::colon, "expected ':' here") ||
10983 parseToken(lltok::lparen, "expected '(' here"))
10984 return true;
10985
10986 do {
10987 unsigned Flag = 0;
10988 switch (Lex.getKind()) {
10989 case lltok::kw_linkage:
10990 Lex.Lex();
10991 if (parseToken(lltok::colon, "expected ':'"))
10992 return true;
10993 bool HasLinkage;
10994 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10995 assert(HasLinkage && "Linkage not optional in summary entry");
10996 Lex.Lex();
10997 break;
10999 Lex.Lex();
11000 if (parseToken(lltok::colon, "expected ':'"))
11001 return true;
11002 parseOptionalVisibility(Flag);
11003 GVFlags.Visibility = Flag;
11004 break;
11006 Lex.Lex();
11007 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11008 return true;
11009 GVFlags.NotEligibleToImport = Flag;
11010 break;
11011 case lltok::kw_live:
11012 Lex.Lex();
11013 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11014 return true;
11015 GVFlags.Live = Flag;
11016 break;
11017 case lltok::kw_dsoLocal:
11018 Lex.Lex();
11019 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11020 return true;
11021 GVFlags.DSOLocal = Flag;
11022 break;
11024 Lex.Lex();
11025 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11026 return true;
11027 GVFlags.CanAutoHide = Flag;
11028 break;
11030 Lex.Lex();
11031 if (parseToken(lltok::colon, "expected ':'"))
11032 return true;
11034 if (parseOptionalImportType(Lex.getKind(), IK))
11035 return true;
11036 GVFlags.ImportType = static_cast<unsigned>(IK);
11037 Lex.Lex();
11038 break;
11040 Lex.Lex();
11041 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11042 return true;
11043 GVFlags.NoRenameOnPromotion = Flag;
11044 break;
11045 default:
11046 return error(Lex.getLoc(), "expected gv flag type");
11047 }
11048 } while (EatIfPresent(lltok::comma));
11049
11050 if (parseToken(lltok::rparen, "expected ')' here"))
11051 return true;
11052
11053 return false;
11054}
11055
11056/// GVarFlags
11057/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
11058/// ',' 'writeonly' ':' Flag
11059/// ',' 'constant' ':' Flag ')'
11060bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11061 assert(Lex.getKind() == lltok::kw_varFlags);
11062 Lex.Lex();
11063
11064 if (parseToken(lltok::colon, "expected ':' here") ||
11065 parseToken(lltok::lparen, "expected '(' here"))
11066 return true;
11067
11068 auto ParseRest = [this](unsigned int &Val) {
11069 Lex.Lex();
11070 if (parseToken(lltok::colon, "expected ':'"))
11071 return true;
11072 return parseFlag(Val);
11073 };
11074
11075 do {
11076 unsigned Flag = 0;
11077 switch (Lex.getKind()) {
11078 case lltok::kw_readonly:
11079 if (ParseRest(Flag))
11080 return true;
11081 GVarFlags.MaybeReadOnly = Flag;
11082 break;
11083 case lltok::kw_writeonly:
11084 if (ParseRest(Flag))
11085 return true;
11086 GVarFlags.MaybeWriteOnly = Flag;
11087 break;
11088 case lltok::kw_constant:
11089 if (ParseRest(Flag))
11090 return true;
11091 GVarFlags.Constant = Flag;
11092 break;
11094 if (ParseRest(Flag))
11095 return true;
11096 GVarFlags.VCallVisibility = Flag;
11097 break;
11098 default:
11099 return error(Lex.getLoc(), "expected gvar flag type");
11100 }
11101 } while (EatIfPresent(lltok::comma));
11102 return parseToken(lltok::rparen, "expected ')' here");
11103}
11104
11105/// ModuleReference
11106/// ::= 'module' ':' UInt
11107bool LLParser::parseModuleReference(StringRef &ModulePath) {
11108 // parse module id.
11109 if (parseToken(lltok::kw_module, "expected 'module' here") ||
11110 parseToken(lltok::colon, "expected ':' here") ||
11111 parseToken(lltok::SummaryID, "expected module ID"))
11112 return true;
11113
11114 unsigned ModuleID = Lex.getUIntVal();
11115 auto I = ModuleIdMap.find(ModuleID);
11116 // We should have already parsed all module IDs
11117 assert(I != ModuleIdMap.end());
11118 ModulePath = I->second;
11119 return false;
11120}
11121
11122/// GVReference
11123/// ::= SummaryID
11124bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11125 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
11126 if (!ReadOnly)
11127 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11128 if (parseToken(lltok::SummaryID, "expected GV ID"))
11129 return true;
11130
11131 GVId = Lex.getUIntVal();
11132 // Check if we already have a VI for this GV
11133 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11134 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11135 VI = NumberedValueInfos[GVId];
11136 } else
11137 // We will create a forward reference to the stored location.
11138 VI = ValueInfo(false, FwdVIRef);
11139
11140 if (ReadOnly)
11141 VI.setReadOnly();
11142 if (WriteOnly)
11143 VI.setWriteOnly();
11144 return false;
11145}
11146
11147/// OptionalAllocs
11148/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11149/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11150/// ',' MemProfs ')'
11151/// Version ::= UInt32
11152bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11153 assert(Lex.getKind() == lltok::kw_allocs);
11154 Lex.Lex();
11155
11156 if (parseToken(lltok::colon, "expected ':' in allocs") ||
11157 parseToken(lltok::lparen, "expected '(' in allocs"))
11158 return true;
11159
11160 // parse each alloc
11161 do {
11162 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
11163 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
11164 parseToken(lltok::colon, "expected ':'") ||
11165 parseToken(lltok::lparen, "expected '(' in versions"))
11166 return true;
11167
11168 SmallVector<uint8_t> Versions;
11169 do {
11170 uint8_t V = 0;
11171 if (parseAllocType(V))
11172 return true;
11173 Versions.push_back(V);
11174 } while (EatIfPresent(lltok::comma));
11175
11176 if (parseToken(lltok::rparen, "expected ')' in versions") ||
11177 parseToken(lltok::comma, "expected ',' in alloc"))
11178 return true;
11179
11180 std::vector<MIBInfo> MIBs;
11181 if (parseMemProfs(MIBs))
11182 return true;
11183
11184 Allocs.push_back({Versions, MIBs});
11185
11186 if (parseToken(lltok::rparen, "expected ')' in alloc"))
11187 return true;
11188 } while (EatIfPresent(lltok::comma));
11189
11190 if (parseToken(lltok::rparen, "expected ')' in allocs"))
11191 return true;
11192
11193 return false;
11194}
11195
11196/// MemProfs
11197/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11198/// MemProf ::= '(' 'type' ':' AllocType
11199/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11200/// StackId ::= UInt64
11201bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11202 assert(Lex.getKind() == lltok::kw_memProf);
11203 Lex.Lex();
11204
11205 if (parseToken(lltok::colon, "expected ':' in memprof") ||
11206 parseToken(lltok::lparen, "expected '(' in memprof"))
11207 return true;
11208
11209 // parse each MIB
11210 do {
11211 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
11212 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
11213 parseToken(lltok::colon, "expected ':'"))
11214 return true;
11215
11216 uint8_t AllocType;
11217 if (parseAllocType(AllocType))
11218 return true;
11219
11220 if (parseToken(lltok::comma, "expected ',' in memprof") ||
11221 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
11222 parseToken(lltok::colon, "expected ':'") ||
11223 parseToken(lltok::lparen, "expected '(' in stackIds"))
11224 return true;
11225
11226 SmallVector<unsigned> StackIdIndices;
11227 // Combined index alloc records may not have a stack id list.
11228 if (Lex.getKind() != lltok::rparen) {
11229 do {
11230 uint64_t StackId = 0;
11231 if (parseUInt64(StackId))
11232 return true;
11233 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11234 } while (EatIfPresent(lltok::comma));
11235 }
11236
11237 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11238 return true;
11239
11240 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11241
11242 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11243 return true;
11244 } while (EatIfPresent(lltok::comma));
11245
11246 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11247 return true;
11248
11249 return false;
11250}
11251
11252/// AllocType
11253/// := ('none'|'notcold'|'cold'|'hot')
11254bool LLParser::parseAllocType(uint8_t &AllocType) {
11255 switch (Lex.getKind()) {
11256 case lltok::kw_none:
11258 break;
11259 case lltok::kw_notcold:
11261 break;
11262 case lltok::kw_cold:
11264 break;
11265 case lltok::kw_hot:
11266 AllocType = (uint8_t)AllocationType::Hot;
11267 break;
11268 default:
11269 return error(Lex.getLoc(), "invalid alloc type");
11270 }
11271 Lex.Lex();
11272 return false;
11273}
11274
11275/// OptionalCallsites
11276/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11277/// Callsite ::= '(' 'callee' ':' GVReference
11278/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11279/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11280/// Version ::= UInt32
11281/// StackId ::= UInt64
11282bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11283 assert(Lex.getKind() == lltok::kw_callsites);
11284 Lex.Lex();
11285
11286 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11287 parseToken(lltok::lparen, "expected '(' in callsites"))
11288 return true;
11289
11290 IdToIndexMapType IdToIndexMap;
11291 // parse each callsite
11292 do {
11293 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11294 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11295 parseToken(lltok::colon, "expected ':'"))
11296 return true;
11297
11298 ValueInfo VI;
11299 unsigned GVId = 0;
11300 LocTy Loc = Lex.getLoc();
11301 if (!EatIfPresent(lltok::kw_null)) {
11302 if (parseGVReference(VI, GVId))
11303 return true;
11304 }
11305
11306 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11307 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11308 parseToken(lltok::colon, "expected ':'") ||
11309 parseToken(lltok::lparen, "expected '(' in clones"))
11310 return true;
11311
11312 SmallVector<unsigned> Clones;
11313 do {
11314 unsigned V = 0;
11315 if (parseUInt32(V))
11316 return true;
11317 Clones.push_back(V);
11318 } while (EatIfPresent(lltok::comma));
11319
11320 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11321 parseToken(lltok::comma, "expected ',' in callsite") ||
11322 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11323 parseToken(lltok::colon, "expected ':'") ||
11324 parseToken(lltok::lparen, "expected '(' in stackIds"))
11325 return true;
11326
11327 SmallVector<unsigned> StackIdIndices;
11328 // Synthesized callsite records will not have a stack id list.
11329 if (Lex.getKind() != lltok::rparen) {
11330 do {
11331 uint64_t StackId = 0;
11332 if (parseUInt64(StackId))
11333 return true;
11334 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11335 } while (EatIfPresent(lltok::comma));
11336 }
11337
11338 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11339 return true;
11340
11341 // Keep track of the Callsites array index needing a forward reference.
11342 // We will save the location of the ValueInfo needing an update, but
11343 // can only do so once the SmallVector is finalized.
11344 if (VI.getRef() == FwdVIRef)
11345 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11346 Callsites.push_back({VI, Clones, StackIdIndices});
11347
11348 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11349 return true;
11350 } while (EatIfPresent(lltok::comma));
11351
11352 // Now that the Callsites vector is finalized, it is safe to save the
11353 // locations of any forward GV references that need updating later.
11354 for (auto I : IdToIndexMap) {
11355 auto &Infos = ForwardRefValueInfos[I.first];
11356 for (auto P : I.second) {
11357 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11358 "Forward referenced ValueInfo expected to be empty");
11359 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11360 }
11361 }
11362
11363 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11364 return true;
11365
11366 return false;
11367}
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
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:253
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)"
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:297
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:278
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1244
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
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
iterator begin() const
Definition ArrayRef.h:130
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:835
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:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ ICMP_SLT
signed less than
Definition InstrTypes.h:705
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:706
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:700
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:699
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:703
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:701
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:704
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:702
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
@ 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:1573
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:1445
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.
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, MDNode *DL)
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, MDNode *DI)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
unsigned size() const
Definition DenseMap.h:110
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:59
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:473
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:468
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:823
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:449
arg_iterator arg_begin()
Definition Function.h:868
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1040
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:357
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
Definition Function.h:1052
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:621
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:678
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:223
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:284
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
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:254
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.
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:96
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:170
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:260
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:237
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:542
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:589
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
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:231
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:108
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:95
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:1080
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1580
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
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:1540
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1529
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1549
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:946
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:224
iterator find(StringRef Key)
Definition StringMap.h:237
StringMapIterBase< Comdat, false > iterator
Definition StringMap.h:221
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
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:483
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:689
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:773
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:608
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:510
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:984
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:314
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:290
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:281
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:293
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:65
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:284
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:287
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:255
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:311
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:201
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:328
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:321
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:310
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:287
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:275
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:110
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:808
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:107
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:318
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 getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:632
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:704
#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 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.
@ 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:765
@ DW_ATE_hi_user
Definition Dwarf.h:163
@ DW_APPLE_ENUM_KIND_max
Definition Dwarf.h:206
@ DW_LANG_hi_user
Definition Dwarf.h:220
MacinfoRecordType
Definition Dwarf.h:815
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:821
@ 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:154
@ kw_riscv_vls_cc
Definition LLToken.h:190
@ kw_cxx_fast_tlscc
Definition LLToken.h:173
@ kw_extractvalue
Definition LLToken.h:376
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:512
@ kw_arm_apcscc
Definition LLToken.h:146
@ kw_inteldialect
Definition LLToken.h:128
@ kw_x86_stdcallcc
Definition LLToken.h:141
@ kw_constant
Definition LLToken.h:48
@ kw_initialexec
Definition LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition LLToken.h:152
@ kw_provenance
Definition LLToken.h:224
@ kw_mustBeUnreachable
Definition LLToken.h:423
@ kw_internal
Definition LLToken.h:54
@ kw_target_mem
Definition LLToken.h:210
@ 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:373
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:193
@ kw_fmaximumnum
Definition LLToken.h:295
@ kw_inaccessiblememonly
Definition LLToken.h:217
@ kw_amdgpu_gfx
Definition LLToken.h:184
@ kw_getelementptr
Definition LLToken.h:370
@ FloatHexLiteral
Definition LLToken.h:531
@ kw_m68k_rtdcc
Definition LLToken.h:187
@ kw_preserve_nonecc
Definition LLToken.h:168
@ kw_x86_fastcallcc
Definition LLToken.h:142
@ kw_visibility
Definition LLToken.h:402
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:192
@ kw_positivezero
Definition LLToken.h:230
@ kw_unordered
Definition LLToken.h:95
@ kw_singleImpl
Definition LLToken.h:465
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:140
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:442
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:150
@ kw_amdgpu_kernel
Definition LLToken.h:183
@ kw_uselistorder
Definition LLToken.h:389
@ 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:144
@ kw_ptx_device
Definition LLToken.h:158
@ kw_personality
Definition LLToken.h:345
@ DwarfEnumKind
Definition LLToken.h:525
@ kw_declaration
Definition LLToken.h:409
@ DwarfAttEncoding
Definition LLToken.h:511
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:159
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:422
@ kw_x86_intrcc
Definition LLToken.h:170
@ kw_addrspacecast
Definition LLToken.h:340
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:509
@ kw_x86_thiscallcc
Definition LLToken.h:143
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:191
@ kw_unnamed_addr
Definition LLToken.h:67
@ kw_uselistorder_bb
Definition LLToken.h:390
@ NameTableKind
Definition LLToken.h:517
@ kw_inlineBits
Definition LLToken.h:460
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:216
@ kw_blockaddress
Definition LLToken.h:378
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:185
@ kw_landingpad
Definition LLToken.h:344
@ kw_aarch64_vector_pcs
Definition LLToken.h:149
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:441
@ FixedPointKind
Definition LLToken.h:518
@ kw_target_mem1
Definition LLToken.h:212
@ kw_ptx_kernel
Definition LLToken.h:157
@ kw_extractelement
Definition LLToken.h:372
@ 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:218
@ 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:182
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:358
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:147
@ kw_read_provenance
Definition LLToken.h:225
@ kw_cleanuppad
Definition LLToken.h:361
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:467
@ kw_target_mem0
Definition LLToken.h:211
@ kw_swifttailcc
Definition LLToken.h:165
@ kw_monotonic
Definition LLToken.h:96
@ kw_typeTestAssumeVCalls
Definition LLToken.h:439
@ kw_preservesign
Definition LLToken.h:229
@ kw_attributes
Definition LLToken.h:196
@ kw_code_model
Definition LLToken.h:122
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:470
@ kw_sideeffect
Definition LLToken.h:127
@ kw_sizeM1BitWidth
Definition LLToken.h:456
@ kw_nodeduplicate
Definition LLToken.h:260
@ kw_avr_signalcc
Definition LLToken.h:156
@ kw_exactmatch
Definition LLToken.h:258
@ kw_fminimumnum
Definition LLToken.h:296
@ kw_unreachable
Definition LLToken.h:356
@ kw_intel_ocl_bicc
Definition LLToken.h:139
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:417
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:151
@ kw_preserve_allcc
Definition LLToken.h:167
@ kw_importType
Definition LLToken.h:407
@ kw_cleanupret
Definition LLToken.h:357
@ kw_shufflevector
Definition LLToken.h:374
@ kw_riscv_vector_cc
Definition LLToken.h:189
@ kw_avr_intrcc
Definition LLToken.h:155
@ 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:209
@ kw_preserve_mostcc
Definition LLToken.h:166
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:148
@ kw_typeTestRes
Definition LLToken.h:449
@ kw_x86_regcallcc
Definition LLToken.h:145
@ kw_typeIdInfo
Definition LLToken.h:437
@ kw_amdgpu_cs_chain
Definition LLToken.h:181
@ kw_dso_local_equivalent
Definition LLToken.h:379
@ kw_x86_64_sysvcc
Definition LLToken.h:161
@ DbgRecordType
Definition LLToken.h:524
@ kw_address_is_null
Definition LLToken.h:223
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:153
@ kw_uniqueRetVal
Definition LLToken.h:471
@ kw_insertvalue
Definition LLToken.h:377
@ kw_indirectbr
Definition LLToken.h:353
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:584
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:557
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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:1668
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.
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
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
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:1635
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:372
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
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
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h:36
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:2011
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:1916
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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
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.