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