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