Thanks to visit codestin.com
Credit goes to llvm.org

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