LLVM 24.0.0git
LLParser.cpp
Go to the documentation of this file.
1//===-- LLParser.cpp - Parser Class ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the parser class for .ll files.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/APSInt.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/ScopeExit.h"
22#include "llvm/IR/Argument.h"
23#include "llvm/IR/Attributes.h"
24#include "llvm/IR/AutoUpgrade.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/CallingConv.h"
27#include "llvm/IR/Comdat.h"
30#include "llvm/IR/Constants.h"
33#include "llvm/IR/Function.h"
35#include "llvm/IR/GlobalIFunc.h"
37#include "llvm/IR/InlineAsm.h"
41#include "llvm/IR/Intrinsics.h"
42#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/Metadata.h"
44#include "llvm/IR/Module.h"
45#include "llvm/IR/Operator.h"
46#include "llvm/IR/Value.h"
52#include "llvm/Support/ModRef.h"
55#include <algorithm>
56#include <cassert>
57#include <cstring>
58#include <optional>
59#include <vector>
60
61using namespace llvm;
62
64 "allow-incomplete-ir", cl::init(false), cl::Hidden,
66 "Allow incomplete IR on a best effort basis (references to unknown "
67 "metadata will be dropped)"));
68
69static std::string getTypeString(Type *T) {
70 std::string Result;
71 raw_string_ostream Tmp(Result);
72 Tmp << *T;
73 return Tmp.str();
74}
75
76/// Return whether skipped trivia contains a block comment that crosses the
77/// boundary between two metadata definitions.
78static bool blockCommentCrossesBoundary(SMLoc BeginLoc, SMLoc EndLoc,
79 SMLoc BoundaryLoc) {
80 const char *Begin = BeginLoc.getPointer();
81 const char *End = EndLoc.getPointer();
82 const char *Boundary = BoundaryLoc.getPointer();
83 const char *BlockCommentStart = nullptr;
84 bool InLineComment = false;
85
86 for (const char *Ptr = Begin; Ptr < End;) {
87 if (BlockCommentStart) {
88 if (Ptr + 1 < End && Ptr[0] == '*' && Ptr[1] == '/') {
89 Ptr += 2;
90 if (BlockCommentStart < Boundary && Ptr > Boundary)
91 return true;
92 BlockCommentStart = nullptr;
93 continue;
94 }
95 ++Ptr;
96 continue;
97 }
98
99 if (InLineComment) {
100 if (*Ptr == '\n' || *Ptr == '\r')
101 InLineComment = false;
102 ++Ptr;
103 continue;
104 }
105
106 if (*Ptr == ';') {
107 InLineComment = true;
108 ++Ptr;
109 continue;
110 }
111 if (Ptr + 1 < End && Ptr[0] == '/' && Ptr[1] == '*') {
112 BlockCommentStart = Ptr;
113 Ptr += 2;
114 continue;
115 }
116 ++Ptr;
117 }
118
119 return BlockCommentStart && BlockCommentStart < Boundary && End > Boundary;
120}
121
122/// Run: module ::= toplevelentity*
124 DataLayoutCallbackTy DataLayoutCallback) {
125 // Prime the lexer.
126 Lex.Lex();
127
128 if (Context.shouldDiscardValueNames())
129 return error(
130 Lex.getLoc(),
131 "Can't read textual IR with a Context that discards named Values");
132
133 if (M) {
134 if (parseTargetDefinitions(DataLayoutCallback))
135 return true;
136 }
137
138 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
139 validateEndOfIndex();
140}
141
143 const SlotMapping *Slots) {
144 restoreParsingState(Slots);
145 Lex.Lex();
146
147 Type *Ty = nullptr;
148 if (parseType(Ty) || parseConstantValue(Ty, C))
149 return true;
150 if (Lex.getKind() != lltok::Eof)
151 return error(Lex.getLoc(), "expected end of string");
152 return false;
153}
154
156 const SlotMapping *Slots) {
157 restoreParsingState(Slots);
158 Lex.Lex();
159
160 Read = 0;
161 SMLoc Start = Lex.getLoc();
162 Ty = nullptr;
163 if (parseType(Ty))
164 return true;
165 SMLoc End = Lex.getLoc();
166 Read = End.getPointer() - Start.getPointer();
167
168 return false;
169}
170
172 const SlotMapping *Slots) {
173 restoreParsingState(Slots);
174 Lex.Lex();
175
176 Read = 0;
177 SMLoc Start = Lex.getLoc();
178 Result = nullptr;
179 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
180 SMLoc End = Lex.getLoc();
181 Read = End.getPointer() - Start.getPointer();
182
183 return Status;
184}
185
187 ArrayRef<SMLoc> DefinitionEnds) {
188 restoreParsingState(&Slots);
189 Lex.Lex();
190
191 for (SMLoc End : DefinitionEnds) {
192 if (Lex.getLoc().getPointer() >= End.getPointer())
193 return error(End, "expected end of metadata definition");
194 if (Lex.getKind() != lltok::exclaim)
195 return tokError("expected a metadata definition");
196 if (parseStandaloneMetadata())
197 return true;
198 if (Lex.getPrevTokEndLoc().getPointer() > End.getPointer() ||
199 (Lex.getKind() != lltok::Eof &&
200 Lex.getLoc().getPointer() < End.getPointer()) ||
201 blockCommentCrossesBoundary(Lex.getPrevTokEndLoc(), Lex.getLoc(), End))
202 return error(End, "expected end of metadata definition");
203 }
204
205 if (Lex.getKind() != lltok::Eof)
206 return tokError("expected end of metadata definitions");
207
208 if (!ForwardRefMDNodes.empty())
209 return error(ForwardRefMDNodes.begin()->second.second,
210 "use of undefined metadata '!" +
211 Twine(ForwardRefMDNodes.begin()->first) + "'");
212
213 for (auto &[_, MD] : NumberedMetadata)
214 if (MD && !MD->isResolved())
215 MD->resolveCycles();
217 NewDistinctSPs.clear();
218
219 Slots.MetadataNodes = std::move(NumberedMetadata);
220 return false;
221}
222
223void LLParser::restoreParsingState(const SlotMapping *Slots) {
224 if (!Slots)
225 return;
226 NumberedVals = Slots->GlobalValues;
227 NumberedMetadata = Slots->MetadataNodes;
228 for (const auto &I : Slots->NamedTypes)
229 NamedTypes.insert(
230 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
231 for (const auto &I : Slots->Types)
232 NumberedTypes.insert(
233 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
234}
235
237 // White-list intrinsics that are safe to drop.
239 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
240 return;
241
243 for (Value *V : II->args())
244 if (auto *MV = dyn_cast<MetadataAsValue>(V))
245 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
246 if (MD->isTemporary())
247 MVs.push_back(MV);
248
249 if (!MVs.empty()) {
250 assert(II->use_empty() && "Cannot have uses");
251 II->eraseFromParent();
252
253 // Also remove no longer used MetadataAsValue wrappers.
254 for (MetadataAsValue *MV : MVs)
255 if (MV->use_empty())
256 delete MV;
257 }
258}
259
260void LLParser::dropUnknownMetadataReferences() {
261 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
262 for (Function &F : *M) {
263 F.eraseMetadataIf(Pred);
264 for (Instruction &I : make_early_inc_range(instructions(F))) {
265 I.eraseMetadataIf(Pred);
266
267 if (auto *II = dyn_cast<IntrinsicInst>(&I))
269 }
270 }
271
272 for (GlobalVariable &GV : M->globals())
273 GV.eraseMetadataIf(Pred);
274
275 llvm::erase_if(PendingDbgRecords,
276 [](const auto &E) { return std::get<2>(E)->isTemporary(); });
277 llvm::erase_if(PendingDbgInsts,
278 [](const auto &E) { return std::get<2>(E)->isTemporary(); });
279
280 for (auto &[FLContext, TempScopes] : FLForwardRefScopes) {
281 llvm::erase_if(TempScopes,
282 [](const auto &E) { return std::get<1>(E)->isTemporary(); });
283 }
284 for (auto &[FLContext, TempFLContexts] : FLForwardRefFLMDs) {
285 llvm::erase_if(TempFLContexts,
286 [](const auto &E) { return std::get<1>(E)->isTemporary(); });
287 }
288
289 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
290 // Check whether there is only a single use left, which would be in our
291 // own NumberedMetadata.
292 if (Info.first->getNumTemporaryUses() == 1) {
293 NumberedMetadata.erase(ID);
294 ForwardRefMDNodes.erase(ID);
295 }
296 }
297}
298
299/// validateEndOfModule - Do final validity and basic correctness checks at the
300/// end of the module.
301bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
302 if (!M)
303 return false;
304
305 // We should have already returned an error if we observed both intrinsics and
306 // records in this IR.
307 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
308 "Mixed debug intrinsics/records seen without a parsing error?");
309
310 // Handle any function attribute group forward references.
311 for (const auto &RAG : ForwardRefAttrGroups) {
312 Value *V = RAG.first;
313 const std::vector<unsigned> &Attrs = RAG.second;
314 AttrBuilder B(Context);
315
316 for (const auto &Attr : Attrs) {
317 auto R = NumberedAttrBuilders.find(Attr);
318 if (R != NumberedAttrBuilders.end())
319 B.merge(R->second);
320 }
321
322 if (Function *Fn = dyn_cast<Function>(V)) {
323 AttributeList AS = Fn->getAttributes();
324 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
325 AS = AS.removeFnAttributes(Context);
326
327 FnAttrs.merge(B);
328
329 // If the alignment was parsed as an attribute, move to the alignment
330 // field.
331 if (MaybeAlign A = FnAttrs.getAlignment()) {
332 Fn->setAlignment(*A);
333 FnAttrs.removeAttribute(Attribute::Alignment);
334 }
335
336 AS = AS.addFnAttributes(Context, FnAttrs);
337 Fn->setAttributes(AS);
338 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
339 AttributeList AS = CI->getAttributes();
340 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
341 AS = AS.removeFnAttributes(Context);
342 FnAttrs.merge(B);
343 AS = AS.addFnAttributes(Context, FnAttrs);
344 CI->setAttributes(AS);
345 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
346 AttributeList AS = II->getAttributes();
347 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
348 AS = AS.removeFnAttributes(Context);
349 FnAttrs.merge(B);
350 AS = AS.addFnAttributes(Context, FnAttrs);
351 II->setAttributes(AS);
352 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
353 AttributeList AS = CBI->getAttributes();
354 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
355 AS = AS.removeFnAttributes(Context);
356 FnAttrs.merge(B);
357 AS = AS.addFnAttributes(Context, FnAttrs);
358 CBI->setAttributes(AS);
359 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
360 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
361 Attrs.merge(B);
362 GV->setAttributes(AttributeSet::get(Context,Attrs));
363 } else {
364 llvm_unreachable("invalid object with forward attribute group reference");
365 }
366 }
367
368 // If there are entries in ForwardRefBlockAddresses at this point, the
369 // function was never defined.
370 if (!ForwardRefBlockAddresses.empty())
371 return error(ForwardRefBlockAddresses.begin()->first.Loc,
372 "expected function name in blockaddress");
373
374 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
375 GlobalValue *FwdRef) {
376 GlobalValue *GV = nullptr;
377 if (GVRef.Kind == ValID::t_GlobalName) {
378 GV = M->getNamedValue(GVRef.StrVal);
379 } else {
380 GV = NumberedVals.get(GVRef.UIntVal);
381 }
382
383 if (!GV)
384 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
385 "' referenced by dso_local_equivalent");
386
387 if (!GV->getValueType()->isFunctionTy())
388 return error(GVRef.Loc,
389 "expected a function, alias to function, or ifunc "
390 "in dso_local_equivalent");
391
392 auto *Equiv = DSOLocalEquivalent::get(GV);
393 FwdRef->replaceAllUsesWith(Equiv);
394 FwdRef->eraseFromParent();
395 return false;
396 };
397
398 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
399 // point, they are references after the function was defined. Resolve those
400 // now.
401 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
402 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
403 return true;
404 }
405 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
406 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
407 return true;
408 }
409 ForwardRefDSOLocalEquivalentIDs.clear();
410 ForwardRefDSOLocalEquivalentNames.clear();
411
412 for (const auto &NT : NumberedTypes)
413 if (NT.second.second.isValid())
414 return error(NT.second.second,
415 "use of undefined type '%" + Twine(NT.first) + "'");
416
417 for (const auto &[Name, TypeInfo] : NamedTypes)
418 if (TypeInfo.second.isValid())
419 return error(TypeInfo.second,
420 "use of undefined type named '" + Name + "'");
421
422 if (!ForwardRefComdats.empty())
423 return error(ForwardRefComdats.begin()->second,
424 "use of undefined comdat '$" +
425 ForwardRefComdats.begin()->first + "'");
426
427 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
428 dropUnknownMetadataReferences();
429
430 if (!ForwardRefMDNodes.empty())
431 return error(ForwardRefMDNodes.begin()->second.second,
432 "use of undefined metadata '!" +
433 Twine(ForwardRefMDNodes.begin()->first) + "'");
434
435 // Set debug locations.
436 for (auto [Loc, DR, MD] : PendingDbgRecords) {
437 if (auto *DI = dyn_cast<DILocation>(MD))
438 DR->setDebugLoc(DebugLoc(DI));
439 else
440 return error(Loc, "invalid debug location");
441 }
442 PendingDbgRecords.clear();
443 for (auto [Loc, I, MD] : PendingDbgInsts) {
444 if (auto *DI = dyn_cast<DILocation>(MD))
445 I->setDebugLoc(DebugLoc(DI));
446 else
447 return error(Loc, "invalid !dbg metadata");
448 }
449 PendingDbgInsts.clear();
450
451 // Apply pending scopes/FLContext references.
452 for (auto &[FLContext, TempScopes] : FLForwardRefScopes)
453 for (auto [ScopeIdx, TempScope] : TempScopes)
454 FLContext->Scopes[ScopeIdx].Scope = dyn_cast<DILocalScope>(TempScope);
455 FLForwardRefScopes.clear();
456 for (auto &[FLContext, TempFLContexts] : FLForwardRefFLMDs)
457 for (auto [InlinedCallIdx, TempFLContext] : TempFLContexts)
458 FLContext->InlinedCalls[InlinedCallIdx].InlineeContext =
460 FLForwardRefFLMDs.clear();
461
462 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
463 if (StringRef(Name).starts_with("llvm.")) {
465 // Automatically create declarations for intrinsics. Intrinsics can only
466 // be called directly, so the call function type directly determines the
467 // declaration function type.
468 //
469 // Additionally, automatically add the required mangling suffix to the
470 // intrinsic name. This means that we may replace a single forward
471 // declaration with multiple functions here.
472 for (Use &U : make_early_inc_range(Info.first->uses())) {
473 auto *CB = dyn_cast<CallBase>(U.getUser());
474 if (!CB || !CB->isCallee(&U))
475 return error(Info.second, "intrinsic can only be used as callee");
476
477 std::string ErrorMsg;
478 raw_string_ostream ErrorOS(ErrorMsg);
479
480 SmallVector<Type *> OverloadTys;
481 if (IID != Intrinsic::not_intrinsic &&
482 Intrinsic::isSignatureValid(IID, CB->getFunctionType(), OverloadTys,
483 ErrorOS)) {
484 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
485 } else {
486 // Try to upgrade the intrinsic.
487 Function *TmpF = Function::Create(CB->getFunctionType(),
489 Function *NewF = nullptr;
490 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
491 if (IID == Intrinsic::not_intrinsic)
492 return error(Info.second, "unknown intrinsic '" + Name + "'");
493 return error(Info.second, ErrorMsg);
494 }
495
496 U.set(TmpF);
497 UpgradeIntrinsicCall(CB, NewF);
498 if (TmpF->use_empty())
499 TmpF->eraseFromParent();
500 }
501 }
502
503 Info.first->eraseFromParent();
504 ForwardRefVals.erase(Name);
505 continue;
506 }
507
508 // If incomplete IR is allowed, also add declarations for
509 // non-intrinsics.
511 continue;
512
513 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
514 FunctionType *FTy = nullptr;
515 for (Use &U : V->uses()) {
516 auto *CB = dyn_cast<CallBase>(U.getUser());
517 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
518 return nullptr;
519 FTy = CB->getFunctionType();
520 }
521 return FTy;
522 };
523
524 // First check whether this global is only used in calls with the same
525 // type, in which case we'll insert a function. Otherwise, fall back to
526 // using a dummy i8 type.
527 Type *Ty = GetCommonFunctionType(Info.first);
528 if (!Ty)
529 Ty = Type::getInt8Ty(Context);
530
531 GlobalValue *GV;
532 if (auto *FTy = dyn_cast<FunctionType>(Ty))
534 else
535 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
537 /*Initializer*/ nullptr, Name);
538 Info.first->replaceAllUsesWith(GV);
539 Info.first->eraseFromParent();
540 ForwardRefVals.erase(Name);
541 }
542
543 if (!ForwardRefVals.empty())
544 return error(ForwardRefVals.begin()->second.second,
545 "use of undefined value '@" + ForwardRefVals.begin()->first +
546 "'");
547
548 if (!ForwardRefValIDs.empty())
549 return error(ForwardRefValIDs.begin()->second.second,
550 "use of undefined value '@" +
551 Twine(ForwardRefValIDs.begin()->first) + "'");
552
553 // Resolve metadata cycles.
554 for (auto &N : NumberedMetadata) {
555 if (N.second && !N.second->isResolved())
556 N.second->resolveCycles();
557 }
558
560 NewDistinctSPs.clear();
561
562 // Look for intrinsic functions and CallInst that need to be upgraded. We use
563 // make_early_inc_range here because we may remove some functions.
566
569
576
577 if (!Slots)
578 return false;
579 // Initialize the slot mapping.
580 // Because by this point we've parsed and validated everything, we can "steal"
581 // the mapping from LLParser as it doesn't need it anymore.
582 Slots->GlobalValues = std::move(NumberedVals);
583 Slots->MetadataNodes = std::move(NumberedMetadata);
584 for (const auto &I : NamedTypes)
585 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
586 for (const auto &I : NumberedTypes)
587 Slots->Types.insert(std::make_pair(I.first, I.second.first));
588
589 return false;
590}
591
592/// Do final validity and basic correctness checks at the end of the index.
593bool LLParser::validateEndOfIndex() {
594 if (!Index)
595 return false;
596
597 if (!ForwardRefValueInfos.empty())
598 return error(ForwardRefValueInfos.begin()->second.front().second,
599 "use of undefined summary '^" +
600 Twine(ForwardRefValueInfos.begin()->first) + "'");
601
602 if (!ForwardRefAliasees.empty())
603 return error(ForwardRefAliasees.begin()->second.front().second,
604 "use of undefined summary '^" +
605 Twine(ForwardRefAliasees.begin()->first) + "'");
606
607 if (!ForwardRefTypeIds.empty())
608 return error(ForwardRefTypeIds.begin()->second.front().second,
609 "use of undefined type id summary '^" +
610 Twine(ForwardRefTypeIds.begin()->first) + "'");
611
612 return false;
613}
614
615//===----------------------------------------------------------------------===//
616// Top-Level Entities
617//===----------------------------------------------------------------------===//
618
619bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
620 // Delay parsing of the data layout string until the target triple is known.
621 // Then, pass both the the target triple and the tentative data layout string
622 // to DataLayoutCallback, allowing to override the DL string.
623 // This enables importing modules with invalid DL strings.
624 std::string TentativeDLStr = M->getDataLayoutStr();
625 LocTy DLStrLoc;
626
627 bool Done = false;
628 while (!Done) {
629 switch (Lex.getKind()) {
630 case lltok::kw_target:
631 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
632 return true;
633 break;
635 if (parseSourceFileName())
636 return true;
637 break;
638 default:
639 Done = true;
640 }
641 }
642 // Run the override callback to potentially change the data layout string, and
643 // parse the data layout string.
644 if (auto LayoutOverride =
645 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
646 TentativeDLStr = *LayoutOverride;
647 DLStrLoc = {};
648 }
649 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
650 if (!MaybeDL)
651 return error(DLStrLoc, toString(MaybeDL.takeError()));
652 M->setDataLayout(MaybeDL.get());
653 return false;
654}
655
656bool LLParser::parseTopLevelEntities() {
657 // If there is no Module, then parse just the summary index entries.
658 if (!M) {
659 while (true) {
660 switch (Lex.getKind()) {
661 case lltok::Eof:
662 return false;
663 case lltok::SummaryID:
664 if (parseSummaryEntry())
665 return true;
666 break;
668 if (parseSourceFileName())
669 return true;
670 break;
671 default:
672 // Skip everything else
673 Lex.Lex();
674 }
675 }
676 }
677 while (true) {
678 switch (Lex.getKind()) {
679 default:
680 return tokError("expected top-level entity");
681 case lltok::Eof: return false;
683 if (parseDeclare())
684 return true;
685 break;
686 case lltok::kw_define:
687 if (parseDefine())
688 return true;
689 break;
690 case lltok::kw_module:
691 if (parseModuleAsm())
692 return true;
693 break;
695 if (parseUnnamedType())
696 return true;
697 break;
698 case lltok::LocalVar:
699 if (parseNamedType())
700 return true;
701 break;
702 case lltok::GlobalID:
703 if (parseUnnamedGlobal())
704 return true;
705 break;
706 case lltok::GlobalVar:
707 if (parseNamedGlobal())
708 return true;
709 break;
710 case lltok::ComdatVar: if (parseComdat()) return true; break;
711 case lltok::exclaim:
712 if (parseStandaloneMetadata())
713 return true;
714 break;
715 case lltok::SummaryID:
716 if (parseSummaryEntry())
717 return true;
718 break;
720 if (parseNamedMetadata())
721 return true;
722 break;
724 if (parseUnnamedAttrGrp())
725 return true;
726 break;
728 if (parseUseListOrder())
729 return true;
730 break;
731 }
732 }
733}
734
735/// toplevelentity
736/// ::= 'module' 'asm' STRINGCONSTANT
737/// ::= 'module' 'asm' '(' 'property_name1:' STRINGCONSTANT ','
738/// 'property_name2:' STRINGCONSTANT ')'
739/// STRINGCONSTANT
740bool LLParser::parseModuleAsm() {
741 assert(Lex.getKind() == lltok::kw_module);
742 Lex.Lex();
743
744 std::string AsmStr;
745 if (parseToken(lltok::kw_asm, "expected 'module asm'"))
746 return true;
747
748 Module::GlobalAsmProperties Props;
749 if (EatIfPresent(lltok::lparen)) {
750 while (true) {
751 std::string Key, Value;
752 SMLoc Loc = Lex.getLoc();
753 if (Lex.getKind() != lltok::LabelStr)
754 return error(Loc, "expected property name followed by ':'");
755
756 Key = Lex.getStrVal();
757 Lex.Lex();
758
759 if (parseStringConstant(Value))
760 return true;
761
762 if (!Props.set(Key, Value))
763 return error(Loc, "unknown property name");
764
765 if (EatIfPresent(lltok::rparen))
766 break;
767 if (parseToken(lltok::comma, "expected ',' or ')'"))
768 return true;
769 }
770 }
771
772 do {
773 std::string AsmStrPart;
774 if (parseStringConstant(AsmStrPart))
775 return true;
776 AsmStr += AsmStrPart + "\n";
777 } while (Lex.getKind() == lltok::StringConstant);
778
779 M->appendModuleInlineAsm({AsmStr, Props});
780 return false;
781}
782
783/// toplevelentity
784/// ::= 'target' 'triple' '=' STRINGCONSTANT
785/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
786bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
787 LocTy &DLStrLoc) {
788 assert(Lex.getKind() == lltok::kw_target);
789 std::string Str;
790 switch (Lex.Lex()) {
791 default:
792 return tokError("unknown target property");
793 case lltok::kw_triple:
794 Lex.Lex();
795 if (parseToken(lltok::equal, "expected '=' after target triple") ||
796 parseStringConstant(Str))
797 return true;
798 M->setTargetTriple(Triple(std::move(Str)));
799 return false;
801 Lex.Lex();
802 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
803 return true;
804 DLStrLoc = Lex.getLoc();
805 if (parseStringConstant(TentativeDLStr))
806 return true;
807 return false;
808 }
809}
810
811/// toplevelentity
812/// ::= 'source_filename' '=' STRINGCONSTANT
813bool LLParser::parseSourceFileName() {
814 assert(Lex.getKind() == lltok::kw_source_filename);
815 Lex.Lex();
816 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
817 parseStringConstant(SourceFileName))
818 return true;
819 if (M)
820 M->setSourceFileName(SourceFileName);
821 return false;
822}
823
824/// parseUnnamedType:
825/// ::= LocalVarID '=' 'type' type
826bool LLParser::parseUnnamedType() {
827 LocTy TypeLoc = Lex.getLoc();
828 unsigned TypeID = Lex.getUIntVal();
829 Lex.Lex(); // eat LocalVarID;
830
831 if (parseToken(lltok::equal, "expected '=' after name") ||
832 parseToken(lltok::kw_type, "expected 'type' after '='"))
833 return true;
834
835 Type *Result = nullptr;
836 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
837 return true;
838
839 if (!isa<StructType>(Result)) {
840 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
841 if (Entry.first)
842 return error(TypeLoc, "non-struct types may not be recursive");
843 Entry.first = Result;
844 Entry.second = SMLoc();
845 }
846
847 return false;
848}
849
850/// toplevelentity
851/// ::= LocalVar '=' 'type' type
852bool LLParser::parseNamedType() {
853 std::string Name = Lex.getStrVal();
854 LocTy NameLoc = Lex.getLoc();
855 Lex.Lex(); // eat LocalVar.
856
857 if (parseToken(lltok::equal, "expected '=' after name") ||
858 parseToken(lltok::kw_type, "expected 'type' after name"))
859 return true;
860
861 Type *Result = nullptr;
862 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
863 return true;
864
865 if (!isa<StructType>(Result)) {
866 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
867 if (Entry.first)
868 return error(NameLoc, "non-struct types may not be recursive");
869 Entry.first = Result;
870 Entry.second = SMLoc();
871 }
872
873 return false;
874}
875
876/// toplevelentity
877/// ::= 'declare' FunctionHeader
878bool LLParser::parseDeclare() {
879 assert(Lex.getKind() == lltok::kw_declare);
880 Lex.Lex();
881
882 std::vector<std::pair<unsigned, MDNode *>> MDs;
883 while (Lex.getKind() == lltok::MetadataVar) {
884 unsigned MDK;
885 MDNode *N;
886 if (parseMetadataAttachment(MDK, N))
887 return true;
888 MDs.push_back({MDK, N});
889 }
890
891 Function *F;
892 unsigned FunctionNumber = -1;
893 SmallVector<unsigned> UnnamedArgNums;
894 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
895 return true;
896 for (auto &MD : MDs)
897 F->addMetadata(MD.first, *MD.second);
898 return false;
899}
900
901/// toplevelentity
902/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
903bool LLParser::parseDefine() {
904 assert(Lex.getKind() == lltok::kw_define);
905
906 FileLoc FunctionStart = getTokLineColumnPos();
907 Lex.Lex();
908
909 Function *F;
910 unsigned FunctionNumber = -1;
911 SmallVector<unsigned> UnnamedArgNums;
912 bool RetValue =
913 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
914 parseOptionalFunctionMetadata(*F) ||
915 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
916 if (ParserContext)
917 ParserContext->addFunctionLocation(
918 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
919
920 return RetValue;
921}
922
923/// parseGlobalType
924/// ::= 'constant'
925/// ::= 'global'
926bool LLParser::parseGlobalType(bool &IsConstant) {
927 if (Lex.getKind() == lltok::kw_constant)
928 IsConstant = true;
929 else if (Lex.getKind() == lltok::kw_global)
930 IsConstant = false;
931 else {
932 IsConstant = false;
933 return tokError("expected 'global' or 'constant'");
934 }
935 Lex.Lex();
936 return false;
937}
938
939bool LLParser::parseOptionalUnnamedAddr(
940 GlobalVariable::UnnamedAddr &UnnamedAddr) {
941 if (EatIfPresent(lltok::kw_unnamed_addr))
943 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
945 else
946 UnnamedAddr = GlobalValue::UnnamedAddr::None;
947 return false;
948}
949
950/// parseUnnamedGlobal:
951/// OptionalVisibility (ALIAS | IFUNC) ...
952/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
953/// OptionalDLLStorageClass
954/// ... -> global variable
955/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
956/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
957/// OptionalVisibility
958/// OptionalDLLStorageClass
959/// ... -> global variable
960bool LLParser::parseUnnamedGlobal() {
961 unsigned VarID;
962 std::string Name;
963 LocTy NameLoc = Lex.getLoc();
964
965 // Handle the GlobalID form.
966 if (Lex.getKind() == lltok::GlobalID) {
967 VarID = Lex.getUIntVal();
968 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
969 return true;
970
971 Lex.Lex(); // eat GlobalID;
972 if (parseToken(lltok::equal, "expected '=' after name"))
973 return true;
974 } else {
975 VarID = NumberedVals.getNext();
976 }
977
978 bool HasLinkage;
979 unsigned Linkage, Visibility, DLLStorageClass;
980 bool DSOLocal;
982 GlobalVariable::UnnamedAddr UnnamedAddr;
983 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
984 DSOLocal) ||
985 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
986 return true;
987
988 switch (Lex.getKind()) {
989 default:
990 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
991 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
992 case lltok::kw_alias:
993 case lltok::kw_ifunc:
994 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
995 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
996 }
997}
998
999/// parseNamedGlobal:
1000/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
1001/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1002/// OptionalVisibility OptionalDLLStorageClass
1003/// ... -> global variable
1004bool LLParser::parseNamedGlobal() {
1005 assert(Lex.getKind() == lltok::GlobalVar);
1006 LocTy NameLoc = Lex.getLoc();
1007 std::string Name = Lex.getStrVal();
1008 Lex.Lex();
1009
1010 bool HasLinkage;
1011 unsigned Linkage, Visibility, DLLStorageClass;
1012 bool DSOLocal;
1014 GlobalVariable::UnnamedAddr UnnamedAddr;
1015 if (parseToken(lltok::equal, "expected '=' in global variable") ||
1016 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
1017 DSOLocal) ||
1018 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
1019 return true;
1020
1021 switch (Lex.getKind()) {
1022 default:
1023 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
1024 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1025 case lltok::kw_alias:
1026 case lltok::kw_ifunc:
1027 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
1028 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1029 }
1030}
1031
1032bool LLParser::parseComdat() {
1033 assert(Lex.getKind() == lltok::ComdatVar);
1034 std::string Name = Lex.getStrVal();
1035 LocTy NameLoc = Lex.getLoc();
1036 Lex.Lex();
1037
1038 if (parseToken(lltok::equal, "expected '=' here"))
1039 return true;
1040
1041 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
1042 return tokError("expected comdat type");
1043
1045 switch (Lex.getKind()) {
1046 default:
1047 return tokError("unknown selection kind");
1048 case lltok::kw_any:
1049 SK = Comdat::Any;
1050 break;
1052 SK = Comdat::ExactMatch;
1053 break;
1054 case lltok::kw_largest:
1055 SK = Comdat::Largest;
1056 break;
1059 break;
1060 case lltok::kw_samesize:
1061 SK = Comdat::SameSize;
1062 break;
1063 }
1064 Lex.Lex();
1065
1066 // See if the comdat was forward referenced, if so, use the comdat.
1067 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1068 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1069 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
1070 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
1071
1072 Comdat *C;
1073 if (I != ComdatSymTab.end())
1074 C = &I->second;
1075 else
1076 C = M->getOrInsertComdat(Name);
1077 C->setSelectionKind(SK);
1078
1079 return false;
1080}
1081
1082// MDString:
1083// ::= '!' STRINGCONSTANT
1084bool LLParser::parseMDString(MDString *&Result) {
1085 std::string Str;
1086 if (parseStringConstant(Str))
1087 return true;
1088 Result = MDString::get(Context, Str);
1089 return false;
1090}
1091
1092// MDNode:
1093// ::= '!' MDNodeNumber
1094bool LLParser::parseMDNodeID(MDNode *&Result) {
1095 // !{ ..., !42, ... }
1096 LocTy IDLoc = Lex.getLoc();
1097 unsigned MID = 0;
1098 if (parseUInt32(MID))
1099 return true;
1100
1101 // If not a forward reference, just return it now.
1102 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
1103 if (!Inserted) {
1104 Result = It->second;
1105 return false;
1106 }
1107
1108 // Otherwise, create MDNode forward reference.
1109 auto &FwdRef = ForwardRefMDNodes[MID];
1110 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
1111
1112 Result = FwdRef.first.get();
1113 It->second.reset(Result);
1114 return false;
1115}
1116
1117/// parseNamedMetadata:
1118/// !foo = !{ !1, !2 }
1119bool LLParser::parseNamedMetadata() {
1120 assert(Lex.getKind() == lltok::MetadataVar);
1121 std::string Name = Lex.getStrVal();
1122 Lex.Lex();
1123
1124 if (parseToken(lltok::equal, "expected '=' here") ||
1125 parseToken(lltok::exclaim, "Expected '!' here") ||
1126 parseToken(lltok::lbrace, "Expected '{' here"))
1127 return true;
1128
1129 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1130 if (Lex.getKind() != lltok::rbrace)
1131 do {
1132 MDNode *N = nullptr;
1133 // parse DIExpressions inline as a special case. They are still MDNodes,
1134 // so they can still appear in named metadata. Remove this logic if they
1135 // become plain Metadata.
1136 if (Lex.getKind() == lltok::MetadataVar &&
1137 Lex.getStrVal() == "DIExpression") {
1138 if (parseDIExpression(N, /*IsDistinct=*/false))
1139 return true;
1140 // DIArgLists should only appear inline in a function, as they may
1141 // contain LocalAsMetadata arguments which require a function context.
1142 } else if (Lex.getKind() == lltok::MetadataVar &&
1143 Lex.getStrVal() == "DIArgList") {
1144 return tokError("found DIArgList outside of function");
1145 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1146 parseMDNodeID(N)) {
1147 return true;
1148 }
1149 NMD->addOperand(N);
1150 } while (EatIfPresent(lltok::comma));
1151
1152 return parseToken(lltok::rbrace, "expected end of metadata node");
1153}
1154
1155/// parseStandaloneMetadata:
1156/// !42 = !{...}
1157bool LLParser::parseStandaloneMetadata() {
1158 assert(Lex.getKind() == lltok::exclaim);
1159 Lex.Lex();
1160 unsigned MetadataID = 0;
1161
1162 MDNode *Init;
1163 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1164 return true;
1165
1166 // Detect common error, from old metadata syntax.
1167 if (Lex.getKind() == lltok::Type)
1168 return tokError("unexpected type in metadata definition");
1169
1170 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1171 if (Lex.getKind() == lltok::MetadataVar) {
1172 if (parseSpecializedMDNode(Init, IsDistinct))
1173 return true;
1174 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1175 parseMDTuple(Init, IsDistinct))
1176 return true;
1177
1178 // See if this was forward referenced, if so, handle it.
1179 auto FI = ForwardRefMDNodes.find(MetadataID);
1180 if (FI != ForwardRefMDNodes.end()) {
1181 auto *ToReplace = FI->second.first.get();
1182 // DIAssignID has its own special forward-reference "replacement" for
1183 // attachments (the temporary attachments are never actually attached).
1184 if (isa<DIAssignID>(Init)) {
1185 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1186 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1187 "Inst unexpectedly already has DIAssignID attachment");
1188 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1189 }
1190 }
1191
1192 ToReplace->replaceAllUsesWith(Init);
1193 ForwardRefMDNodes.erase(FI);
1194
1195 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1196 } else {
1197 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1198 if (!Inserted)
1199 return tokError("Metadata id is already used");
1200 It->second.reset(Init);
1201 }
1202
1203 return false;
1204}
1205
1206// Skips a single module summary entry.
1207bool LLParser::skipModuleSummaryEntry() {
1208 // Each module summary entry consists of a tag for the entry
1209 // type, followed by a colon, then the fields which may be surrounded by
1210 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1211 // support is in place we will look for the tokens corresponding to the
1212 // expected tags.
1213 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1214 Lex.getKind() != lltok::kw_typeid &&
1215 Lex.getKind() != lltok::kw_typeidCompatibleVTable &&
1216 Lex.getKind() != lltok::kw_flags &&
1217 Lex.getKind() != lltok::kw_blockcount &&
1218 Lex.getKind() != lltok::kw_cfiFunctionDefs &&
1219 Lex.getKind() != lltok::kw_cfiFunctionDecls)
1220 return tokError("Expected 'gv', 'module', 'typeid', "
1221 "'typeidCompatibleVTable', 'flags', 'blockcount', "
1222 "'cfiFunctionDefs' or 'cfiFunctionDecls' at the start of "
1223 "summary entry");
1224 if (Lex.getKind() == lltok::kw_flags)
1225 return parseSummaryIndexFlags();
1226 if (Lex.getKind() == lltok::kw_blockcount)
1227 return parseBlockCount();
1228 Lex.Lex();
1229 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1230 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1231 return true;
1232 // Now walk through the parenthesized entry, until the number of open
1233 // parentheses goes back down to 0 (the first '(' was parsed above).
1234 unsigned NumOpenParen = 1;
1235 do {
1236 switch (Lex.getKind()) {
1237 case lltok::lparen:
1238 NumOpenParen++;
1239 break;
1240 case lltok::rparen:
1241 NumOpenParen--;
1242 break;
1243 case lltok::Eof:
1244 return tokError("found end of file while parsing summary entry");
1245 default:
1246 // Skip everything in between parentheses.
1247 break;
1248 }
1249 Lex.Lex();
1250 } while (NumOpenParen > 0);
1251 return false;
1252}
1253
1254/// SummaryEntry
1255/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1256bool LLParser::parseSummaryEntry() {
1257 assert(Lex.getKind() == lltok::SummaryID);
1258 unsigned SummaryID = Lex.getUIntVal();
1259
1260 // For summary entries, colons should be treated as distinct tokens,
1261 // not an indication of the end of a label token.
1262 Lex.setIgnoreColonInIdentifiers(true);
1263
1264 Lex.Lex();
1265 if (parseToken(lltok::equal, "expected '=' here"))
1266 return true;
1267
1268 // If we don't have an index object, skip the summary entry.
1269 if (!Index)
1270 return skipModuleSummaryEntry();
1271
1272 bool result = false;
1273 switch (Lex.getKind()) {
1274 case lltok::kw_gv:
1275 result = parseGVEntry(SummaryID);
1276 break;
1277 case lltok::kw_module:
1278 result = parseModuleEntry(SummaryID);
1279 break;
1280 case lltok::kw_typeid:
1281 result = parseTypeIdEntry(SummaryID);
1282 break;
1284 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1285 break;
1286 case lltok::kw_flags:
1287 result = parseSummaryIndexFlags();
1288 break;
1290 result = parseBlockCount();
1291 break;
1294 result = parseCfiFunctions();
1295 break;
1296 default:
1297 result = error(Lex.getLoc(), "unexpected summary kind");
1298 break;
1299 }
1300 Lex.setIgnoreColonInIdentifiers(false);
1301 return result;
1302}
1303
1312
1313// If there was an explicit dso_local, update GV. In the absence of an explicit
1314// dso_local we keep the default value.
1315static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1316 if (DSOLocal)
1317 GV.setDSOLocal(true);
1318}
1319
1320/// parseAliasOrIFunc:
1321/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1322/// OptionalVisibility OptionalDLLStorageClass
1323/// OptionalThreadLocal OptionalUnnamedAddr
1324/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1325///
1326/// AliaseeOrResolver
1327/// ::= TypeAndValue
1328///
1329/// SymbolAttrs
1330/// ::= ',' 'partition' StringConstant
1331///
1332/// Everything through OptionalUnnamedAddr has already been parsed.
1333///
1334bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1335 LocTy NameLoc, unsigned L, unsigned Visibility,
1336 unsigned DLLStorageClass, bool DSOLocal,
1338 GlobalVariable::UnnamedAddr UnnamedAddr) {
1339 bool IsAlias;
1340 if (Lex.getKind() == lltok::kw_alias)
1341 IsAlias = true;
1342 else if (Lex.getKind() == lltok::kw_ifunc)
1343 IsAlias = false;
1344 else
1345 llvm_unreachable("Not an alias or ifunc!");
1346 Lex.Lex();
1347
1349
1350 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1351 return error(NameLoc, "invalid linkage type for alias");
1352
1353 if (!isValidVisibilityForLinkage(Visibility, L))
1354 return error(NameLoc,
1355 "symbol with local linkage must have default visibility");
1356
1357 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1358 return error(NameLoc,
1359 "symbol with local linkage cannot have a DLL storage class");
1360
1361 Type *Ty;
1362 LocTy ExplicitTypeLoc = Lex.getLoc();
1363 if (parseType(Ty) ||
1364 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1365 return true;
1366
1367 Constant *Aliasee;
1368 LocTy AliaseeLoc = Lex.getLoc();
1369 if (Lex.getKind() != lltok::kw_bitcast &&
1370 Lex.getKind() != lltok::kw_getelementptr &&
1371 Lex.getKind() != lltok::kw_addrspacecast &&
1372 Lex.getKind() != lltok::kw_inttoptr) {
1373 if (parseGlobalTypeAndValue(Aliasee))
1374 return true;
1375 } else {
1376 // The bitcast dest type is not present, it is implied by the dest type.
1377 ValID ID;
1378 if (parseValID(ID, /*PFS=*/nullptr))
1379 return true;
1380 if (ID.Kind != ValID::t_Constant)
1381 return error(AliaseeLoc, "invalid aliasee");
1382 Aliasee = ID.ConstantVal;
1383 }
1384
1385 Type *AliaseeType = Aliasee->getType();
1386 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1387 if (!PTy)
1388 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1389 unsigned AddrSpace = PTy->getAddressSpace();
1390
1391 GlobalValue *GVal = nullptr;
1392
1393 // See if the alias was forward referenced, if so, prepare to replace the
1394 // forward reference.
1395 if (!Name.empty()) {
1396 auto I = ForwardRefVals.find(Name);
1397 if (I != ForwardRefVals.end()) {
1398 GVal = I->second.first;
1399 ForwardRefVals.erase(Name);
1400 } else if (M->getNamedValue(Name)) {
1401 return error(NameLoc, "redefinition of global '@" + Name + "'");
1402 }
1403 } else {
1404 auto I = ForwardRefValIDs.find(NameID);
1405 if (I != ForwardRefValIDs.end()) {
1406 GVal = I->second.first;
1407 ForwardRefValIDs.erase(I);
1408 }
1409 }
1410
1411 // Okay, create the alias/ifunc but do not insert it into the module yet.
1412 std::unique_ptr<GlobalAlias> GA;
1413 std::unique_ptr<GlobalIFunc> GI;
1414 GlobalValue *GV;
1415 if (IsAlias) {
1416 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1417 /*Parent=*/nullptr));
1418 GV = GA.get();
1419 } else {
1420 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1421 /*Parent=*/nullptr));
1422 GV = GI.get();
1423 }
1424 GV->setThreadLocalMode(TLM);
1427 GV->setUnnamedAddr(UnnamedAddr);
1428 maybeSetDSOLocal(DSOLocal, *GV);
1429
1430 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1431 // Now parse them if there are any.
1432 while (Lex.getKind() == lltok::comma) {
1433 Lex.Lex();
1434
1435 if (Lex.getKind() == lltok::kw_partition) {
1436 Lex.Lex();
1437 GV->setPartition(Lex.getStrVal());
1438 if (parseToken(lltok::StringConstant, "expected partition string"))
1439 return true;
1440 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1441 if (parseGlobalObjectMetadataAttachment(*GI))
1442 return true;
1443 } else {
1444 return tokError("unknown alias or ifunc property!");
1445 }
1446 }
1447
1448 if (Name.empty())
1449 NumberedVals.add(NameID, GV);
1450
1451 if (GVal) {
1452 // Verify that types agree.
1453 if (GVal->getType() != GV->getType())
1454 return error(
1455 ExplicitTypeLoc,
1456 "forward reference and definition of alias have different types");
1457
1458 // If they agree, just RAUW the old value with the alias and remove the
1459 // forward ref info.
1460 GVal->replaceAllUsesWith(GV);
1461 GVal->eraseFromParent();
1462 }
1463
1464 // Insert into the module, we know its name won't collide now.
1465 if (IsAlias)
1466 M->insertAlias(GA.release());
1467 else
1468 M->insertIFunc(GI.release());
1469 assert(GV->getName() == Name && "Should not be a name conflict!");
1470
1471 return false;
1472}
1473
1474static bool isSanitizer(lltok::Kind Kind) {
1475 switch (Kind) {
1478 case lltok::kw_sanitize_memtag:
1480 return true;
1481 default:
1482 return false;
1483 }
1484}
1485
1486bool LLParser::parseSanitizer(GlobalVariable *GV) {
1487 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1489 if (GV->hasSanitizerMetadata())
1490 Meta = GV->getSanitizerMetadata();
1491
1492 switch (Lex.getKind()) {
1494 Meta.NoAddress = true;
1495 break;
1497 Meta.NoHWAddress = true;
1498 break;
1499 case lltok::kw_sanitize_memtag:
1500 Meta.Memtag = true;
1501 break;
1503 Meta.IsDynInit = true;
1504 break;
1505 default:
1506 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1507 }
1508 GV->setSanitizerMetadata(Meta);
1509 Lex.Lex();
1510 return false;
1511}
1512
1513/// parseGlobal
1514/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1515/// OptionalVisibility OptionalDLLStorageClass
1516/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1517/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1518/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1519/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1520/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1521/// Const OptionalAttrs
1522///
1523/// Everything up to and including OptionalUnnamedAddr has been parsed
1524/// already.
1525///
1526bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1527 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1528 unsigned Visibility, unsigned DLLStorageClass,
1529 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1530 GlobalVariable::UnnamedAddr UnnamedAddr) {
1531 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1532 return error(NameLoc,
1533 "symbol with local linkage must have default visibility");
1534
1535 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1536 return error(NameLoc,
1537 "symbol with local linkage cannot have a DLL storage class");
1538
1539 unsigned AddrSpace;
1540 bool IsConstant, IsExternallyInitialized;
1541 LocTy IsExternallyInitializedLoc;
1542 LocTy TyLoc;
1543
1544 Type *Ty = nullptr;
1545 if (parseOptionalAddrSpace(AddrSpace) ||
1546 parseOptionalToken(lltok::kw_externally_initialized,
1547 IsExternallyInitialized,
1548 &IsExternallyInitializedLoc) ||
1549 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1550 return true;
1551
1552 // If the linkage is specified and is external, then no initializer is
1553 // present.
1554 Constant *Init = nullptr;
1555 if (!HasLinkage ||
1558 if (parseGlobalValue(Ty, Init))
1559 return true;
1560 }
1561
1563 return error(TyLoc, "invalid type for global variable");
1564
1565 GlobalValue *GVal = nullptr;
1566
1567 // See if the global was forward referenced, if so, use the global.
1568 if (!Name.empty()) {
1569 auto I = ForwardRefVals.find(Name);
1570 if (I != ForwardRefVals.end()) {
1571 GVal = I->second.first;
1572 ForwardRefVals.erase(I);
1573 } else if (M->getNamedValue(Name)) {
1574 return error(NameLoc, "redefinition of global '@" + Name + "'");
1575 }
1576 } else {
1577 // Handle @"", where a name is syntactically specified, but semantically
1578 // missing.
1579 if (NameID == (unsigned)-1)
1580 NameID = NumberedVals.getNext();
1581
1582 auto I = ForwardRefValIDs.find(NameID);
1583 if (I != ForwardRefValIDs.end()) {
1584 GVal = I->second.first;
1585 ForwardRefValIDs.erase(I);
1586 }
1587 }
1588
1589 GlobalVariable *GV = new GlobalVariable(
1590 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1592
1593 if (Name.empty())
1594 NumberedVals.add(NameID, GV);
1595
1596 // Set the parsed properties on the global.
1597 if (Init)
1598 GV->setInitializer(Init);
1599 GV->setConstant(IsConstant);
1601 maybeSetDSOLocal(DSOLocal, *GV);
1604 GV->setExternallyInitialized(IsExternallyInitialized);
1605 GV->setThreadLocalMode(TLM);
1606 GV->setUnnamedAddr(UnnamedAddr);
1607
1608 if (GVal) {
1609 if (GVal->getAddressSpace() != AddrSpace)
1610 return error(
1611 TyLoc,
1612 "forward reference and definition of global have different types");
1613
1614 GVal->replaceAllUsesWith(GV);
1615 GVal->eraseFromParent();
1616 }
1617
1618 // parse attributes on the global.
1619 while (Lex.getKind() == lltok::comma) {
1620 Lex.Lex();
1621
1622 if (Lex.getKind() == lltok::kw_section) {
1623 Lex.Lex();
1624 GV->setSection(Lex.getStrVal());
1625 if (parseToken(lltok::StringConstant, "expected global section string"))
1626 return true;
1627 } else if (Lex.getKind() == lltok::kw_partition) {
1628 Lex.Lex();
1629 GV->setPartition(Lex.getStrVal());
1630 if (parseToken(lltok::StringConstant, "expected partition string"))
1631 return true;
1632 } else if (Lex.getKind() == lltok::kw_align) {
1633 MaybeAlign Alignment;
1634 if (parseOptionalAlignment(Alignment))
1635 return true;
1636 if (Alignment)
1637 GV->setAlignment(*Alignment);
1638 } else if (Lex.getKind() == lltok::kw_code_model) {
1640 if (parseOptionalCodeModel(CodeModel))
1641 return true;
1642 GV->setCodeModel(CodeModel);
1643 } else if (Lex.getKind() == lltok::MetadataVar) {
1644 if (parseGlobalObjectMetadataAttachment(*GV))
1645 return true;
1646 } else if (isSanitizer(Lex.getKind())) {
1647 if (parseSanitizer(GV))
1648 return true;
1649 } else {
1650 Comdat *C;
1651 if (parseOptionalComdat(Name, C))
1652 return true;
1653 if (C)
1654 GV->setComdat(C);
1655 else
1656 return tokError("unknown global variable property!");
1657 }
1658 }
1659
1660 AttrBuilder Attrs(M->getContext());
1661 LocTy BuiltinLoc;
1662 std::vector<unsigned> FwdRefAttrGrps;
1663 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1664 return true;
1665 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1666 GV->setAttributes(AttributeSet::get(Context, Attrs));
1667 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1668 }
1669
1670 return false;
1671}
1672
1673/// parseUnnamedAttrGrp
1674/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1675bool LLParser::parseUnnamedAttrGrp() {
1676 assert(Lex.getKind() == lltok::kw_attributes);
1677 LocTy AttrGrpLoc = Lex.getLoc();
1678 Lex.Lex();
1679
1680 if (Lex.getKind() != lltok::AttrGrpID)
1681 return tokError("expected attribute group id");
1682
1683 unsigned VarID = Lex.getUIntVal();
1684 std::vector<unsigned> unused;
1685 LocTy BuiltinLoc;
1686 Lex.Lex();
1687
1688 if (parseToken(lltok::equal, "expected '=' here") ||
1689 parseToken(lltok::lbrace, "expected '{' here"))
1690 return true;
1691
1692 auto R = NumberedAttrBuilders.find(VarID);
1693 if (R == NumberedAttrBuilders.end())
1694 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1695
1696 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1697 parseToken(lltok::rbrace, "expected end of attribute group"))
1698 return true;
1699
1700 if (!R->second.hasAttributes())
1701 return error(AttrGrpLoc, "attribute group has no attributes");
1702
1703 return false;
1704}
1705
1707 switch (Kind) {
1708#define GET_ATTR_NAMES
1709#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1710 case lltok::kw_##DISPLAY_NAME: \
1711 return Attribute::ENUM_NAME;
1712#include "llvm/IR/Attributes.inc"
1713 default:
1714 return Attribute::None;
1715 }
1716}
1717
1718bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1719 bool InAttrGroup) {
1720 if (Attribute::isTypeAttrKind(Attr))
1721 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1722
1723 switch (Attr) {
1724 case Attribute::Alignment: {
1725 MaybeAlign Alignment;
1726 if (InAttrGroup) {
1727 uint32_t Value = 0;
1728 Lex.Lex();
1729 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1730 return true;
1732 } else {
1733 if (parseOptionalAlignment(Alignment, true))
1734 return true;
1735 }
1736 B.addAlignmentAttr(Alignment);
1737 return false;
1738 }
1739 case Attribute::StackAlignment: {
1740 unsigned Alignment;
1741 if (InAttrGroup) {
1742 Lex.Lex();
1743 if (parseToken(lltok::equal, "expected '=' here") ||
1744 parseUInt32(Alignment))
1745 return true;
1746 } else {
1747 if (parseOptionalStackAlignment(Alignment))
1748 return true;
1749 }
1750 B.addStackAlignmentAttr(Alignment);
1751 return false;
1752 }
1753 case Attribute::AllocSize: {
1754 unsigned ElemSizeArg;
1755 std::optional<unsigned> NumElemsArg;
1756 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1757 return true;
1758 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1759 return false;
1760 }
1761 case Attribute::VScaleRange: {
1762 unsigned MinValue, MaxValue;
1763 if (parseVScaleRangeArguments(MinValue, MaxValue))
1764 return true;
1765 B.addVScaleRangeAttr(MinValue,
1766 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1767 return false;
1768 }
1769 case Attribute::Dereferenceable: {
1770 std::optional<uint64_t> Bytes;
1771 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1772 return true;
1773 assert(Bytes.has_value());
1774 B.addDereferenceableAttr(Bytes.value());
1775 return false;
1776 }
1777 case Attribute::DeadOnReturn: {
1778 std::optional<uint64_t> Bytes;
1779 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1780 /*ErrorNoBytes=*/false))
1781 return true;
1782 if (Bytes.has_value()) {
1783 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1784 } else {
1785 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1786 }
1787 return false;
1788 }
1789 case Attribute::DereferenceableOrNull: {
1790 std::optional<uint64_t> Bytes;
1791 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1792 return true;
1793 assert(Bytes.has_value());
1794 B.addDereferenceableOrNullAttr(Bytes.value());
1795 return false;
1796 }
1797 case Attribute::UWTable: {
1799 if (parseOptionalUWTableKind(Kind))
1800 return true;
1801 B.addUWTableAttr(Kind);
1802 return false;
1803 }
1804 case Attribute::AllocKind: {
1806 if (parseAllocKind(Kind))
1807 return true;
1808 B.addAllocKindAttr(Kind);
1809 return false;
1810 }
1811 case Attribute::Memory: {
1812 std::optional<MemoryEffects> ME = parseMemoryAttr();
1813 if (!ME)
1814 return true;
1815 B.addMemoryAttr(*ME);
1816 return false;
1817 }
1818 case Attribute::DenormalFPEnv: {
1819 std::optional<DenormalFPEnv> Mode = parseDenormalFPEnvAttr();
1820 if (!Mode)
1821 return true;
1822
1823 B.addDenormalFPEnvAttr(*Mode);
1824 return false;
1825 }
1826 case Attribute::NoFPClass: {
1827 if (FPClassTest NoFPClass =
1828 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1829 B.addNoFPClassAttr(NoFPClass);
1830 return false;
1831 }
1832
1833 return true;
1834 }
1835 case Attribute::Range:
1836 return parseRangeAttr(B);
1837 case Attribute::Initializes:
1838 return parseInitializesAttr(B);
1839 case Attribute::Captures:
1840 return parseCapturesAttr(B);
1841 default:
1842 B.addAttribute(Attr);
1843 Lex.Lex();
1844 return false;
1845 }
1846}
1847
1849 switch (Kind) {
1850 case lltok::kw_readnone:
1851 ME &= MemoryEffects::none();
1852 return true;
1853 case lltok::kw_readonly:
1855 return true;
1856 case lltok::kw_writeonly:
1858 return true;
1861 return true;
1864 return true;
1867 return true;
1868 default:
1869 return false;
1870 }
1871}
1872
1873/// parseFnAttributeValuePairs
1874/// ::= <attr> | <attr> '=' <value>
1875bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1876 std::vector<unsigned> &FwdRefAttrGrps,
1877 bool InAttrGrp, LocTy &BuiltinLoc) {
1878 bool HaveError = false;
1879
1880 B.clear();
1881
1883 while (true) {
1884 lltok::Kind Token = Lex.getKind();
1885 if (Token == lltok::rbrace)
1886 break; // Finished.
1887
1888 if (Token == lltok::StringConstant) {
1889 if (parseStringAttribute(B))
1890 return true;
1891 continue;
1892 }
1893
1894 if (Token == lltok::AttrGrpID) {
1895 // Allow a function to reference an attribute group:
1896 //
1897 // define void @foo() #1 { ... }
1898 if (InAttrGrp) {
1899 HaveError |= error(
1900 Lex.getLoc(),
1901 "cannot have an attribute group reference in an attribute group");
1902 } else {
1903 // Save the reference to the attribute group. We'll fill it in later.
1904 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1905 }
1906 Lex.Lex();
1907 continue;
1908 }
1909
1910 SMLoc Loc = Lex.getLoc();
1911 if (Token == lltok::kw_builtin)
1912 BuiltinLoc = Loc;
1913
1914 if (upgradeMemoryAttr(ME, Token)) {
1915 Lex.Lex();
1916 continue;
1917 }
1918
1920 if (Attr == Attribute::None) {
1921 if (!InAttrGrp)
1922 break;
1923 return error(Lex.getLoc(), "unterminated attribute group");
1924 }
1925
1926 if (parseEnumAttribute(Attr, B, InAttrGrp))
1927 return true;
1928
1929 // As a hack, we allow function alignment to be initially parsed as an
1930 // attribute on a function declaration/definition or added to an attribute
1931 // group and later moved to the alignment field.
1932 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1933 HaveError |= error(Loc, "this attribute does not apply to functions");
1934 }
1935
1936 if (ME != MemoryEffects::unknown())
1937 B.addMemoryAttr(ME);
1938 return HaveError;
1939}
1940
1941//===----------------------------------------------------------------------===//
1942// GlobalValue Reference/Resolution Routines.
1943//===----------------------------------------------------------------------===//
1944
1946 // The used global type does not matter. We will later RAUW it with a
1947 // global/function of the correct type.
1948 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1951 PTy->getAddressSpace());
1952}
1953
1954Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1955 Value *Val) {
1956 Type *ValTy = Val->getType();
1957 if (ValTy == Ty)
1958 return Val;
1959 if (Ty->isLabelTy())
1960 error(Loc, "'" + Name + "' is not a basic block");
1961 else
1962 error(Loc, "'" + Name + "' defined with type '" +
1963 getTypeString(Val->getType()) + "' but expected '" +
1964 getTypeString(Ty) + "'");
1965 return nullptr;
1966}
1967
1968/// getGlobalVal - Get a value with the specified name or ID, creating a
1969/// forward reference record if needed. This can return null if the value
1970/// exists but does not have the right type.
1971GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1972 LocTy Loc) {
1974 if (!PTy) {
1975 error(Loc, "global variable reference must have pointer type");
1976 return nullptr;
1977 }
1978
1979 // Look this name up in the normal function symbol table.
1980 GlobalValue *Val =
1981 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1982
1983 // If this is a forward reference for the value, see if we already created a
1984 // forward ref record.
1985 if (!Val) {
1986 auto I = ForwardRefVals.find(Name);
1987 if (I != ForwardRefVals.end())
1988 Val = I->second.first;
1989 }
1990
1991 // If we have the value in the symbol table or fwd-ref table, return it.
1992 if (Val)
1994 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1995
1996 // Otherwise, create a new forward reference for this value and remember it.
1997 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1998 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1999 return FwdVal;
2000}
2001
2002GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
2004 if (!PTy) {
2005 error(Loc, "global variable reference must have pointer type");
2006 return nullptr;
2007 }
2008
2009 GlobalValue *Val = NumberedVals.get(ID);
2010
2011 // If this is a forward reference for the value, see if we already created a
2012 // forward ref record.
2013 if (!Val) {
2014 auto I = ForwardRefValIDs.find(ID);
2015 if (I != ForwardRefValIDs.end())
2016 Val = I->second.first;
2017 }
2018
2019 // If we have the value in the symbol table or fwd-ref table, return it.
2020 if (Val)
2022 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
2023
2024 // Otherwise, create a new forward reference for this value and remember it.
2025 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
2026 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2027 return FwdVal;
2028}
2029
2030//===----------------------------------------------------------------------===//
2031// Comdat Reference/Resolution Routines.
2032//===----------------------------------------------------------------------===//
2033
2034Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
2035 // Look this name up in the comdat symbol table.
2036 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
2037 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
2038 if (I != ComdatSymTab.end())
2039 return &I->second;
2040
2041 // Otherwise, create a new forward reference for this value and remember it.
2042 Comdat *C = M->getOrInsertComdat(Name);
2043 ForwardRefComdats[Name] = Loc;
2044 return C;
2045}
2046
2047//===----------------------------------------------------------------------===//
2048// Helper Routines.
2049//===----------------------------------------------------------------------===//
2050
2051/// parseToken - If the current token has the specified kind, eat it and return
2052/// success. Otherwise, emit the specified error and return failure.
2053bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
2054 if (Lex.getKind() != T)
2055 return tokError(ErrMsg);
2056 Lex.Lex();
2057 return false;
2058}
2059
2060/// parseStringConstant
2061/// ::= StringConstant
2062bool LLParser::parseStringConstant(std::string &Result) {
2063 if (Lex.getKind() != lltok::StringConstant)
2064 return tokError("expected string constant");
2065 Result = Lex.getStrVal();
2066 Lex.Lex();
2067 return false;
2068}
2069
2070/// parseUInt32
2071/// ::= uint32
2072bool LLParser::parseUInt32(uint32_t &Val) {
2073 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2074 return tokError("expected integer");
2075 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
2076 if (Val64 != unsigned(Val64))
2077 return tokError("expected 32-bit integer (too large)");
2078 Val = Val64;
2079 Lex.Lex();
2080 return false;
2081}
2082
2083/// parseUInt64
2084/// ::= uint64
2085bool LLParser::parseUInt64(uint64_t &Val) {
2086 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2087 return tokError("expected integer");
2088 Val = Lex.getAPSIntVal().getLimitedValue();
2089 Lex.Lex();
2090 return false;
2091}
2092
2093/// parseTLSModel
2094/// := 'localdynamic'
2095/// := 'initialexec'
2096/// := 'localexec'
2097bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
2098 switch (Lex.getKind()) {
2099 default:
2100 return tokError("expected localdynamic, initialexec or localexec");
2103 break;
2106 break;
2109 break;
2110 }
2111
2112 Lex.Lex();
2113 return false;
2114}
2115
2116/// parseOptionalThreadLocal
2117/// := /*empty*/
2118/// := 'thread_local'
2119/// := 'thread_local' '(' tlsmodel ')'
2120bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
2122 if (!EatIfPresent(lltok::kw_thread_local))
2123 return false;
2124
2126 if (Lex.getKind() == lltok::lparen) {
2127 Lex.Lex();
2128 return parseTLSModel(TLM) ||
2129 parseToken(lltok::rparen, "expected ')' after thread local model");
2130 }
2131 return false;
2132}
2133
2134/// parseOptionalAddrSpace
2135/// := /*empty*/
2136/// := 'addrspace' '(' uint32 ')'
2137bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
2138 AddrSpace = DefaultAS;
2139 if (!EatIfPresent(lltok::kw_addrspace))
2140 return false;
2141
2142 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
2143 if (Lex.getKind() == lltok::StringConstant) {
2144 const std::string &AddrSpaceStr = Lex.getStrVal();
2145 if (AddrSpaceStr == "A") {
2146 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2147 } else if (AddrSpaceStr == "G") {
2148 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2149 } else if (AddrSpaceStr == "P") {
2150 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2151 } else if (std::optional<unsigned> AS =
2152 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2153 AddrSpace = *AS;
2154 } else {
2155 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
2156 }
2157 Lex.Lex();
2158 return false;
2159 }
2160 if (Lex.getKind() != lltok::APSInt)
2161 return tokError("expected integer or string constant");
2162 SMLoc Loc = Lex.getLoc();
2163 if (parseUInt32(AddrSpace))
2164 return true;
2165 if (!isUInt<24>(AddrSpace))
2166 return error(Loc, "invalid address space, must be a 24-bit integer");
2167 return false;
2168 };
2169
2170 return parseToken(lltok::lparen, "expected '(' in address space") ||
2171 ParseAddrspaceValue(AddrSpace) ||
2172 parseToken(lltok::rparen, "expected ')' in address space");
2173}
2174
2175/// parseStringAttribute
2176/// := StringConstant
2177/// := StringConstant '=' StringConstant
2178bool LLParser::parseStringAttribute(AttrBuilder &B) {
2179 std::string Attr = Lex.getStrVal();
2180 Lex.Lex();
2181 std::string Val;
2182 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
2183 return true;
2184 B.addAttribute(Attr, Val);
2185 return false;
2186}
2187
2188/// Parse a potentially empty list of parameter or return attributes.
2189bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2190 bool HaveError = false;
2191
2192 B.clear();
2193
2194 while (true) {
2195 lltok::Kind Token = Lex.getKind();
2196 if (Token == lltok::StringConstant) {
2197 if (parseStringAttribute(B))
2198 return true;
2199 continue;
2200 }
2201
2202 if (Token == lltok::kw_nocapture) {
2203 Lex.Lex();
2204 B.addCapturesAttr(CaptureInfo::none());
2205 continue;
2206 }
2207
2208 SMLoc Loc = Lex.getLoc();
2210 if (Attr == Attribute::None)
2211 return HaveError;
2212
2213 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2214 return true;
2215
2216 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2217 HaveError |= error(Loc, "this attribute does not apply to parameters");
2218 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2219 HaveError |= error(Loc, "this attribute does not apply to return values");
2220 }
2221}
2222
2223static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2224 HasLinkage = true;
2225 switch (Kind) {
2226 default:
2227 HasLinkage = false;
2229 case lltok::kw_private:
2231 case lltok::kw_internal:
2233 case lltok::kw_weak:
2235 case lltok::kw_weak_odr:
2237 case lltok::kw_linkonce:
2245 case lltok::kw_common:
2249 case lltok::kw_external:
2251 }
2252}
2253
2254/// parseOptionalLinkage
2255/// ::= /*empty*/
2256/// ::= 'private'
2257/// ::= 'internal'
2258/// ::= 'weak'
2259/// ::= 'weak_odr'
2260/// ::= 'linkonce'
2261/// ::= 'linkonce_odr'
2262/// ::= 'available_externally'
2263/// ::= 'appending'
2264/// ::= 'common'
2265/// ::= 'extern_weak'
2266/// ::= 'external'
2267bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2268 unsigned &Visibility,
2269 unsigned &DLLStorageClass, bool &DSOLocal) {
2270 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2271 if (HasLinkage)
2272 Lex.Lex();
2273 parseOptionalDSOLocal(DSOLocal);
2274 parseOptionalVisibility(Visibility);
2275 parseOptionalDLLStorageClass(DLLStorageClass);
2276
2277 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2278 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2279 }
2280
2281 return false;
2282}
2283
2284void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2285 switch (Lex.getKind()) {
2286 default:
2287 DSOLocal = false;
2288 break;
2290 DSOLocal = true;
2291 Lex.Lex();
2292 break;
2294 DSOLocal = false;
2295 Lex.Lex();
2296 break;
2297 }
2298}
2299
2300/// parseOptionalVisibility
2301/// ::= /*empty*/
2302/// ::= 'default'
2303/// ::= 'hidden'
2304/// ::= 'protected'
2305///
2306void LLParser::parseOptionalVisibility(unsigned &Res) {
2307 switch (Lex.getKind()) {
2308 default:
2310 return;
2311 case lltok::kw_default:
2313 break;
2314 case lltok::kw_hidden:
2316 break;
2319 break;
2320 }
2321 Lex.Lex();
2322}
2323
2324bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2326 switch (Kind) {
2327 default:
2328 return tokError("unknown import kind. Expect definition or declaration.");
2331 return false;
2334 return false;
2335 }
2336}
2337
2338/// parseOptionalDLLStorageClass
2339/// ::= /*empty*/
2340/// ::= 'dllimport'
2341/// ::= 'dllexport'
2342///
2343void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2344 switch (Lex.getKind()) {
2345 default:
2347 return;
2350 break;
2353 break;
2354 }
2355 Lex.Lex();
2356}
2357
2358/// parseOptionalCallingConv
2359/// ::= /*empty*/
2360/// ::= 'ccc'
2361/// ::= 'fastcc'
2362/// ::= 'intel_ocl_bicc'
2363/// ::= 'coldcc'
2364/// ::= 'cfguard_checkcc'
2365/// ::= 'x86_stdcallcc'
2366/// ::= 'x86_fastcallcc'
2367/// ::= 'x86_thiscallcc'
2368/// ::= 'x86_vectorcallcc'
2369/// ::= 'arm_apcscc'
2370/// ::= 'arm_aapcscc'
2371/// ::= 'arm_aapcs_vfpcc'
2372/// ::= 'aarch64_vector_pcs'
2373/// ::= 'aarch64_sve_vector_pcs'
2374/// ::= 'aarch64_sme_preservemost_from_x0'
2375/// ::= 'aarch64_sme_preservemost_from_x1'
2376/// ::= 'aarch64_sme_preservemost_from_x2'
2377/// ::= 'msp430_intrcc'
2378/// ::= 'avr_intrcc'
2379/// ::= 'avr_signalcc'
2380/// ::= 'avr_builtincc'
2381/// ::= 'ptx_kernel'
2382/// ::= 'ptx_device'
2383/// ::= 'spir_func'
2384/// ::= 'spir_kernel'
2385/// ::= 'x86_64_sysvcc'
2386/// ::= 'win64cc'
2387/// ::= 'anyregcc'
2388/// ::= 'preserve_mostcc'
2389/// ::= 'preserve_allcc'
2390/// ::= 'preserve_nonecc'
2391/// ::= 'ghccc'
2392/// ::= 'swiftcc'
2393/// ::= 'swifttailcc'
2394/// ::= 'x86_intrcc'
2395/// ::= 'hhvmcc'
2396/// ::= 'hhvm_ccc'
2397/// ::= 'cxx_fast_tlscc'
2398/// ::= 'amdgpu_vs'
2399/// ::= 'amdgpu_ls'
2400/// ::= 'amdgpu_hs'
2401/// ::= 'amdgpu_es'
2402/// ::= 'amdgpu_gs'
2403/// ::= 'amdgpu_ps'
2404/// ::= 'amdgpu_cs'
2405/// ::= 'amdgpu_cs_chain'
2406/// ::= 'amdgpu_cs_chain_preserve'
2407/// ::= 'amdgpu_kernel'
2408/// ::= 'tailcc'
2409/// ::= 'm68k_rtdcc'
2410/// ::= 'wasm_emscripten_invokecc'
2411/// ::= 'graalcc'
2412/// ::= 'riscv_vector_cc'
2413/// ::= 'riscv_vls_cc'
2414/// ::= 'cc' UINT
2415///
2416bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2417 switch (Lex.getKind()) {
2418 default: CC = CallingConv::C; return false;
2419 case lltok::kw_ccc: CC = CallingConv::C; break;
2420 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2421 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2434 break;
2437 break;
2440 break;
2443 break;
2449 break;
2461 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2465 case lltok::kw_hhvmcc:
2467 break;
2468 case lltok::kw_hhvm_ccc:
2470 break;
2482 break;
2485 break;
2489 break;
2490 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2494 break;
2498 break;
2500 // Default ABI_VLEN
2502 Lex.Lex();
2503 if (!EatIfPresent(lltok::lparen))
2504 break;
2505 uint32_t ABIVlen;
2506 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2507 return true;
2508 switch (ABIVlen) {
2509 default:
2510 return tokError("unknown RISC-V ABI VLEN");
2511#define CC_VLS_CASE(ABIVlen) \
2512 case ABIVlen: \
2513 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2514 break;
2515 CC_VLS_CASE(32)
2516 CC_VLS_CASE(64)
2517 CC_VLS_CASE(128)
2518 CC_VLS_CASE(256)
2519 CC_VLS_CASE(512)
2520 CC_VLS_CASE(1024)
2521 CC_VLS_CASE(2048)
2522 CC_VLS_CASE(4096)
2523 CC_VLS_CASE(8192)
2524 CC_VLS_CASE(16384)
2525 CC_VLS_CASE(32768)
2526 CC_VLS_CASE(65536)
2527#undef CC_VLS_CASE
2528 }
2529 return false;
2532 break;
2535 break;
2538 break;
2539 case lltok::kw_cc: {
2540 Lex.Lex();
2541 return parseUInt32(CC);
2542 }
2543 }
2544
2545 Lex.Lex();
2546 return false;
2547}
2548
2549/// parseMetadataAttachment
2550/// ::= !dbg !42
2551bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2552 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2553
2554 std::string Name = Lex.getStrVal();
2555 Kind = M->getMDKindID(Name);
2556 Lex.Lex();
2557
2558 return parseMDNode(MD);
2559}
2560
2561/// parseInstructionMetadata
2562/// ::= !dbg !42 (',' !dbg !57)*
2563bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2564 do {
2565 if (Lex.getKind() != lltok::MetadataVar)
2566 return tokError("expected metadata after comma");
2567
2568 unsigned MDK;
2569 MDNode *N;
2570 auto Loc = Lex.getLoc();
2571 if (parseMetadataAttachment(MDK, N))
2572 return true;
2573
2574 if (MDK == LLVMContext::MD_DIAssignID)
2575 TempDIAssignIDAttachments[N].push_back(&Inst);
2576 else if (MDK == LLVMContext::MD_dbg)
2577 PendingDbgInsts.emplace_back(Loc, &Inst, N);
2578 else
2579 Inst.setMetadata(MDK, N);
2580
2581 // If this is the end of the list, we're done.
2582 } while (EatIfPresent(lltok::comma));
2583 return false;
2584}
2585
2586/// parseGlobalObjectMetadataAttachment
2587/// ::= !dbg !57
2588bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2589 unsigned MDK;
2590 MDNode *N;
2591 if (parseMetadataAttachment(MDK, N))
2592 return true;
2593
2594 GO.addMetadata(MDK, *N);
2595 return false;
2596}
2597
2598/// parseOptionalFunctionMetadata
2599/// ::= (!dbg !57)*
2600bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2601 while (Lex.getKind() == lltok::MetadataVar)
2602 if (parseGlobalObjectMetadataAttachment(F))
2603 return true;
2604 return false;
2605}
2606
2607/// parseOptionalAlignment
2608/// ::= /* empty */
2609/// ::= 'align' 4
2610bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2611 Alignment = std::nullopt;
2612 if (!EatIfPresent(lltok::kw_align))
2613 return false;
2614 LocTy AlignLoc = Lex.getLoc();
2615 uint64_t Value = 0;
2616
2617 LocTy ParenLoc = Lex.getLoc();
2618 bool HaveParens = false;
2619 if (AllowParens) {
2620 if (EatIfPresent(lltok::lparen))
2621 HaveParens = true;
2622 }
2623
2624 if (parseUInt64(Value))
2625 return true;
2626
2627 if (HaveParens && !EatIfPresent(lltok::rparen))
2628 return error(ParenLoc, "expected ')'");
2629
2630 if (!isPowerOf2_64(Value))
2631 return error(AlignLoc, "alignment is not a power of two");
2633 return error(AlignLoc, "huge alignments are not supported yet");
2635 return false;
2636}
2637
2638/// parseOptionalPrefAlignment
2639/// ::= /* empty */
2640/// ::= 'prefalign' '(' 4 ')'
2641bool LLParser::parseOptionalPrefAlignment(MaybeAlign &Alignment) {
2642 Alignment = std::nullopt;
2643 if (!EatIfPresent(lltok::kw_prefalign))
2644 return false;
2645 LocTy AlignLoc = Lex.getLoc();
2646 uint64_t Value = 0;
2647
2648 LocTy ParenLoc = Lex.getLoc();
2649 if (!EatIfPresent(lltok::lparen))
2650 return error(ParenLoc, "expected '('");
2651
2652 if (parseUInt64(Value))
2653 return true;
2654
2655 ParenLoc = Lex.getLoc();
2656 if (!EatIfPresent(lltok::rparen))
2657 return error(ParenLoc, "expected ')'");
2658
2659 if (!isPowerOf2_64(Value))
2660 return error(AlignLoc, "alignment is not a power of two");
2662 return error(AlignLoc, "huge alignments are not supported yet");
2664 return false;
2665}
2666
2667/// parseOptionalCodeModel
2668/// ::= /* empty */
2669/// ::= 'code_model' "large"
2670bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2671 Lex.Lex();
2672 auto StrVal = Lex.getStrVal();
2673 auto ErrMsg = "expected global code model string";
2674 if (StrVal == "tiny")
2675 model = CodeModel::Tiny;
2676 else if (StrVal == "small")
2677 model = CodeModel::Small;
2678 else if (StrVal == "kernel")
2679 model = CodeModel::Kernel;
2680 else if (StrVal == "medium")
2681 model = CodeModel::Medium;
2682 else if (StrVal == "large")
2683 model = CodeModel::Large;
2684 else
2685 return tokError(ErrMsg);
2686 if (parseToken(lltok::StringConstant, ErrMsg))
2687 return true;
2688 return false;
2689}
2690
2691/// parseOptionalAttrBytes
2692/// ::= /* empty */
2693/// ::= AttrKind '(' 4 ')'
2694///
2695/// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or
2696/// 'dead_on_return'
2697bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind,
2698 std::optional<uint64_t> &Bytes,
2699 bool ErrorNoBytes) {
2700 assert((AttrKind == lltok::kw_dereferenceable ||
2701 AttrKind == lltok::kw_dereferenceable_or_null ||
2702 AttrKind == lltok::kw_dead_on_return) &&
2703 "contract!");
2704
2705 Bytes = 0;
2706 if (!EatIfPresent(AttrKind))
2707 return false;
2708 LocTy ParenLoc = Lex.getLoc();
2709 if (!EatIfPresent(lltok::lparen)) {
2710 if (ErrorNoBytes)
2711 return error(ParenLoc, "expected '('");
2712 Bytes = std::nullopt;
2713 return false;
2714 }
2715 LocTy DerefLoc = Lex.getLoc();
2716 if (parseUInt64(Bytes.value()))
2717 return true;
2718 ParenLoc = Lex.getLoc();
2719 if (!EatIfPresent(lltok::rparen))
2720 return error(ParenLoc, "expected ')'");
2721 if (!Bytes.value())
2722 return error(DerefLoc, "byte count specified must be non-zero");
2723 return false;
2724}
2725
2726bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2727 Lex.Lex();
2729 if (!EatIfPresent(lltok::lparen))
2730 return false;
2731 LocTy KindLoc = Lex.getLoc();
2732 if (Lex.getKind() == lltok::kw_sync)
2734 else if (Lex.getKind() == lltok::kw_async)
2736 else
2737 return error(KindLoc, "expected unwind table kind");
2738 Lex.Lex();
2739 return parseToken(lltok::rparen, "expected ')'");
2740}
2741
2742bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2743 Lex.Lex();
2744 LocTy ParenLoc = Lex.getLoc();
2745 if (!EatIfPresent(lltok::lparen))
2746 return error(ParenLoc, "expected '('");
2747 LocTy KindLoc = Lex.getLoc();
2748 std::string Arg;
2749 if (parseStringConstant(Arg))
2750 return error(KindLoc, "expected allockind value");
2751 for (StringRef A : llvm::split(Arg, ",")) {
2752 if (A == "alloc") {
2754 } else if (A == "realloc") {
2756 } else if (A == "free") {
2758 } else if (A == "uninitialized") {
2760 } else if (A == "zeroed") {
2762 } else if (A == "aligned") {
2764 } else {
2765 return error(KindLoc, Twine("unknown allockind ") + A);
2766 }
2767 }
2768 ParenLoc = Lex.getLoc();
2769 if (!EatIfPresent(lltok::rparen))
2770 return error(ParenLoc, "expected ')'");
2771 if (Kind == AllocFnKind::Unknown)
2772 return error(KindLoc, "expected allockind value");
2773 return false;
2774}
2775
2777 using Loc = IRMemLocation;
2778
2779 switch (Tok) {
2780 case lltok::kw_argmem:
2781 return {Loc::ArgMem};
2783 return {Loc::InaccessibleMem};
2784 case lltok::kw_errnomem:
2785 return {Loc::ErrnoMem};
2787 return {Loc::TargetMem0};
2789 return {Loc::TargetMem1};
2790 case lltok::kw_target_mem: {
2793 Targets.push_back(Loc);
2794 return Targets;
2795 }
2796 default:
2797 return {};
2798 }
2799}
2800
2801static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2802 switch (Tok) {
2803 case lltok::kw_none:
2804 return ModRefInfo::NoModRef;
2805 case lltok::kw_read:
2806 return ModRefInfo::Ref;
2807 case lltok::kw_write:
2808 return ModRefInfo::Mod;
2810 return ModRefInfo::ModRef;
2811 default:
2812 return std::nullopt;
2813 }
2814}
2815
2816static std::optional<DenormalMode::DenormalModeKind>
2818 switch (Tok) {
2819 case lltok::kw_ieee:
2820 return DenormalMode::IEEE;
2825 case lltok::kw_dynamic:
2826 return DenormalMode::Dynamic;
2827 default:
2828 return std::nullopt;
2829 }
2830}
2831
2832std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2834
2835 // We use syntax like memory(argmem: read), so the colon should not be
2836 // interpreted as a label terminator.
2837 Lex.setIgnoreColonInIdentifiers(true);
2838 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2839
2840 Lex.Lex();
2841 if (!EatIfPresent(lltok::lparen)) {
2842 tokError("expected '('");
2843 return std::nullopt;
2844 }
2845
2846 bool SeenLoc = false;
2847 bool SeenTargetLoc = false;
2848 do {
2849 SmallVector<IRMemLocation, 2> Locs = keywordToLoc(Lex.getKind());
2850 if (!Locs.empty()) {
2851 Lex.Lex();
2852 if (!EatIfPresent(lltok::colon)) {
2853 tokError("expected ':' after location");
2854 return std::nullopt;
2855 }
2856 }
2857
2858 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2859 if (!MR) {
2860 if (Locs.empty())
2861 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2862 "or access kind (none, read, write, readwrite)");
2863 else
2864 tokError("expected access kind (none, read, write, readwrite)");
2865 return std::nullopt;
2866 }
2867
2868 Lex.Lex();
2869 if (!Locs.empty()) {
2870 SeenLoc = true;
2871 for (IRMemLocation Loc : Locs) {
2872 ME = ME.getWithModRef(Loc, *MR);
2873 if (ME.isTargetMemLoc(Loc) && Locs.size() == 1)
2874 SeenTargetLoc = true;
2875 }
2876 if (Locs.size() > 1 && SeenTargetLoc) {
2877 tokError("target memory default access kind must be specified first");
2878 return std::nullopt;
2879 }
2880
2881 } else {
2882 if (SeenLoc) {
2883 tokError("default access kind must be specified first");
2884 return std::nullopt;
2885 }
2886 ME = MemoryEffects(*MR);
2887 }
2888
2889 if (EatIfPresent(lltok::rparen))
2890 return ME;
2891 } while (EatIfPresent(lltok::comma));
2892
2893 tokError("unterminated memory attribute");
2894 return std::nullopt;
2895}
2896
2897std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2898 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2899 keywordToDenormalModeKind(Lex.getKind());
2900 if (!OutputMode) {
2901 tokError("expected denormal behavior kind (ieee, preservesign, "
2902 "positivezero, dynamic)");
2903 return {};
2904 }
2905
2906 Lex.Lex();
2907
2908 std::optional<DenormalMode::DenormalModeKind> InputMode;
2909 if (EatIfPresent(lltok::bar)) {
2910 InputMode = keywordToDenormalModeKind(Lex.getKind());
2911 if (!InputMode) {
2912 tokError("expected denormal behavior kind (ieee, preservesign, "
2913 "positivezero, dynamic)");
2914 return {};
2915 }
2916
2917 Lex.Lex();
2918 } else {
2919 // Single item, input == output mode
2920 InputMode = OutputMode;
2921 }
2922
2923 return DenormalMode(*OutputMode, *InputMode);
2924}
2925
2926std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2927 // We use syntax like denormal_fpenv(float: preservesign), so the colon should
2928 // not be interpreted as a label terminator.
2929 Lex.setIgnoreColonInIdentifiers(true);
2930 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2931
2932 Lex.Lex();
2933
2934 if (parseToken(lltok::lparen, "expected '('"))
2935 return {};
2936
2937 DenormalMode DefaultMode = DenormalMode::getIEEE();
2938 DenormalMode F32Mode = DenormalMode::getInvalid();
2939
2940 bool HasDefaultSection = false;
2941 if (Lex.getKind() != lltok::Type) {
2942 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2943 if (!ParsedDefaultMode)
2944 return {};
2945 DefaultMode = *ParsedDefaultMode;
2946 HasDefaultSection = true;
2947 }
2948
2949 bool HasComma = EatIfPresent(lltok::comma);
2950 if (Lex.getKind() == lltok::Type) {
2951 if (HasDefaultSection && !HasComma) {
2952 tokError("expected ',' before float:");
2953 return {};
2954 }
2955
2956 Type *Ty = nullptr;
2957 if (parseType(Ty) || !Ty->isFloatTy()) {
2958 tokError("expected float:");
2959 return {};
2960 }
2961
2962 if (parseToken(lltok::colon, "expected ':' before float denormal_fpenv"))
2963 return {};
2964
2965 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2966 if (!ParsedF32Mode)
2967 return {};
2968
2969 F32Mode = *ParsedF32Mode;
2970 }
2971
2972 if (parseToken(lltok::rparen, "unterminated denormal_fpenv"))
2973 return {};
2974
2975 return DenormalFPEnv(DefaultMode, F32Mode);
2976}
2977
2978static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2979 switch (Tok) {
2980 case lltok::kw_all:
2981 return fcAllFlags;
2982 case lltok::kw_nan:
2983 return fcNan;
2984 case lltok::kw_snan:
2985 return fcSNan;
2986 case lltok::kw_qnan:
2987 return fcQNan;
2988 case lltok::kw_inf:
2989 return fcInf;
2990 case lltok::kw_ninf:
2991 return fcNegInf;
2992 case lltok::kw_pinf:
2993 return fcPosInf;
2994 case lltok::kw_norm:
2995 return fcNormal;
2996 case lltok::kw_nnorm:
2997 return fcNegNormal;
2998 case lltok::kw_pnorm:
2999 return fcPosNormal;
3000 case lltok::kw_sub:
3001 return fcSubnormal;
3002 case lltok::kw_nsub:
3003 return fcNegSubnormal;
3004 case lltok::kw_psub:
3005 return fcPosSubnormal;
3006 case lltok::kw_zero:
3007 return fcZero;
3008 case lltok::kw_nzero:
3009 return fcNegZero;
3010 case lltok::kw_pzero:
3011 return fcPosZero;
3012 default:
3013 return 0;
3014 }
3015}
3016
3017unsigned LLParser::parseNoFPClassAttr() {
3018 unsigned Mask = fcNone;
3019
3020 Lex.Lex();
3021 if (!EatIfPresent(lltok::lparen)) {
3022 tokError("expected '('");
3023 return 0;
3024 }
3025
3026 do {
3027 uint64_t Value = 0;
3028 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
3029 if (TestMask != 0) {
3030 Mask |= TestMask;
3031 // TODO: Disallow overlapping masks to avoid copy paste errors
3032 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
3033 !parseUInt64(Value)) {
3034 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
3035 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
3036 return 0;
3037 }
3038
3039 if (!EatIfPresent(lltok::rparen)) {
3040 error(Lex.getLoc(), "expected ')'");
3041 return 0;
3042 }
3043
3044 return Value;
3045 } else {
3046 error(Lex.getLoc(), "expected nofpclass test mask");
3047 return 0;
3048 }
3049
3050 Lex.Lex();
3051 if (EatIfPresent(lltok::rparen))
3052 return Mask;
3053 } while (1);
3054
3055 llvm_unreachable("unterminated nofpclass attribute");
3056}
3057
3058/// parseOptionalCommaAlign
3059/// ::=
3060/// ::= ',' align 4
3061///
3062/// This returns with AteExtraComma set to true if it ate an excess comma at the
3063/// end.
3064bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
3065 bool &AteExtraComma) {
3066 AteExtraComma = false;
3067 while (EatIfPresent(lltok::comma)) {
3068 // Metadata at the end is an early exit.
3069 if (Lex.getKind() == lltok::MetadataVar) {
3070 AteExtraComma = true;
3071 return false;
3072 }
3073
3074 if (Lex.getKind() != lltok::kw_align)
3075 return error(Lex.getLoc(), "expected metadata or 'align'");
3076
3077 if (parseOptionalAlignment(Alignment))
3078 return true;
3079 }
3080
3081 return false;
3082}
3083
3084/// parseOptionalCommaAddrSpace
3085/// ::=
3086/// ::= ',' addrspace(1)
3087///
3088/// This returns with AteExtraComma set to true if it ate an excess comma at the
3089/// end.
3090bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
3091 bool &AteExtraComma) {
3092 AteExtraComma = false;
3093 while (EatIfPresent(lltok::comma)) {
3094 // Metadata at the end is an early exit.
3095 if (Lex.getKind() == lltok::MetadataVar) {
3096 AteExtraComma = true;
3097 return false;
3098 }
3099
3100 Loc = Lex.getLoc();
3101 if (Lex.getKind() != lltok::kw_addrspace)
3102 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
3103
3104 if (parseOptionalAddrSpace(AddrSpace))
3105 return true;
3106 }
3107
3108 return false;
3109}
3110
3111bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
3112 std::optional<unsigned> &HowManyArg) {
3113 Lex.Lex();
3114
3115 auto StartParen = Lex.getLoc();
3116 if (!EatIfPresent(lltok::lparen))
3117 return error(StartParen, "expected '('");
3118
3119 if (parseUInt32(BaseSizeArg))
3120 return true;
3121
3122 if (EatIfPresent(lltok::comma)) {
3123 auto HowManyAt = Lex.getLoc();
3124 unsigned HowMany;
3125 if (parseUInt32(HowMany))
3126 return true;
3127 if (HowMany == BaseSizeArg)
3128 return error(HowManyAt,
3129 "'allocsize' indices can't refer to the same parameter");
3130 HowManyArg = HowMany;
3131 } else
3132 HowManyArg = std::nullopt;
3133
3134 auto EndParen = Lex.getLoc();
3135 if (!EatIfPresent(lltok::rparen))
3136 return error(EndParen, "expected ')'");
3137 return false;
3138}
3139
3140bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
3141 unsigned &MaxValue) {
3142 Lex.Lex();
3143
3144 auto StartParen = Lex.getLoc();
3145 if (!EatIfPresent(lltok::lparen))
3146 return error(StartParen, "expected '('");
3147
3148 if (parseUInt32(MinValue))
3149 return true;
3150
3151 if (EatIfPresent(lltok::comma)) {
3152 if (parseUInt32(MaxValue))
3153 return true;
3154 } else
3155 MaxValue = MinValue;
3156
3157 auto EndParen = Lex.getLoc();
3158 if (!EatIfPresent(lltok::rparen))
3159 return error(EndParen, "expected ')'");
3160 return false;
3161}
3162
3163/// parseScopeAndOrdering
3164/// if isAtomic: ::= SyncScope? AtomicOrdering
3165/// else: ::=
3166///
3167/// This sets Scope and Ordering to the parsed values.
3168bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
3169 AtomicOrdering &Ordering) {
3170 if (!IsAtomic)
3171 return false;
3172
3173 return parseScope(SSID) || parseOrdering(Ordering);
3174}
3175
3176/// parseScope
3177/// ::= syncscope("singlethread" | "<target scope>")?
3178///
3179/// This sets synchronization scope ID to the ID of the parsed value.
3180bool LLParser::parseScope(SyncScope::ID &SSID) {
3181 SSID = SyncScope::System;
3182 if (EatIfPresent(lltok::kw_syncscope)) {
3183 auto StartParenAt = Lex.getLoc();
3184 if (!EatIfPresent(lltok::lparen))
3185 return error(StartParenAt, "Expected '(' in syncscope");
3186
3187 std::string SSN;
3188 auto SSNAt = Lex.getLoc();
3189 if (parseStringConstant(SSN))
3190 return error(SSNAt, "Expected synchronization scope name");
3191
3192 auto EndParenAt = Lex.getLoc();
3193 if (!EatIfPresent(lltok::rparen))
3194 return error(EndParenAt, "Expected ')' in syncscope");
3195
3196 SSID = Context.getOrInsertSyncScopeID(SSN);
3197 }
3198
3199 return false;
3200}
3201
3202/// parseOrdering
3203/// ::= AtomicOrdering
3204///
3205/// This sets Ordering to the parsed value.
3206bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
3207 switch (Lex.getKind()) {
3208 default:
3209 return tokError("Expected ordering on atomic instruction");
3212 // Not specified yet:
3213 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
3217 case lltok::kw_seq_cst:
3219 break;
3220 }
3221 Lex.Lex();
3222 return false;
3223}
3224
3225/// parseOptionalStackAlignment
3226/// ::= /* empty */
3227/// ::= 'alignstack' '(' 4 ')'
3228bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
3229 Alignment = 0;
3230 if (!EatIfPresent(lltok::kw_alignstack))
3231 return false;
3232 LocTy ParenLoc = Lex.getLoc();
3233 if (!EatIfPresent(lltok::lparen))
3234 return error(ParenLoc, "expected '('");
3235 LocTy AlignLoc = Lex.getLoc();
3236 if (parseUInt32(Alignment))
3237 return true;
3238 ParenLoc = Lex.getLoc();
3239 if (!EatIfPresent(lltok::rparen))
3240 return error(ParenLoc, "expected ')'");
3241 if (!isPowerOf2_32(Alignment))
3242 return error(AlignLoc, "stack alignment is not a power of two");
3243 return false;
3244}
3245
3246/// parseIndexList - This parses the index list for an insert/extractvalue
3247/// instruction. This sets AteExtraComma in the case where we eat an extra
3248/// comma at the end of the line and find that it is followed by metadata.
3249/// Clients that don't allow metadata can call the version of this function that
3250/// only takes one argument.
3251///
3252/// parseIndexList
3253/// ::= (',' uint32)+
3254///
3255bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
3256 bool &AteExtraComma) {
3257 AteExtraComma = false;
3258
3259 if (Lex.getKind() != lltok::comma)
3260 return tokError("expected ',' as start of index list");
3261
3262 while (EatIfPresent(lltok::comma)) {
3263 if (Lex.getKind() == lltok::MetadataVar) {
3264 if (Indices.empty())
3265 return tokError("expected index");
3266 AteExtraComma = true;
3267 return false;
3268 }
3269 unsigned Idx = 0;
3270 if (parseUInt32(Idx))
3271 return true;
3272 Indices.push_back(Idx);
3273 }
3274
3275 return false;
3276}
3277
3278//===----------------------------------------------------------------------===//
3279// Type Parsing.
3280//===----------------------------------------------------------------------===//
3281
3282/// parseType - parse a type.
3283bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
3284 SMLoc TypeLoc = Lex.getLoc();
3285 switch (Lex.getKind()) {
3286 default:
3287 return tokError(Msg);
3288 case lltok::Type:
3289 // Type ::= 'float' | 'void' (etc)
3290 Result = Lex.getTyVal();
3291 Lex.Lex();
3292
3293 // Handle "ptr" opaque pointer type.
3294 //
3295 // Type ::= ptr ('addrspace' '(' uint32 ')')?
3296 if (Result->isPointerTy()) {
3297 unsigned AddrSpace;
3298 if (parseOptionalAddrSpace(AddrSpace))
3299 return true;
3300 Result = PointerType::get(getContext(), AddrSpace);
3301
3302 // Give a nice error for 'ptr*'.
3303 if (Lex.getKind() == lltok::star)
3304 return tokError("ptr* is invalid - use ptr instead");
3305
3306 // Fall through to parsing the type suffixes only if this 'ptr' is a
3307 // function return. Otherwise, return success, implicitly rejecting other
3308 // suffixes.
3309 if (Lex.getKind() != lltok::lparen)
3310 return false;
3311 }
3312 break;
3313 case lltok::kw_target: {
3314 // Type ::= TargetExtType
3315 if (parseTargetExtType(Result))
3316 return true;
3317 break;
3318 }
3319 case lltok::lbrace:
3320 // Type ::= StructType
3321 if (parseAnonStructType(Result, false))
3322 return true;
3323 break;
3324 case lltok::lsquare:
3325 // Type ::= '[' ... ']'
3326 Lex.Lex(); // eat the lsquare.
3327 if (parseArrayVectorType(Result, false))
3328 return true;
3329 break;
3330 case lltok::less: // Either vector or packed struct.
3331 // Type ::= '<' ... '>'
3332 Lex.Lex();
3333 if (Lex.getKind() == lltok::lbrace) {
3334 if (parseAnonStructType(Result, true) ||
3335 parseToken(lltok::greater, "expected '>' at end of packed struct"))
3336 return true;
3337 } else if (parseArrayVectorType(Result, true))
3338 return true;
3339 break;
3340 case lltok::LocalVar: {
3341 // Type ::= %foo
3342 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3343
3344 // If the type hasn't been defined yet, create a forward definition and
3345 // remember where that forward def'n was seen (in case it never is defined).
3346 if (!Entry.first) {
3347 Entry.first = StructType::create(Context, Lex.getStrVal());
3348 Entry.second = Lex.getLoc();
3349 }
3350 Result = Entry.first;
3351 Lex.Lex();
3352 break;
3353 }
3354
3355 case lltok::LocalVarID: {
3356 // Type ::= %4
3357 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3358
3359 // If the type hasn't been defined yet, create a forward definition and
3360 // remember where that forward def'n was seen (in case it never is defined).
3361 if (!Entry.first) {
3362 Entry.first = StructType::create(Context);
3363 Entry.second = Lex.getLoc();
3364 }
3365 Result = Entry.first;
3366 Lex.Lex();
3367 break;
3368 }
3369 }
3370
3371 // parse the type suffixes.
3372 while (true) {
3373 switch (Lex.getKind()) {
3374 // End of type.
3375 default:
3376 if (!AllowVoid && Result->isVoidTy())
3377 return error(TypeLoc, "void type only allowed for function results");
3378 return false;
3379
3380 // Type ::= Type '*'
3381 case lltok::star:
3382 if (Result->isLabelTy())
3383 return tokError("basic block pointers are invalid");
3384 if (Result->isVoidTy())
3385 return tokError("pointers to void are invalid - use i8* instead");
3387 return tokError("pointer to this type is invalid");
3388 Result = PointerType::getUnqual(Context);
3389 Lex.Lex();
3390 break;
3391
3392 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3393 case lltok::kw_addrspace: {
3394 if (Result->isLabelTy())
3395 return tokError("basic block pointers are invalid");
3396 if (Result->isVoidTy())
3397 return tokError("pointers to void are invalid; use i8* instead");
3399 return tokError("pointer to this type is invalid");
3400 unsigned AddrSpace;
3401 if (parseOptionalAddrSpace(AddrSpace) ||
3402 parseToken(lltok::star, "expected '*' in address space"))
3403 return true;
3404
3405 Result = PointerType::get(Context, AddrSpace);
3406 break;
3407 }
3408
3409 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3410 case lltok::lparen:
3411 if (parseFunctionType(Result))
3412 return true;
3413 break;
3414 }
3415 }
3416}
3417
3418/// parseParameterList
3419/// ::= '(' ')'
3420/// ::= '(' Arg (',' Arg)* ')'
3421/// Arg
3422/// ::= Type OptionalAttributes Value OptionalAttributes
3423bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3424 PerFunctionState &PFS, bool IsMustTailCall,
3425 bool InVarArgsFunc) {
3426 if (parseToken(lltok::lparen, "expected '(' in call"))
3427 return true;
3428
3429 while (Lex.getKind() != lltok::rparen) {
3430 // If this isn't the first argument, we need a comma.
3431 if (!ArgList.empty() &&
3432 parseToken(lltok::comma, "expected ',' in argument list"))
3433 return true;
3434
3435 // parse an ellipsis if this is a musttail call in a variadic function.
3436 if (Lex.getKind() == lltok::dotdotdot) {
3437 const char *Msg = "unexpected ellipsis in argument list for ";
3438 if (!IsMustTailCall)
3439 return tokError(Twine(Msg) + "non-musttail call");
3440 if (!InVarArgsFunc)
3441 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3442 Lex.Lex(); // Lex the '...', it is purely for readability.
3443 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3444 }
3445
3446 // parse the argument.
3447 LocTy ArgLoc;
3448 Type *ArgTy = nullptr;
3449 Value *V;
3450 if (parseType(ArgTy, ArgLoc))
3451 return true;
3453 return error(ArgLoc, "invalid type for function argument");
3454
3455 AttrBuilder ArgAttrs(M->getContext());
3456
3457 if (ArgTy->isMetadataTy()) {
3458 if (parseMetadataAsValue(V, PFS))
3459 return true;
3460 } else {
3461 // Otherwise, handle normal operands.
3462 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3463 return true;
3464 }
3465 ArgList.push_back(ParamInfo(
3466 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3467 }
3468
3469 if (IsMustTailCall && InVarArgsFunc)
3470 return tokError("expected '...' at end of argument list for musttail call "
3471 "in varargs function");
3472
3473 Lex.Lex(); // Lex the ')'.
3474 return false;
3475}
3476
3477/// parseRequiredTypeAttr
3478/// ::= attrname(<ty>)
3479bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3480 Attribute::AttrKind AttrKind) {
3481 Type *Ty = nullptr;
3482 if (!EatIfPresent(AttrToken))
3483 return true;
3484 if (!EatIfPresent(lltok::lparen))
3485 return error(Lex.getLoc(), "expected '('");
3486 if (parseType(Ty))
3487 return true;
3488 if (!EatIfPresent(lltok::rparen))
3489 return error(Lex.getLoc(), "expected ')'");
3490
3491 B.addTypeAttr(AttrKind, Ty);
3492 return false;
3493}
3494
3495/// parseRangeAttr
3496/// ::= range(<ty> <n>,<n>)
3497bool LLParser::parseRangeAttr(AttrBuilder &B) {
3498 Lex.Lex();
3499
3500 APInt Lower;
3501 APInt Upper;
3502 Type *Ty = nullptr;
3503 LocTy TyLoc;
3504
3505 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3506 if (Lex.getKind() != lltok::APSInt)
3507 return tokError("expected integer");
3508 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3509 return tokError(
3510 "integer is too large for the bit width of specified type");
3511 Val = Lex.getAPSIntVal().extend(BitWidth);
3512 Lex.Lex();
3513 return false;
3514 };
3515
3516 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3517 return true;
3518 if (!Ty->isIntegerTy())
3519 return error(TyLoc, "the range must have integer type!");
3520
3521 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3522
3523 if (ParseAPSInt(BitWidth, Lower) ||
3524 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3525 return true;
3526 if (Lower == Upper && !Lower.isZero())
3527 return tokError("the range represent the empty set but limits aren't 0!");
3528
3529 if (parseToken(lltok::rparen, "expected ')'"))
3530 return true;
3531
3532 B.addRangeAttr(ConstantRange(Lower, Upper));
3533 return false;
3534}
3535
3536/// parseInitializesAttr
3537/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3538bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3539 Lex.Lex();
3540
3541 auto ParseAPSInt = [&](APInt &Val) {
3542 if (Lex.getKind() != lltok::APSInt)
3543 return tokError("expected integer");
3544 Val = Lex.getAPSIntVal().extend(64);
3545 Lex.Lex();
3546 return false;
3547 };
3548
3549 if (parseToken(lltok::lparen, "expected '('"))
3550 return true;
3551
3553 // Parse each constant range.
3554 do {
3555 APInt Lower, Upper;
3556 if (parseToken(lltok::lparen, "expected '('"))
3557 return true;
3558
3559 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3560 ParseAPSInt(Upper))
3561 return true;
3562
3563 if (Lower == Upper)
3564 return tokError("the range should not represent the full or empty set!");
3565
3566 if (parseToken(lltok::rparen, "expected ')'"))
3567 return true;
3568
3569 RangeList.push_back(ConstantRange(Lower, Upper));
3570 } while (EatIfPresent(lltok::comma));
3571
3572 if (parseToken(lltok::rparen, "expected ')'"))
3573 return true;
3574
3575 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3576 if (!CRLOrNull.has_value())
3577 return tokError("Invalid (unordered or overlapping) range list");
3578 B.addInitializesAttr(*CRLOrNull);
3579 return false;
3580}
3581
3582bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3584 std::optional<CaptureComponents> Ret;
3585
3586 // We use syntax like captures(ret: address, provenance), so the colon
3587 // should not be interpreted as a label terminator.
3588 Lex.setIgnoreColonInIdentifiers(true);
3589 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
3590
3591 Lex.Lex();
3592 if (parseToken(lltok::lparen, "expected '('"))
3593 return true;
3594
3595 CaptureComponents *Current = &Other;
3596 bool SeenComponent = false;
3597 while (true) {
3598 if (EatIfPresent(lltok::kw_ret)) {
3599 if (parseToken(lltok::colon, "expected ':'"))
3600 return true;
3601 if (Ret)
3602 return tokError("duplicate 'ret' location");
3604 Current = &*Ret;
3605 SeenComponent = false;
3606 }
3607
3608 if (EatIfPresent(lltok::kw_none)) {
3609 if (SeenComponent)
3610 return tokError("cannot use 'none' with other component");
3611 *Current = CaptureComponents::None;
3612 } else {
3613 if (SeenComponent && capturesNothing(*Current))
3614 return tokError("cannot use 'none' with other component");
3615
3616 if (EatIfPresent(lltok::kw_address_is_null))
3618 else if (EatIfPresent(lltok::kw_address))
3619 *Current |= CaptureComponents::Address;
3620 else if (EatIfPresent(lltok::kw_provenance))
3622 else if (EatIfPresent(lltok::kw_read_provenance))
3624 else
3625 return tokError("expected one of 'none', 'address', 'address_is_null', "
3626 "'provenance' or 'read_provenance'");
3627 }
3628
3629 SeenComponent = true;
3630 if (EatIfPresent(lltok::rparen))
3631 break;
3632
3633 if (parseToken(lltok::comma, "expected ',' or ')'"))
3634 return true;
3635 }
3636
3637 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3638 return false;
3639}
3640
3641/// parseOptionalOperandBundles
3642/// ::= /*empty*/
3643/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3644///
3645/// OperandBundle
3646/// ::= bundle-tag '(' ')'
3647/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3648///
3649/// bundle-tag ::= String Constant
3650bool LLParser::parseOptionalOperandBundles(
3651 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3652 LocTy BeginLoc = Lex.getLoc();
3653 if (!EatIfPresent(lltok::lsquare))
3654 return false;
3655
3656 while (Lex.getKind() != lltok::rsquare) {
3657 // If this isn't the first operand bundle, we need a comma.
3658 if (!BundleList.empty() &&
3659 parseToken(lltok::comma, "expected ',' in input list"))
3660 return true;
3661
3662 std::string Tag;
3663 if (parseStringConstant(Tag))
3664 return true;
3665
3666 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3667 return true;
3668
3669 std::vector<Value *> Inputs;
3670 while (Lex.getKind() != lltok::rparen) {
3671 // If this isn't the first input, we need a comma.
3672 if (!Inputs.empty() &&
3673 parseToken(lltok::comma, "expected ',' in input list"))
3674 return true;
3675
3676 Type *Ty = nullptr;
3677 Value *Input = nullptr;
3678 if (parseType(Ty))
3679 return true;
3680 if (Ty->isMetadataTy()) {
3681 if (parseMetadataAsValue(Input, PFS))
3682 return true;
3683 } else if (parseValue(Ty, Input, PFS)) {
3684 return true;
3685 }
3686 Inputs.push_back(Input);
3687 }
3688
3689 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3690
3691 Lex.Lex(); // Lex the ')'.
3692 }
3693
3694 if (BundleList.empty())
3695 return error(BeginLoc, "operand bundle set must not be empty");
3696
3697 Lex.Lex(); // Lex the ']'.
3698 return false;
3699}
3700
3701bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3702 unsigned NextID, unsigned ID) {
3703 if (ID < NextID)
3704 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3705 Twine(NextID) + "' or greater");
3706
3707 return false;
3708}
3709
3710/// parseArgumentList - parse the argument list for a function type or function
3711/// prototype.
3712/// ::= '(' ArgTypeListI ')'
3713/// ArgTypeListI
3714/// ::= /*empty*/
3715/// ::= '...'
3716/// ::= ArgTypeList ',' '...'
3717/// ::= ArgType (',' ArgType)*
3718///
3719bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3720 SmallVectorImpl<unsigned> &UnnamedArgNums,
3721 bool &IsVarArg) {
3722 unsigned CurValID = 0;
3723 IsVarArg = false;
3724 assert(Lex.getKind() == lltok::lparen);
3725 Lex.Lex(); // eat the (.
3726
3727 if (Lex.getKind() != lltok::rparen) {
3728 do {
3729 // Handle ... at end of arg list.
3730 if (EatIfPresent(lltok::dotdotdot)) {
3731 IsVarArg = true;
3732 break;
3733 }
3734
3735 // Otherwise must be an argument type.
3736 LocTy TypeLoc = Lex.getLoc();
3737 Type *ArgTy = nullptr;
3738 AttrBuilder Attrs(M->getContext());
3739 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3740 return true;
3741
3742 if (ArgTy->isVoidTy())
3743 return error(TypeLoc, "argument can not have void type");
3744
3745 std::string Name;
3746 FileLoc IdentStart;
3747 FileLoc IdentEnd;
3748 bool Unnamed = false;
3749 if (Lex.getKind() == lltok::LocalVar) {
3750 Name = Lex.getStrVal();
3751 IdentStart = getTokLineColumnPos();
3752 Lex.Lex();
3753 IdentEnd = getPrevTokEndLineColumnPos();
3754 } else {
3755 unsigned ArgID;
3756 if (Lex.getKind() == lltok::LocalVarID) {
3757 ArgID = Lex.getUIntVal();
3758 IdentStart = getTokLineColumnPos();
3759 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3760 return true;
3761 Lex.Lex();
3762 IdentEnd = getPrevTokEndLineColumnPos();
3763 } else {
3764 ArgID = CurValID;
3765 Unnamed = true;
3766 }
3767 UnnamedArgNums.push_back(ArgID);
3768 CurValID = ArgID + 1;
3769 }
3770
3772 return error(TypeLoc, "invalid type for function argument");
3773
3774 ArgList.emplace_back(
3775 TypeLoc, ArgTy,
3776 Unnamed ? std::nullopt
3777 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3778 AttributeSet::get(ArgTy->getContext(), Attrs), std::move(Name));
3779 } while (EatIfPresent(lltok::comma));
3780 }
3781
3782 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3783}
3784
3785/// parseFunctionType
3786/// ::= Type ArgumentList OptionalAttrs
3787bool LLParser::parseFunctionType(Type *&Result) {
3788 assert(Lex.getKind() == lltok::lparen);
3789
3791 return tokError("invalid function return type");
3792
3794 bool IsVarArg;
3795 SmallVector<unsigned> UnnamedArgNums;
3796 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3797 return true;
3798
3799 // Reject names on the arguments lists.
3800 for (const ArgInfo &Arg : ArgList) {
3801 if (!Arg.Name.empty())
3802 return error(Arg.Loc, "argument name invalid in function type");
3803 if (Arg.Attrs.hasAttributes())
3804 return error(Arg.Loc, "argument attributes invalid in function type");
3805 }
3806
3807 SmallVector<Type*, 16> ArgListTy;
3808 for (const ArgInfo &Arg : ArgList)
3809 ArgListTy.push_back(Arg.Ty);
3810
3811 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3812 return false;
3813}
3814
3815/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3816/// other structs.
3817bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3819 if (parseStructBody(Elts))
3820 return true;
3821
3822 Result = StructType::get(Context, Elts, Packed);
3823 return false;
3824}
3825
3826/// parseStructDefinition - parse a struct in a 'type' definition.
3827bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3828 std::pair<Type *, LocTy> &Entry,
3829 Type *&ResultTy) {
3830 // If the type was already defined, diagnose the redefinition.
3831 if (Entry.first && !Entry.second.isValid())
3832 return error(TypeLoc, "redefinition of type");
3833
3834 // If we have opaque, just return without filling in the definition for the
3835 // struct. This counts as a definition as far as the .ll file goes.
3836 if (EatIfPresent(lltok::kw_opaque)) {
3837 // This type is being defined, so clear the location to indicate this.
3838 Entry.second = SMLoc();
3839
3840 // If this type number has never been uttered, create it.
3841 if (!Entry.first)
3842 Entry.first = StructType::create(Context, Name);
3843 ResultTy = Entry.first;
3844 return false;
3845 }
3846
3847 // If the type starts with '<', then it is either a packed struct or a vector.
3848 bool isPacked = EatIfPresent(lltok::less);
3849
3850 // If we don't have a struct, then we have a random type alias, which we
3851 // accept for compatibility with old files. These types are not allowed to be
3852 // forward referenced and not allowed to be recursive.
3853 if (Lex.getKind() != lltok::lbrace) {
3854 if (Entry.first)
3855 return error(TypeLoc, "forward references to non-struct type");
3856
3857 ResultTy = nullptr;
3858 if (isPacked)
3859 return parseArrayVectorType(ResultTy, true);
3860 return parseType(ResultTy);
3861 }
3862
3863 // This type is being defined, so clear the location to indicate this.
3864 Entry.second = SMLoc();
3865
3866 // If this type number has never been uttered, create it.
3867 if (!Entry.first)
3868 Entry.first = StructType::create(Context, Name);
3869
3870 StructType *STy = cast<StructType>(Entry.first);
3871
3873 if (parseStructBody(Body) ||
3874 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3875 return true;
3876
3877 if (auto E = STy->setBodyOrError(Body, isPacked))
3878 return tokError(toString(std::move(E)));
3879
3880 ResultTy = STy;
3881 return false;
3882}
3883
3884/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3885/// StructType
3886/// ::= '{' '}'
3887/// ::= '{' Type (',' Type)* '}'
3888/// ::= '<' '{' '}' '>'
3889/// ::= '<' '{' Type (',' Type)* '}' '>'
3890bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3891 assert(Lex.getKind() == lltok::lbrace);
3892 Lex.Lex(); // Consume the '{'
3893
3894 // Handle the empty struct.
3895 if (EatIfPresent(lltok::rbrace))
3896 return false;
3897
3898 LocTy EltTyLoc = Lex.getLoc();
3899 Type *Ty = nullptr;
3900 if (parseType(Ty))
3901 return true;
3902 Body.push_back(Ty);
3903
3905 return error(EltTyLoc, "invalid element type for struct");
3906
3907 while (EatIfPresent(lltok::comma)) {
3908 EltTyLoc = Lex.getLoc();
3909 if (parseType(Ty))
3910 return true;
3911
3913 return error(EltTyLoc, "invalid element type for struct");
3914
3915 Body.push_back(Ty);
3916 }
3917
3918 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3919}
3920
3921/// parseArrayVectorType - parse an array or vector type, assuming the first
3922/// token has already been consumed.
3923/// Type
3924/// ::= '[' APSINTVAL 'x' Types ']'
3925/// ::= '<' APSINTVAL 'x' Types '>'
3926/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3927bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3928 bool Scalable = false;
3929
3930 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3931 Lex.Lex(); // consume the 'vscale'
3932 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3933 return true;
3934
3935 Scalable = true;
3936 }
3937
3938 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3939 Lex.getAPSIntVal().getBitWidth() > 64)
3940 return tokError("expected number in address space");
3941
3942 LocTy SizeLoc = Lex.getLoc();
3943 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3944 Lex.Lex();
3945
3946 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3947 return true;
3948
3949 LocTy TypeLoc = Lex.getLoc();
3950 Type *EltTy = nullptr;
3951 if (parseType(EltTy))
3952 return true;
3953
3954 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3955 "expected end of sequential type"))
3956 return true;
3957
3958 if (IsVector) {
3959 if (Size == 0)
3960 return error(SizeLoc, "zero element vector is illegal");
3961 if ((unsigned)Size != Size)
3962 return error(SizeLoc, "size too large for vector");
3964 return error(TypeLoc, "invalid vector element type");
3965 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3966 } else {
3968 return error(TypeLoc, "invalid array element type");
3969 Result = ArrayType::get(EltTy, Size);
3970 }
3971 return false;
3972}
3973
3974/// parseTargetExtType - handle target extension type syntax
3975/// TargetExtType
3976/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3977///
3978/// TargetExtTypeParams
3979/// ::= /*empty*/
3980/// ::= ',' Type TargetExtTypeParams
3981///
3982/// TargetExtIntParams
3983/// ::= /*empty*/
3984/// ::= ',' uint32 TargetExtIntParams
3985bool LLParser::parseTargetExtType(Type *&Result) {
3986 Lex.Lex(); // Eat the 'target' keyword.
3987
3988 // Get the mandatory type name.
3989 std::string TypeName;
3990 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3991 parseStringConstant(TypeName))
3992 return true;
3993
3994 // Parse all of the integer and type parameters at the same time; the use of
3995 // SeenInt will allow us to catch cases where type parameters follow integer
3996 // parameters.
3997 SmallVector<Type *> TypeParams;
3998 SmallVector<unsigned> IntParams;
3999 bool SeenInt = false;
4000 while (Lex.getKind() == lltok::comma) {
4001 Lex.Lex(); // Eat the comma.
4002
4003 if (Lex.getKind() == lltok::APSInt) {
4004 SeenInt = true;
4005 unsigned IntVal;
4006 if (parseUInt32(IntVal))
4007 return true;
4008 IntParams.push_back(IntVal);
4009 } else if (SeenInt) {
4010 // The only other kind of parameter we support is type parameters, which
4011 // must precede the integer parameters. This is therefore an error.
4012 return tokError("expected uint32 param");
4013 } else {
4014 Type *TypeParam;
4015 if (parseType(TypeParam, /*AllowVoid=*/true))
4016 return true;
4017 TypeParams.push_back(TypeParam);
4018 }
4019 }
4020
4021 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
4022 return true;
4023
4024 auto TTy =
4025 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
4026 if (auto E = TTy.takeError())
4027 return tokError(toString(std::move(E)));
4028
4029 Result = *TTy;
4030 return false;
4031}
4032
4033//===----------------------------------------------------------------------===//
4034// Function Semantic Analysis.
4035//===----------------------------------------------------------------------===//
4036
4037LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
4038 int functionNumber,
4039 ArrayRef<unsigned> UnnamedArgNums)
4040 : P(p), F(f), FunctionNumber(functionNumber) {
4041
4042 // Insert unnamed arguments into the NumberedVals list.
4043 auto It = UnnamedArgNums.begin();
4044 for (Argument &A : F.args()) {
4045 if (!A.hasName()) {
4046 unsigned ArgNum = *It++;
4047 NumberedVals.add(ArgNum, &A);
4048 }
4049 }
4050}
4051
4052LLParser::PerFunctionState::~PerFunctionState() {
4053 // If there were any forward referenced non-basicblock values, delete them.
4054
4055 for (const auto &P : ForwardRefVals) {
4056 if (isa<BasicBlock>(P.second.first))
4057 continue;
4058 P.second.first->replaceAllUsesWith(
4059 PoisonValue::get(P.second.first->getType()));
4060 P.second.first->deleteValue();
4061 }
4062
4063 for (const auto &P : ForwardRefValIDs) {
4064 if (isa<BasicBlock>(P.second.first))
4065 continue;
4066 P.second.first->replaceAllUsesWith(
4067 PoisonValue::get(P.second.first->getType()));
4068 P.second.first->deleteValue();
4069 }
4070}
4071
4072bool LLParser::PerFunctionState::finishFunction() {
4073 if (!ForwardRefVals.empty())
4074 return P.error(ForwardRefVals.begin()->second.second,
4075 "use of undefined value '%" + ForwardRefVals.begin()->first +
4076 "'");
4077 if (!ForwardRefValIDs.empty())
4078 return P.error(ForwardRefValIDs.begin()->second.second,
4079 "use of undefined value '%" +
4080 Twine(ForwardRefValIDs.begin()->first) + "'");
4081 return false;
4082}
4083
4084/// getVal - Get a value with the specified name or ID, creating a
4085/// forward reference record if needed. This can return null if the value
4086/// exists but does not have the right type.
4087Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
4088 LocTy Loc) {
4089 // Look this name up in the normal function symbol table.
4090 Value *Val = F.getValueSymbolTable()->lookup(Name);
4091
4092 // If this is a forward reference for the value, see if we already created a
4093 // forward ref record.
4094 if (!Val) {
4095 auto I = ForwardRefVals.find(Name);
4096 if (I != ForwardRefVals.end())
4097 Val = I->second.first;
4098 }
4099
4100 // If we have the value in the symbol table or fwd-ref table, return it.
4101 if (Val)
4102 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
4103
4104 // Don't make placeholders with invalid type.
4105 if (!Ty->isFirstClassType()) {
4106 P.error(Loc, "invalid use of a non-first-class type");
4107 return nullptr;
4108 }
4109
4110 // Otherwise, create a new forward reference for this value and remember it.
4111 Value *FwdVal;
4112 if (Ty->isLabelTy()) {
4113 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
4114 } else {
4115 FwdVal = new Argument(Ty, Name);
4116 }
4117 if (FwdVal->getName() != Name) {
4118 P.error(Loc, "name is too long which can result in name collisions, "
4119 "consider making the name shorter or "
4120 "increasing -non-global-value-max-name-size");
4121 return nullptr;
4122 }
4123
4124 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
4125 return FwdVal;
4126}
4127
4128Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
4129 // Look this name up in the normal function symbol table.
4130 Value *Val = NumberedVals.get(ID);
4131
4132 // If this is a forward reference for the value, see if we already created a
4133 // forward ref record.
4134 if (!Val) {
4135 auto I = ForwardRefValIDs.find(ID);
4136 if (I != ForwardRefValIDs.end())
4137 Val = I->second.first;
4138 }
4139
4140 // If we have the value in the symbol table or fwd-ref table, return it.
4141 if (Val)
4142 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
4143
4144 if (!Ty->isFirstClassType()) {
4145 P.error(Loc, "invalid use of a non-first-class type");
4146 return nullptr;
4147 }
4148
4149 // Otherwise, create a new forward reference for this value and remember it.
4150 Value *FwdVal;
4151 if (Ty->isLabelTy()) {
4152 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
4153 } else {
4154 FwdVal = new Argument(Ty);
4155 }
4156
4157 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
4158 return FwdVal;
4159}
4160
4161/// setInstName - After an instruction is parsed and inserted into its
4162/// basic block, this installs its name.
4163bool LLParser::PerFunctionState::setInstName(int NameID,
4164 const std::string &NameStr,
4165 LocTy NameLoc, Instruction *Inst) {
4166 // If this instruction has void type, it cannot have a name or ID specified.
4167 if (Inst->getType()->isVoidTy()) {
4168 if (NameID != -1 || !NameStr.empty())
4169 return P.error(NameLoc, "instructions returning void cannot have a name");
4170 return false;
4171 }
4172
4173 // If this was a numbered instruction, verify that the instruction is the
4174 // expected value and resolve any forward references.
4175 if (NameStr.empty()) {
4176 // If neither a name nor an ID was specified, just use the next ID.
4177 if (NameID == -1)
4178 NameID = NumberedVals.getNext();
4179
4180 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
4181 NameID))
4182 return true;
4183
4184 auto FI = ForwardRefValIDs.find(NameID);
4185 if (FI != ForwardRefValIDs.end()) {
4186 Value *Sentinel = FI->second.first;
4187 if (Sentinel->getType() != Inst->getType())
4188 return P.error(NameLoc, "instruction forward referenced with type '" +
4189 getTypeString(FI->second.first->getType()) +
4190 "'");
4191
4192 Sentinel->replaceAllUsesWith(Inst);
4193 Sentinel->deleteValue();
4194 ForwardRefValIDs.erase(FI);
4195 }
4196
4197 NumberedVals.add(NameID, Inst);
4198 return false;
4199 }
4200
4201 // Otherwise, the instruction had a name. Resolve forward refs and set it.
4202 auto FI = ForwardRefVals.find(NameStr);
4203 if (FI != ForwardRefVals.end()) {
4204 Value *Sentinel = FI->second.first;
4205 if (Sentinel->getType() != Inst->getType())
4206 return P.error(NameLoc, "instruction forward referenced with type '" +
4207 getTypeString(FI->second.first->getType()) +
4208 "'");
4209
4210 Sentinel->replaceAllUsesWith(Inst);
4211 Sentinel->deleteValue();
4212 ForwardRefVals.erase(FI);
4213 }
4214
4215 // Set the name on the instruction.
4216 Inst->setName(NameStr);
4217
4218 if (Inst->getName() != NameStr)
4219 return P.error(NameLoc, "multiple definition of local value named '" +
4220 NameStr + "'");
4221 return false;
4222}
4223
4224/// getBB - Get a basic block with the specified name or ID, creating a
4225/// forward reference record if needed.
4226BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
4227 LocTy Loc) {
4229 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
4230}
4231
4232BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
4234 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
4235}
4236
4237/// defineBB - Define the specified basic block, which is either named or
4238/// unnamed. If there is an error, this returns null otherwise it returns
4239/// the block being defined.
4240BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
4241 int NameID, LocTy Loc) {
4242 BasicBlock *BB;
4243 if (Name.empty()) {
4244 if (NameID != -1) {
4245 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
4246 return nullptr;
4247 } else {
4248 NameID = NumberedVals.getNext();
4249 }
4250 BB = getBB(NameID, Loc);
4251 if (!BB) {
4252 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
4253 return nullptr;
4254 }
4255 } else {
4256 BB = getBB(Name, Loc);
4257 if (!BB) {
4258 P.error(Loc, "unable to create block named '" + Name + "'");
4259 return nullptr;
4260 }
4261 }
4262
4263 // Move the block to the end of the function. Forward ref'd blocks are
4264 // inserted wherever they happen to be referenced.
4265 F.splice(F.end(), &F, BB->getIterator());
4266
4267 // Remove the block from forward ref sets.
4268 if (Name.empty()) {
4269 ForwardRefValIDs.erase(NameID);
4270 NumberedVals.add(NameID, BB);
4271 } else {
4272 // BB forward references are already in the function symbol table.
4273 ForwardRefVals.erase(Name);
4274 }
4275
4276 return BB;
4277}
4278
4279//===----------------------------------------------------------------------===//
4280// Constants.
4281//===----------------------------------------------------------------------===//
4282
4283/// parseValID - parse an abstract value that doesn't necessarily have a
4284/// type implied. For example, if we parse "4" we don't know what integer type
4285/// it has. The value will later be combined with its type and checked for
4286/// basic correctness. PFS is used to convert function-local operands of
4287/// metadata (since metadata operands are not just parsed here but also
4288/// converted to values). PFS can be null when we are not parsing metadata
4289/// values inside a function.
4290bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
4291 ID.Loc = Lex.getLoc();
4292 switch (Lex.getKind()) {
4293 default:
4294 return tokError("expected value token");
4295 case lltok::GlobalID: // @42
4296 ID.UIntVal = Lex.getUIntVal();
4297 ID.Kind = ValID::t_GlobalID;
4298 break;
4299 case lltok::GlobalVar: // @foo
4300 ID.StrVal = Lex.getStrVal();
4301 ID.Kind = ValID::t_GlobalName;
4302 break;
4303 case lltok::LocalVarID: // %42
4304 ID.UIntVal = Lex.getUIntVal();
4305 ID.Kind = ValID::t_LocalID;
4306 break;
4307 case lltok::LocalVar: // %foo
4308 ID.StrVal = Lex.getStrVal();
4309 ID.Kind = ValID::t_LocalName;
4310 break;
4311 case lltok::APSInt:
4312 ID.APSIntVal = Lex.getAPSIntVal();
4313 ID.Kind = ValID::t_APSInt;
4314 break;
4315 case lltok::APFloat: {
4316 ID.APFloatVal = Lex.getAPFloatVal();
4317 ID.Kind = ValID::t_APFloat;
4318 break;
4319 }
4320 case lltok::FloatLiteral: {
4321 if (!ExpectedTy)
4322 return error(ID.Loc, "unexpected floating-point literal");
4323 if (!ExpectedTy->isFloatingPointTy())
4324 return error(ID.Loc, "floating-point constant invalid for type");
4325 ID.APFloatVal = APFloat(ExpectedTy->getFltSemantics());
4326 APFloat::opStatus Except =
4327 cantFail(ID.APFloatVal.convertFromString(
4328 Lex.getStrVal(), RoundingMode::NearestTiesToEven),
4329 "Invalid float strings should be caught by the lexer");
4330 // Forbid overflowing and underflowing literals, but permit inexact
4331 // literals. Underflow is thrown when the result is denormal, so to allow
4332 // denormals, only reject underflowing literals that resulted in a zero.
4333 if (Except & APFloat::opOverflow)
4334 return error(ID.Loc, "floating-point constant overflowed type");
4335 if ((Except & APFloat::opUnderflow) && ID.APFloatVal.isZero())
4336 return error(ID.Loc, "floating-point constant underflowed type");
4337 ID.Kind = ValID::t_APFloat;
4338 break;
4339 }
4341 if (!ExpectedTy)
4342 return error(ID.Loc, "unexpected floating-point literal");
4343 const auto &Semantics = ExpectedTy->getFltSemantics();
4344 const APInt &Bits = Lex.getAPSIntVal();
4345 if (APFloat::getSizeInBits(Semantics) != Bits.getBitWidth())
4346 return error(ID.Loc, "float hex literal has incorrect number of bits");
4347 ID.APFloatVal = APFloat(Semantics, Bits);
4348 ID.Kind = ValID::t_APFloat;
4349 break;
4350 }
4351 case lltok::kw_true:
4352 ID.ConstantVal = ConstantInt::getTrue(Context);
4353 ID.Kind = ValID::t_Constant;
4354 break;
4355 case lltok::kw_false:
4356 ID.ConstantVal = ConstantInt::getFalse(Context);
4357 ID.Kind = ValID::t_Constant;
4358 break;
4359 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
4360 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
4361 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
4362 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
4363 case lltok::kw_none: ID.Kind = ValID::t_None; break;
4364
4365 case lltok::lbrace: {
4366 // ValID ::= '{' ConstVector '}'
4367 Lex.Lex();
4369 if (parseGlobalValueVector(Elts) ||
4370 parseToken(lltok::rbrace, "expected end of struct constant"))
4371 return true;
4372
4373 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4374 ID.UIntVal = Elts.size();
4375 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4376 Elts.size() * sizeof(Elts[0]));
4378 return false;
4379 }
4380 case lltok::less: {
4381 // ValID ::= '<' ConstVector '>' --> Vector.
4382 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
4383 Lex.Lex();
4384 bool isPackedStruct = EatIfPresent(lltok::lbrace);
4385
4387 LocTy FirstEltLoc = Lex.getLoc();
4388 if (parseGlobalValueVector(Elts) ||
4389 (isPackedStruct &&
4390 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4391 parseToken(lltok::greater, "expected end of constant"))
4392 return true;
4393
4394 if (isPackedStruct) {
4395 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4396 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4397 Elts.size() * sizeof(Elts[0]));
4398 ID.UIntVal = Elts.size();
4400 return false;
4401 }
4402
4403 if (Elts.empty())
4404 return error(ID.Loc, "constant vector must not be empty");
4405
4406 if (!Elts[0]->getType()->isIntegerTy() && !Elts[0]->getType()->isByteTy() &&
4407 !Elts[0]->getType()->isFloatingPointTy() &&
4408 !Elts[0]->getType()->isPointerTy())
4409 return error(
4410 FirstEltLoc,
4411 "vector elements must have integer, byte, pointer or floating point "
4412 "type");
4413
4414 // Verify that all the vector elements have the same type.
4415 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4416 if (Elts[i]->getType() != Elts[0]->getType())
4417 return error(FirstEltLoc, "vector element #" + Twine(i) +
4418 " is not of type '" +
4419 getTypeString(Elts[0]->getType()));
4420
4421 ID.ConstantVal = ConstantVector::get(Elts);
4422 ID.Kind = ValID::t_Constant;
4423 return false;
4424 }
4425 case lltok::lsquare: { // Array Constant
4426 Lex.Lex();
4428 LocTy FirstEltLoc = Lex.getLoc();
4429 if (parseGlobalValueVector(Elts) ||
4430 parseToken(lltok::rsquare, "expected end of array constant"))
4431 return true;
4432
4433 // Handle empty element.
4434 if (Elts.empty()) {
4435 // Use undef instead of an array because it's inconvenient to determine
4436 // the element type at this point, there being no elements to examine.
4437 ID.Kind = ValID::t_EmptyArray;
4438 return false;
4439 }
4440
4441 if (!Elts[0]->getType()->isFirstClassType())
4442 return error(FirstEltLoc, "invalid array element type: " +
4443 getTypeString(Elts[0]->getType()));
4444
4445 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4446
4447 // Verify all elements are correct type!
4448 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4449 if (Elts[i]->getType() != Elts[0]->getType())
4450 return error(FirstEltLoc, "array element #" + Twine(i) +
4451 " is not of type '" +
4452 getTypeString(Elts[0]->getType()));
4453 }
4454
4455 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4456 ID.Kind = ValID::t_Constant;
4457 return false;
4458 }
4459 case lltok::kw_c: { // c "foo"
4460 Lex.Lex();
4461 ArrayType *ATy = cast<ArrayType>(ExpectedTy);
4462 ID.ConstantVal = ConstantDataArray::getString(
4463 Context, Lex.getStrVal(), false, ATy->getElementType()->isByteTy());
4464 if (parseToken(lltok::StringConstant, "expected string"))
4465 return true;
4466 ID.Kind = ValID::t_Constant;
4467 return false;
4468 }
4469 case lltok::kw_asm: {
4470 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4471 // STRINGCONSTANT
4472 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4473 Lex.Lex();
4474 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4475 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4476 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4477 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4478 parseStringConstant(ID.StrVal) ||
4479 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4480 parseToken(lltok::StringConstant, "expected constraint string"))
4481 return true;
4482 ID.StrVal2 = Lex.getStrVal();
4483 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4484 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4485 ID.Kind = ValID::t_InlineAsm;
4486 return false;
4487 }
4488
4490 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4491 Lex.Lex();
4492
4493 ValID Fn, Label;
4494
4495 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4496 parseValID(Fn, PFS) ||
4497 parseToken(lltok::comma,
4498 "expected comma in block address expression") ||
4499 parseValID(Label, PFS) ||
4500 parseToken(lltok::rparen, "expected ')' in block address expression"))
4501 return true;
4502
4504 return error(Fn.Loc, "expected function name in blockaddress");
4505 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4506 return error(Label.Loc, "expected basic block name in blockaddress");
4507
4508 // Try to find the function (but skip it if it's forward-referenced).
4509 GlobalValue *GV = nullptr;
4510 if (Fn.Kind == ValID::t_GlobalID) {
4511 GV = NumberedVals.get(Fn.UIntVal);
4512 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4513 GV = M->getNamedValue(Fn.StrVal);
4514 }
4515 Function *F = nullptr;
4516 if (GV) {
4517 // Confirm that it's actually a function with a definition.
4518 if (!isa<Function>(GV))
4519 return error(Fn.Loc, "expected function name in blockaddress");
4520 F = cast<Function>(GV);
4521 if (F->isDeclaration())
4522 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4523 }
4524
4525 if (!F) {
4526 // Make a global variable as a placeholder for this reference.
4527 GlobalValue *&FwdRef =
4528 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4529 if (!FwdRef) {
4530 unsigned FwdDeclAS;
4531 if (ExpectedTy) {
4532 // If we know the type that the blockaddress is being assigned to,
4533 // we can use the address space of that type.
4534 if (!ExpectedTy->isPointerTy())
4535 return error(ID.Loc,
4536 "type of blockaddress must be a pointer and not '" +
4537 getTypeString(ExpectedTy) + "'");
4538 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4539 } else if (PFS) {
4540 // Otherwise, we default the address space of the current function.
4541 FwdDeclAS = PFS->getFunction().getAddressSpace();
4542 } else {
4543 llvm_unreachable("Unknown address space for blockaddress");
4544 }
4545 FwdRef = new GlobalVariable(
4546 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4547 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4548 }
4549
4550 ID.ConstantVal = FwdRef;
4551 ID.Kind = ValID::t_Constant;
4552 return false;
4553 }
4554
4555 // We found the function; now find the basic block. Don't use PFS, since we
4556 // might be inside a constant expression.
4557 BasicBlock *BB;
4558 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4559 if (Label.Kind == ValID::t_LocalID)
4560 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4561 else
4562 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4563 if (!BB)
4564 return error(Label.Loc, "referenced value is not a basic block");
4565 } else {
4566 if (Label.Kind == ValID::t_LocalID)
4567 return error(Label.Loc, "cannot take address of numeric label after "
4568 "the function is defined");
4570 F->getValueSymbolTable()->lookup(Label.StrVal));
4571 if (!BB)
4572 return error(Label.Loc, "referenced value is not a basic block");
4573 }
4574
4575 ID.ConstantVal = BlockAddress::get(F, BB);
4576 ID.Kind = ValID::t_Constant;
4577 return false;
4578 }
4579
4581 // ValID ::= 'dso_local_equivalent' @foo
4582 Lex.Lex();
4583
4584 ValID Fn;
4585
4586 if (parseValID(Fn, PFS))
4587 return true;
4588
4590 return error(Fn.Loc,
4591 "expected global value name in dso_local_equivalent");
4592
4593 // Try to find the function (but skip it if it's forward-referenced).
4594 GlobalValue *GV = nullptr;
4595 if (Fn.Kind == ValID::t_GlobalID) {
4596 GV = NumberedVals.get(Fn.UIntVal);
4597 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4598 GV = M->getNamedValue(Fn.StrVal);
4599 }
4600
4601 if (!GV) {
4602 // Make a placeholder global variable as a placeholder for this reference.
4603 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4604 ? ForwardRefDSOLocalEquivalentIDs
4605 : ForwardRefDSOLocalEquivalentNames;
4606 GlobalValue *&FwdRef = FwdRefMap[Fn];
4607 if (!FwdRef) {
4608 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4609 GlobalValue::InternalLinkage, nullptr, "",
4611 }
4612
4613 ID.ConstantVal = FwdRef;
4614 ID.Kind = ValID::t_Constant;
4615 return false;
4616 }
4617
4618 if (!GV->getValueType()->isFunctionTy())
4619 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4620 "in dso_local_equivalent");
4621
4622 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4623 ID.Kind = ValID::t_Constant;
4624 return false;
4625 }
4626
4627 case lltok::kw_no_cfi: {
4628 // ValID ::= 'no_cfi' @foo
4629 Lex.Lex();
4630
4631 if (parseValID(ID, PFS))
4632 return true;
4633
4634 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4635 return error(ID.Loc, "expected global value name in no_cfi");
4636
4637 ID.NoCFI = true;
4638 return false;
4639 }
4640 case lltok::kw_ptrauth: {
4641 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4642 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4643 // )? )? ')'
4644 Lex.Lex();
4645
4646 Constant *Ptr, *Key;
4647 Constant *Disc = nullptr, *AddrDisc = nullptr,
4648 *DeactivationSymbol = nullptr;
4649
4650 if (parseToken(lltok::lparen,
4651 "expected '(' in constant ptrauth expression") ||
4652 parseGlobalTypeAndValue(Ptr) ||
4653 parseToken(lltok::comma,
4654 "expected comma in constant ptrauth expression") ||
4655 parseGlobalTypeAndValue(Key))
4656 return true;
4657 // If present, parse the optional disc/addrdisc/ds.
4658 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(Disc))
4659 return true;
4660 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4661 return true;
4662 if (EatIfPresent(lltok::comma) &&
4663 parseGlobalTypeAndValue(DeactivationSymbol))
4664 return true;
4665 if (parseToken(lltok::rparen,
4666 "expected ')' in constant ptrauth expression"))
4667 return true;
4668
4669 if (!Ptr->getType()->isPointerTy())
4670 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4671
4672 auto *KeyC = dyn_cast<ConstantInt>(Key);
4673 if (!KeyC || KeyC->getBitWidth() != 32)
4674 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4675
4676 ConstantInt *DiscC = nullptr;
4677 if (Disc) {
4678 DiscC = dyn_cast<ConstantInt>(Disc);
4679 if (!DiscC || DiscC->getBitWidth() != 64)
4680 return error(
4681 ID.Loc,
4682 "constant ptrauth integer discriminator must be i64 constant");
4683 } else {
4684 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4685 }
4686
4687 if (AddrDisc) {
4688 if (!AddrDisc->getType()->isPointerTy())
4689 return error(
4690 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4691 } else {
4692 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4693 }
4694
4695 if (!DeactivationSymbol)
4696 DeactivationSymbol =
4698 if (!DeactivationSymbol->getType()->isPointerTy())
4699 return error(ID.Loc,
4700 "constant ptrauth deactivation symbol must be a pointer");
4701
4702 ID.ConstantVal =
4703 ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc, DeactivationSymbol);
4704 ID.Kind = ValID::t_Constant;
4705 return false;
4706 }
4707
4708 case lltok::kw_trunc:
4709 case lltok::kw_bitcast:
4711 case lltok::kw_inttoptr:
4713 case lltok::kw_ptrtoint: {
4714 unsigned Opc = Lex.getUIntVal();
4715 Type *DestTy = nullptr;
4716 Constant *SrcVal;
4717 Lex.Lex();
4718 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4719 parseGlobalTypeAndValue(SrcVal) ||
4720 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4721 parseType(DestTy) ||
4722 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4723 return true;
4724 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4725 return error(ID.Loc, "invalid cast opcode for cast from '" +
4726 getTypeString(SrcVal->getType()) + "' to '" +
4727 getTypeString(DestTy) + "'");
4729 SrcVal, DestTy);
4730 ID.Kind = ValID::t_Constant;
4731 return false;
4732 }
4734 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4736 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4737 case lltok::kw_udiv:
4738 return error(ID.Loc, "udiv constexprs are no longer supported");
4739 case lltok::kw_sdiv:
4740 return error(ID.Loc, "sdiv constexprs are no longer supported");
4741 case lltok::kw_urem:
4742 return error(ID.Loc, "urem constexprs are no longer supported");
4743 case lltok::kw_srem:
4744 return error(ID.Loc, "srem constexprs are no longer supported");
4745 case lltok::kw_fadd:
4746 return error(ID.Loc, "fadd constexprs are no longer supported");
4747 case lltok::kw_fsub:
4748 return error(ID.Loc, "fsub constexprs are no longer supported");
4749 case lltok::kw_fmul:
4750 return error(ID.Loc, "fmul constexprs are no longer supported");
4751 case lltok::kw_fdiv:
4752 return error(ID.Loc, "fdiv constexprs are no longer supported");
4753 case lltok::kw_frem:
4754 return error(ID.Loc, "frem constexprs are no longer supported");
4755 case lltok::kw_and:
4756 return error(ID.Loc, "and constexprs are no longer supported");
4757 case lltok::kw_or:
4758 return error(ID.Loc, "or constexprs are no longer supported");
4759 case lltok::kw_lshr:
4760 return error(ID.Loc, "lshr constexprs are no longer supported");
4761 case lltok::kw_ashr:
4762 return error(ID.Loc, "ashr constexprs are no longer supported");
4763 case lltok::kw_shl:
4764 return error(ID.Loc, "shl constexprs are no longer supported");
4765 case lltok::kw_mul:
4766 return error(ID.Loc, "mul constexprs are no longer supported");
4767 case lltok::kw_fneg:
4768 return error(ID.Loc, "fneg constexprs are no longer supported");
4769 case lltok::kw_select:
4770 return error(ID.Loc, "select constexprs are no longer supported");
4771 case lltok::kw_zext:
4772 return error(ID.Loc, "zext constexprs are no longer supported");
4773 case lltok::kw_sext:
4774 return error(ID.Loc, "sext constexprs are no longer supported");
4775 case lltok::kw_fptrunc:
4776 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4777 case lltok::kw_fpext:
4778 return error(ID.Loc, "fpext constexprs are no longer supported");
4779 case lltok::kw_uitofp:
4780 return error(ID.Loc, "uitofp constexprs are no longer supported");
4781 case lltok::kw_sitofp:
4782 return error(ID.Loc, "sitofp constexprs are no longer supported");
4783 case lltok::kw_fptoui:
4784 return error(ID.Loc, "fptoui constexprs are no longer supported");
4785 case lltok::kw_fptosi:
4786 return error(ID.Loc, "fptosi constexprs are no longer supported");
4787 case lltok::kw_icmp:
4788 return error(ID.Loc, "icmp constexprs are no longer supported");
4789 case lltok::kw_fcmp:
4790 return error(ID.Loc, "fcmp constexprs are no longer supported");
4791
4792 // Binary Operators.
4793 case lltok::kw_add:
4794 case lltok::kw_sub:
4795 case lltok::kw_xor: {
4796 bool NUW = false;
4797 bool NSW = false;
4798 unsigned Opc = Lex.getUIntVal();
4799 Constant *Val0, *Val1;
4800 Lex.Lex();
4801 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4802 Opc == Instruction::Mul) {
4803 if (EatIfPresent(lltok::kw_nuw))
4804 NUW = true;
4805 if (EatIfPresent(lltok::kw_nsw)) {
4806 NSW = true;
4807 if (EatIfPresent(lltok::kw_nuw))
4808 NUW = true;
4809 }
4810 }
4811 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4812 parseGlobalTypeAndValue(Val0) ||
4813 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4814 parseGlobalTypeAndValue(Val1) ||
4815 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4816 return true;
4817 if (Val0->getType() != Val1->getType())
4818 return error(ID.Loc, "operands of constexpr must have same type");
4819 // Check that the type is valid for the operator.
4820 if (!Val0->getType()->isIntOrIntVectorTy())
4821 return error(ID.Loc,
4822 "constexpr requires integer or integer vector operands");
4823 unsigned Flags = 0;
4826 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4827 ID.Kind = ValID::t_Constant;
4828 return false;
4829 }
4830
4831 case lltok::kw_splat: {
4832 Lex.Lex();
4833 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4834 return true;
4835 Constant *C;
4836 if (parseGlobalTypeAndValue(C))
4837 return true;
4838 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4839 return true;
4840
4841 ID.ConstantVal = C;
4843 return false;
4844 }
4845
4850 unsigned Opc = Lex.getUIntVal();
4852 GEPNoWrapFlags NW;
4853 bool HasInRange = false;
4854 APSInt InRangeStart;
4855 APSInt InRangeEnd;
4856 Type *Ty;
4857 Lex.Lex();
4858
4859 if (Opc == Instruction::GetElementPtr) {
4860 while (true) {
4861 if (EatIfPresent(lltok::kw_inbounds))
4863 else if (EatIfPresent(lltok::kw_nusw))
4865 else if (EatIfPresent(lltok::kw_nuw))
4867 else
4868 break;
4869 }
4870
4871 if (EatIfPresent(lltok::kw_inrange)) {
4872 if (parseToken(lltok::lparen, "expected '('"))
4873 return true;
4874 if (Lex.getKind() != lltok::APSInt)
4875 return tokError("expected integer");
4876 InRangeStart = Lex.getAPSIntVal();
4877 Lex.Lex();
4878 if (parseToken(lltok::comma, "expected ','"))
4879 return true;
4880 if (Lex.getKind() != lltok::APSInt)
4881 return tokError("expected integer");
4882 InRangeEnd = Lex.getAPSIntVal();
4883 Lex.Lex();
4884 if (parseToken(lltok::rparen, "expected ')'"))
4885 return true;
4886 HasInRange = true;
4887 }
4888 }
4889
4890 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4891 return true;
4892
4893 if (Opc == Instruction::GetElementPtr) {
4894 if (parseType(Ty) ||
4895 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4896 return true;
4897 }
4898
4899 if (parseGlobalValueVector(Elts) ||
4900 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4901 return true;
4902
4903 if (Opc == Instruction::GetElementPtr) {
4904 if (Elts.size() == 0 ||
4905 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4906 return error(ID.Loc, "base of getelementptr must be a pointer");
4907
4908 Type *BaseType = Elts[0]->getType();
4909 std::optional<ConstantRange> InRange;
4910 if (HasInRange) {
4911 unsigned IndexWidth =
4912 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4913 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4914 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4915 if (InRangeStart.sge(InRangeEnd))
4916 return error(ID.Loc, "expected end to be larger than start");
4917 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4918 }
4919
4920 unsigned GEPWidth =
4921 BaseType->isVectorTy()
4922 ? cast<FixedVectorType>(BaseType)->getNumElements()
4923 : 0;
4924
4925 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4926 for (Constant *Val : Indices) {
4927 Type *ValTy = Val->getType();
4928 if (!ValTy->isIntOrIntVectorTy())
4929 return error(ID.Loc, "getelementptr index must be an integer");
4930 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4931 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4932 if (GEPWidth && (ValNumEl != GEPWidth))
4933 return error(
4934 ID.Loc,
4935 "getelementptr vector index has a wrong number of elements");
4936 // GEPWidth may have been unknown because the base is a scalar,
4937 // but it is known now.
4938 GEPWidth = ValNumEl;
4939 }
4940 }
4941
4942 if (!Indices.empty() && !Ty->isSized())
4943 return error(ID.Loc, "base element of getelementptr must be sized");
4944
4946 return error(ID.Loc, "invalid base element for constant getelementptr");
4947
4948 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4949 return error(ID.Loc, "invalid getelementptr indices");
4950
4952 ID.ConstantVal =
4953 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4955 } else if (Opc == Instruction::ShuffleVector) {
4956 if (Elts.size() != 3)
4957 return error(ID.Loc, "expected three operands to shufflevector");
4958 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4959 return error(ID.Loc, "invalid operands to shufflevector");
4960 SmallVector<int, 16> Mask;
4962 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4963 } else if (Opc == Instruction::ExtractElement) {
4964 if (Elts.size() != 2)
4965 return error(ID.Loc, "expected two operands to extractelement");
4966 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4967 return error(ID.Loc, "invalid extractelement operands");
4968 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4969 } else {
4970 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4971 if (Elts.size() != 3)
4972 return error(ID.Loc, "expected three operands to insertelement");
4973 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4974 return error(ID.Loc, "invalid insertelement operands");
4975 ID.ConstantVal =
4976 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4977 }
4978
4979 ID.Kind = ValID::t_Constant;
4980 return false;
4981 }
4982 }
4983
4984 Lex.Lex();
4985 return false;
4986}
4987
4988/// parseGlobalValue - parse a global value with the specified type.
4989bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4990 C = nullptr;
4991 ValID ID;
4992 Value *V = nullptr;
4993 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4994 convertValIDToValue(Ty, ID, V, nullptr);
4995 if (V && !(C = dyn_cast<Constant>(V)))
4996 return error(ID.Loc, "global values must be constants");
4997 return Parsed;
4998}
4999
5000bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
5001 Type *Ty = nullptr;
5002 return parseType(Ty) || parseGlobalValue(Ty, V);
5003}
5004
5005bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
5006 C = nullptr;
5007
5008 LocTy KwLoc = Lex.getLoc();
5009 if (!EatIfPresent(lltok::kw_comdat))
5010 return false;
5011
5012 if (EatIfPresent(lltok::lparen)) {
5013 if (Lex.getKind() != lltok::ComdatVar)
5014 return tokError("expected comdat variable");
5015 C = getComdat(Lex.getStrVal(), Lex.getLoc());
5016 Lex.Lex();
5017 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
5018 return true;
5019 } else {
5020 if (GlobalName.empty())
5021 return tokError("comdat cannot be unnamed");
5022 C = getComdat(std::string(GlobalName), KwLoc);
5023 }
5024
5025 return false;
5026}
5027
5028/// parseGlobalValueVector
5029/// ::= /*empty*/
5030/// ::= TypeAndValue (',' TypeAndValue)*
5031bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
5032 // Empty list.
5033 if (Lex.getKind() == lltok::rbrace ||
5034 Lex.getKind() == lltok::rsquare ||
5035 Lex.getKind() == lltok::greater ||
5036 Lex.getKind() == lltok::rparen)
5037 return false;
5038
5039 do {
5040 // Let the caller deal with inrange.
5041 if (Lex.getKind() == lltok::kw_inrange)
5042 return false;
5043
5044 Constant *C;
5045 if (parseGlobalTypeAndValue(C))
5046 return true;
5047 Elts.push_back(C);
5048 } while (EatIfPresent(lltok::comma));
5049
5050 return false;
5051}
5052
5053bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
5055 if (parseMDNodeVector(Elts))
5056 return true;
5057
5058 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
5059 return false;
5060}
5061
5062/// MDNode:
5063/// ::= !{ ... }
5064/// ::= !7
5065/// ::= !DILocation(...)
5066bool LLParser::parseMDNode(MDNode *&N) {
5067 if (Lex.getKind() == lltok::MetadataVar)
5068 return parseSpecializedMDNode(N);
5069
5070 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
5071}
5072
5073bool LLParser::parseMDNodeTail(MDNode *&N) {
5074 // !{ ... }
5075 if (Lex.getKind() == lltok::lbrace)
5076 return parseMDTuple(N);
5077
5078 // !42
5079 return parseMDNodeID(N);
5080}
5081
5082namespace {
5083
5084/// Structure to represent an optional metadata field.
5085template <class FieldTy> struct MDFieldImpl {
5086 typedef MDFieldImpl ImplTy;
5087 FieldTy Val;
5088 bool Seen;
5089
5090 void assign(FieldTy Val) {
5091 Seen = true;
5092 this->Val = std::move(Val);
5093 }
5094
5095 explicit MDFieldImpl(FieldTy Default)
5096 : Val(std::move(Default)), Seen(false) {}
5097};
5098
5099/// Structure to represent an optional metadata field that
5100/// can be of either type (A or B) and encapsulates the
5101/// MD<typeofA>Field and MD<typeofB>Field structs, so not
5102/// to reimplement the specifics for representing each Field.
5103template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
5104 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
5105 FieldTypeA A;
5106 FieldTypeB B;
5107 bool Seen;
5108
5109 enum {
5110 IsInvalid = 0,
5111 IsTypeA = 1,
5112 IsTypeB = 2
5113 } WhatIs;
5114
5115 void assign(FieldTypeA A) {
5116 Seen = true;
5117 this->A = std::move(A);
5118 WhatIs = IsTypeA;
5119 }
5120
5121 void assign(FieldTypeB B) {
5122 Seen = true;
5123 this->B = std::move(B);
5124 WhatIs = IsTypeB;
5125 }
5126
5127 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5128 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
5129 WhatIs(IsInvalid) {}
5130};
5131
5132struct MDUnsignedField : public MDFieldImpl<uint64_t> {
5133 uint64_t Max;
5134
5135 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
5136 : ImplTy(Default), Max(Max) {}
5137};
5138
5139struct LineField : public MDUnsignedField {
5140 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5141};
5142
5143struct ColumnField : public MDUnsignedField {
5144 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5145};
5146
5147struct DwarfTagField : public MDUnsignedField {
5148 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
5149 DwarfTagField(dwarf::Tag DefaultTag)
5150 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
5151};
5152
5153struct DwarfMacinfoTypeField : public MDUnsignedField {
5154 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
5155 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
5156 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
5157};
5158
5159struct DwarfAttEncodingField : public MDUnsignedField {
5160 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
5161};
5162
5163struct DwarfVirtualityField : public MDUnsignedField {
5164 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
5165};
5166
5167struct DwarfLangField : public MDUnsignedField {
5168 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
5169};
5170
5171struct DwarfSourceLangNameField : public MDUnsignedField {
5172 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5173};
5174
5175struct DwarfLangDialectField : public MDUnsignedField {
5176 DwarfLangDialectField()
5177 : MDUnsignedField(0, dwarf::DW_LLVM_LANG_DIALECT_max) {}
5178};
5179
5180struct DwarfCCField : public MDUnsignedField {
5181 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
5182};
5183
5184struct DwarfEnumKindField : public MDUnsignedField {
5185 DwarfEnumKindField()
5186 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
5187 dwarf::DW_APPLE_ENUM_KIND_max) {}
5188};
5189
5190struct EmissionKindField : public MDUnsignedField {
5191 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5192};
5193
5194struct FixedPointKindField : public MDUnsignedField {
5195 FixedPointKindField()
5196 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5197};
5198
5199struct NameTableKindField : public MDUnsignedField {
5200 NameTableKindField()
5201 : MDUnsignedField(
5202 0, (unsigned)
5203 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5204};
5205
5206struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
5207 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5208};
5209
5210struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
5211 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5212};
5213
5214struct MDAPSIntField : public MDFieldImpl<APSInt> {
5215 MDAPSIntField() : ImplTy(APSInt()) {}
5216};
5217
5218struct MDSignedField : public MDFieldImpl<int64_t> {
5219 int64_t Min = INT64_MIN;
5220 int64_t Max = INT64_MAX;
5221
5222 MDSignedField(int64_t Default = 0)
5223 : ImplTy(Default) {}
5224 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
5225 : ImplTy(Default), Min(Min), Max(Max) {}
5226};
5227
5228struct MDBoolField : public MDFieldImpl<bool> {
5229 MDBoolField(bool Default = false) : ImplTy(Default) {}
5230};
5231
5232struct MDField : public MDFieldImpl<Metadata *> {
5233 bool AllowNull;
5234
5235 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5236};
5237
5238// Similar to MDField, but will only accept MDNode arguments (!<num>).
5239struct MDNodeField : public MDFieldImpl<MDNode *> {
5240 bool AllowNull;
5241
5242 MDNodeField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5243};
5244
5245struct MDStringField : public MDFieldImpl<MDString *> {
5246 enum class EmptyIs {
5247 Null, //< Allow empty input string, map to nullptr
5248 Empty, //< Allow empty input string, map to an empty MDString
5249 Error, //< Disallow empty string, map to an error
5250 } EmptyIs;
5251 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
5252 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5253};
5254
5255struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
5256 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
5257};
5258
5259struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
5260 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
5261};
5262
5263struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5264 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
5265 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
5266
5267 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
5268 bool AllowNull = true)
5269 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
5270
5271 bool isMDSignedField() const { return WhatIs == IsTypeA; }
5272 bool isMDField() const { return WhatIs == IsTypeB; }
5273 int64_t getMDSignedValue() const {
5274 assert(isMDSignedField() && "Wrong field type");
5275 return A.Val;
5276 }
5277 Metadata *getMDFieldValue() const {
5278 assert(isMDField() && "Wrong field type");
5279 return B.Val;
5280 }
5281};
5282
5283struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5284 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
5285 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
5286
5287 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
5288 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
5289
5290 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
5291 bool isMDField() const { return WhatIs == IsTypeB; }
5292 uint64_t getMDUnsignedValue() const {
5293 assert(isMDUnsignedField() && "Wrong field type");
5294 return A.Val;
5295 }
5296 Metadata *getMDFieldValue() const {
5297 assert(isMDField() && "Wrong field type");
5298 return B.Val;
5299 }
5300
5301 Metadata *getValueAsMetadata(LLVMContext &Context) const {
5302 if (isMDUnsignedField())
5304 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
5305 if (isMDField())
5306 return getMDFieldValue();
5307 return nullptr;
5308 }
5309};
5310
5311} // end anonymous namespace
5312
5313namespace llvm {
5314
5315template <>
5316bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
5317 if (Lex.getKind() != lltok::APSInt)
5318 return tokError("expected integer");
5319
5320 Result.assign(Lex.getAPSIntVal());
5321 Lex.Lex();
5322 return false;
5323}
5324
5325template <>
5326bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5327 MDUnsignedField &Result) {
5328 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5329 return tokError("expected unsigned integer");
5330
5331 auto &U = Lex.getAPSIntVal();
5332 if (U.ugt(Result.Max))
5333 return tokError("value for '" + Name + "' too large, limit is " +
5334 Twine(Result.Max));
5335 Result.assign(U.getZExtValue());
5336 assert(Result.Val <= Result.Max && "Expected value in range");
5337 Lex.Lex();
5338 return false;
5339}
5340
5341template <>
5342bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
5343 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5344}
5345template <>
5346bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
5347 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5348}
5349
5350template <>
5351bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
5352 if (Lex.getKind() == lltok::APSInt)
5353 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5354
5355 if (Lex.getKind() != lltok::DwarfTag)
5356 return tokError("expected DWARF tag");
5357
5358 unsigned Tag = dwarf::getTag(Lex.getStrVal());
5360 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
5361 assert(Tag <= Result.Max && "Expected valid DWARF tag");
5362
5363 Result.assign(Tag);
5364 Lex.Lex();
5365 return false;
5366}
5367
5368template <>
5369bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5370 DwarfMacinfoTypeField &Result) {
5371 if (Lex.getKind() == lltok::APSInt)
5372 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5373
5374 if (Lex.getKind() != lltok::DwarfMacinfo)
5375 return tokError("expected DWARF macinfo type");
5376
5377 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
5378 if (Macinfo == dwarf::DW_MACINFO_invalid)
5379 return tokError("invalid DWARF macinfo type" + Twine(" '") +
5380 Lex.getStrVal() + "'");
5381 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
5382
5383 Result.assign(Macinfo);
5384 Lex.Lex();
5385 return false;
5386}
5387
5388template <>
5389bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5390 DwarfVirtualityField &Result) {
5391 if (Lex.getKind() == lltok::APSInt)
5392 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5393
5394 if (Lex.getKind() != lltok::DwarfVirtuality)
5395 return tokError("expected DWARF virtuality code");
5396
5397 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
5398 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5399 return tokError("invalid DWARF virtuality code" + Twine(" '") +
5400 Lex.getStrVal() + "'");
5401 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5402 Result.assign(Virtuality);
5403 Lex.Lex();
5404 return false;
5405}
5406
5407template <>
5408bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5409 DwarfEnumKindField &Result) {
5410 if (Lex.getKind() == lltok::APSInt)
5411 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5412
5413 if (Lex.getKind() != lltok::DwarfEnumKind)
5414 return tokError("expected DWARF enum kind code");
5415
5416 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5417 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5418 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5419 Lex.getStrVal() + "'");
5420 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5421 Result.assign(EnumKind);
5422 Lex.Lex();
5423 return false;
5424}
5425
5426template <>
5427bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5428 if (Lex.getKind() == lltok::APSInt)
5429 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5430
5431 if (Lex.getKind() != lltok::DwarfLang)
5432 return tokError("expected DWARF language");
5433
5434 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5435 if (!Lang)
5436 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5437 "'");
5438 assert(Lang <= Result.Max && "Expected valid DWARF language");
5439 Result.assign(Lang);
5440 Lex.Lex();
5441 return false;
5442}
5443
5444template <>
5445bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5446 DwarfSourceLangNameField &Result) {
5447 if (Lex.getKind() == lltok::APSInt)
5448 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5449
5450 if (Lex.getKind() != lltok::DwarfSourceLangName)
5451 return tokError("expected DWARF source language name");
5452
5453 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5454 if (!Lang)
5455 return tokError("invalid DWARF source language name" + Twine(" '") +
5456 Lex.getStrVal() + "'");
5457 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5458 Result.assign(Lang);
5459 Lex.Lex();
5460 return false;
5461}
5462
5463template <>
5464bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5465 DwarfLangDialectField &Result) {
5466 // Specifying the dialect field requires a recognized dialect: simt or
5467 // tile (numerically 1 or 2). Omitting the field is the only way to
5468 // express "no dialect specified".
5469 if (Lex.getKind() == lltok::APSInt) {
5470 if (Lex.getAPSIntVal() == 0)
5471 return tokError("value for 'dialect' must be a known DWARF language "
5472 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5473 "DW_LLVM_LANG_DIALECT_tile)");
5474 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5475 }
5476
5477 if (Lex.getKind() != lltok::DwarfLangDialect)
5478 return tokError("expected DWARF language dialect");
5479
5480 StringRef DialectString = Lex.getStrVal();
5481 // getLanguageDialect returns a sentinel above Result.Max for unknown
5482 // spellings; only simt and tile are registered, so any unrecognized
5483 // DW_LLVM_LANG_DIALECT_* token is rejected here.
5484 unsigned Dialect = dwarf::getLanguageDialect(DialectString);
5485 if (Dialect > Result.Max)
5486 return tokError("invalid DWARF language dialect" + Twine(" '") +
5487 DialectString + "'");
5488 Result.assign(Dialect);
5489 Lex.Lex();
5490 return false;
5491}
5492
5493template <>
5494bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5495 if (Lex.getKind() == lltok::APSInt)
5496 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5497
5498 if (Lex.getKind() != lltok::DwarfCC)
5499 return tokError("expected DWARF calling convention");
5500
5501 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5502 if (!CC)
5503 return tokError("invalid DWARF calling convention" + Twine(" '") +
5504 Lex.getStrVal() + "'");
5505 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5506 Result.assign(CC);
5507 Lex.Lex();
5508 return false;
5509}
5510
5511template <>
5512bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5513 EmissionKindField &Result) {
5514 if (Lex.getKind() == lltok::APSInt)
5515 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5516
5517 if (Lex.getKind() != lltok::EmissionKind)
5518 return tokError("expected emission kind");
5519
5520 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5521 if (!Kind)
5522 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5523 "'");
5524 assert(*Kind <= Result.Max && "Expected valid emission kind");
5525 Result.assign(*Kind);
5526 Lex.Lex();
5527 return false;
5528}
5529
5530template <>
5531bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5532 FixedPointKindField &Result) {
5533 if (Lex.getKind() == lltok::APSInt)
5534 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5535
5536 if (Lex.getKind() != lltok::FixedPointKind)
5537 return tokError("expected fixed-point kind");
5538
5539 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5540 if (!Kind)
5541 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5542 "'");
5543 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5544 Result.assign(*Kind);
5545 Lex.Lex();
5546 return false;
5547}
5548
5549template <>
5550bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5551 NameTableKindField &Result) {
5552 if (Lex.getKind() == lltok::APSInt)
5553 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5554
5555 if (Lex.getKind() != lltok::NameTableKind)
5556 return tokError("expected nameTable kind");
5557
5558 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5559 if (!Kind)
5560 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5561 "'");
5562 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5563 Result.assign((unsigned)*Kind);
5564 Lex.Lex();
5565 return false;
5566}
5567
5568template <>
5569bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5570 DwarfAttEncodingField &Result) {
5571 if (Lex.getKind() == lltok::APSInt)
5572 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5573
5574 if (Lex.getKind() != lltok::DwarfAttEncoding)
5575 return tokError("expected DWARF type attribute encoding");
5576
5577 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5578 if (!Encoding)
5579 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5580 Lex.getStrVal() + "'");
5581 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5582 Result.assign(Encoding);
5583 Lex.Lex();
5584 return false;
5585}
5586
5587/// DIFlagField
5588/// ::= uint32
5589/// ::= DIFlagVector
5590/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5591template <>
5592bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5593
5594 // parser for a single flag.
5595 auto parseFlag = [&](DINode::DIFlags &Val) {
5596 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5597 uint32_t TempVal = static_cast<uint32_t>(Val);
5598 bool Res = parseUInt32(TempVal);
5599 Val = static_cast<DINode::DIFlags>(TempVal);
5600 return Res;
5601 }
5602
5603 if (Lex.getKind() != lltok::DIFlag)
5604 return tokError("expected debug info flag");
5605
5606 Val = DINode::getFlag(Lex.getStrVal());
5607 if (!Val)
5608 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5609 "'");
5610 Lex.Lex();
5611 return false;
5612 };
5613
5614 // parse the flags and combine them together.
5615 DINode::DIFlags Combined = DINode::FlagZero;
5616 do {
5617 DINode::DIFlags Val;
5618 if (parseFlag(Val))
5619 return true;
5620 Combined |= Val;
5621 } while (EatIfPresent(lltok::bar));
5622
5623 Result.assign(Combined);
5624 return false;
5625}
5626
5627/// DISPFlagField
5628/// ::= uint32
5629/// ::= DISPFlagVector
5630/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5631template <>
5632bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5633
5634 // parser for a single flag.
5635 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5636 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5637 uint32_t TempVal = static_cast<uint32_t>(Val);
5638 bool Res = parseUInt32(TempVal);
5639 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5640 return Res;
5641 }
5642
5643 if (Lex.getKind() != lltok::DISPFlag)
5644 return tokError("expected debug info flag");
5645
5646 Val = DISubprogram::getFlag(Lex.getStrVal());
5647 if (!Val)
5648 return tokError(Twine("invalid subprogram debug info flag '") +
5649 Lex.getStrVal() + "'");
5650 Lex.Lex();
5651 return false;
5652 };
5653
5654 // parse the flags and combine them together.
5655 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5656 do {
5658 if (parseFlag(Val))
5659 return true;
5660 Combined |= Val;
5661 } while (EatIfPresent(lltok::bar));
5662
5663 Result.assign(Combined);
5664 return false;
5665}
5666
5667template <>
5668bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5669 if (Lex.getKind() != lltok::APSInt)
5670 return tokError("expected signed integer");
5671
5672 auto &S = Lex.getAPSIntVal();
5673 if (S < Result.Min)
5674 return tokError("value for '" + Name + "' too small, limit is " +
5675 Twine(Result.Min));
5676 if (S > Result.Max)
5677 return tokError("value for '" + Name + "' too large, limit is " +
5678 Twine(Result.Max));
5679 Result.assign(S.getExtValue());
5680 assert(Result.Val >= Result.Min && "Expected value in range");
5681 assert(Result.Val <= Result.Max && "Expected value in range");
5682 Lex.Lex();
5683 return false;
5684}
5685
5686template <>
5687bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5688 switch (Lex.getKind()) {
5689 default:
5690 return tokError("expected 'true' or 'false'");
5691 case lltok::kw_true:
5692 Result.assign(true);
5693 break;
5694 case lltok::kw_false:
5695 Result.assign(false);
5696 break;
5697 }
5698 Lex.Lex();
5699 return false;
5700}
5701
5702template <>
5703bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDNodeField &Result) {
5704 if (Lex.getKind() == lltok::kw_null) {
5705 if (!Result.AllowNull)
5706 return tokError("'" + Name + "' cannot be null");
5707 Lex.Lex();
5708 Result.assign(nullptr);
5709 return false;
5710 }
5711
5712 MDNode *MD;
5713 if (parseMDNode(MD))
5714 return true;
5715
5716 Result.assign(MD);
5717 return false;
5718}
5719
5720template <>
5721bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5722 if (Lex.getKind() == lltok::kw_null) {
5723 if (!Result.AllowNull)
5724 return tokError("'" + Name + "' cannot be null");
5725 Lex.Lex();
5726 Result.assign(nullptr);
5727 return false;
5728 }
5729
5730 Metadata *MD;
5731 if (parseMetadata(MD, nullptr))
5732 return true;
5733
5734 Result.assign(MD);
5735 return false;
5736}
5737
5738template <>
5739bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5740 MDSignedOrMDField &Result) {
5741 // Try to parse a signed int.
5742 if (Lex.getKind() == lltok::APSInt) {
5743 MDSignedField Res = Result.A;
5744 if (!parseMDField(Loc, Name, Res)) {
5745 Result.assign(Res);
5746 return false;
5747 }
5748 return true;
5749 }
5750
5751 // Otherwise, try to parse as an MDField.
5752 MDField Res = Result.B;
5753 if (!parseMDField(Loc, Name, Res)) {
5754 Result.assign(Res);
5755 return false;
5756 }
5757
5758 return true;
5759}
5760
5761template <>
5762bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5763 MDUnsignedOrMDField &Result) {
5764 // Try to parse an unsigned int.
5765 if (Lex.getKind() == lltok::APSInt) {
5766 MDUnsignedField Res = Result.A;
5767 if (!parseMDField(Loc, Name, Res)) {
5768 Result.assign(Res);
5769 return false;
5770 }
5771 return true;
5772 }
5773
5774 // Otherwise, try to parse as an MDField.
5775 MDField Res = Result.B;
5776 if (!parseMDField(Loc, Name, Res)) {
5777 Result.assign(Res);
5778 return false;
5779 }
5780
5781 return true;
5782}
5783
5784template <>
5785bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5786 LocTy ValueLoc = Lex.getLoc();
5787 std::string S;
5788 if (parseStringConstant(S))
5789 return true;
5790
5791 if (S.empty()) {
5792 switch (Result.EmptyIs) {
5793 case MDStringField::EmptyIs::Null:
5794 Result.assign(nullptr);
5795 return false;
5796 case MDStringField::EmptyIs::Empty:
5797 break;
5798 case MDStringField::EmptyIs::Error:
5799 return error(ValueLoc, "'" + Name + "' cannot be empty");
5800 }
5801 }
5802
5803 Result.assign(MDString::get(Context, S));
5804 return false;
5805}
5806
5807template <>
5808bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5810 if (parseMDNodeVector(MDs))
5811 return true;
5812
5813 Result.assign(std::move(MDs));
5814 return false;
5815}
5816
5817template <>
5818bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5819 ChecksumKindField &Result) {
5820 std::optional<DIFile::ChecksumKind> CSKind =
5821 DIFile::getChecksumKind(Lex.getStrVal());
5822
5823 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5824 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5825 "'");
5826
5827 Result.assign(*CSKind);
5828 Lex.Lex();
5829 return false;
5830}
5831
5832} // end namespace llvm
5833
5834template <class ParserTy>
5835bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5836 do {
5837 if (Lex.getKind() != lltok::LabelStr)
5838 return tokError("expected field label here");
5839
5840 if (ParseField())
5841 return true;
5842 } while (EatIfPresent(lltok::comma));
5843
5844 return false;
5845}
5846
5847template <class ParserTy>
5848bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5849 assert((Lex.getKind() == lltok::MetadataVar ||
5850 Lex.getKind() == lltok::FLMDType) &&
5851 "Expected metadata type name");
5852 Lex.Lex();
5853
5854 if (parseToken(lltok::lparen, "expected '(' here"))
5855 return true;
5856 if (Lex.getKind() != lltok::rparen)
5857 if (parseMDFieldsImplBody(ParseField))
5858 return true;
5859
5860 ClosingLoc = Lex.getLoc();
5861 return parseToken(lltok::rparen, "expected ')' here");
5862}
5863
5864template <class FieldTy>
5865bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5866 if (Result.Seen)
5867 return tokError("field '" + Name + "' cannot be specified more than once");
5868
5869 LocTy Loc = Lex.getLoc();
5870 Lex.Lex();
5871 return parseMDField(Loc, Name, Result);
5872}
5873
5874bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5875 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5876
5877#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5878 if (Lex.getStrVal() == #CLASS) \
5879 return parse##CLASS(N, IsDistinct);
5880#include "llvm/IR/Metadata.def"
5881
5882 return tokError("expected metadata type");
5883}
5884
5885#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5886#define NOP_FIELD(NAME, TYPE, INIT)
5887#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5888 if (!NAME.Seen) \
5889 return error(ClosingLoc, "missing required field '" #NAME "'");
5890#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5891 if (Lex.getStrVal() == #NAME) \
5892 return parseMDField(#NAME, NAME);
5893#define PARSE_MD_FIELDS() \
5894 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5895 do { \
5896 LocTy ClosingLoc; \
5897 if (parseMDFieldsImpl( \
5898 [&]() -> bool { \
5899 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5900 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5901 "'"); \
5902 }, \
5903 ClosingLoc)) \
5904 return true; \
5905 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5906 } while (false)
5907#define GET_OR_DISTINCT(CLASS, ARGS) \
5908 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5909
5910bool LLParser::parseFLMDEntry(LocTy Loc, FLScope &Result, uint32_t Index,
5911 MDFunctionLocalContext *Context) {
5912 if (Lex.getKind() != lltok::FLMDType || Lex.getStrVal() != "scope")
5913 return tokError("expected !!scope");
5914#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5915 REQUIRED(scope, MDNodeField, (/* AllowNull */ false));
5917#undef VISIT_MD_FIELDS
5918 // If this is a forward reference, track it elsewhere, as FLScope does not use
5919 // a tracking metadata ref.
5920 if (scope.Val) {
5921 FLForwardRefScopes.try_emplace(Context).first->second.emplace_back(
5922 Index, scope.Val);
5923 }
5924 Result = FLScope(nullptr);
5925 return false;
5926}
5927
5928bool LLParser::parseFLMDEntry(LocTy Loc, FLSrcLoc &Result, uint32_t Index,
5930 if (Lex.getKind() != lltok::FLMDType || Lex.getStrVal() != "srcLoc")
5931 return tokError("expected !!srcLoc");
5932#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5933 REQUIRED(line, LineField, ); \
5934 OPTIONAL(column, ColumnField, ); \
5935 REQUIRED(scope, MDUnsignedField, (0, UINT16_MAX - 1));
5937#undef VISIT_MD_FIELDS
5938 Result = FLSrcLoc(line.Val, column.Val, scope.Val);
5939 return false;
5940}
5941
5942bool LLParser::parseFLMDEntry(LocTy Loc, FLInlinedCall &Result, uint32_t Index,
5944 if (Lex.getKind() != lltok::FLMDType || Lex.getStrVal() != "inlinedCall")
5945 return tokError("expected !!inlinedCall");
5946#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5947 OPTIONAL(srcLoc, MDUnsignedField, (0, UINT32_MAX - 1)); \
5948 OPTIONAL(inlinedAt, MDUnsignedField, (0, UINT16_MAX - 1)); \
5949 OPTIONAL(uniquable, MDBoolField, (false)); \
5950 REQUIRED(inlineeContext, MDNodeField, (/* AllowNull */ false));
5952#undef VISIT_MD_FIELDS
5953 // There isn't a valid unsigned default value for FLIndex fields, so manually
5954 // check the 'Seen' field to check whether we want to use them.
5955 FLIndex<FLSrcLoc> ActualSrcLoc;
5956 if (srcLoc.Seen)
5957 ActualSrcLoc = FLIndex<FLSrcLoc>(srcLoc.Val);
5958 FLIndex<FLInlinedCall> ActualInlinedAt;
5959 if (inlinedAt.Seen)
5960 ActualInlinedAt = FLIndex<FLInlinedCall>(inlinedAt.Val);
5961 if (inlineeContext.Val) {
5962 FLForwardRefFLMDs.try_emplace(Context).first->second.emplace_back(
5963 Index, inlineeContext.Val);
5964 }
5965 Result = FLInlinedCall(ActualSrcLoc, ActualInlinedAt, nullptr, uniquable.Val);
5966 return false;
5967}
5968
5969template <class FLMDTy>
5970bool LLParser::parseFLMDStorage(LocTy Loc, SmallVectorImpl<FLMDTy> &Result,
5972 if (parseToken(lltok::lsquare, "expected '[' at FLMD storage field"))
5973 return true;
5974
5975 // Empty storage array.
5976 if (Lex.getKind() == lltok::rsquare) {
5977 Lex.Lex();
5978 return false;
5979 }
5980 uint32_t EntryIndex = 0;
5981 FLMDTy NextEntry;
5982 if (parseFLMDEntry(Loc, NextEntry, EntryIndex++, Context))
5983 return true;
5984 Result.push_back(NextEntry);
5985 while (Lex.getKind() != lltok::rsquare) {
5986 if (parseToken(lltok::comma, "expected ',' between FLMD storage entries"))
5987 return true;
5988 // For ergonomic reasons, we allow a trailing comma in storage arrays.
5989 if (Lex.getKind() == lltok::rsquare)
5990 break;
5991 if (parseFLMDEntry(Loc, NextEntry, EntryIndex++, Context))
5992 return true;
5993 Result.push_back(NextEntry);
5994 }
5995 Lex.Lex();
5996 return false;
5997}
5998
5999/// parseMDFunctionLocalContext:
6000/// ::= !MDFunctionLocalContext(nonDebug: false, scopes: [...],
6001/// srcLocs: [...], inlinedCalls: [...])
6002bool LLParser::parseMDFunctionLocalContext(MDNode *&Result, bool IsDistinct) {
6003 if (!IsDistinct)
6004 return tokError("missing 'distinct', required for "
6005 "!MDFunctionLocalContext()");
6006 // There is an awkward order of operations here: we don't have all the
6007 // constructor arguments for MDFunctionLocalContext yet (missing NonDebug),
6008 // but the storage field parsing logic is much simpler if we can pass a valid
6009 // context to the parser, so we use a deferred approach.
6010 MDFunctionLocalContext *FLMD = MDFunctionLocalContext::getDistinct(Context);
6011 MDBoolField NonDebug(false);
6012 bool SeenScopes = false;
6013 SmallVector<FLScope> ScopesStorage;
6014 bool SeenSrcLocs = false;
6015 SmallVector<FLSrcLoc> SrcLocsStorage;
6016 bool SeenInlinedCalls = false;
6017 SmallVector<FLInlinedCall> InlinedCallsStorage;
6018 auto ParseStorageField = [&](StringRef Name, bool &Seen, auto &Storage) {
6019 if (Seen)
6020 return tokError("field '" + Name +
6021 "' cannot be specified more than once");
6022 Seen = true;
6023
6024 LocTy Loc = Lex.getLoc();
6025 Lex.Lex();
6026 return parseFLMDStorage(Loc, Storage, FLMD);
6027 };
6028 LocTy ClosingLoc;
6029 if (parseMDFieldsImpl(
6030 [&]() {
6031 StringRef Label = Lex.getStrVal();
6032 if (Label == "nonDebug")
6033 return parseMDField("nonDebug", NonDebug);
6034 if (Label == "scopes")
6035 return ParseStorageField("scopes", SeenScopes, ScopesStorage);
6036 if (Label == "srcLocs")
6037 return ParseStorageField("srcLocs", SeenSrcLocs, SrcLocsStorage);
6038 if (Label == "inlinedCalls")
6039 return ParseStorageField("inlinedCalls", SeenInlinedCalls,
6040 InlinedCallsStorage);
6041 return tokError(Twine("invalid field '") + Label + "'");
6042 },
6043 ClosingLoc))
6044 return true;
6045
6046 // Write to FLMD fields directly to construct it efficiently.
6047 FLMD->setNonDebug(NonDebug.Val);
6048 FLMD->SrcLocs.append(SrcLocsStorage);
6049 FLMD->Scopes.append(ScopesStorage);
6050 FLMD->InlinedCalls.append(InlinedCallsStorage);
6051 Result = FLMD;
6052 return false;
6053}
6054
6055/// parseDILocationFields:
6056/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
6057/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
6058bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
6059#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6060 OPTIONAL(line, LineField, ); \
6061 OPTIONAL(column, ColumnField, ); \
6062 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6063 OPTIONAL(inlinedAt, MDField, ); \
6064 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
6065 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
6066 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX)); \
6067 OPTIONAL(irlayers, MDField, );
6069#undef VISIT_MD_FIELDS
6070
6071 Result =
6072 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
6073 inlinedAt.Val, isImplicitCode.Val,
6074 atomGroup.Val, atomRank.Val, irlayers.Val));
6075 return false;
6076}
6077
6078bool LLParser::parseDILayerLoc(MDNode *&Result, bool IsDistinct) {
6079#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6080 OPTIONAL(line, LineField, ); \
6081 OPTIONAL(column, ColumnField, ); \
6082 REQUIRED(file, MDField, (/* AllowNull */ false)); \
6083 REQUIRED(kind, MDStringField, );
6085#undef VISIT_MD_FIELDS
6086
6087 Result = GET_OR_DISTINCT(DILayerLoc,
6088 (Context, kind.Val, file.Val, line.Val, column.Val));
6089 return false;
6090}
6091
6092bool LLParser::parseDILayerLocList(MDNode *&Result, bool IsDistinct) {
6093 // ::= !DILayerLocList(!a, !b, ...)
6094 Lex.Lex(); // eat the '!DILayerLocList' type name
6095 if (parseToken(lltok::lparen, "expected '(' here"))
6096 return true;
6098 if (!EatIfPresent(lltok::rparen)) {
6099 do {
6100 Metadata *MD;
6101 if (parseMetadata(MD, nullptr))
6102 return true;
6103 Layers.push_back(MD);
6104 } while (EatIfPresent(lltok::comma));
6105 if (parseToken(lltok::rparen, "expected ')' here"))
6106 return true;
6107 }
6108 Result = GET_OR_DISTINCT(DILayerLocList, (Context, Layers));
6109 return false;
6110}
6111
6112/// parseDIAssignID:
6113/// ::= distinct !DIAssignID()
6114bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
6115 if (!IsDistinct)
6116 return tokError("missing 'distinct', required for !DIAssignID()");
6117
6118 Lex.Lex();
6119
6120 // Now eat the parens.
6121 if (parseToken(lltok::lparen, "expected '(' here"))
6122 return true;
6123 if (parseToken(lltok::rparen, "expected ')' here"))
6124 return true;
6125
6127 return false;
6128}
6129
6130/// parseGenericDINode:
6131/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
6132bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
6133#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6134 REQUIRED(tag, DwarfTagField, ); \
6135 OPTIONAL(header, MDStringField, ); \
6136 OPTIONAL(operands, MDFieldList, );
6138#undef VISIT_MD_FIELDS
6139
6140 Result = GET_OR_DISTINCT(GenericDINode,
6141 (Context, tag.Val, header.Val, operands.Val));
6142 return false;
6143}
6144
6145/// parseDISubrangeType:
6146/// ::= !DISubrangeType(name: "whatever", file: !0,
6147/// line: 7, scope: !1, baseType: !2, size: 32,
6148/// align: 32, flags: 0, lowerBound: !3
6149/// upperBound: !4, stride: !5, bias: !6)
6150bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
6151#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6152 OPTIONAL(name, MDStringField, ); \
6153 OPTIONAL(file, MDField, ); \
6154 OPTIONAL(line, LineField, ); \
6155 OPTIONAL(scope, MDField, ); \
6156 OPTIONAL(baseType, MDField, ); \
6157 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6158 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6159 OPTIONAL(flags, DIFlagField, ); \
6160 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6161 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6162 OPTIONAL(stride, MDSignedOrMDField, ); \
6163 OPTIONAL(bias, MDSignedOrMDField, );
6165#undef VISIT_MD_FIELDS
6166
6167 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
6168 if (Bound.isMDSignedField())
6170 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
6171 if (Bound.isMDField())
6172 return Bound.getMDFieldValue();
6173 return nullptr;
6174 };
6175
6176 Metadata *LowerBound = convToMetadata(lowerBound);
6177 Metadata *UpperBound = convToMetadata(upperBound);
6178 Metadata *Stride = convToMetadata(stride);
6179 Metadata *Bias = convToMetadata(bias);
6180
6182 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
6183 size.getValueAsMetadata(Context), align.Val, flags.Val,
6184 baseType.Val, LowerBound, UpperBound, Stride, Bias));
6185
6186 return false;
6187}
6188
6189/// parseDISubrange:
6190/// ::= !DISubrange(count: 30, lowerBound: 2)
6191/// ::= !DISubrange(count: !node, lowerBound: 2)
6192/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
6193bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
6194#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6195 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
6196 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6197 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6198 OPTIONAL(stride, MDSignedOrMDField, );
6200#undef VISIT_MD_FIELDS
6201
6202 Metadata *Count = nullptr;
6203 Metadata *LowerBound = nullptr;
6204 Metadata *UpperBound = nullptr;
6205 Metadata *Stride = nullptr;
6206
6207 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
6208 if (Bound.isMDSignedField())
6210 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
6211 if (Bound.isMDField())
6212 return Bound.getMDFieldValue();
6213 return nullptr;
6214 };
6215
6216 Count = convToMetadata(count);
6217 LowerBound = convToMetadata(lowerBound);
6218 UpperBound = convToMetadata(upperBound);
6219 Stride = convToMetadata(stride);
6220
6221 Result = GET_OR_DISTINCT(DISubrange,
6222 (Context, Count, LowerBound, UpperBound, Stride));
6223
6224 return false;
6225}
6226
6227/// parseDIGenericSubrange:
6228/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
6229/// !node3)
6230bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
6231#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6232 OPTIONAL(count, MDSignedOrMDField, ); \
6233 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6234 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6235 OPTIONAL(stride, MDSignedOrMDField, );
6237#undef VISIT_MD_FIELDS
6238
6239 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
6240 if (Bound.isMDSignedField())
6241 return DIExpression::get(
6242 Context, {dwarf::DW_OP_consts,
6243 static_cast<uint64_t>(Bound.getMDSignedValue())});
6244 if (Bound.isMDField())
6245 return Bound.getMDFieldValue();
6246 return nullptr;
6247 };
6248
6249 Metadata *Count = ConvToMetadata(count);
6250 Metadata *LowerBound = ConvToMetadata(lowerBound);
6251 Metadata *UpperBound = ConvToMetadata(upperBound);
6252 Metadata *Stride = ConvToMetadata(stride);
6253
6254 Result = GET_OR_DISTINCT(DIGenericSubrange,
6255 (Context, Count, LowerBound, UpperBound, Stride));
6256
6257 return false;
6258}
6259
6260/// parseDIEnumerator:
6261/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
6262bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
6263#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6264 REQUIRED(name, MDStringField, ); \
6265 REQUIRED(value, MDAPSIntField, ); \
6266 OPTIONAL(isUnsigned, MDBoolField, (false));
6268#undef VISIT_MD_FIELDS
6269
6270 if (isUnsigned.Val && value.Val.isNegative())
6271 return tokError("unsigned enumerator with negative value");
6272
6273 APSInt Value(value.Val);
6274 // Add a leading zero so that unsigned values with the msb set are not
6275 // mistaken for negative values when used for signed enumerators.
6276 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
6277 Value = Value.zext(Value.getBitWidth() + 1);
6278
6279 Result =
6280 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
6281
6282 return false;
6283}
6284
6285/// parseDIBasicType:
6286/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
6287/// encoding: DW_ATE_encoding, flags: 0)
6288bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
6289#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6290 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6291 OPTIONAL(name, MDStringField, ); \
6292 OPTIONAL(file, MDField, ); \
6293 OPTIONAL(line, LineField, ); \
6294 OPTIONAL(scope, MDField, ); \
6295 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6296 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6297 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
6298 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6299 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6300 OPTIONAL(flags, DIFlagField, );
6302#undef VISIT_MD_FIELDS
6303
6305 DIBasicType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6306 size.getValueAsMetadata(Context), align.Val, encoding.Val,
6307 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
6308 return false;
6309}
6310
6311/// parseDIFixedPointType:
6312/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
6313/// align: 32, encoding: DW_ATE_signed_fixed,
6314/// flags: 0, kind: Rational, factor: 3, numerator: 1,
6315/// denominator: 8)
6316bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
6317#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6318 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6319 OPTIONAL(name, MDStringField, ); \
6320 OPTIONAL(file, MDField, ); \
6321 OPTIONAL(line, LineField, ); \
6322 OPTIONAL(scope, MDField, ); \
6323 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6324 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6325 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6326 OPTIONAL(flags, DIFlagField, ); \
6327 OPTIONAL(kind, FixedPointKindField, ); \
6328 OPTIONAL(factor, MDSignedField, ); \
6329 OPTIONAL(numerator, MDAPSIntField, ); \
6330 OPTIONAL(denominator, MDAPSIntField, );
6332#undef VISIT_MD_FIELDS
6333
6334 Result = GET_OR_DISTINCT(DIFixedPointType,
6335 (Context, tag.Val, name.Val, file.Val, line.Val,
6336 scope.Val, size.getValueAsMetadata(Context),
6337 align.Val, encoding.Val, flags.Val, kind.Val,
6338 factor.Val, numerator.Val, denominator.Val));
6339 return false;
6340}
6341
6342/// parseDIStringType:
6343/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
6344bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
6345#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6346 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6347 OPTIONAL(name, MDStringField, ); \
6348 OPTIONAL(stringLength, MDField, ); \
6349 OPTIONAL(stringLengthExpression, MDField, ); \
6350 OPTIONAL(stringLocationExpression, MDField, ); \
6351 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6352 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6353 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6354 OPTIONAL(charType, MDField, );
6356#undef VISIT_MD_FIELDS
6357
6359 DIStringType,
6360 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
6361 stringLocationExpression.Val, size.getValueAsMetadata(Context),
6362 align.Val, encoding.Val, charType.Val));
6363 return false;
6364}
6365
6366/// parseDIDerivedType:
6367/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
6368/// line: 7, scope: !1, baseType: !2, size: 32,
6369/// align: 32, offset: 0, flags: 0, extraData: !3,
6370/// dwarfAddressSpace: 3, ptrAuthKey: 1,
6371/// ptrAuthIsAddressDiscriminated: true,
6372/// ptrAuthExtraDiscriminator: 0x1234,
6373/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
6374/// )
6375bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
6376#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6377 REQUIRED(tag, DwarfTagField, ); \
6378 OPTIONAL(name, MDStringField, ); \
6379 OPTIONAL(file, MDField, ); \
6380 OPTIONAL(line, LineField, ); \
6381 OPTIONAL(scope, MDField, ); \
6382 REQUIRED(baseType, MDField, ); \
6383 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6384 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6385 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6386 OPTIONAL(flags, DIFlagField, ); \
6387 OPTIONAL(extraData, MDField, ); \
6388 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6389 OPTIONAL(annotations, MDField, ); \
6390 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6391 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6392 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6393 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6394 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6396#undef VISIT_MD_FIELDS
6397
6398 std::optional<unsigned> DWARFAddressSpace;
6399 if (dwarfAddressSpace.Val != UINT32_MAX)
6400 DWARFAddressSpace = dwarfAddressSpace.Val;
6401 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6402 if (ptrAuthKey.Val)
6403 PtrAuthData.emplace(
6404 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6405 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6406 ptrAuthAuthenticatesNullValues.Val);
6407
6409 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6410 baseType.Val, size.getValueAsMetadata(Context), align.Val,
6411 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6412 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6413 return false;
6414}
6415
6416bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
6417#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6418 REQUIRED(tag, DwarfTagField, ); \
6419 OPTIONAL(name, MDStringField, ); \
6420 OPTIONAL(file, MDField, ); \
6421 OPTIONAL(line, LineField, ); \
6422 OPTIONAL(scope, MDField, ); \
6423 OPTIONAL(baseType, MDField, ); \
6424 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6425 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6426 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6427 OPTIONAL(flags, DIFlagField, ); \
6428 OPTIONAL(elements, MDField, ); \
6429 OPTIONAL(runtimeLang, DwarfLangField, ); \
6430 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6431 OPTIONAL(vtableHolder, MDField, ); \
6432 OPTIONAL(templateParams, MDField, ); \
6433 OPTIONAL(identifier, MDStringField, ); \
6434 OPTIONAL(discriminator, MDField, ); \
6435 OPTIONAL(dataLocation, MDField, ); \
6436 OPTIONAL(associated, MDField, ); \
6437 OPTIONAL(allocated, MDField, ); \
6438 OPTIONAL(rank, MDSignedOrMDField, ); \
6439 OPTIONAL(annotations, MDField, ); \
6440 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6441 OPTIONAL(specification, MDField, ); \
6442 OPTIONAL(bitStride, MDField, );
6444#undef VISIT_MD_FIELDS
6445
6446 Metadata *Rank = nullptr;
6447 if (rank.isMDSignedField())
6449 Type::getInt64Ty(Context), rank.getMDSignedValue()));
6450 else if (rank.isMDField())
6451 Rank = rank.getMDFieldValue();
6452
6453 std::optional<unsigned> EnumKind;
6454 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
6455 EnumKind = enumKind.Val;
6456
6457 // If this has an identifier try to build an ODR type.
6458 if (identifier.Val)
6459 if (auto *CT = DICompositeType::buildODRType(
6460 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
6461 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
6462 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6463 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6464 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6465 dataLocation.Val, associated.Val, allocated.Val, Rank,
6466 annotations.Val, bitStride.Val)) {
6467 Result = CT;
6468 return false;
6469 }
6470
6471 // Create a new node, and save it in the context if it belongs in the type
6472 // map.
6474 DICompositeType,
6475 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
6476 size.getValueAsMetadata(Context), align.Val,
6477 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6478 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6479 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6480 allocated.Val, Rank, annotations.Val, specification.Val,
6481 num_extra_inhabitants.Val, bitStride.Val));
6482 return false;
6483}
6484
6485bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
6486#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6487 OPTIONAL(flags, DIFlagField, ); \
6488 OPTIONAL(cc, DwarfCCField, ); \
6489 REQUIRED(types, MDField, );
6491#undef VISIT_MD_FIELDS
6492
6493 Result = GET_OR_DISTINCT(DISubroutineType,
6494 (Context, flags.Val, cc.Val, types.Val));
6495 return false;
6496}
6497
6498/// parseDIFileType:
6499/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
6500/// checksumkind: CSK_MD5,
6501/// checksum: "000102030405060708090a0b0c0d0e0f",
6502/// source: "source file contents")
6503bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
6504 // The default constructed value for checksumkind is required, but will never
6505 // be used, as the parser checks if the field was actually Seen before using
6506 // the Val.
6507#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6508 REQUIRED(filename, MDStringField, ); \
6509 REQUIRED(directory, MDStringField, ); \
6510 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6511 OPTIONAL(checksum, MDStringField, ); \
6512 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6514#undef VISIT_MD_FIELDS
6515
6516 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6517 if (checksumkind.Seen && checksum.Seen)
6518 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6519 else if (checksumkind.Seen || checksum.Seen)
6520 return tokError("'checksumkind' and 'checksum' must be provided together");
6521
6522 MDString *Source = nullptr;
6523 if (source.Seen)
6524 Source = source.Val;
6526 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
6527 return false;
6528}
6529
6530/// parseDICompileUnit:
6531/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
6532/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
6533/// splitDebugFilename: "abc.debug",
6534/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
6535/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
6536/// sysroot: "/", sdk: "MacOSX.sdk",
6537/// dialect: DW_LLVM_LANG_DIALECT_simt)
6538bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
6539 if (!IsDistinct)
6540 return tokError("missing 'distinct', required for !DICompileUnit");
6541
6542 LocTy Loc = Lex.getLoc();
6543
6544#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6545 REQUIRED(file, MDField, (/* AllowNull */ false)); \
6546 OPTIONAL(language, DwarfLangField, ); \
6547 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6548 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6549 OPTIONAL(producer, MDStringField, ); \
6550 OPTIONAL(isOptimized, MDBoolField, ); \
6551 OPTIONAL(flags, MDStringField, ); \
6552 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6553 OPTIONAL(splitDebugFilename, MDStringField, ); \
6554 OPTIONAL(emissionKind, EmissionKindField, ); \
6555 OPTIONAL(enums, MDField, ); \
6556 OPTIONAL(retainedTypes, MDField, ); \
6557 OPTIONAL(globals, MDField, ); \
6558 OPTIONAL(imports, MDField, ); \
6559 OPTIONAL(macros, MDField, ); \
6560 OPTIONAL(dwoId, MDUnsignedField, ); \
6561 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6562 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6563 OPTIONAL(nameTableKind, NameTableKindField, ); \
6564 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6565 OPTIONAL(sysroot, MDStringField, ); \
6566 OPTIONAL(sdk, MDStringField, ); \
6567 OPTIONAL(dialect, DwarfLangDialectField, );
6569#undef VISIT_MD_FIELDS
6570
6571 if (!language.Seen && !sourceLanguageName.Seen)
6572 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
6573 "required for !DICompileUnit");
6574
6575 if (language.Seen && sourceLanguageName.Seen)
6576 return error(Loc, "can only specify one of 'language' and "
6577 "'sourceLanguageName' on !DICompileUnit");
6578
6579 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6580 return error(Loc, "'sourceLanguageVersion' requires an associated "
6581 "'sourceLanguageName' on !DICompileUnit");
6582
6583 uint16_t Dialect = static_cast<uint16_t>(dialect.Val);
6584 DISourceLanguageName SourceLanguage =
6585 language.Seen
6586 ? DISourceLanguageName(static_cast<uint16_t>(language.Val), Dialect)
6587 : DISourceLanguageName(
6588 static_cast<uint16_t>(sourceLanguageName.Val),
6589 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6590
6592 Context, SourceLanguage, file.Val, producer.Val, isOptimized.Val,
6593 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6594 enums.Val, retainedTypes.Val, globals.Val, imports.Val, macros.Val,
6595 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6596 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6597 return false;
6598}
6599
6600/// parseDISubprogram:
6601/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
6602/// file: !1, line: 7, type: !2, isLocal: false,
6603/// isDefinition: true, scopeLine: 8, containingType: !3,
6604/// virtuality: DW_VIRTUALTIY_pure_virtual,
6605/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
6606/// spFlags: 10, isOptimized: false, templateParams: !4,
6607/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
6608/// annotations: !8)
6609bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
6610 auto Loc = Lex.getLoc();
6611#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6612 OPTIONAL(scope, MDField, ); \
6613 OPTIONAL(name, MDStringField, ); \
6614 OPTIONAL(linkageName, MDStringField, ); \
6615 OPTIONAL(file, MDField, ); \
6616 OPTIONAL(line, LineField, ); \
6617 REQUIRED(type, MDField, (/* AllowNull */ false)); \
6618 OPTIONAL(isLocal, MDBoolField, ); \
6619 OPTIONAL(isDefinition, MDBoolField, (true)); \
6620 OPTIONAL(scopeLine, LineField, ); \
6621 OPTIONAL(containingType, MDField, ); \
6622 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6623 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6624 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6625 OPTIONAL(flags, DIFlagField, ); \
6626 OPTIONAL(spFlags, DISPFlagField, ); \
6627 OPTIONAL(isOptimized, MDBoolField, ); \
6628 OPTIONAL(unit, MDField, ); \
6629 OPTIONAL(templateParams, MDField, ); \
6630 OPTIONAL(declaration, MDField, ); \
6631 OPTIONAL(retainedNodes, MDField, ); \
6632 OPTIONAL(thrownTypes, MDField, ); \
6633 OPTIONAL(annotations, MDField, ); \
6634 OPTIONAL(targetFuncName, MDStringField, ); \
6635 OPTIONAL(keyInstructions, MDBoolField, );
6637#undef VISIT_MD_FIELDS
6638
6639 // An explicit spFlags field takes precedence over individual fields in
6640 // older IR versions.
6641 DISubprogram::DISPFlags SPFlags =
6642 spFlags.Seen ? spFlags.Val
6643 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
6644 isOptimized.Val, virtuality.Val);
6645 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6646 return error(
6647 Loc,
6648 "missing 'distinct', required for !DISubprogram that is a Definition");
6650 DISubprogram,
6651 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6652 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6653 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6654 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6655 targetFuncName.Val, keyInstructions.Val));
6656
6657 if (IsDistinct)
6658 NewDistinctSPs.push_back(cast<DISubprogram>(Result));
6659
6660 return false;
6661}
6662
6663/// parseDILexicalBlock:
6664/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6665bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6666#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6667 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6668 OPTIONAL(file, MDField, ); \
6669 OPTIONAL(line, LineField, ); \
6670 OPTIONAL(column, ColumnField, );
6672#undef VISIT_MD_FIELDS
6673
6675 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6676 return false;
6677}
6678
6679/// parseDILexicalBlockFile:
6680/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6681bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6682#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6683 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6684 OPTIONAL(file, MDField, ); \
6685 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6687#undef VISIT_MD_FIELDS
6688
6689 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6690 (Context, scope.Val, file.Val, discriminator.Val));
6691 return false;
6692}
6693
6694/// parseDICommonBlock:
6695/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6696bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6697#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6698 REQUIRED(scope, MDField, ); \
6699 OPTIONAL(declaration, MDField, ); \
6700 OPTIONAL(name, MDStringField, ); \
6701 OPTIONAL(file, MDField, ); \
6702 OPTIONAL(line, LineField, );
6704#undef VISIT_MD_FIELDS
6705
6706 Result = GET_OR_DISTINCT(DICommonBlock,
6707 (Context, scope.Val, declaration.Val, name.Val,
6708 file.Val, line.Val));
6709 return false;
6710}
6711
6712/// parseDINamespace:
6713/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6714bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6715#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6716 REQUIRED(scope, MDField, ); \
6717 OPTIONAL(name, MDStringField, ); \
6718 OPTIONAL(exportSymbols, MDBoolField, );
6720#undef VISIT_MD_FIELDS
6721
6722 Result = GET_OR_DISTINCT(DINamespace,
6723 (Context, scope.Val, name.Val, exportSymbols.Val));
6724 return false;
6725}
6726
6727/// parseDIMacro:
6728/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6729/// "SomeValue")
6730bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6731#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6732 REQUIRED(type, DwarfMacinfoTypeField, ); \
6733 OPTIONAL(line, LineField, ); \
6734 REQUIRED(name, MDStringField, ); \
6735 OPTIONAL(value, MDStringField, );
6737#undef VISIT_MD_FIELDS
6738
6739 Result = GET_OR_DISTINCT(DIMacro,
6740 (Context, type.Val, line.Val, name.Val, value.Val));
6741 return false;
6742}
6743
6744/// parseDIMacroFile:
6745/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6746bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6747#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6748 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6749 OPTIONAL(line, LineField, ); \
6750 REQUIRED(file, MDField, ); \
6751 OPTIONAL(nodes, MDField, );
6753#undef VISIT_MD_FIELDS
6754
6755 Result = GET_OR_DISTINCT(DIMacroFile,
6756 (Context, type.Val, line.Val, file.Val, nodes.Val));
6757 return false;
6758}
6759
6760/// parseDIModule:
6761/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6762/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6763/// file: !1, line: 4, isDecl: false)
6764bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6765#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6766 REQUIRED(scope, MDField, ); \
6767 REQUIRED(name, MDStringField, ); \
6768 OPTIONAL(configMacros, MDStringField, ); \
6769 OPTIONAL(includePath, MDStringField, ); \
6770 OPTIONAL(apinotes, MDStringField, ); \
6771 OPTIONAL(file, MDField, ); \
6772 OPTIONAL(line, LineField, ); \
6773 OPTIONAL(isDecl, MDBoolField, );
6775#undef VISIT_MD_FIELDS
6776
6777 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6778 configMacros.Val, includePath.Val,
6779 apinotes.Val, line.Val, isDecl.Val));
6780 return false;
6781}
6782
6783/// parseDITemplateTypeParameter:
6784/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6785bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6786#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6787 OPTIONAL(name, MDStringField, ); \
6788 REQUIRED(type, MDField, ); \
6789 OPTIONAL(defaulted, MDBoolField, );
6791#undef VISIT_MD_FIELDS
6792
6793 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6794 (Context, name.Val, type.Val, defaulted.Val));
6795 return false;
6796}
6797
6798/// parseDITemplateValueParameter:
6799/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6800/// name: "V", type: !1, defaulted: false,
6801/// value: i32 7)
6802bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6803#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6804 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6805 OPTIONAL(name, MDStringField, ); \
6806 OPTIONAL(type, MDField, ); \
6807 OPTIONAL(defaulted, MDBoolField, ); \
6808 REQUIRED(value, MDField, );
6809
6811#undef VISIT_MD_FIELDS
6812
6814 DITemplateValueParameter,
6815 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6816 return false;
6817}
6818
6819/// parseDIGlobalVariable:
6820/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6821/// file: !1, line: 7, type: !2, isLocal: false,
6822/// isDefinition: true, templateParams: !3,
6823/// declaration: !4, align: 8)
6824bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6825#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6826 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6827 OPTIONAL(scope, MDField, ); \
6828 OPTIONAL(linkageName, MDStringField, ); \
6829 OPTIONAL(file, MDField, ); \
6830 OPTIONAL(line, LineField, ); \
6831 OPTIONAL(type, MDField, ); \
6832 OPTIONAL(isLocal, MDBoolField, ); \
6833 OPTIONAL(isDefinition, MDBoolField, (true)); \
6834 OPTIONAL(templateParams, MDField, ); \
6835 OPTIONAL(declaration, MDField, ); \
6836 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6837 OPTIONAL(annotations, MDField, );
6839#undef VISIT_MD_FIELDS
6840
6841 Result =
6842 GET_OR_DISTINCT(DIGlobalVariable,
6843 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6844 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6845 declaration.Val, templateParams.Val, align.Val,
6846 annotations.Val));
6847 return false;
6848}
6849
6850/// parseDILocalVariable:
6851/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6852/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6853/// align: 8)
6854/// ::= !DILocalVariable(scope: !0, name: "foo",
6855/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6856/// align: 8)
6857bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6858#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6859 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6860 OPTIONAL(name, MDStringField, ); \
6861 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6862 OPTIONAL(file, MDField, ); \
6863 OPTIONAL(line, LineField, ); \
6864 OPTIONAL(type, MDField, ); \
6865 OPTIONAL(flags, DIFlagField, ); \
6866 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6867 OPTIONAL(annotations, MDField, );
6869#undef VISIT_MD_FIELDS
6870
6871 Result = GET_OR_DISTINCT(DILocalVariable,
6872 (Context, scope.Val, name.Val, file.Val, line.Val,
6873 type.Val, arg.Val, flags.Val, align.Val,
6874 annotations.Val));
6875 return false;
6876}
6877
6878/// parseDILabel:
6879/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6880bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6881#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6882 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6883 REQUIRED(name, MDStringField, ); \
6884 REQUIRED(file, MDField, ); \
6885 REQUIRED(line, LineField, ); \
6886 OPTIONAL(column, ColumnField, ); \
6887 OPTIONAL(isArtificial, MDBoolField, ); \
6888 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6890#undef VISIT_MD_FIELDS
6891
6892 std::optional<unsigned> CoroSuspendIdx =
6893 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6894 : std::nullopt;
6895
6896 Result = GET_OR_DISTINCT(DILabel,
6897 (Context, scope.Val, name.Val, file.Val, line.Val,
6898 column.Val, isArtificial.Val, CoroSuspendIdx));
6899 return false;
6900}
6901
6902/// parseDIExpressionBody:
6903/// ::= (0, 7, -1)
6904bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6905 if (parseToken(lltok::lparen, "expected '(' here"))
6906 return true;
6907
6908 SmallVector<uint64_t, 8> Elements;
6909 if (Lex.getKind() != lltok::rparen)
6910 do {
6911 if (Lex.getKind() == lltok::DwarfOp) {
6912 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6913 Lex.Lex();
6914 Elements.push_back(Op);
6915 continue;
6916 }
6917 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6918 }
6919
6920 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6921 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6922 Lex.Lex();
6923 Elements.push_back(Op);
6924 continue;
6925 }
6926 return tokError(Twine("invalid DWARF attribute encoding '") +
6927 Lex.getStrVal() + "'");
6928 }
6929
6930 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6931 return tokError("expected unsigned integer");
6932
6933 auto &U = Lex.getAPSIntVal();
6934 if (U.ugt(UINT64_MAX))
6935 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6936 Elements.push_back(U.getZExtValue());
6937 Lex.Lex();
6938 } while (EatIfPresent(lltok::comma));
6939
6940 if (parseToken(lltok::rparen, "expected ')' here"))
6941 return true;
6942
6943 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6944 return false;
6945}
6946
6947/// parseDIExpression:
6948/// ::= !DIExpression(0, 7, -1)
6949bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6950 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6951 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6952 Lex.Lex();
6953
6954 return parseDIExpressionBody(Result, IsDistinct);
6955}
6956
6957/// ParseDIArgList:
6958/// ::= !DIArgList(i32 7, i64 %0)
6959bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6960 assert(PFS && "Expected valid function state");
6961 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6962 Lex.Lex();
6963
6964 if (parseToken(lltok::lparen, "expected '(' here"))
6965 return true;
6966
6968 if (Lex.getKind() != lltok::rparen)
6969 do {
6970 Metadata *MD;
6971 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6972 return true;
6973 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6974 } while (EatIfPresent(lltok::comma));
6975
6976 if (parseToken(lltok::rparen, "expected ')' here"))
6977 return true;
6978
6979 MD = DIArgList::get(Context, Args);
6980 return false;
6981}
6982
6983/// parseDIGlobalVariableExpression:
6984/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6985bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6986 bool IsDistinct) {
6987#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6988 REQUIRED(var, MDField, ); \
6989 REQUIRED(expr, MDField, );
6991#undef VISIT_MD_FIELDS
6992
6993 Result =
6994 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6995 return false;
6996}
6997
6998/// parseDIObjCProperty:
6999/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
7000/// getter: "getFoo", attributes: 7, type: !2)
7001bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
7002#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
7003 OPTIONAL(name, MDStringField, ); \
7004 OPTIONAL(file, MDField, ); \
7005 OPTIONAL(line, LineField, ); \
7006 OPTIONAL(setter, MDStringField, ); \
7007 OPTIONAL(getter, MDStringField, ); \
7008 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
7009 OPTIONAL(type, MDField, );
7011#undef VISIT_MD_FIELDS
7012
7013 Result = GET_OR_DISTINCT(DIObjCProperty,
7014 (Context, name.Val, file.Val, line.Val, getter.Val,
7015 setter.Val, attributes.Val, type.Val));
7016 return false;
7017}
7018
7019/// parseDIProperty:
7020/// ::= !DIProperty(name: "x", file: !1, line: 7, type: !2,
7021/// backing_storage: !3)
7022bool LLParser::parseDIProperty(MDNode *&Result, bool IsDistinct) {
7023#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
7024 OPTIONAL(name, MDStringField, ); \
7025 OPTIONAL(file, MDField, ); \
7026 OPTIONAL(line, LineField, ); \
7027 OPTIONAL(type, MDField, ); \
7028 OPTIONAL(backing_storage, MDField, );
7030#undef VISIT_MD_FIELDS
7031
7032 Result = GET_OR_DISTINCT(DIProperty, (Context, name.Val, file.Val, line.Val,
7033 type.Val, backing_storage.Val));
7034 return false;
7035}
7036
7037/// parseDIImportedEntity:
7038/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
7039/// line: 7, name: "foo", elements: !2)
7040bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
7041#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
7042 REQUIRED(tag, DwarfTagField, ); \
7043 REQUIRED(scope, MDField, ); \
7044 OPTIONAL(entity, MDField, ); \
7045 OPTIONAL(file, MDField, ); \
7046 OPTIONAL(line, LineField, ); \
7047 OPTIONAL(name, MDStringField, ); \
7048 OPTIONAL(elements, MDField, );
7050#undef VISIT_MD_FIELDS
7051
7052 Result = GET_OR_DISTINCT(DIImportedEntity,
7053 (Context, tag.Val, scope.Val, entity.Val, file.Val,
7054 line.Val, name.Val, elements.Val));
7055 return false;
7056}
7057
7058#undef PARSE_MD_FIELD
7059#undef NOP_FIELD
7060#undef REQUIRE_FIELD
7061#undef DECLARE_FIELD
7062
7063/// parseMetadataAsValue
7064/// ::= metadata i32 %local
7065/// ::= metadata i32 @global
7066/// ::= metadata i32 7
7067/// ::= metadata !0
7068/// ::= metadata !{...}
7069/// ::= metadata !"string"
7070bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
7071 // Note: the type 'metadata' has already been parsed.
7072 Metadata *MD;
7073 if (parseMetadata(MD, &PFS))
7074 return true;
7075
7076 V = MetadataAsValue::get(Context, MD);
7077 return false;
7078}
7079
7080/// parseValueAsMetadata
7081/// ::= i32 %local
7082/// ::= i32 @global
7083/// ::= i32 7
7084bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
7085 PerFunctionState *PFS) {
7086 Type *Ty;
7087 LocTy Loc;
7088 if (parseType(Ty, TypeMsg, Loc))
7089 return true;
7090 if (Ty->isMetadataTy())
7091 return error(Loc, "invalid metadata-value-metadata roundtrip");
7092
7093 Value *V;
7094 if (parseValue(Ty, V, PFS))
7095 return true;
7096
7097 MD = ValueAsMetadata::get(V);
7098 return false;
7099}
7100
7101/// parseMetadata
7102/// ::= i32 %local
7103/// ::= i32 @global
7104/// ::= i32 7
7105/// ::= !42
7106/// ::= !{...}
7107/// ::= !"string"
7108/// ::= !DILocation(...)
7109bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
7110 if (Lex.getKind() == lltok::MetadataVar) {
7111 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
7112 // so parsing this requires a Function State.
7113 if (Lex.getStrVal() == "DIArgList") {
7114 Metadata *AL;
7115 if (parseDIArgList(AL, PFS))
7116 return true;
7117 MD = AL;
7118 return false;
7119 }
7120 MDNode *N;
7121 if (parseSpecializedMDNode(N)) {
7122 return true;
7123 }
7124 MD = N;
7125 return false;
7126 }
7127
7128 // ValueAsMetadata:
7129 // <type> <value>
7130 if (Lex.getKind() != lltok::exclaim)
7131 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
7132
7133 // '!'.
7134 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
7135 Lex.Lex();
7136
7137 // MDString:
7138 // ::= '!' STRINGCONSTANT
7139 if (Lex.getKind() == lltok::StringConstant) {
7140 MDString *S;
7141 if (parseMDString(S))
7142 return true;
7143 MD = S;
7144 return false;
7145 }
7146
7147 // MDNode:
7148 // !{ ... }
7149 // !7
7150 MDNode *N;
7151 if (parseMDNodeTail(N))
7152 return true;
7153 MD = N;
7154 return false;
7155}
7156
7157//===----------------------------------------------------------------------===//
7158// Function Parsing.
7159//===----------------------------------------------------------------------===//
7160
7161bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
7162 PerFunctionState *PFS) {
7163 if (Ty->isFunctionTy())
7164 return error(ID.Loc, "functions are not values, refer to them as pointers");
7165
7166 switch (ID.Kind) {
7167 case ValID::t_LocalID:
7168 if (!PFS)
7169 return error(ID.Loc, "invalid use of function-local name");
7170 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
7171 return V == nullptr;
7172 case ValID::t_LocalName:
7173 if (!PFS)
7174 return error(ID.Loc, "invalid use of function-local name");
7175 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
7176 return V == nullptr;
7177 case ValID::t_InlineAsm: {
7178 if (!ID.FTy)
7179 return error(ID.Loc, "invalid type for inline asm constraint string");
7180 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
7181 return error(ID.Loc, toString(std::move(Err)));
7182 V = InlineAsm::get(
7183 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
7184 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
7185 return false;
7186 }
7188 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
7189 if (V && ID.NoCFI)
7191 return V == nullptr;
7192 case ValID::t_GlobalID:
7193 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
7194 if (V && ID.NoCFI)
7196 return V == nullptr;
7197 case ValID::t_APSInt:
7198 if (!Ty->isIntegerTy() && !Ty->isByteTy())
7199 return error(ID.Loc, "integer/byte constant must have integer/byte type");
7200 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
7201 Ty->isIntegerTy() ? V = ConstantInt::get(Context, ID.APSIntVal)
7202 : V = ConstantByte::get(Context, ID.APSIntVal);
7203 return false;
7204 case ValID::t_APFloat:
7205 if (!Ty->isFloatingPointTy() ||
7206 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
7207 return error(ID.Loc, "floating point constant invalid for type");
7208
7209 // The lexer has no type info, so builds all half, bfloat, float, and double
7210 // FP constants as double. Fix this here. Long double does not need this.
7211 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
7212 // Check for signaling before potentially converting and losing that info.
7213 bool IsSNAN = ID.APFloatVal.isSignaling();
7214 bool Ignored;
7215 if (Ty->isHalfTy())
7216 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
7217 &Ignored);
7218 else if (Ty->isBFloatTy())
7219 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
7220 &Ignored);
7221 else if (Ty->isFloatTy())
7222 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
7223 &Ignored);
7224 if (IsSNAN) {
7225 // The convert call above may quiet an SNaN, so manufacture another
7226 // SNaN. The bitcast works because the payload (significand) parameter
7227 // is truncated to fit.
7228 APInt Payload = ID.APFloatVal.bitcastToAPInt();
7229 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
7230 ID.APFloatVal.isNegative(), &Payload);
7231 }
7232 }
7233 V = ConstantFP::get(Context, ID.APFloatVal);
7234
7235 if (V->getType() != Ty)
7236 return error(ID.Loc, "floating point constant does not have type '" +
7237 getTypeString(Ty) + "'");
7238
7239 return false;
7240 case ValID::t_Null:
7241 if (!Ty->isPointerTy())
7242 return error(ID.Loc, "null must be a pointer type");
7244 return false;
7245 case ValID::t_Undef:
7246 // FIXME: LabelTy should not be a first-class type.
7247 if (!Ty->isFirstClassType() || Ty->isLabelTy())
7248 return error(ID.Loc, "invalid type for undef constant");
7249 V = UndefValue::get(Ty);
7250 return false;
7252 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
7253 return error(ID.Loc, "invalid empty array initializer");
7254 V = PoisonValue::get(Ty);
7255 return false;
7256 case ValID::t_Zero:
7257 // FIXME: LabelTy should not be a first-class type.
7258 if (!Ty->isFirstClassType() || Ty->isLabelTy())
7259 return error(ID.Loc, "invalid type for null constant");
7260 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
7261 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
7262 return error(ID.Loc, "invalid type for null constant");
7264 return false;
7265 case ValID::t_None:
7266 if (!Ty->isTokenTy())
7267 return error(ID.Loc, "invalid type for none constant");
7269 return false;
7270 case ValID::t_Poison:
7271 // FIXME: LabelTy should not be a first-class type.
7272 if (!Ty->isFirstClassType() || Ty->isLabelTy())
7273 return error(ID.Loc, "invalid type for poison constant");
7274 V = PoisonValue::get(Ty);
7275 return false;
7276 case ValID::t_Constant:
7277 if (ID.ConstantVal->getType() != Ty)
7278 return error(ID.Loc, "constant expression type mismatch: got type '" +
7279 getTypeString(ID.ConstantVal->getType()) +
7280 "' but expected '" + getTypeString(Ty) + "'");
7281 V = ID.ConstantVal;
7282 return false;
7284 if (!Ty->isVectorTy())
7285 return error(ID.Loc, "vector constant must have vector type");
7286 if (ID.ConstantVal->getType() != Ty->getScalarType())
7287 return error(ID.Loc, "constant expression type mismatch: got type '" +
7288 getTypeString(ID.ConstantVal->getType()) +
7289 "' but expected '" +
7290 getTypeString(Ty->getScalarType()) + "'");
7291 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
7292 ID.ConstantVal);
7293 return false;
7296 if (StructType *ST = dyn_cast<StructType>(Ty)) {
7297 if (ST->getNumElements() != ID.UIntVal)
7298 return error(ID.Loc,
7299 "initializer with struct type has wrong # elements");
7300 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
7301 return error(ID.Loc, "packed'ness of initializer and type don't match");
7302
7303 // Verify that the elements are compatible with the structtype.
7304 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
7305 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
7306 return error(
7307 ID.Loc,
7308 "element " + Twine(i) +
7309 " of struct initializer doesn't match struct element type");
7310
7312 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
7313 } else
7314 return error(ID.Loc, "constant expression type mismatch");
7315 return false;
7316 }
7317 llvm_unreachable("Invalid ValID");
7318}
7319
7320bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
7321 C = nullptr;
7322 ValID ID;
7323 auto Loc = Lex.getLoc();
7324 if (parseValID(ID, /*PFS=*/nullptr, /*ExpectedTy=*/Ty))
7325 return true;
7326 switch (ID.Kind) {
7327 case ValID::t_APSInt:
7328 case ValID::t_APFloat:
7329 case ValID::t_Undef:
7330 case ValID::t_Poison:
7331 case ValID::t_Zero:
7332 case ValID::t_Constant:
7336 Value *V;
7337 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
7338 return true;
7339 assert(isa<Constant>(V) && "Expected a constant value");
7340 C = cast<Constant>(V);
7341 return false;
7342 }
7343 case ValID::t_Null:
7345 return false;
7346 default:
7347 return error(Loc, "expected a constant value");
7348 }
7349}
7350
7351bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
7352 V = nullptr;
7353 ValID ID;
7354
7355 FileLoc Start = getTokLineColumnPos();
7356 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
7357 if (!Ret && ParserContext) {
7358 FileLoc End = getPrevTokEndLineColumnPos();
7359 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
7360 }
7361 return Ret;
7362}
7363
7364bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
7365 Type *Ty = nullptr;
7366 return parseType(Ty) || parseValue(Ty, V, PFS);
7367}
7368
7369bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
7370 PerFunctionState &PFS) {
7371 Value *V;
7372 Loc = Lex.getLoc();
7373 if (parseTypeAndValue(V, PFS))
7374 return true;
7375 if (!isa<BasicBlock>(V))
7376 return error(Loc, "expected a basic block");
7377 BB = cast<BasicBlock>(V);
7378 return false;
7379}
7380
7382 // Exit early for the common (non-debug-intrinsic) case.
7383 // We can make this the only check when we begin supporting all "llvm.dbg"
7384 // intrinsics in the new debug info format.
7385 if (!Name.starts_with("llvm.dbg."))
7386 return false;
7388 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7389 FnID == Intrinsic::dbg_assign;
7390}
7391
7392/// FunctionHeader
7393/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
7394/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
7395/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
7396/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
7397bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
7398 unsigned &FunctionNumber,
7399 SmallVectorImpl<unsigned> &UnnamedArgNums) {
7400 // parse the linkage.
7401 LocTy LinkageLoc = Lex.getLoc();
7402 unsigned Linkage;
7403 unsigned Visibility;
7404 unsigned DLLStorageClass;
7405 bool DSOLocal;
7406 AttrBuilder RetAttrs(M->getContext());
7407 unsigned CC;
7408 bool HasLinkage;
7409 Type *RetType = nullptr;
7410 LocTy RetTypeLoc = Lex.getLoc();
7411 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
7412 DSOLocal) ||
7413 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7414 parseType(RetType, RetTypeLoc, true /*void allowed*/))
7415 return true;
7416
7417 // Verify that the linkage is ok.
7420 break; // always ok.
7422 if (IsDefine)
7423 return error(LinkageLoc, "invalid linkage for function definition");
7424 break;
7432 if (!IsDefine)
7433 return error(LinkageLoc, "invalid linkage for function declaration");
7434 break;
7437 return error(LinkageLoc, "invalid function linkage type");
7438 }
7439
7440 if (!isValidVisibilityForLinkage(Visibility, Linkage))
7441 return error(LinkageLoc,
7442 "symbol with local linkage must have default visibility");
7443
7444 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
7445 return error(LinkageLoc,
7446 "symbol with local linkage cannot have a DLL storage class");
7447
7448 if (!FunctionType::isValidReturnType(RetType))
7449 return error(RetTypeLoc, "invalid function return type");
7450
7451 LocTy NameLoc = Lex.getLoc();
7452
7453 std::string FunctionName;
7454 if (Lex.getKind() == lltok::GlobalVar) {
7455 FunctionName = Lex.getStrVal();
7456 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
7457 FunctionNumber = Lex.getUIntVal();
7458 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
7459 FunctionNumber))
7460 return true;
7461 } else {
7462 return tokError("expected function name");
7463 }
7464
7465 Lex.Lex();
7466
7467 if (Lex.getKind() != lltok::lparen)
7468 return tokError("expected '(' in function argument list");
7469
7471 bool IsVarArg;
7472 AttrBuilder FuncAttrs(M->getContext());
7473 std::vector<unsigned> FwdRefAttrGrps;
7474 LocTy BuiltinLoc;
7475 std::string Section;
7476 std::string Partition;
7477 MaybeAlign Alignment, PrefAlignment;
7478 std::string GC;
7480 unsigned AddrSpace = 0;
7481 Constant *Prefix = nullptr;
7482 Constant *Prologue = nullptr;
7483 Constant *PersonalityFn = nullptr;
7484 Comdat *C;
7485
7486 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7487 parseOptionalUnnamedAddr(UnnamedAddr) ||
7488 parseOptionalProgramAddrSpace(AddrSpace) ||
7489 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
7490 BuiltinLoc) ||
7491 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
7492 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
7493 parseOptionalComdat(FunctionName, C) ||
7494 parseOptionalAlignment(Alignment) ||
7495 parseOptionalPrefAlignment(PrefAlignment) ||
7496 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
7497 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
7498 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
7499 (EatIfPresent(lltok::kw_personality) &&
7500 parseGlobalTypeAndValue(PersonalityFn)))
7501 return true;
7502
7503 if (FuncAttrs.contains(Attribute::Builtin))
7504 return error(BuiltinLoc, "'builtin' attribute not valid on function");
7505
7506 // If the alignment was parsed as an attribute, move to the alignment field.
7507 if (MaybeAlign A = FuncAttrs.getAlignment()) {
7508 Alignment = A;
7509 FuncAttrs.removeAttribute(Attribute::Alignment);
7510 }
7511
7512 // Okay, if we got here, the function is syntactically valid. Convert types
7513 // and do semantic checks.
7514 std::vector<Type*> ParamTypeList;
7516
7517 for (const ArgInfo &Arg : ArgList) {
7518 ParamTypeList.push_back(Arg.Ty);
7519 Attrs.push_back(Arg.Attrs);
7520 }
7521
7522 AttributeList PAL =
7523 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
7524 AttributeSet::get(Context, RetAttrs), Attrs);
7525
7526 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
7527 return error(RetTypeLoc, "functions with 'sret' argument must return void");
7528
7529 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
7530 PointerType *PFT = PointerType::get(Context, AddrSpace);
7531
7532 Fn = nullptr;
7533 GlobalValue *FwdFn = nullptr;
7534 if (!FunctionName.empty()) {
7535 // If this was a definition of a forward reference, remove the definition
7536 // from the forward reference table and fill in the forward ref.
7537 auto FRVI = ForwardRefVals.find(FunctionName);
7538 if (FRVI != ForwardRefVals.end()) {
7539 FwdFn = FRVI->second.first;
7540 if (FwdFn->getType() != PFT)
7541 return error(FRVI->second.second,
7542 "invalid forward reference to "
7543 "function '" +
7544 FunctionName +
7545 "' with wrong type: "
7546 "expected '" +
7547 getTypeString(PFT) + "' but was '" +
7548 getTypeString(FwdFn->getType()) + "'");
7549 ForwardRefVals.erase(FRVI);
7550 } else if ((Fn = M->getFunction(FunctionName))) {
7551 // Reject redefinitions.
7552 return error(NameLoc,
7553 "invalid redefinition of function '" + FunctionName + "'");
7554 } else if (M->getNamedValue(FunctionName)) {
7555 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
7556 }
7557
7558 } else {
7559 // Handle @"", where a name is syntactically specified, but semantically
7560 // missing.
7561 if (FunctionNumber == (unsigned)-1)
7562 FunctionNumber = NumberedVals.getNext();
7563
7564 // If this is a definition of a forward referenced function, make sure the
7565 // types agree.
7566 auto I = ForwardRefValIDs.find(FunctionNumber);
7567 if (I != ForwardRefValIDs.end()) {
7568 FwdFn = I->second.first;
7569 if (FwdFn->getType() != PFT)
7570 return error(NameLoc, "type of definition and forward reference of '@" +
7571 Twine(FunctionNumber) +
7572 "' disagree: "
7573 "expected '" +
7574 getTypeString(PFT) + "' but was '" +
7575 getTypeString(FwdFn->getType()) + "'");
7576 ForwardRefValIDs.erase(I);
7577 }
7578 }
7579
7581 FunctionName, M);
7582
7583 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
7584
7585 if (FunctionName.empty())
7586 NumberedVals.add(FunctionNumber, Fn);
7587
7589 maybeSetDSOLocal(DSOLocal, *Fn);
7592 Fn->setCallingConv(CC);
7593 Fn->setAttributes(PAL);
7594 Fn->setUnnamedAddr(UnnamedAddr);
7595 if (Alignment)
7596 Fn->setAlignment(*Alignment);
7597 Fn->setPreferredAlignment(PrefAlignment);
7598 Fn->setSection(Section);
7599 Fn->setPartition(Partition);
7600 Fn->setComdat(C);
7601 Fn->setPersonalityFn(PersonalityFn);
7602 if (!GC.empty()) Fn->setGC(GC);
7603 Fn->setPrefixData(Prefix);
7604 Fn->setPrologueData(Prologue);
7605 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7606
7607 // Add all of the arguments we parsed to the function.
7608 Function::arg_iterator ArgIt = Fn->arg_begin();
7609 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7610 if (ParserContext && ArgList[i].IdentLoc)
7611 ParserContext->addInstructionOrArgumentLocation(
7612 &*ArgIt, ArgList[i].IdentLoc.value());
7613 // If the argument has a name, insert it into the argument symbol table.
7614 if (ArgList[i].Name.empty()) continue;
7615
7616 // Set the name, if it conflicted, it will be auto-renamed.
7617 ArgIt->setName(ArgList[i].Name);
7618
7619 if (ArgIt->getName() != ArgList[i].Name)
7620 return error(ArgList[i].Loc,
7621 "redefinition of argument '%" + ArgList[i].Name + "'");
7622 }
7623
7624 if (FwdFn) {
7625 FwdFn->replaceAllUsesWith(Fn);
7626 FwdFn->eraseFromParent();
7627 }
7628
7629 if (IsDefine)
7630 return false;
7631
7632 // Check the declaration has no block address forward references.
7633 ValID ID;
7634 if (FunctionName.empty()) {
7635 ID.Kind = ValID::t_GlobalID;
7636 ID.UIntVal = FunctionNumber;
7637 } else {
7638 ID.Kind = ValID::t_GlobalName;
7639 ID.StrVal = FunctionName;
7640 }
7641 auto Blocks = ForwardRefBlockAddresses.find(ID);
7642 if (Blocks != ForwardRefBlockAddresses.end())
7643 return error(Blocks->first.Loc,
7644 "cannot take blockaddress inside a declaration");
7645 return false;
7646}
7647
7648bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7649 ValID ID;
7650 if (FunctionNumber == -1) {
7651 ID.Kind = ValID::t_GlobalName;
7652 ID.StrVal = std::string(F.getName());
7653 } else {
7654 ID.Kind = ValID::t_GlobalID;
7655 ID.UIntVal = FunctionNumber;
7656 }
7657
7658 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7659 if (Blocks == P.ForwardRefBlockAddresses.end())
7660 return false;
7661
7662 for (const auto &I : Blocks->second) {
7663 const ValID &BBID = I.first;
7664 GlobalValue *GV = I.second;
7665
7666 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7667 "Expected local id or name");
7668 BasicBlock *BB;
7669 if (BBID.Kind == ValID::t_LocalName)
7670 BB = getBB(BBID.StrVal, BBID.Loc);
7671 else
7672 BB = getBB(BBID.UIntVal, BBID.Loc);
7673 if (!BB)
7674 return P.error(BBID.Loc, "referenced value is not a basic block");
7675
7676 Value *ResolvedVal = BlockAddress::get(&F, BB);
7677 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7678 ResolvedVal);
7679 if (!ResolvedVal)
7680 return true;
7681 GV->replaceAllUsesWith(ResolvedVal);
7682 GV->eraseFromParent();
7683 }
7684
7685 P.ForwardRefBlockAddresses.erase(Blocks);
7686 return false;
7687}
7688
7689/// parseFunctionBody
7690/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7691bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7692 ArrayRef<unsigned> UnnamedArgNums) {
7693 if (Lex.getKind() != lltok::lbrace)
7694 return tokError("expected '{' in function body");
7695 Lex.Lex(); // eat the {.
7696
7697 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7698
7699 // Resolve block addresses and allow basic blocks to be forward-declared
7700 // within this function.
7701 if (PFS.resolveForwardRefBlockAddresses())
7702 return true;
7703 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7704
7705 // We need at least one basic block.
7706 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7707 return tokError("function body requires at least one basic block");
7708
7709 while (Lex.getKind() != lltok::rbrace &&
7710 Lex.getKind() != lltok::kw_uselistorder)
7711 if (parseBasicBlock(PFS))
7712 return true;
7713
7714 while (Lex.getKind() != lltok::rbrace)
7715 if (parseUseListOrder(&PFS))
7716 return true;
7717
7718 // Eat the }.
7719 Lex.Lex();
7720
7721 // Verify function is ok.
7722 return PFS.finishFunction();
7723}
7724
7725/// parseBasicBlock
7726/// ::= (LabelStr|LabelID)? Instruction*
7727bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7728 FileLoc BBStart = getTokLineColumnPos();
7729
7730 // If this basic block starts out with a name, remember it.
7731 std::string Name;
7732 int NameID = -1;
7733 LocTy NameLoc = Lex.getLoc();
7734 if (Lex.getKind() == lltok::LabelStr) {
7735 Name = Lex.getStrVal();
7736 Lex.Lex();
7737 } else if (Lex.getKind() == lltok::LabelID) {
7738 NameID = Lex.getUIntVal();
7739 Lex.Lex();
7740 }
7741
7742 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7743 if (!BB)
7744 return true;
7745
7746 std::string NameStr;
7747
7748 // Parse the instructions and debug values in this block until we get a
7749 // terminator.
7750 Instruction *Inst;
7751 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7752 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7753 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7754 do {
7755 // Handle debug records first - there should always be an instruction
7756 // following the debug records, i.e. they cannot appear after the block
7757 // terminator.
7758 while (Lex.getKind() == lltok::hash) {
7759 if (SeenOldDbgInfoFormat)
7760 return error(Lex.getLoc(), "debug record should not appear in a module "
7761 "containing debug info intrinsics");
7762 SeenNewDbgInfoFormat = true;
7763 Lex.Lex();
7764
7765 DbgRecord *DR;
7766 if (parseDebugRecord(DR, PFS))
7767 return true;
7768 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7769 }
7770
7771 FileLoc InstStart = getTokLineColumnPos();
7772 // This instruction may have three possibilities for a name: a) none
7773 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7774 LocTy NameLoc = Lex.getLoc();
7775 int NameID = -1;
7776 NameStr = "";
7777
7778 if (Lex.getKind() == lltok::LocalVarID) {
7779 NameID = Lex.getUIntVal();
7780 Lex.Lex();
7781 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7782 return true;
7783 } else if (Lex.getKind() == lltok::LocalVar) {
7784 NameStr = Lex.getStrVal();
7785 Lex.Lex();
7786 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7787 return true;
7788 }
7789
7790 switch (parseInstruction(Inst, BB, PFS)) {
7791 default:
7792 llvm_unreachable("Unknown parseInstruction result!");
7793 case InstError: return true;
7794 case InstNormal:
7795 Inst->insertInto(BB, BB->end());
7796
7797 // With a normal result, we check to see if the instruction is followed by
7798 // a comma and metadata.
7799 if (EatIfPresent(lltok::comma))
7800 if (parseInstructionMetadata(*Inst))
7801 return true;
7802 break;
7803 case InstExtraComma:
7804 Inst->insertInto(BB, BB->end());
7805
7806 // If the instruction parser ate an extra comma at the end of it, it
7807 // *must* be followed by metadata.
7808 if (parseInstructionMetadata(*Inst))
7809 return true;
7810 break;
7811 }
7812
7813 // Set the name on the instruction.
7814 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7815 return true;
7816
7817 // Attach any preceding debug values to this instruction.
7818 for (DbgRecordPtr &DR : TrailingDbgRecord)
7819 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7820 TrailingDbgRecord.clear();
7821 if (ParserContext) {
7822 ParserContext->addInstructionOrArgumentLocation(
7823 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7824 }
7825 } while (!Inst->isTerminator());
7826
7827 if (ParserContext)
7828 ParserContext->addBlockLocation(
7829 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7830
7831 assert(TrailingDbgRecord.empty() &&
7832 "All debug values should have been attached to an instruction.");
7833
7834 return false;
7835}
7836
7837/// parseDebugRecord
7838/// ::= #dbg_label '(' MDNode ')'
7839/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7840/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7841bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7842 using RecordKind = DbgRecord::Kind;
7843 using LocType = DbgVariableRecord::LocationType;
7844 LocTy DVRLoc = Lex.getLoc();
7845 if (Lex.getKind() != lltok::DbgRecordType)
7846 return error(DVRLoc, "expected debug record type here");
7847 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7848 .Case("declare", RecordKind::ValueKind)
7849 .Case("value", RecordKind::ValueKind)
7850 .Case("assign", RecordKind::ValueKind)
7851 .Case("label", RecordKind::LabelKind)
7852 .Case("declare_value", RecordKind::ValueKind);
7853
7854 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7855 // full DbgVariableRecord processing stage.
7856 if (RecordType == RecordKind::LabelKind) {
7857 Lex.Lex();
7858 if (parseToken(lltok::lparen, "Expected '(' here"))
7859 return true;
7860 MDNode *Label;
7861 if (parseMDNode(Label))
7862 return true;
7863 if (parseToken(lltok::comma, "Expected ',' here"))
7864 return true;
7865 MDNode *DbgLoc;
7866 if (parseMDNode(DbgLoc))
7867 return true;
7868 if (parseToken(lltok::rparen, "Expected ')' here"))
7869 return true;
7871 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7872 return false;
7873 }
7874
7875 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7876 .Case("declare", LocType::Declare)
7877 .Case("value", LocType::Value)
7878 .Case("assign", LocType::Assign)
7879 .Case("declare_value", LocType::DeclareValue);
7880
7881 Lex.Lex();
7882 if (parseToken(lltok::lparen, "Expected '(' here"))
7883 return true;
7884
7885 // Parse Value field.
7886 Metadata *ValLocMD;
7887 if (parseMetadata(ValLocMD, &PFS))
7888 return true;
7889 if (parseToken(lltok::comma, "Expected ',' here"))
7890 return true;
7891
7892 // Parse Variable field.
7893 MDNode *Variable;
7894 if (parseMDNode(Variable))
7895 return true;
7896 if (parseToken(lltok::comma, "Expected ',' here"))
7897 return true;
7898
7899 // Parse Expression field.
7900 MDNode *Expression;
7901 if (parseMDNode(Expression))
7902 return true;
7903 if (parseToken(lltok::comma, "Expected ',' here"))
7904 return true;
7905
7906 // Parse additional fields for #dbg_assign.
7907 MDNode *AssignID = nullptr;
7908 Metadata *AddressLocation = nullptr;
7909 MDNode *AddressExpression = nullptr;
7910 if (ValueType == LocType::Assign) {
7911 // Parse DIAssignID.
7912 if (parseMDNode(AssignID))
7913 return true;
7914 if (parseToken(lltok::comma, "Expected ',' here"))
7915 return true;
7916
7917 // Parse address ValueAsMetadata.
7918 if (parseMetadata(AddressLocation, &PFS))
7919 return true;
7920 if (parseToken(lltok::comma, "Expected ',' here"))
7921 return true;
7922
7923 // Parse address DIExpression.
7924 if (parseMDNode(AddressExpression))
7925 return true;
7926 if (parseToken(lltok::comma, "Expected ',' here"))
7927 return true;
7928 }
7929
7930 /// Parse DILocation.
7931 MDNode *DebugLoc;
7932 if (parseMDNode(DebugLoc))
7933 return true;
7934
7935 if (parseToken(lltok::rparen, "Expected ')' here"))
7936 return true;
7938 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7939 AddressExpression);
7940 PendingDbgRecords.emplace_back(DVRLoc, DR, DebugLoc);
7941 return false;
7942}
7943//===----------------------------------------------------------------------===//
7944// Instruction Parsing.
7945//===----------------------------------------------------------------------===//
7946
7947/// parseInstruction - parse one of the many different instructions.
7948///
7949int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7950 PerFunctionState &PFS) {
7951 lltok::Kind Token = Lex.getKind();
7952 if (Token == lltok::Eof)
7953 return tokError("found end of file when expecting more instructions");
7954 LocTy Loc = Lex.getLoc();
7955 unsigned KeywordVal = Lex.getUIntVal();
7956 Lex.Lex(); // Eat the keyword.
7957
7958 switch (Token) {
7959 default:
7960 return error(Loc, "expected instruction opcode");
7961 // Terminator Instructions.
7962 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7963 case lltok::kw_ret:
7964 return parseRet(Inst, BB, PFS);
7965 case lltok::kw_br:
7966 return parseBr(Inst, PFS);
7967 case lltok::kw_switch:
7968 return parseSwitch(Inst, PFS);
7970 return parseIndirectBr(Inst, PFS);
7971 case lltok::kw_invoke:
7972 return parseInvoke(Inst, PFS);
7973 case lltok::kw_resume:
7974 return parseResume(Inst, PFS);
7976 return parseCleanupRet(Inst, PFS);
7977 case lltok::kw_catchret:
7978 return parseCatchRet(Inst, PFS);
7980 return parseCatchSwitch(Inst, PFS);
7981 case lltok::kw_catchpad:
7982 return parseCatchPad(Inst, PFS);
7984 return parseCleanupPad(Inst, PFS);
7985 case lltok::kw_callbr:
7986 return parseCallBr(Inst, PFS);
7987 // Unary Operators.
7988 case lltok::kw_fneg: {
7989 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7990 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7991 if (Res != 0)
7992 return Res;
7993 if (FMF.any())
7994 Inst->setFastMathFlags(FMF);
7995 return false;
7996 }
7997 // Binary Operators.
7998 case lltok::kw_add:
7999 case lltok::kw_sub:
8000 case lltok::kw_mul:
8001 case lltok::kw_shl: {
8002 bool NUW = EatIfPresent(lltok::kw_nuw);
8003 bool NSW = EatIfPresent(lltok::kw_nsw);
8004 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
8005
8006 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
8007 return true;
8008
8009 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
8010 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
8011 return false;
8012 }
8013 case lltok::kw_fadd:
8014 case lltok::kw_fsub:
8015 case lltok::kw_fmul:
8016 case lltok::kw_fdiv:
8017 case lltok::kw_frem: {
8018 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8019 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
8020 if (Res != 0)
8021 return Res;
8022 if (FMF.any())
8023 Inst->setFastMathFlags(FMF);
8024 return 0;
8025 }
8026
8027 case lltok::kw_sdiv:
8028 case lltok::kw_udiv:
8029 case lltok::kw_lshr:
8030 case lltok::kw_ashr: {
8031 bool Exact = EatIfPresent(lltok::kw_exact);
8032
8033 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
8034 return true;
8035 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
8036 return false;
8037 }
8038
8039 case lltok::kw_urem:
8040 case lltok::kw_srem:
8041 return parseArithmetic(Inst, PFS, KeywordVal,
8042 /*IsFP*/ false);
8043 case lltok::kw_or: {
8044 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
8045 if (parseLogical(Inst, PFS, KeywordVal))
8046 return true;
8047 if (Disjoint)
8048 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
8049 return false;
8050 }
8051 case lltok::kw_and:
8052 case lltok::kw_xor:
8053 return parseLogical(Inst, PFS, KeywordVal);
8054 case lltok::kw_icmp: {
8055 bool SameSign = EatIfPresent(lltok::kw_samesign);
8056 if (parseCompare(Inst, PFS, KeywordVal))
8057 return true;
8058 if (SameSign)
8059 cast<ICmpInst>(Inst)->setSameSign();
8060 return false;
8061 }
8062 case lltok::kw_fcmp: {
8063 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8064 int Res = parseCompare(Inst, PFS, KeywordVal);
8065 if (Res != 0)
8066 return Res;
8067 if (FMF.any())
8068 Inst->setFastMathFlags(FMF);
8069 return 0;
8070 }
8071
8072 // Casts.
8073 case lltok::kw_uitofp: {
8074 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8075 bool NonNeg = EatIfPresent(lltok::kw_nneg);
8076 bool Res = parseCast(Inst, PFS, KeywordVal);
8077 if (Res != 0)
8078 return Res;
8079 if (NonNeg)
8080 Inst->setNonNeg();
8081 Inst->setFastMathFlags(FMF);
8082 return 0;
8083 }
8084 case lltok::kw_zext: {
8085 bool NonNeg = EatIfPresent(lltok::kw_nneg);
8086 bool Res = parseCast(Inst, PFS, KeywordVal);
8087 if (Res != 0)
8088 return Res;
8089 if (NonNeg)
8090 Inst->setNonNeg();
8091 return 0;
8092 }
8093 case lltok::kw_trunc: {
8094 bool NUW = EatIfPresent(lltok::kw_nuw);
8095 bool NSW = EatIfPresent(lltok::kw_nsw);
8096 if (!NUW)
8097 NUW = EatIfPresent(lltok::kw_nuw);
8098 if (parseCast(Inst, PFS, KeywordVal))
8099 return true;
8100 if (NUW)
8101 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
8102 if (NSW)
8103 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
8104 return false;
8105 }
8107 bool NonNull = EatIfPresent(lltok::kw_nonnull);
8108 if (parseCast(Inst, PFS, KeywordVal))
8109 return true;
8110 if (NonNull)
8111 cast<AddrSpaceCastInst>(Inst)->setNonNull();
8112 return false;
8113 }
8114 case lltok::kw_sext:
8115 case lltok::kw_bitcast:
8116 case lltok::kw_fptoui:
8117 case lltok::kw_fptosi:
8118 case lltok::kw_inttoptr:
8120 case lltok::kw_ptrtoint:
8121 return parseCast(Inst, PFS, KeywordVal);
8122 case lltok::kw_fptrunc:
8123 case lltok::kw_fpext:
8124 case lltok::kw_sitofp: {
8125 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8126 if (parseCast(Inst, PFS, KeywordVal))
8127 return true;
8128 if (FMF.any())
8129 Inst->setFastMathFlags(FMF);
8130 return false;
8131 }
8132
8133 // Other.
8134 case lltok::kw_select: {
8135 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8136 int Res = parseSelect(Inst, PFS);
8137 if (Res != 0)
8138 return Res;
8139 if (FMF.any()) {
8140 if (!isa<FPMathOperator>(Inst)) {
8141 Inst->deleteValue();
8142 return error(Loc, "fast-math-flags specified for select without "
8143 "floating-point scalar or vector return type");
8144 }
8145 Inst->setFastMathFlags(FMF);
8146 }
8147 return 0;
8148 }
8149 case lltok::kw_va_arg:
8150 return parseVAArg(Inst, PFS);
8152 return parseExtractElement(Inst, PFS);
8154 return parseInsertElement(Inst, PFS);
8156 return parseShuffleVector(Inst, PFS);
8157 case lltok::kw_phi: {
8158 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8159 int Res = parsePHI(Inst, PFS);
8160 if (Res != 0)
8161 return Res;
8162 if (FMF.any()) {
8163 if (!isa<FPMathOperator>(Inst)) {
8164 Inst->deleteValue();
8165 return error(Loc, "fast-math-flags specified for phi without "
8166 "floating-point scalar or vector return type");
8167 }
8168 Inst->setFastMathFlags(FMF);
8169 }
8170 return 0;
8171 }
8173 return parseLandingPad(Inst, PFS);
8174 case lltok::kw_freeze:
8175 return parseFreeze(Inst, PFS);
8177 return parseBitInsert(Inst, PFS);
8179 return parseBitExtract(Inst, PFS);
8180 // Call.
8181 case lltok::kw_call:
8182 return parseCall(Inst, PFS, CallInst::TCK_None);
8183 case lltok::kw_tail:
8184 return parseCall(Inst, PFS, CallInst::TCK_Tail);
8185 case lltok::kw_musttail:
8186 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
8187 case lltok::kw_notail:
8188 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
8189 // Memory.
8190 case lltok::kw_alloca:
8191 return parseAlloc(Inst, PFS);
8192 case lltok::kw_load:
8193 return parseLoad(Inst, PFS);
8194 case lltok::kw_store:
8195 return parseStore(Inst, PFS);
8196 case lltok::kw_cmpxchg:
8197 return parseCmpXchg(Inst, PFS);
8199 return parseAtomicRMW(Inst, PFS);
8200 case lltok::kw_fence:
8201 return parseFence(Inst, PFS);
8203 return parseGetElementPtr(Inst, PFS);
8205 return parseExtractValue(Inst, PFS);
8207 return parseInsertValue(Inst, PFS);
8208 }
8209}
8210
8211/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
8212bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
8213 if (Opc == Instruction::FCmp) {
8214 switch (Lex.getKind()) {
8215 default:
8216 return tokError("expected fcmp predicate (e.g. 'oeq')");
8217 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
8218 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
8219 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
8220 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
8221 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
8222 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
8223 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
8224 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
8225 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
8226 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
8227 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
8228 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
8229 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
8230 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
8231 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
8232 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
8233 }
8234 } else {
8235 switch (Lex.getKind()) {
8236 default:
8237 return tokError("expected icmp predicate (e.g. 'eq')");
8238 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
8239 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
8240 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
8241 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
8242 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
8243 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
8244 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
8245 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
8246 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
8247 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
8248 }
8249 }
8250 Lex.Lex();
8251 return false;
8252}
8253
8254//===----------------------------------------------------------------------===//
8255// Terminator Instructions.
8256//===----------------------------------------------------------------------===//
8257
8258/// parseRet - parse a return instruction.
8259/// ::= 'ret' void (',' !dbg, !1)*
8260/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
8261bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
8262 PerFunctionState &PFS) {
8263 SMLoc TypeLoc = Lex.getLoc();
8264 Type *Ty = nullptr;
8265 if (parseType(Ty, true /*void allowed*/))
8266 return true;
8267
8268 Type *ResType = PFS.getFunction().getReturnType();
8269
8270 if (Ty->isVoidTy()) {
8271 if (!ResType->isVoidTy())
8272 return error(TypeLoc, "value doesn't match function result type '" +
8273 getTypeString(ResType) + "'");
8274
8275 Inst = ReturnInst::Create(Context);
8276 return false;
8277 }
8278
8279 Value *RV;
8280 if (parseValue(Ty, RV, PFS))
8281 return true;
8282
8283 if (ResType != RV->getType())
8284 return error(TypeLoc, "value doesn't match function result type '" +
8285 getTypeString(ResType) + "'");
8286
8287 Inst = ReturnInst::Create(Context, RV);
8288 return false;
8289}
8290
8291/// parseBr
8292/// ::= 'br' TypeAndValue
8293/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8294bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
8295 LocTy Loc, Loc2;
8296 Value *Op0;
8297 BasicBlock *Op1, *Op2;
8298 if (parseTypeAndValue(Op0, Loc, PFS))
8299 return true;
8300
8301 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
8302 Inst = UncondBrInst::Create(BB);
8303 return false;
8304 }
8305
8306 if (Op0->getType() != Type::getInt1Ty(Context))
8307 return error(Loc, "branch condition must have 'i1' type");
8308
8309 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
8310 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
8311 parseToken(lltok::comma, "expected ',' after true destination") ||
8312 parseTypeAndBasicBlock(Op2, Loc2, PFS))
8313 return true;
8314
8315 Inst = CondBrInst::Create(Op0, Op1, Op2);
8316 return false;
8317}
8318
8319/// parseSwitch
8320/// Instruction
8321/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
8322/// JumpTable
8323/// ::= (TypeAndValue ',' TypeAndValue)*
8324bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8325 LocTy CondLoc, BBLoc;
8326 Value *Cond;
8327 BasicBlock *DefaultBB;
8328 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
8329 parseToken(lltok::comma, "expected ',' after switch condition") ||
8330 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
8331 parseToken(lltok::lsquare, "expected '[' with switch table"))
8332 return true;
8333
8334 if (!Cond->getType()->isIntegerTy())
8335 return error(CondLoc, "switch condition must have integer type");
8336
8337 // parse the jump table pairs.
8338 SmallPtrSet<Value*, 32> SeenCases;
8340 while (Lex.getKind() != lltok::rsquare) {
8341 Value *Constant;
8342 BasicBlock *DestBB;
8343
8344 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8345 parseToken(lltok::comma, "expected ',' after case value") ||
8346 parseTypeAndBasicBlock(DestBB, PFS))
8347 return true;
8348
8349 if (!SeenCases.insert(Constant).second)
8350 return error(CondLoc, "duplicate case value in switch");
8351 if (!isa<ConstantInt>(Constant))
8352 return error(CondLoc, "case value is not a constant integer");
8353
8354 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
8355 }
8356
8357 Lex.Lex(); // Eat the ']'.
8358
8359 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
8360 for (const auto &[OnVal, Dest] : Table)
8361 SI->addCase(OnVal, Dest);
8362 Inst = SI;
8363 return false;
8364}
8365
8366/// parseIndirectBr
8367/// Instruction
8368/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
8369bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8370 LocTy AddrLoc;
8371 Value *Address;
8372 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
8373 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
8374 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
8375 return true;
8376
8377 if (!Address->getType()->isPointerTy())
8378 return error(AddrLoc, "indirectbr address must have pointer type");
8379
8380 // parse the destination list.
8381 SmallVector<BasicBlock*, 16> DestList;
8382
8383 if (Lex.getKind() != lltok::rsquare) {
8384 BasicBlock *DestBB;
8385 if (parseTypeAndBasicBlock(DestBB, PFS))
8386 return true;
8387 DestList.push_back(DestBB);
8388
8389 while (EatIfPresent(lltok::comma)) {
8390 if (parseTypeAndBasicBlock(DestBB, PFS))
8391 return true;
8392 DestList.push_back(DestBB);
8393 }
8394 }
8395
8396 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8397 return true;
8398
8399 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
8400 for (BasicBlock *Dest : DestList)
8401 IBI->addDestination(Dest);
8402 Inst = IBI;
8403 return false;
8404}
8405
8406// If RetType is a non-function pointer type, then this is the short syntax
8407// for the call, which means that RetType is just the return type. Infer the
8408// rest of the function argument types from the arguments that are present.
8409bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
8410 FunctionType *&FuncTy) {
8411 FuncTy = dyn_cast<FunctionType>(RetType);
8412 if (!FuncTy) {
8413 // Pull out the types of all of the arguments...
8414 SmallVector<Type *, 8> ParamTypes;
8415 ParamTypes.reserve(ArgList.size());
8416 for (const ParamInfo &Arg : ArgList)
8417 ParamTypes.push_back(Arg.V->getType());
8418
8419 if (!FunctionType::isValidReturnType(RetType))
8420 return true;
8421
8422 FuncTy = FunctionType::get(RetType, ParamTypes, false);
8423 }
8424 return false;
8425}
8426
8427/// parseInvoke
8428/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
8429/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
8430bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8431 LocTy CallLoc = Lex.getLoc();
8432 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8433 std::vector<unsigned> FwdRefAttrGrps;
8434 LocTy NoBuiltinLoc;
8435 unsigned CC;
8436 unsigned InvokeAddrSpace;
8437 Type *RetType = nullptr;
8438 LocTy RetTypeLoc;
8439 ValID CalleeID;
8442
8443 BasicBlock *NormalBB, *UnwindBB;
8444 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8445 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8446 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8447 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8448 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8449 NoBuiltinLoc) ||
8450 parseOptionalOperandBundles(BundleList, PFS) ||
8451 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
8452 parseTypeAndBasicBlock(NormalBB, PFS) ||
8453 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
8454 parseTypeAndBasicBlock(UnwindBB, PFS))
8455 return true;
8456
8457 // If RetType is a non-function pointer type, then this is the short syntax
8458 // for the call, which means that RetType is just the return type. Infer the
8459 // rest of the function argument types from the arguments that are present.
8460 FunctionType *Ty;
8461 if (resolveFunctionType(RetType, ArgList, Ty))
8462 return error(RetTypeLoc, "Invalid result type for LLVM function");
8463
8464 CalleeID.FTy = Ty;
8465
8466 // Look up the callee.
8467 Value *Callee;
8468 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
8469 Callee, &PFS))
8470 return true;
8471
8472 // Set up the Attribute for the function.
8473 SmallVector<Value *, 8> Args;
8475
8476 // Loop through FunctionType's arguments and ensure they are specified
8477 // correctly. Also, gather any parameter attributes.
8478 FunctionType::param_iterator I = Ty->param_begin();
8479 FunctionType::param_iterator E = Ty->param_end();
8480 for (const ParamInfo &Arg : ArgList) {
8481 Type *ExpectedTy = nullptr;
8482 if (I != E) {
8483 ExpectedTy = *I++;
8484 } else if (!Ty->isVarArg()) {
8485 return error(Arg.Loc, "too many arguments specified");
8486 }
8487
8488 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8489 return error(Arg.Loc, "argument is not of expected type '" +
8490 getTypeString(ExpectedTy) + "'");
8491 Args.push_back(Arg.V);
8492 ArgAttrs.push_back(Arg.Attrs);
8493 }
8494
8495 if (I != E)
8496 return error(CallLoc, "not enough parameters specified for call");
8497
8498 // Finish off the Attribute and check them
8499 AttributeList PAL =
8500 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8501 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8502
8503 InvokeInst *II =
8504 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
8505 II->setCallingConv(CC);
8506 II->setAttributes(PAL);
8507 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
8508 Inst = II;
8509 return false;
8510}
8511
8512/// parseResume
8513/// ::= 'resume' TypeAndValue
8514bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8515 Value *Exn; LocTy ExnLoc;
8516 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8517 return true;
8518
8519 ResumeInst *RI = ResumeInst::Create(Exn);
8520 Inst = RI;
8521 return false;
8522}
8523
8524bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8525 PerFunctionState &PFS) {
8526 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
8527 return true;
8528
8529 while (Lex.getKind() != lltok::rsquare) {
8530 // If this isn't the first argument, we need a comma.
8531 if (!Args.empty() &&
8532 parseToken(lltok::comma, "expected ',' in argument list"))
8533 return true;
8534
8535 // parse the argument.
8536 LocTy ArgLoc;
8537 Type *ArgTy = nullptr;
8538 if (parseType(ArgTy, ArgLoc))
8539 return true;
8540
8541 Value *V;
8542 if (ArgTy->isMetadataTy()) {
8543 if (parseMetadataAsValue(V, PFS))
8544 return true;
8545 } else {
8546 if (parseValue(ArgTy, V, PFS))
8547 return true;
8548 }
8549 Args.push_back(V);
8550 }
8551
8552 Lex.Lex(); // Lex the ']'.
8553 return false;
8554}
8555
8556/// parseCleanupRet
8557/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
8558bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8559 Value *CleanupPad = nullptr;
8560
8561 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
8562 return true;
8563
8564 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
8565 return true;
8566
8567 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
8568 return true;
8569
8570 BasicBlock *UnwindBB = nullptr;
8571 if (Lex.getKind() == lltok::kw_to) {
8572 Lex.Lex();
8573 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
8574 return true;
8575 } else {
8576 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8577 return true;
8578 }
8579 }
8580
8581 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
8582 return false;
8583}
8584
8585/// parseCatchRet
8586/// ::= 'catchret' from Parent Value 'to' TypeAndValue
8587bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8588 Value *CatchPad = nullptr;
8589
8590 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
8591 return true;
8592
8593 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
8594 return true;
8595
8596 BasicBlock *BB;
8597 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
8598 parseTypeAndBasicBlock(BB, PFS))
8599 return true;
8600
8601 Inst = CatchReturnInst::Create(CatchPad, BB);
8602 return false;
8603}
8604
8605/// parseCatchSwitch
8606/// ::= 'catchswitch' within Parent
8607bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8608 Value *ParentPad;
8609
8610 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
8611 return true;
8612
8613 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8614 Lex.getKind() != lltok::LocalVarID)
8615 return tokError("expected scope value for catchswitch");
8616
8617 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8618 return true;
8619
8620 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
8621 return true;
8622
8624 do {
8625 BasicBlock *DestBB;
8626 if (parseTypeAndBasicBlock(DestBB, PFS))
8627 return true;
8628 Table.push_back(DestBB);
8629 } while (EatIfPresent(lltok::comma));
8630
8631 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
8632 return true;
8633
8634 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
8635 return true;
8636
8637 BasicBlock *UnwindBB = nullptr;
8638 if (EatIfPresent(lltok::kw_to)) {
8639 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
8640 return true;
8641 } else {
8642 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8643 return true;
8644 }
8645
8646 auto *CatchSwitch =
8647 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
8648 for (BasicBlock *DestBB : Table)
8649 CatchSwitch->addHandler(DestBB);
8650 Inst = CatchSwitch;
8651 return false;
8652}
8653
8654/// parseCatchPad
8655/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
8656bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8657 Value *CatchSwitch = nullptr;
8658
8659 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
8660 return true;
8661
8662 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
8663 return tokError("expected scope value for catchpad");
8664
8665 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
8666 return true;
8667
8668 SmallVector<Value *, 8> Args;
8669 if (parseExceptionArgs(Args, PFS))
8670 return true;
8671
8672 Inst = CatchPadInst::Create(CatchSwitch, Args);
8673 return false;
8674}
8675
8676/// parseCleanupPad
8677/// ::= 'cleanuppad' within Parent ParamList
8678bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8679 Value *ParentPad = nullptr;
8680
8681 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
8682 return true;
8683
8684 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8685 Lex.getKind() != lltok::LocalVarID)
8686 return tokError("expected scope value for cleanuppad");
8687
8688 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8689 return true;
8690
8691 SmallVector<Value *, 8> Args;
8692 if (parseExceptionArgs(Args, PFS))
8693 return true;
8694
8695 Inst = CleanupPadInst::Create(ParentPad, Args);
8696 return false;
8697}
8698
8699//===----------------------------------------------------------------------===//
8700// Unary Operators.
8701//===----------------------------------------------------------------------===//
8702
8703/// parseUnaryOp
8704/// ::= UnaryOp TypeAndValue ',' Value
8705///
8706/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8707/// operand is allowed.
8708bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8709 unsigned Opc, bool IsFP) {
8710 LocTy Loc; Value *LHS;
8711 if (parseTypeAndValue(LHS, Loc, PFS))
8712 return true;
8713
8714 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8716
8717 if (!Valid)
8718 return error(Loc, "invalid operand type for instruction");
8719
8721 return false;
8722}
8723
8724/// parseCallBr
8725/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8726/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8727/// '[' LabelList ']'
8728bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8729 LocTy CallLoc = Lex.getLoc();
8730 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8731 std::vector<unsigned> FwdRefAttrGrps;
8732 LocTy NoBuiltinLoc;
8733 unsigned CC;
8734 Type *RetType = nullptr;
8735 LocTy RetTypeLoc;
8736 ValID CalleeID;
8739
8740 BasicBlock *DefaultDest;
8741 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8742 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8743 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8744 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8745 NoBuiltinLoc) ||
8746 parseOptionalOperandBundles(BundleList, PFS) ||
8747 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8748 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8749 parseToken(lltok::lsquare, "expected '[' in callbr"))
8750 return true;
8751
8752 // parse the destination list.
8753 SmallVector<BasicBlock *, 16> IndirectDests;
8754
8755 if (Lex.getKind() != lltok::rsquare) {
8756 BasicBlock *DestBB;
8757 if (parseTypeAndBasicBlock(DestBB, PFS))
8758 return true;
8759 IndirectDests.push_back(DestBB);
8760
8761 while (EatIfPresent(lltok::comma)) {
8762 if (parseTypeAndBasicBlock(DestBB, PFS))
8763 return true;
8764 IndirectDests.push_back(DestBB);
8765 }
8766 }
8767
8768 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8769 return true;
8770
8771 // If RetType is a non-function pointer type, then this is the short syntax
8772 // for the call, which means that RetType is just the return type. Infer the
8773 // rest of the function argument types from the arguments that are present.
8774 FunctionType *Ty;
8775 if (resolveFunctionType(RetType, ArgList, Ty))
8776 return error(RetTypeLoc, "Invalid result type for LLVM function");
8777
8778 CalleeID.FTy = Ty;
8779
8780 // Look up the callee.
8781 Value *Callee;
8782 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8783 &PFS))
8784 return true;
8785
8786 // Set up the Attribute for the function.
8787 SmallVector<Value *, 8> Args;
8789
8790 // Loop through FunctionType's arguments and ensure they are specified
8791 // correctly. Also, gather any parameter attributes.
8792 FunctionType::param_iterator I = Ty->param_begin();
8793 FunctionType::param_iterator E = Ty->param_end();
8794 for (const ParamInfo &Arg : ArgList) {
8795 Type *ExpectedTy = nullptr;
8796 if (I != E) {
8797 ExpectedTy = *I++;
8798 } else if (!Ty->isVarArg()) {
8799 return error(Arg.Loc, "too many arguments specified");
8800 }
8801
8802 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8803 return error(Arg.Loc, "argument is not of expected type '" +
8804 getTypeString(ExpectedTy) + "'");
8805 Args.push_back(Arg.V);
8806 ArgAttrs.push_back(Arg.Attrs);
8807 }
8808
8809 if (I != E)
8810 return error(CallLoc, "not enough parameters specified for call");
8811
8812 // Finish off the Attribute and check them
8813 AttributeList PAL =
8814 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8815 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8816
8817 CallBrInst *CBI =
8818 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8819 BundleList);
8820 CBI->setCallingConv(CC);
8821 CBI->setAttributes(PAL);
8822 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8823 Inst = CBI;
8824 return false;
8825}
8826
8827//===----------------------------------------------------------------------===//
8828// Binary Operators.
8829//===----------------------------------------------------------------------===//
8830
8831/// parseArithmetic
8832/// ::= ArithmeticOps TypeAndValue ',' Value
8833///
8834/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8835/// operand is allowed.
8836bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8837 unsigned Opc, bool IsFP) {
8838 LocTy Loc; Value *LHS, *RHS;
8839 if (parseTypeAndValue(LHS, Loc, PFS) ||
8840 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8841 parseValue(LHS->getType(), RHS, PFS))
8842 return true;
8843
8844 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8846
8847 if (!Valid)
8848 return error(Loc, "invalid operand type for instruction");
8849
8851 return false;
8852}
8853
8854/// parseLogical
8855/// ::= ArithmeticOps TypeAndValue ',' Value {
8856bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8857 unsigned Opc) {
8858 LocTy Loc; Value *LHS, *RHS;
8859 if (parseTypeAndValue(LHS, Loc, PFS) ||
8860 parseToken(lltok::comma, "expected ',' in logical operation") ||
8861 parseValue(LHS->getType(), RHS, PFS))
8862 return true;
8863
8864 if (!LHS->getType()->isIntOrIntVectorTy())
8865 return error(Loc,
8866 "instruction requires integer or integer vector operands");
8867
8869 return false;
8870}
8871
8872/// parseCompare
8873/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8874/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8875bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8876 unsigned Opc) {
8877 // parse the integer/fp comparison predicate.
8878 LocTy Loc;
8879 unsigned Pred;
8880 Value *LHS, *RHS;
8881 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8882 parseToken(lltok::comma, "expected ',' after compare value") ||
8883 parseValue(LHS->getType(), RHS, PFS))
8884 return true;
8885
8886 if (Opc == Instruction::FCmp) {
8887 if (!LHS->getType()->isFPOrFPVectorTy())
8888 return error(Loc, "fcmp requires floating point operands");
8889 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8890 } else {
8891 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8892 if (!LHS->getType()->isIntOrIntVectorTy() &&
8894 return error(Loc, "icmp requires integer operands");
8895 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8896 }
8897 return false;
8898}
8899
8900//===----------------------------------------------------------------------===//
8901// Other Instructions.
8902//===----------------------------------------------------------------------===//
8903
8904/// parseCast
8905/// ::= CastOpc TypeAndValue 'to' Type
8906bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8907 unsigned Opc) {
8908 LocTy Loc;
8909 Value *Op;
8910 Type *DestTy = nullptr;
8911 if (parseTypeAndValue(Op, Loc, PFS) ||
8912 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8913 parseType(DestTy))
8914 return true;
8915
8917 return error(Loc, "invalid cast opcode for cast from '" +
8918 getTypeString(Op->getType()) + "' to '" +
8919 getTypeString(DestTy) + "'");
8920 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8921 return false;
8922}
8923
8924/// parseSelect
8925/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8926bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8927 LocTy Loc;
8928 Value *Op0, *Op1, *Op2;
8929 if (parseTypeAndValue(Op0, Loc, PFS) ||
8930 parseToken(lltok::comma, "expected ',' after select condition") ||
8931 parseTypeAndValue(Op1, PFS) ||
8932 parseToken(lltok::comma, "expected ',' after select value") ||
8933 parseTypeAndValue(Op2, PFS))
8934 return true;
8935
8936 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8937 return error(Loc, Reason);
8938
8939 Inst = SelectInst::Create(Op0, Op1, Op2);
8940 return false;
8941}
8942
8943/// parseVAArg
8944/// ::= 'va_arg' TypeAndValue ',' Type
8945bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8946 Value *Op;
8947 Type *EltTy = nullptr;
8948 LocTy TypeLoc;
8949 if (parseTypeAndValue(Op, PFS) ||
8950 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8951 parseType(EltTy, TypeLoc))
8952 return true;
8953
8954 if (!EltTy->isFirstClassType())
8955 return error(TypeLoc, "va_arg requires operand with first class type");
8956
8957 Inst = new VAArgInst(Op, EltTy);
8958 return false;
8959}
8960
8961/// parseExtractElement
8962/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8963bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8964 LocTy Loc;
8965 Value *Op0, *Op1;
8966 if (parseTypeAndValue(Op0, Loc, PFS) ||
8967 parseToken(lltok::comma, "expected ',' after extract value") ||
8968 parseTypeAndValue(Op1, PFS))
8969 return true;
8970
8972 return error(Loc, "invalid extractelement operands");
8973
8974 Inst = ExtractElementInst::Create(Op0, Op1);
8975 return false;
8976}
8977
8978/// parseInsertElement
8979/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8980bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8981 LocTy Loc;
8982 Value *Op0, *Op1, *Op2;
8983 if (parseTypeAndValue(Op0, Loc, PFS) ||
8984 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8985 parseTypeAndValue(Op1, PFS) ||
8986 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8987 parseTypeAndValue(Op2, PFS))
8988 return true;
8989
8990 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8991 return error(Loc, "invalid insertelement operands");
8992
8993 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8994 return false;
8995}
8996
8997// parseBitExtract
8998// ::= 'bitextract' Type ',' TypeAndValue ',' TypeAndValue
8999bool LLParser::parseBitExtract(Instruction *&Inst, PerFunctionState &PFS) {
9000 LocTy Loc;
9001 Type *Ty = nullptr;
9002 Value *Op0, *Op1;
9003 if (parseType(Ty, Loc) ||
9004 parseToken(lltok::comma, "expected ',' after bitextract type") ||
9005 parseTypeAndValue(Op0, Loc, PFS) ||
9006 parseToken(lltok::comma, "expected ',' after bitextract source value") ||
9007 parseTypeAndValue(Op1, PFS))
9008 return true;
9009
9010 if (const char *Reason = BitExtractInst::areInvalidOperands(Ty, Op0, Op1))
9011 return error(Loc, Reason);
9012
9013 Inst = BitExtractInst::Create(Ty, Op0, Op1);
9014 return false;
9015}
9016
9017// parseBitInsert
9018// ::= 'bitinsert' TypeAndValue ',' TypeAndValue ',' TypeAndValue
9019bool LLParser::parseBitInsert(Instruction *&Inst, PerFunctionState &PFS) {
9020 LocTy Loc;
9021 Value *Op0, *Op1, *Op2;
9022 if (parseTypeAndValue(Op0, Loc, PFS) ||
9023 parseToken(lltok::comma, "expected ',' after bitinsert source value") ||
9024 parseTypeAndValue(Op1, PFS) ||
9025 parseToken(lltok::comma, "expected ',' after bitinsert insert value") ||
9026 parseTypeAndValue(Op2, PFS))
9027 return true;
9028
9029 if (const char *Reason = BitInsertInst::areInvalidOperands(Op0, Op1, Op2))
9030 return error(Loc, Reason);
9031
9032 Inst = BitInsertInst::Create(Op0, Op1, Op2);
9033 return false;
9034}
9035
9036/// parseShuffleVector
9037/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
9038bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
9039 LocTy Loc;
9040 Value *Op0, *Op1, *Op2;
9041 if (parseTypeAndValue(Op0, Loc, PFS) ||
9042 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
9043 parseTypeAndValue(Op1, PFS) ||
9044 parseToken(lltok::comma, "expected ',' after shuffle value") ||
9045 parseTypeAndValue(Op2, PFS))
9046 return true;
9047
9048 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
9049 return error(Loc, "invalid shufflevector operands");
9050
9051 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
9052 return false;
9053}
9054
9055/// parsePHI
9056/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
9057int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
9058 Type *Ty = nullptr; LocTy TypeLoc;
9059 Value *Op0, *Op1;
9060
9061 if (parseType(Ty, TypeLoc))
9062 return true;
9063
9064 if (!Ty->isFirstClassType())
9065 return error(TypeLoc, "phi node must have first class type");
9066
9067 bool First = true;
9068 bool AteExtraComma = false;
9070
9071 while (true) {
9072 if (First) {
9073 if (Lex.getKind() != lltok::lsquare)
9074 break;
9075 First = false;
9076 } else if (!EatIfPresent(lltok::comma))
9077 break;
9078
9079 if (Lex.getKind() == lltok::MetadataVar) {
9080 AteExtraComma = true;
9081 break;
9082 }
9083
9084 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
9085 parseValue(Ty, Op0, PFS) ||
9086 parseToken(lltok::comma, "expected ',' after insertelement value") ||
9087 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
9088 parseToken(lltok::rsquare, "expected ']' in phi value list"))
9089 return true;
9090
9091 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
9092 }
9093
9094 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
9095 for (const auto &[Val, BB] : PHIVals)
9096 PN->addIncoming(Val, BB);
9097 Inst = PN;
9098 return AteExtraComma ? InstExtraComma : InstNormal;
9099}
9100
9101/// parseLandingPad
9102/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
9103/// Clause
9104/// ::= 'catch' TypeAndValue
9105/// ::= 'filter'
9106/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
9107bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
9108 Type *Ty = nullptr; LocTy TyLoc;
9109
9110 if (parseType(Ty, TyLoc))
9111 return true;
9112
9113 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
9114 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
9115
9116 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
9118 if (EatIfPresent(lltok::kw_catch))
9120 else if (EatIfPresent(lltok::kw_filter))
9122 else
9123 return tokError("expected 'catch' or 'filter' clause type");
9124
9125 Value *V;
9126 LocTy VLoc;
9127 if (parseTypeAndValue(V, VLoc, PFS))
9128 return true;
9129
9130 // A 'catch' type expects a non-array constant. A filter clause expects an
9131 // array constant.
9132 if (CT == LandingPadInst::Catch) {
9133 if (isa<ArrayType>(V->getType()))
9134 return error(VLoc, "'catch' clause has an invalid type");
9135 } else {
9136 if (!isa<ArrayType>(V->getType()))
9137 return error(VLoc, "'filter' clause has an invalid type");
9138 }
9139
9141 if (!CV)
9142 return error(VLoc, "clause argument must be a constant");
9143 LP->addClause(CV);
9144 }
9145
9146 Inst = LP.release();
9147 return false;
9148}
9149
9150/// parseFreeze
9151/// ::= 'freeze' Type Value
9152bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
9153 LocTy Loc;
9154 Value *Op;
9155 if (parseTypeAndValue(Op, Loc, PFS))
9156 return true;
9157
9158 Inst = new FreezeInst(Op);
9159 return false;
9160}
9161
9162/// parseCall
9163/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
9164/// OptionalAttrs Type Value ParameterList OptionalAttrs
9165/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
9166/// OptionalAttrs Type Value ParameterList OptionalAttrs
9167/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
9168/// OptionalAttrs Type Value ParameterList OptionalAttrs
9169/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
9170/// OptionalAttrs Type Value ParameterList OptionalAttrs
9171bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
9173 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
9174 std::vector<unsigned> FwdRefAttrGrps;
9175 LocTy BuiltinLoc;
9176 unsigned CallAddrSpace;
9177 unsigned CC;
9178 Type *RetType = nullptr;
9179 LocTy RetTypeLoc;
9180 ValID CalleeID;
9183 LocTy CallLoc = Lex.getLoc();
9184
9185 if (TCK != CallInst::TCK_None &&
9186 parseToken(lltok::kw_call,
9187 "expected 'tail call', 'musttail call', or 'notail call'"))
9188 return true;
9189
9190 FastMathFlags FMF = EatFastMathFlagsIfPresent();
9191
9192 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
9193 parseOptionalProgramAddrSpace(CallAddrSpace) ||
9194 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
9195 parseValID(CalleeID, &PFS) ||
9196 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
9197 PFS.getFunction().isVarArg()) ||
9198 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
9199 parseOptionalOperandBundles(BundleList, PFS))
9200 return true;
9201
9202 // If RetType is a non-function pointer type, then this is the short syntax
9203 // for the call, which means that RetType is just the return type. Infer the
9204 // rest of the function argument types from the arguments that are present.
9205 FunctionType *Ty;
9206 if (resolveFunctionType(RetType, ArgList, Ty))
9207 return error(RetTypeLoc, "Invalid result type for LLVM function");
9208
9209 CalleeID.FTy = Ty;
9210
9211 // Look up the callee.
9212 Value *Callee;
9213 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
9214 Callee, &PFS))
9215 return true;
9216
9217 // Set up the Attribute for the function.
9219
9220 SmallVector<Value*, 8> Args;
9221
9222 // Loop through FunctionType's arguments and ensure they are specified
9223 // correctly. Also, gather any parameter attributes.
9224 FunctionType::param_iterator I = Ty->param_begin();
9225 FunctionType::param_iterator E = Ty->param_end();
9226 for (const ParamInfo &Arg : ArgList) {
9227 Type *ExpectedTy = nullptr;
9228 if (I != E) {
9229 ExpectedTy = *I++;
9230 } else if (!Ty->isVarArg()) {
9231 return error(Arg.Loc, "too many arguments specified");
9232 }
9233
9234 if (ExpectedTy && ExpectedTy != Arg.V->getType())
9235 return error(Arg.Loc, "argument is not of expected type '" +
9236 getTypeString(ExpectedTy) + "'");
9237 Args.push_back(Arg.V);
9238 Attrs.push_back(Arg.Attrs);
9239 }
9240
9241 if (I != E)
9242 return error(CallLoc, "not enough parameters specified for call");
9243
9244 // Finish off the Attribute and check them
9245 AttributeList PAL =
9246 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
9247 AttributeSet::get(Context, RetAttrs), Attrs);
9248
9249 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
9250 CI->setTailCallKind(TCK);
9251 CI->setCallingConv(CC);
9252 if (FMF.any()) {
9253 if (!isa<FPMathOperator>(CI)) {
9254 CI->deleteValue();
9255 return error(CallLoc, "fast-math-flags specified for call without "
9256 "floating-point scalar or vector return type");
9257 }
9258 CI->setFastMathFlags(FMF);
9259 }
9260
9261 if (CalleeID.Kind == ValID::t_GlobalName &&
9262 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
9263 if (SeenNewDbgInfoFormat) {
9264 CI->deleteValue();
9265 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
9266 "using non-intrinsic debug info");
9267 }
9268 SeenOldDbgInfoFormat = true;
9269 }
9270 CI->setAttributes(PAL);
9271 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
9272 Inst = CI;
9273 return false;
9274}
9275
9276//===----------------------------------------------------------------------===//
9277// Memory Instructions.
9278//===----------------------------------------------------------------------===//
9279
9280/// parseAlloc
9281/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
9282/// (',' 'align' i32)? (',', 'addrspace(n))?
9283int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
9284 Value *Size = nullptr;
9285 LocTy SizeLoc, TyLoc, ASLoc;
9286 MaybeAlign Alignment;
9287 unsigned AddrSpace = 0;
9288 Type *Ty = nullptr;
9289
9290 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
9291 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
9292
9293 if (parseType(Ty, TyLoc))
9294 return true;
9295
9297 return error(TyLoc, "invalid type for alloca");
9298
9299 bool AteExtraComma = false;
9300 if (EatIfPresent(lltok::comma)) {
9301 if (Lex.getKind() == lltok::kw_align) {
9302 if (parseOptionalAlignment(Alignment))
9303 return true;
9304 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9305 return true;
9306 } else if (Lex.getKind() == lltok::kw_addrspace) {
9307 ASLoc = Lex.getLoc();
9308 if (parseOptionalAddrSpace(AddrSpace))
9309 return true;
9310 } else if (Lex.getKind() == lltok::MetadataVar) {
9311 AteExtraComma = true;
9312 } else {
9313 if (parseTypeAndValue(Size, SizeLoc, PFS))
9314 return true;
9315 if (EatIfPresent(lltok::comma)) {
9316 if (Lex.getKind() == lltok::kw_align) {
9317 if (parseOptionalAlignment(Alignment))
9318 return true;
9319 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9320 return true;
9321 } else if (Lex.getKind() == lltok::kw_addrspace) {
9322 ASLoc = Lex.getLoc();
9323 if (parseOptionalAddrSpace(AddrSpace))
9324 return true;
9325 } else if (Lex.getKind() == lltok::MetadataVar) {
9326 AteExtraComma = true;
9327 }
9328 }
9329 }
9330 }
9331
9332 if (Size && !Size->getType()->isIntegerTy())
9333 return error(SizeLoc, "element count must have integer type");
9334
9335 if (!Alignment && !Ty->isSized())
9336 return error(TyLoc, "Cannot allocate unsized type");
9337 if (!Alignment)
9338 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
9339 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
9340 AI->setUsedWithInAlloca(IsInAlloca);
9341 AI->setSwiftError(IsSwiftError);
9342 Inst = AI;
9343 return AteExtraComma ? InstExtraComma : InstNormal;
9344}
9345
9346/// parseLoad
9347/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
9348/// ::= 'load' 'atomic' 'volatile'? 'elementwise'? TypeAndValue
9349/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
9350int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
9351 Value *Val; LocTy Loc;
9352 MaybeAlign Alignment;
9353 bool AteExtraComma = false;
9354 bool isAtomic = false;
9357
9358 if (Lex.getKind() == lltok::kw_atomic) {
9359 isAtomic = true;
9360 Lex.Lex();
9361 }
9362
9363 bool isVolatile = false;
9364 if (Lex.getKind() == lltok::kw_volatile) {
9365 isVolatile = true;
9366 Lex.Lex();
9367 }
9368
9369 bool IsElementwise = false;
9370 if (Lex.getKind() == lltok::kw_elementwise) {
9371 IsElementwise = true;
9372 Lex.Lex();
9373 }
9374
9375 Type *Ty;
9376 LocTy ExplicitTypeLoc = Lex.getLoc();
9377 if (parseType(Ty) ||
9378 parseToken(lltok::comma, "expected comma after load's type") ||
9379 parseTypeAndValue(Val, Loc, PFS) ||
9380 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9381 parseOptionalCommaAlign(Alignment, AteExtraComma))
9382 return true;
9383
9384 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
9385 return error(Loc, "load operand must be a pointer to a first class type");
9386
9387 if (IsElementwise && !isAtomic)
9388 return error(Loc, "elementwise load must be atomic");
9389
9390 if (IsElementwise && !isa<FixedVectorType>(Ty))
9391 return error(ExplicitTypeLoc,
9392 "atomic elementwise load operand must have fixed vector type");
9393
9394 if (isAtomic && !Alignment)
9395 return error(Loc, "atomic load must have explicit non-zero alignment");
9396
9397 if (Ordering == AtomicOrdering::Release ||
9399 return error(Loc, "atomic load cannot use Release ordering");
9400 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9401 return error(Loc,
9402 "atomic elementwise load cannot be sequentially consistent");
9403
9404 if (!Alignment && !Ty->isSized())
9405 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
9406 if (!Alignment)
9407 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9408 Inst = new LoadInst(Ty, Val, "",
9409 LoadStoreInstProperties{isVolatile, *Alignment, Ordering,
9410 SSID, IsElementwise},
9411 /*InsertBefore=*/nullptr);
9412 return AteExtraComma ? InstExtraComma : InstNormal;
9413}
9414
9415/// parseStore
9416
9417/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
9418/// ::= 'store' 'atomic' 'volatile'? 'elementwise'? TypeAndValue ','
9419/// TypeAndValue 'singlethread'? AtomicOrdering (',' 'align' i32)?
9420int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9421 Value *Val, *Ptr;
9422 LocTy Loc, PtrLoc;
9423 MaybeAlign Alignment;
9424 bool AteExtraComma = false;
9425 bool isAtomic = false;
9428
9429 if (Lex.getKind() == lltok::kw_atomic) {
9430 isAtomic = true;
9431 Lex.Lex();
9432 }
9433
9434 bool isVolatile = false;
9435 if (Lex.getKind() == lltok::kw_volatile) {
9436 isVolatile = true;
9437 Lex.Lex();
9438 }
9439
9440 bool IsElementwise = false;
9441 if (Lex.getKind() == lltok::kw_elementwise) {
9442 IsElementwise = true;
9443 Lex.Lex();
9444 }
9445
9446 if (parseTypeAndValue(Val, Loc, PFS) ||
9447 parseToken(lltok::comma, "expected ',' after store operand") ||
9448 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9449 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9450 parseOptionalCommaAlign(Alignment, AteExtraComma))
9451 return true;
9452
9453 if (!Ptr->getType()->isPointerTy())
9454 return error(PtrLoc, "store operand must be a pointer");
9455 if (!Val->getType()->isFirstClassType())
9456 return error(Loc, "store operand must be a first class value");
9457 if (isAtomic && !Alignment)
9458 return error(Loc, "atomic store must have explicit non-zero alignment");
9459 if (Ordering == AtomicOrdering::Acquire ||
9461 return error(Loc, "atomic store cannot use Acquire ordering");
9462
9463 if (IsElementwise && !isAtomic)
9464 return error(Loc, "elementwise store must be atomic");
9465
9466 if (IsElementwise && !isa<FixedVectorType>(Val->getType()))
9467 return error(
9468 Loc, "atomic elementwise store operand must have fixed vector type");
9469
9470 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9471 return error(Loc,
9472 "atomic elementwise store cannot be sequentially consistent");
9473
9474 if (!Alignment && !Val->getType()->isSized())
9475 return error(Loc, "storing unsized types is not allowed");
9476 if (!Alignment)
9477 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
9478
9479 Inst = new StoreInst(Val, Ptr,
9480 LoadStoreInstProperties{isVolatile, *Alignment, Ordering,
9481 SSID, IsElementwise},
9482 /*InsertBefore=*/nullptr);
9483 return AteExtraComma ? InstExtraComma : InstNormal;
9484}
9485
9486/// parseCmpXchg
9487/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
9488/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
9489/// 'Align'?
9490int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9491 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
9492 bool AteExtraComma = false;
9493 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
9494 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
9496 bool isVolatile = false;
9497 bool isWeak = false;
9498 MaybeAlign Alignment;
9499
9500 if (EatIfPresent(lltok::kw_weak))
9501 isWeak = true;
9502
9503 if (EatIfPresent(lltok::kw_volatile))
9504 isVolatile = true;
9505
9506 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9507 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
9508 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9509 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
9510 parseTypeAndValue(New, NewLoc, PFS) ||
9511 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
9512 parseOrdering(FailureOrdering) ||
9513 parseOptionalCommaAlign(Alignment, AteExtraComma))
9514 return true;
9515
9516 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
9517 return tokError("invalid cmpxchg success ordering");
9518 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
9519 return tokError("invalid cmpxchg failure ordering");
9520 if (!Ptr->getType()->isPointerTy())
9521 return error(PtrLoc, "cmpxchg operand must be a pointer");
9522 if (Cmp->getType() != New->getType())
9523 return error(NewLoc, "compare value and new value type do not match");
9524 if (!New->getType()->isFirstClassType())
9525 return error(NewLoc, "cmpxchg operand must be a first class value");
9526
9527 const Align DefaultAlignment(
9528 PFS.getFunction().getDataLayout().getTypeStoreSize(
9529 Cmp->getType()));
9530
9531 AtomicCmpXchgInst *CXI =
9532 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
9533 SuccessOrdering, FailureOrdering, SSID);
9534 CXI->setVolatile(isVolatile);
9535 CXI->setWeak(isWeak);
9536
9537 Inst = CXI;
9538 return AteExtraComma ? InstExtraComma : InstNormal;
9539}
9540
9541/// parseAtomicRMW
9542/// ::= 'atomicrmw' 'volatile'? 'elementwise'? BinOp TypeAndValue ','
9543/// TypeAndValue
9544/// 'singlethread'? AtomicOrdering
9545int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9546 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
9547 bool AteExtraComma = false;
9550 bool IsVolatile = false;
9551 bool IsElementwise = false;
9552 bool IsFP = false;
9554 MaybeAlign Alignment;
9555
9556 if (EatIfPresent(lltok::kw_volatile))
9557 IsVolatile = true;
9558 if (EatIfPresent(lltok::kw_elementwise))
9559 IsElementwise = true;
9560
9561 switch (Lex.getKind()) {
9562 default:
9563 return tokError("expected binary operation in atomicrmw");
9577 break;
9580 break;
9583 break;
9584 case lltok::kw_usub_sat:
9586 break;
9587 case lltok::kw_fadd:
9589 IsFP = true;
9590 break;
9591 case lltok::kw_fsub:
9593 IsFP = true;
9594 break;
9595 case lltok::kw_fmax:
9597 IsFP = true;
9598 break;
9599 case lltok::kw_fmin:
9601 IsFP = true;
9602 break;
9603 case lltok::kw_fmaximum:
9605 IsFP = true;
9606 break;
9607 case lltok::kw_fminimum:
9609 IsFP = true;
9610 break;
9613 IsFP = true;
9614 break;
9617 IsFP = true;
9618 break;
9619 }
9620 Lex.Lex(); // Eat the operation.
9621
9622 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9623 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
9624 parseTypeAndValue(Val, ValLoc, PFS) ||
9625 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
9626 parseOptionalCommaAlign(Alignment, AteExtraComma))
9627 return true;
9628
9629 if (Ordering == AtomicOrdering::Unordered)
9630 return tokError("atomicrmw cannot be unordered");
9631 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9632 return tokError("atomicrmw elementwise cannot be sequentially consistent");
9633 if (!Ptr->getType()->isPointerTy())
9634 return error(PtrLoc, "atomicrmw operand must be a pointer");
9635 if (Val->getType()->isScalableTy())
9636 return error(ValLoc, "atomicrmw operand may not be scalable");
9637
9638 Type *ValTy = Val->getType();
9639 if (IsElementwise) {
9640 if (!isa<FixedVectorType>(Val->getType()))
9641 return error(ValLoc,
9642 "atomicrmw elementwise operand must be a fixed vector type");
9643 }
9644
9646 if (!ValTy->isIntOrIntVectorTy() && !ValTy->isFPOrFPVectorTy() &&
9647 !ValTy->isPtrOrPtrVectorTy()) {
9648 return error(
9649 ValLoc,
9651 " operand must be an integer type, a floating-point type, a "
9652 "pointer type, or a fixed vector of any of these types");
9653 }
9654 } else if (IsFP) {
9655 if (!ValTy->isFPOrFPVectorTy()) {
9656 return error(ValLoc, "atomicrmw " +
9658 " operand must be a floating point or fixed "
9659 "vector of floating point type");
9660 }
9661 } else {
9662 if (!ValTy->isIntOrIntVectorTy()) {
9663 return error(
9664 ValLoc,
9666 " operand must be an integer or fixed vector of integer type");
9667 }
9668 }
9669
9670 unsigned Size =
9671 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9672 if (Size < 8 || (Size & (Size - 1)))
9673 return error(ValLoc,
9674 "atomicrmw operand must have a power-of-two byte size");
9675 const Align DefaultAlignment(
9676 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->getType()));
9677 AtomicRMWInst *RMWI = new AtomicRMWInst(Operation, Ptr, Val,
9678 Alignment.value_or(DefaultAlignment),
9679 Ordering, SSID, IsElementwise);
9680 RMWI->setVolatile(IsVolatile);
9681 Inst = RMWI;
9682 return AteExtraComma ? InstExtraComma : InstNormal;
9683}
9684
9685/// parseFence
9686/// ::= 'fence' 'singlethread'? AtomicOrdering
9687int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9690 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
9691 return true;
9692
9693 if (Ordering == AtomicOrdering::Unordered)
9694 return tokError("fence cannot be unordered");
9695 if (Ordering == AtomicOrdering::Monotonic)
9696 return tokError("fence cannot be monotonic");
9697
9698 Inst = new FenceInst(Context, Ordering, SSID);
9699 return InstNormal;
9700}
9701
9702/// parseGetElementPtr
9703/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9704int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9705 Value *Ptr = nullptr;
9706 Value *Val = nullptr;
9707 LocTy Loc, EltLoc;
9708 GEPNoWrapFlags NW;
9709
9710 while (true) {
9711 if (EatIfPresent(lltok::kw_inbounds))
9713 else if (EatIfPresent(lltok::kw_nusw))
9715 else if (EatIfPresent(lltok::kw_nuw))
9717 else
9718 break;
9719 }
9720
9721 Type *Ty = nullptr;
9722 if (parseType(Ty) ||
9723 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
9724 parseTypeAndValue(Ptr, Loc, PFS))
9725 return true;
9726
9727 Type *BaseType = Ptr->getType();
9728 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
9729 if (!BasePointerType)
9730 return error(Loc, "base of getelementptr must be a pointer");
9731
9732 SmallVector<Value*, 16> Indices;
9733 bool AteExtraComma = false;
9734 // GEP returns a vector of pointers if at least one of parameters is a vector.
9735 // All vector parameters should have the same vector width.
9736 ElementCount GEPWidth = BaseType->isVectorTy()
9737 ? cast<VectorType>(BaseType)->getElementCount()
9739
9740 while (EatIfPresent(lltok::comma)) {
9741 if (Lex.getKind() == lltok::MetadataVar) {
9742 AteExtraComma = true;
9743 break;
9744 }
9745 if (parseTypeAndValue(Val, EltLoc, PFS))
9746 return true;
9747 if (!Val->getType()->isIntOrIntVectorTy())
9748 return error(EltLoc, "getelementptr index must be an integer");
9749
9750 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
9751 ElementCount ValNumEl = ValVTy->getElementCount();
9752 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
9753 return error(
9754 EltLoc,
9755 "getelementptr vector index has a wrong number of elements");
9756 GEPWidth = ValNumEl;
9757 }
9758 Indices.push_back(Val);
9759 }
9760
9761 if (!Indices.empty() && !Ty->isSized())
9762 return error(Loc, "base element of getelementptr must be sized");
9763
9764 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
9765 return error(Loc, "invalid getelementptr indices");
9766 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
9767 Inst = GEP;
9768 GEP->setNoWrapFlags(NW);
9769 return AteExtraComma ? InstExtraComma : InstNormal;
9770}
9771
9772/// parseExtractValue
9773/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9774int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9775 Value *Val; LocTy Loc;
9776 SmallVector<unsigned, 4> Indices;
9777 bool AteExtraComma;
9778 if (parseTypeAndValue(Val, Loc, PFS) ||
9779 parseIndexList(Indices, AteExtraComma))
9780 return true;
9781
9782 if (!Val->getType()->isAggregateType())
9783 return error(Loc, "extractvalue operand must be aggregate type");
9784
9785 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9786 return error(Loc, "invalid indices for extractvalue");
9787 Inst = ExtractValueInst::Create(Val, Indices);
9788 return AteExtraComma ? InstExtraComma : InstNormal;
9789}
9790
9791/// parseInsertValue
9792/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9793int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9794 Value *Val0, *Val1; LocTy Loc0, Loc1;
9795 SmallVector<unsigned, 4> Indices;
9796 bool AteExtraComma;
9797 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9798 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9799 parseTypeAndValue(Val1, Loc1, PFS) ||
9800 parseIndexList(Indices, AteExtraComma))
9801 return true;
9802
9803 if (!Val0->getType()->isAggregateType())
9804 return error(Loc0, "insertvalue operand must be aggregate type");
9805
9806 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9807 if (!IndexedType)
9808 return error(Loc0, "invalid indices for insertvalue");
9809 if (IndexedType != Val1->getType())
9810 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9811 getTypeString(Val1->getType()) + "' instead of '" +
9812 getTypeString(IndexedType) + "'");
9813 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9814 return AteExtraComma ? InstExtraComma : InstNormal;
9815}
9816
9817//===----------------------------------------------------------------------===//
9818// Embedded metadata.
9819//===----------------------------------------------------------------------===//
9820
9821/// parseMDNodeVector
9822/// ::= { Element (',' Element)* }
9823/// Element
9824/// ::= 'null' | Metadata
9825bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9826 if (parseToken(lltok::lbrace, "expected '{' here"))
9827 return true;
9828
9829 // Check for an empty list.
9830 if (EatIfPresent(lltok::rbrace))
9831 return false;
9832
9833 do {
9834 if (EatIfPresent(lltok::kw_null)) {
9835 Elts.push_back(nullptr);
9836 continue;
9837 }
9838
9839 Metadata *MD;
9840 if (parseMetadata(MD, nullptr))
9841 return true;
9842 Elts.push_back(MD);
9843 } while (EatIfPresent(lltok::comma));
9844
9845 return parseToken(lltok::rbrace, "expected end of metadata node");
9846}
9847
9848//===----------------------------------------------------------------------===//
9849// Use-list order directives.
9850//===----------------------------------------------------------------------===//
9851bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9852 SMLoc Loc) {
9853 if (!V->hasUseList())
9854 return false;
9855 if (V->use_empty())
9856 return error(Loc, "value has no uses");
9857
9858 unsigned NumUses = 0;
9859 SmallDenseMap<const Use *, unsigned, 16> Order;
9860 for (const Use &U : V->uses()) {
9861 if (++NumUses > Indexes.size())
9862 break;
9863 Order[&U] = Indexes[NumUses - 1];
9864 }
9865 if (NumUses < 2)
9866 return error(Loc, "value only has one use");
9867 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9868 return error(Loc,
9869 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9870
9871 V->sortUseList([&](const Use &L, const Use &R) {
9872 return Order.lookup(&L) < Order.lookup(&R);
9873 });
9874 return false;
9875}
9876
9877/// parseUseListOrderIndexes
9878/// ::= '{' uint32 (',' uint32)+ '}'
9879bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9880 SMLoc Loc = Lex.getLoc();
9881 if (parseToken(lltok::lbrace, "expected '{' here"))
9882 return true;
9883 if (Lex.getKind() == lltok::rbrace)
9884 return tokError("expected non-empty list of uselistorder indexes");
9885
9886 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9887 // indexes should be distinct numbers in the range [0, size-1], and should
9888 // not be in order.
9889 unsigned Offset = 0;
9890 unsigned Max = 0;
9891 bool IsOrdered = true;
9892 assert(Indexes.empty() && "Expected empty order vector");
9893 do {
9894 unsigned Index;
9895 if (parseUInt32(Index))
9896 return true;
9897
9898 // Update consistency checks.
9899 Offset += Index - Indexes.size();
9900 Max = std::max(Max, Index);
9901 IsOrdered &= Index == Indexes.size();
9902
9903 Indexes.push_back(Index);
9904 } while (EatIfPresent(lltok::comma));
9905
9906 if (parseToken(lltok::rbrace, "expected '}' here"))
9907 return true;
9908
9909 if (Indexes.size() < 2)
9910 return error(Loc, "expected >= 2 uselistorder indexes");
9911 if (Offset != 0 || Max >= Indexes.size())
9912 return error(Loc,
9913 "expected distinct uselistorder indexes in range [0, size)");
9914 if (IsOrdered)
9915 return error(Loc, "expected uselistorder indexes to change the order");
9916
9917 return false;
9918}
9919
9920/// parseUseListOrder
9921/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9922bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9923 SMLoc Loc = Lex.getLoc();
9924 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9925 return true;
9926
9927 Value *V;
9928 SmallVector<unsigned, 16> Indexes;
9929 if (parseTypeAndValue(V, PFS) ||
9930 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9931 parseUseListOrderIndexes(Indexes))
9932 return true;
9933
9934 return sortUseListOrder(V, Indexes, Loc);
9935}
9936
9937/// ModuleEntry
9938/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9939/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9940bool LLParser::parseModuleEntry(unsigned ID) {
9941 assert(Lex.getKind() == lltok::kw_module);
9942 Lex.Lex();
9943
9944 std::string Path;
9945 if (parseToken(lltok::colon, "expected ':' here") ||
9946 parseToken(lltok::lparen, "expected '(' here") ||
9947 parseToken(lltok::kw_path, "expected 'path' here") ||
9948 parseToken(lltok::colon, "expected ':' here") ||
9949 parseStringConstant(Path) ||
9950 parseToken(lltok::comma, "expected ',' here") ||
9951 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9952 parseToken(lltok::colon, "expected ':' here") ||
9953 parseToken(lltok::lparen, "expected '(' here"))
9954 return true;
9955
9956 ModuleHash Hash;
9957 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9958 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9959 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9960 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9961 parseUInt32(Hash[4]))
9962 return true;
9963
9964 if (parseToken(lltok::rparen, "expected ')' here") ||
9965 parseToken(lltok::rparen, "expected ')' here"))
9966 return true;
9967
9968 auto ModuleEntry = Index->addModule(Path, Hash);
9969 ModuleIdMap[ID] = ModuleEntry->first();
9970
9971 return false;
9972}
9973
9974/// TypeIdEntry
9975/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9976bool LLParser::parseTypeIdEntry(unsigned ID) {
9977 assert(Lex.getKind() == lltok::kw_typeid);
9978 Lex.Lex();
9979
9980 std::string Name;
9981 if (parseToken(lltok::colon, "expected ':' here") ||
9982 parseToken(lltok::lparen, "expected '(' here") ||
9983 parseToken(lltok::kw_name, "expected 'name' here") ||
9984 parseToken(lltok::colon, "expected ':' here") ||
9985 parseStringConstant(Name))
9986 return true;
9987
9988 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9989 if (parseToken(lltok::comma, "expected ',' here") ||
9990 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9991 return true;
9992
9993 // Check if this ID was forward referenced, and if so, update the
9994 // corresponding GUIDs.
9995 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9996 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9997 for (auto TIDRef : FwdRefTIDs->second) {
9998 assert(!*TIDRef.first &&
9999 "Forward referenced type id GUID expected to be 0");
10000 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
10001 }
10002 ForwardRefTypeIds.erase(FwdRefTIDs);
10003 }
10004
10005 return false;
10006}
10007
10008/// TypeIdSummary
10009/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
10010bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
10011 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
10012 parseToken(lltok::colon, "expected ':' here") ||
10013 parseToken(lltok::lparen, "expected '(' here") ||
10014 parseTypeTestResolution(TIS.TTRes))
10015 return true;
10016
10017 if (EatIfPresent(lltok::comma)) {
10018 // Expect optional wpdResolutions field
10019 if (parseOptionalWpdResolutions(TIS.WPDRes))
10020 return true;
10021 }
10022
10023 if (parseToken(lltok::rparen, "expected ')' here"))
10024 return true;
10025
10026 return false;
10027}
10028
10031
10032/// TypeIdCompatibleVtableEntry
10033/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
10034/// TypeIdCompatibleVtableInfo
10035/// ')'
10036bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
10038 Lex.Lex();
10039
10040 std::string Name;
10041 if (parseToken(lltok::colon, "expected ':' here") ||
10042 parseToken(lltok::lparen, "expected '(' here") ||
10043 parseToken(lltok::kw_name, "expected 'name' here") ||
10044 parseToken(lltok::colon, "expected ':' here") ||
10045 parseStringConstant(Name))
10046 return true;
10047
10049 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
10050 if (parseToken(lltok::comma, "expected ',' here") ||
10051 parseToken(lltok::kw_summary, "expected 'summary' here") ||
10052 parseToken(lltok::colon, "expected ':' here") ||
10053 parseToken(lltok::lparen, "expected '(' here"))
10054 return true;
10055
10056 IdToIndexMapType IdToIndexMap;
10057 // parse each call edge
10058 do {
10060 if (parseToken(lltok::lparen, "expected '(' here") ||
10061 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10062 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
10063 parseToken(lltok::comma, "expected ',' here"))
10064 return true;
10065
10066 LocTy Loc = Lex.getLoc();
10067 unsigned GVId;
10068 ValueInfo VI;
10069 if (parseGVReference(VI, GVId))
10070 return true;
10071
10072 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
10073 // forward reference. We will save the location of the ValueInfo needing an
10074 // update, but can only do so once the std::vector is finalized.
10075 if (VI == EmptyVI)
10076 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
10077 TI.push_back({Offset, VI});
10078
10079 if (parseToken(lltok::rparen, "expected ')' in call"))
10080 return true;
10081 } while (EatIfPresent(lltok::comma));
10082
10083 // Now that the TI vector is finalized, it is safe to save the locations
10084 // of any forward GV references that need updating later.
10085 for (auto I : IdToIndexMap) {
10086 auto &Infos = ForwardRefValueInfos[I.first];
10087 for (auto P : I.second) {
10088 assert(TI[P.first].VTableVI == EmptyVI &&
10089 "Forward referenced ValueInfo expected to be empty");
10090 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
10091 }
10092 }
10093
10094 if (parseToken(lltok::rparen, "expected ')' here") ||
10095 parseToken(lltok::rparen, "expected ')' here"))
10096 return true;
10097
10098 // Check if this ID was forward referenced, and if so, update the
10099 // corresponding GUIDs.
10100 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
10101 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
10102 for (auto TIDRef : FwdRefTIDs->second) {
10103 assert(!*TIDRef.first &&
10104 "Forward referenced type id GUID expected to be 0");
10105 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
10106 }
10107 ForwardRefTypeIds.erase(FwdRefTIDs);
10108 }
10109
10110 return false;
10111}
10112
10113/// TypeTestResolution
10114/// ::= 'typeTestRes' ':' '(' 'kind' ':'
10115/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
10116/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
10117/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
10118/// [',' 'inlinesBits' ':' UInt64]? ')'
10119bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
10120 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
10121 parseToken(lltok::colon, "expected ':' here") ||
10122 parseToken(lltok::lparen, "expected '(' here") ||
10123 parseToken(lltok::kw_kind, "expected 'kind' here") ||
10124 parseToken(lltok::colon, "expected ':' here"))
10125 return true;
10126
10127 switch (Lex.getKind()) {
10128 case lltok::kw_unknown:
10130 break;
10131 case lltok::kw_unsat:
10133 break;
10136 break;
10137 case lltok::kw_inline:
10139 break;
10140 case lltok::kw_single:
10142 break;
10143 case lltok::kw_allOnes:
10145 break;
10146 default:
10147 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
10148 }
10149 Lex.Lex();
10150
10151 if (parseToken(lltok::comma, "expected ',' here") ||
10152 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
10153 parseToken(lltok::colon, "expected ':' here") ||
10154 parseUInt32(TTRes.SizeM1BitWidth))
10155 return true;
10156
10157 // parse optional fields
10158 while (EatIfPresent(lltok::comma)) {
10159 switch (Lex.getKind()) {
10161 Lex.Lex();
10162 if (parseToken(lltok::colon, "expected ':'") ||
10163 parseUInt64(TTRes.AlignLog2))
10164 return true;
10165 break;
10166 case lltok::kw_sizeM1:
10167 Lex.Lex();
10168 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
10169 return true;
10170 break;
10171 case lltok::kw_bitMask: {
10172 unsigned Val;
10173 Lex.Lex();
10174 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
10175 return true;
10176 assert(Val <= 0xff);
10177 TTRes.BitMask = (uint8_t)Val;
10178 break;
10179 }
10181 Lex.Lex();
10182 if (parseToken(lltok::colon, "expected ':'") ||
10183 parseUInt64(TTRes.InlineBits))
10184 return true;
10185 break;
10186 default:
10187 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
10188 }
10189 }
10190
10191 if (parseToken(lltok::rparen, "expected ')' here"))
10192 return true;
10193
10194 return false;
10195}
10196
10197/// OptionalWpdResolutions
10198/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
10199/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
10200bool LLParser::parseOptionalWpdResolutions(
10201 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
10202 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
10203 parseToken(lltok::colon, "expected ':' here") ||
10204 parseToken(lltok::lparen, "expected '(' here"))
10205 return true;
10206
10207 do {
10209 WholeProgramDevirtResolution WPDRes;
10210 if (parseToken(lltok::lparen, "expected '(' here") ||
10211 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10212 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
10213 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
10214 parseToken(lltok::rparen, "expected ')' here"))
10215 return true;
10216 WPDResMap[Offset] = WPDRes;
10217 } while (EatIfPresent(lltok::comma));
10218
10219 if (parseToken(lltok::rparen, "expected ')' here"))
10220 return true;
10221
10222 return false;
10223}
10224
10225/// WpdRes
10226/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
10227/// [',' OptionalResByArg]? ')'
10228/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
10229/// ',' 'singleImplName' ':' STRINGCONSTANT ','
10230/// [',' OptionalResByArg]? ')'
10231/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
10232/// [',' OptionalResByArg]? ')'
10233bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
10234 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
10235 parseToken(lltok::colon, "expected ':' here") ||
10236 parseToken(lltok::lparen, "expected '(' here") ||
10237 parseToken(lltok::kw_kind, "expected 'kind' here") ||
10238 parseToken(lltok::colon, "expected ':' here"))
10239 return true;
10240
10241 switch (Lex.getKind()) {
10242 case lltok::kw_indir:
10244 break;
10247 break;
10250 break;
10253 break;
10254 default:
10255 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
10256 }
10257 Lex.Lex();
10258
10259 // parse optional fields
10260 while (EatIfPresent(lltok::comma)) {
10261 switch (Lex.getKind()) {
10263 Lex.Lex();
10264 if (parseToken(lltok::colon, "expected ':' here") ||
10265 parseStringConstant(WPDRes.SingleImplName))
10266 return true;
10267 break;
10268 case lltok::kw_resByArg:
10269 if (parseOptionalResByArg(WPDRes.ResByArg))
10270 return true;
10271 break;
10272 default:
10273 return error(Lex.getLoc(),
10274 "expected optional WholeProgramDevirtResolution field");
10275 }
10276 }
10277
10278 if (parseToken(lltok::rparen, "expected ')' here"))
10279 return true;
10280
10281 return false;
10282}
10283
10284/// OptionalResByArg
10285/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
10286/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
10287/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
10288/// 'virtualConstProp' )
10289/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
10290/// [',' 'bit' ':' UInt32]? ')'
10291bool LLParser::parseOptionalResByArg(
10292 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
10293 &ResByArg) {
10294 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
10295 parseToken(lltok::colon, "expected ':' here") ||
10296 parseToken(lltok::lparen, "expected '(' here"))
10297 return true;
10298
10299 do {
10300 std::vector<uint64_t> Args;
10301 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
10302 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
10303 parseToken(lltok::colon, "expected ':' here") ||
10304 parseToken(lltok::lparen, "expected '(' here") ||
10305 parseToken(lltok::kw_kind, "expected 'kind' here") ||
10306 parseToken(lltok::colon, "expected ':' here"))
10307 return true;
10308
10309 WholeProgramDevirtResolution::ByArg ByArg;
10310 switch (Lex.getKind()) {
10311 case lltok::kw_indir:
10313 break;
10316 break;
10319 break;
10322 break;
10323 default:
10324 return error(Lex.getLoc(),
10325 "unexpected WholeProgramDevirtResolution::ByArg kind");
10326 }
10327 Lex.Lex();
10328
10329 // parse optional fields
10330 while (EatIfPresent(lltok::comma)) {
10331 switch (Lex.getKind()) {
10332 case lltok::kw_info:
10333 Lex.Lex();
10334 if (parseToken(lltok::colon, "expected ':' here") ||
10335 parseUInt64(ByArg.Info))
10336 return true;
10337 break;
10338 case lltok::kw_byte:
10339 Lex.Lex();
10340 if (parseToken(lltok::colon, "expected ':' here") ||
10341 parseUInt32(ByArg.Byte))
10342 return true;
10343 break;
10344 case lltok::kw_bit:
10345 Lex.Lex();
10346 if (parseToken(lltok::colon, "expected ':' here") ||
10347 parseUInt32(ByArg.Bit))
10348 return true;
10349 break;
10350 default:
10351 return error(Lex.getLoc(),
10352 "expected optional whole program devirt field");
10353 }
10354 }
10355
10356 if (parseToken(lltok::rparen, "expected ')' here"))
10357 return true;
10358
10359 ResByArg[Args] = ByArg;
10360 } while (EatIfPresent(lltok::comma));
10361
10362 if (parseToken(lltok::rparen, "expected ')' here"))
10363 return true;
10364
10365 return false;
10366}
10367
10368/// OptionalResByArg
10369/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
10370bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
10371 if (parseToken(lltok::kw_args, "expected 'args' here") ||
10372 parseToken(lltok::colon, "expected ':' here") ||
10373 parseToken(lltok::lparen, "expected '(' here"))
10374 return true;
10375
10376 do {
10377 uint64_t Val;
10378 if (parseUInt64(Val))
10379 return true;
10380 Args.push_back(Val);
10381 } while (EatIfPresent(lltok::comma));
10382
10383 if (parseToken(lltok::rparen, "expected ')' here"))
10384 return true;
10385
10386 return false;
10387}
10388
10390
10391static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
10392 bool ReadOnly = Fwd->isReadOnly();
10393 bool WriteOnly = Fwd->isWriteOnly();
10394 assert(!(ReadOnly && WriteOnly));
10395 *Fwd = Resolved;
10396 if (ReadOnly)
10397 Fwd->setReadOnly();
10398 if (WriteOnly)
10399 Fwd->setWriteOnly();
10400}
10401
10402/// Stores the given Name/GUID and associated summary into the Index.
10403/// Also updates any forward references to the associated entry ID.
10404bool LLParser::addGlobalValueToIndex(
10405 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
10406 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
10407 // First create the ValueInfo utilizing the Name or GUID.
10408 ValueInfo VI;
10409 if (GUID != 0) {
10410 assert(Name.empty());
10411 VI = Index->getOrInsertValueInfo(GUID);
10412 } else {
10413 assert(!Name.empty());
10414 if (M) {
10415 auto *GV = M->getNamedValue(Name);
10416 if (!GV)
10417 return error(Loc, "Reference to undefined global \"" + Name + "\"");
10418
10419 // Be a little lenient here, to accomodate older files without GUIDs
10420 // already computed and assigned as metadata.
10421 GUID = GV->getGUIDOrFallback();
10422
10423 VI = Index->getOrInsertValueInfo(GV, GUID);
10424 } else {
10425 assert(
10426 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
10427 "Need a source_filename to compute GUID for local");
10429 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
10430 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10431 }
10432 }
10433
10434 // Resolve forward references from calls/refs
10435 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10436 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10437 for (auto VIRef : FwdRefVIs->second) {
10438 assert(VIRef.first->getRef() == FwdVIRef &&
10439 "Forward referenced ValueInfo expected to be empty");
10440 resolveFwdRef(VIRef.first, VI);
10441 }
10442 ForwardRefValueInfos.erase(FwdRefVIs);
10443 }
10444
10445 // Resolve forward references from aliases
10446 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10447 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10448 for (auto AliaseeRef : FwdRefAliasees->second) {
10449 assert(!AliaseeRef.first->hasAliasee() &&
10450 "Forward referencing alias already has aliasee");
10451 assert(Summary && "Aliasee must be a definition");
10452 AliaseeRef.first->setAliasee(VI, Summary.get());
10453 }
10454 ForwardRefAliasees.erase(FwdRefAliasees);
10455 }
10456
10457 // Add the summary if one was provided.
10458 if (Summary)
10459 Index->addGlobalValueSummary(VI, std::move(Summary));
10460
10461 // Save the associated ValueInfo for use in later references by ID.
10462 if (ID == NumberedValueInfos.size())
10463 NumberedValueInfos.push_back(VI);
10464 else {
10465 // Handle non-continuous numbers (to make test simplification easier).
10466 if (ID > NumberedValueInfos.size())
10467 NumberedValueInfos.resize(ID + 1);
10468 NumberedValueInfos[ID] = VI;
10469 }
10470
10471 return false;
10472}
10473
10474/// parseSummaryIndexFlags
10475/// ::= 'flags' ':' UInt64
10476bool LLParser::parseSummaryIndexFlags() {
10477 assert(Lex.getKind() == lltok::kw_flags);
10478 Lex.Lex();
10479
10480 if (parseToken(lltok::colon, "expected ':' here"))
10481 return true;
10483 if (parseUInt64(Flags))
10484 return true;
10485 if (Index)
10486 Index->setFlags(Flags);
10487 return false;
10488}
10489
10490/// parseBlockCount
10491/// ::= 'blockcount' ':' UInt64
10492bool LLParser::parseBlockCount() {
10493 assert(Lex.getKind() == lltok::kw_blockcount);
10494 Lex.Lex();
10495
10496 if (parseToken(lltok::colon, "expected ':' here"))
10497 return true;
10498 uint64_t BlockCount;
10499 if (parseUInt64(BlockCount))
10500 return true;
10501 if (Index)
10502 Index->setBlockCount(BlockCount);
10503 return false;
10504}
10505
10506/// parseCfiFunctions
10507/// ::= ('cfiFunctionDefs' | 'cfiFunctionDecls') ':' '(' CfiFunction
10508/// [',' CfiFunction]* ')'
10509/// CfiFunction ::= '(' 'guid' ':' UInt64 ',' 'name' ':' STRINGCONSTANT ')'
10510bool LLParser::parseCfiFunctions() {
10511 assert(Lex.getKind() == lltok::kw_cfiFunctionDefs ||
10512 Lex.getKind() == lltok::kw_cfiFunctionDecls);
10513 CfiFunctionIndex &CfiIndex = Lex.getKind() == lltok::kw_cfiFunctionDefs
10514 ? Index->cfiFunctionDefs()
10515 : Index->cfiFunctionDecls();
10516 Lex.Lex();
10517
10518 if (parseToken(lltok::colon, "expected ':' here") ||
10519 parseToken(lltok::lparen, "expected '(' here"))
10520 return true;
10521
10522 do {
10524 std::string Name;
10525 if (parseToken(lltok::lparen, "expected '(' here") ||
10526 parseToken(lltok::kw_guid, "expected 'guid' here") ||
10527 parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID) ||
10528 parseToken(lltok::comma, "expected ',' here") ||
10529 parseToken(lltok::kw_name, "expected 'name' here") ||
10530 parseToken(lltok::colon, "expected ':' here") ||
10531 parseStringConstant(Name) ||
10532 parseToken(lltok::rparen, "expected ')' here"))
10533 return true;
10534 CfiIndex.addSymbolWithThinLTOGUID(Name, GUID);
10535 } while (EatIfPresent(lltok::comma));
10536
10537 return parseToken(lltok::rparen, "expected ')' here");
10538}
10539
10540/// parseGVEntry
10541/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
10542/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
10543/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
10544bool LLParser::parseGVEntry(unsigned ID) {
10545 assert(Lex.getKind() == lltok::kw_gv);
10546 Lex.Lex();
10547
10548 if (parseToken(lltok::colon, "expected ':' here") ||
10549 parseToken(lltok::lparen, "expected '(' here"))
10550 return true;
10551
10552 LocTy Loc = Lex.getLoc();
10553 std::string Name;
10555 switch (Lex.getKind()) {
10556 case lltok::kw_name:
10557 Lex.Lex();
10558 if (parseToken(lltok::colon, "expected ':' here") ||
10559 parseStringConstant(Name))
10560 return true;
10561 // Can't create GUID/ValueInfo until we have the linkage.
10562 break;
10563 case lltok::kw_guid:
10564 Lex.Lex();
10565 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
10566 return true;
10567 break;
10568 default:
10569 return error(Lex.getLoc(), "expected name or guid tag");
10570 }
10571
10572 if (!EatIfPresent(lltok::comma)) {
10573 // No summaries. Wrap up.
10574 if (parseToken(lltok::rparen, "expected ')' here"))
10575 return true;
10576 // This was created for a call to an external or indirect target.
10577 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
10578 // created for indirect calls with VP. A Name with no GUID came from
10579 // an external definition. We pass ExternalLinkage since that is only
10580 // used when the GUID must be computed from Name, and in that case
10581 // the symbol must have external linkage.
10582 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
10583 nullptr, Loc);
10584 }
10585
10586 // Have a list of summaries
10587 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
10588 parseToken(lltok::colon, "expected ':' here") ||
10589 parseToken(lltok::lparen, "expected '(' here"))
10590 return true;
10591 do {
10592 switch (Lex.getKind()) {
10593 case lltok::kw_function:
10594 if (parseFunctionSummary(Name, GUID, ID))
10595 return true;
10596 break;
10597 case lltok::kw_variable:
10598 if (parseVariableSummary(Name, GUID, ID))
10599 return true;
10600 break;
10601 case lltok::kw_alias:
10602 if (parseAliasSummary(Name, GUID, ID))
10603 return true;
10604 break;
10605 default:
10606 return error(Lex.getLoc(), "expected summary type");
10607 }
10608 } while (EatIfPresent(lltok::comma));
10609
10610 if (parseToken(lltok::rparen, "expected ')' here") ||
10611 parseToken(lltok::rparen, "expected ')' here"))
10612 return true;
10613
10614 return false;
10615}
10616
10617/// FunctionSummary
10618/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10619/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10620/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10621/// [',' OptionalRefs]? ')'
10622bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10623 unsigned ID) {
10624 LocTy Loc = Lex.getLoc();
10625 assert(Lex.getKind() == lltok::kw_function);
10626 Lex.Lex();
10627
10628 StringRef ModulePath;
10629 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10631 /*NotEligibleToImport=*/false,
10632 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10633 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10634 unsigned InstCount;
10636 FunctionSummary::TypeIdInfo TypeIdInfo;
10637 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10639 std::vector<CallsiteInfo> Callsites;
10640 std::vector<AllocInfo> Allocs;
10641 // Default is all-zeros (conservative values).
10642 FunctionSummary::FFlags FFlags = {};
10643 if (parseToken(lltok::colon, "expected ':' here") ||
10644 parseToken(lltok::lparen, "expected '(' here") ||
10645 parseModuleReference(ModulePath) ||
10646 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10647 parseToken(lltok::comma, "expected ',' here") ||
10648 parseToken(lltok::kw_insts, "expected 'insts' here") ||
10649 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
10650 return true;
10651
10652 // parse optional fields
10653 while (EatIfPresent(lltok::comma)) {
10654 switch (Lex.getKind()) {
10656 if (parseOptionalFFlags(FFlags))
10657 return true;
10658 break;
10659 case lltok::kw_calls:
10660 if (parseOptionalCalls(Calls))
10661 return true;
10662 break;
10664 if (parseOptionalTypeIdInfo(TypeIdInfo))
10665 return true;
10666 break;
10667 case lltok::kw_refs:
10668 if (parseOptionalRefs(Refs))
10669 return true;
10670 break;
10671 case lltok::kw_params:
10672 if (parseOptionalParamAccesses(ParamAccesses))
10673 return true;
10674 break;
10675 case lltok::kw_allocs:
10676 if (parseOptionalAllocs(Allocs))
10677 return true;
10678 break;
10680 if (parseOptionalCallsites(Callsites))
10681 return true;
10682 break;
10683 default:
10684 return error(Lex.getLoc(), "expected optional function summary field");
10685 }
10686 }
10687
10688 if (parseToken(lltok::rparen, "expected ')' here"))
10689 return true;
10690
10691 auto FS = std::make_unique<FunctionSummary>(
10692 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10693 std::move(TypeIdInfo.TypeTests),
10694 std::move(TypeIdInfo.TypeTestAssumeVCalls),
10695 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10696 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10697 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10698 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10699
10700 FS->setModulePath(ModulePath);
10701
10702 return addGlobalValueToIndex(Name, GUID,
10704 std::move(FS), Loc);
10705}
10706
10707/// VariableSummary
10708/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10709/// [',' OptionalRefs]? ')'
10710bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10711 unsigned ID) {
10712 LocTy Loc = Lex.getLoc();
10713 assert(Lex.getKind() == lltok::kw_variable);
10714 Lex.Lex();
10715
10716 StringRef ModulePath;
10717 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10719 /*NotEligibleToImport=*/false,
10720 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10721 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10722 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10723 /* WriteOnly */ false,
10724 /* Constant */ false,
10727 VTableFuncList VTableFuncs;
10728 if (parseToken(lltok::colon, "expected ':' here") ||
10729 parseToken(lltok::lparen, "expected '(' here") ||
10730 parseModuleReference(ModulePath) ||
10731 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10732 parseToken(lltok::comma, "expected ',' here") ||
10733 parseGVarFlags(GVarFlags))
10734 return true;
10735
10736 // parse optional fields
10737 while (EatIfPresent(lltok::comma)) {
10738 switch (Lex.getKind()) {
10740 if (parseOptionalVTableFuncs(VTableFuncs))
10741 return true;
10742 break;
10743 case lltok::kw_refs:
10744 if (parseOptionalRefs(Refs))
10745 return true;
10746 break;
10747 default:
10748 return error(Lex.getLoc(), "expected optional variable summary field");
10749 }
10750 }
10751
10752 if (parseToken(lltok::rparen, "expected ')' here"))
10753 return true;
10754
10755 auto GS =
10756 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10757
10758 GS->setModulePath(ModulePath);
10759 GS->setVTableFuncs(std::move(VTableFuncs));
10760
10761 return addGlobalValueToIndex(Name, GUID,
10763 std::move(GS), Loc);
10764}
10765
10766/// AliasSummary
10767/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10768/// 'aliasee' ':' GVReference ')'
10769bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10770 unsigned ID) {
10771 assert(Lex.getKind() == lltok::kw_alias);
10772 LocTy Loc = Lex.getLoc();
10773 Lex.Lex();
10774
10775 StringRef ModulePath;
10776 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10778 /*NotEligibleToImport=*/false,
10779 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10780 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10781 if (parseToken(lltok::colon, "expected ':' here") ||
10782 parseToken(lltok::lparen, "expected '(' here") ||
10783 parseModuleReference(ModulePath) ||
10784 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10785 parseToken(lltok::comma, "expected ',' here") ||
10786 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10787 parseToken(lltok::colon, "expected ':' here"))
10788 return true;
10789
10790 ValueInfo AliaseeVI;
10791 unsigned GVId;
10792 auto AS = std::make_unique<AliasSummary>(GVFlags);
10793 AS->setModulePath(ModulePath);
10794
10795 if (!EatIfPresent(lltok::kw_null)) {
10796 if (parseGVReference(AliaseeVI, GVId))
10797 return true;
10798
10799 // Record forward reference if the aliasee is not parsed yet.
10800 if (AliaseeVI.getRef() == FwdVIRef) {
10801 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10802 } else {
10803 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10804 assert(Summary && "Aliasee must be a definition");
10805 AS->setAliasee(AliaseeVI, Summary);
10806 }
10807 }
10808
10809 if (parseToken(lltok::rparen, "expected ')' here"))
10810 return true;
10811
10812 return addGlobalValueToIndex(Name, GUID,
10814 std::move(AS), Loc);
10815}
10816
10817/// Flag
10818/// ::= [0|1]
10819bool LLParser::parseFlag(unsigned &Val) {
10820 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10821 return tokError("expected integer");
10822 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10823 Lex.Lex();
10824 return false;
10825}
10826
10827/// OptionalFFlags
10828/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10829/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10830/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10831/// [',' 'noInline' ':' Flag]? ')'
10832/// [',' 'alwaysInline' ':' Flag]? ')'
10833/// [',' 'noUnwind' ':' Flag]? ')'
10834/// [',' 'mayThrow' ':' Flag]? ')'
10835/// [',' 'hasUnknownCall' ':' Flag]? ')'
10836/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10837/// [',' 'hasEscapingBlockAddress' ':' Flag]? ')'
10838
10839bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10840 assert(Lex.getKind() == lltok::kw_funcFlags);
10841 Lex.Lex();
10842
10843 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10844 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10845 return true;
10846
10847 do {
10848 unsigned Val = 0;
10849 switch (Lex.getKind()) {
10850 case lltok::kw_readNone:
10851 Lex.Lex();
10852 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10853 return true;
10854 FFlags.ReadNone = Val;
10855 break;
10856 case lltok::kw_readOnly:
10857 Lex.Lex();
10858 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10859 return true;
10860 FFlags.ReadOnly = Val;
10861 break;
10863 Lex.Lex();
10864 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10865 return true;
10866 FFlags.NoRecurse = Val;
10867 break;
10869 Lex.Lex();
10870 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10871 return true;
10872 FFlags.ReturnDoesNotAlias = Val;
10873 break;
10874 case lltok::kw_noInline:
10875 Lex.Lex();
10876 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10877 return true;
10878 FFlags.NoInline = Val;
10879 break;
10881 Lex.Lex();
10882 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10883 return true;
10884 FFlags.AlwaysInline = Val;
10885 break;
10886 case lltok::kw_noUnwind:
10887 Lex.Lex();
10888 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10889 return true;
10890 FFlags.NoUnwind = Val;
10891 break;
10892 case lltok::kw_mayThrow:
10893 Lex.Lex();
10894 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10895 return true;
10896 FFlags.MayThrow = Val;
10897 break;
10899 Lex.Lex();
10900 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10901 return true;
10902 FFlags.HasUnknownCall = Val;
10903 break;
10905 Lex.Lex();
10906 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10907 return true;
10908 FFlags.MustBeUnreachable = Val;
10909 break;
10911 Lex.Lex();
10912 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10913 return true;
10914 FFlags.HasEscapingBlockAddress = Val;
10915 break;
10916 default:
10917 return error(Lex.getLoc(), "expected function flag type");
10918 }
10919 } while (EatIfPresent(lltok::comma));
10920
10921 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10922 return true;
10923
10924 return false;
10925}
10926
10927/// OptionalCalls
10928/// := 'calls' ':' '(' Call [',' Call]* ')'
10929/// Call ::= '(' 'callee' ':' GVReference
10930/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10931/// [ ',' 'tail' ]? ')'
10932bool LLParser::parseOptionalCalls(
10933 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10934 assert(Lex.getKind() == lltok::kw_calls);
10935 Lex.Lex();
10936
10937 if (parseToken(lltok::colon, "expected ':' in calls") ||
10938 parseToken(lltok::lparen, "expected '(' in calls"))
10939 return true;
10940
10941 IdToIndexMapType IdToIndexMap;
10942 // parse each call edge
10943 do {
10944 ValueInfo VI;
10945 if (parseToken(lltok::lparen, "expected '(' in call") ||
10946 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10947 parseToken(lltok::colon, "expected ':'"))
10948 return true;
10949
10950 LocTy Loc = Lex.getLoc();
10951 unsigned GVId;
10952 if (parseGVReference(VI, GVId))
10953 return true;
10954
10956 unsigned RelBF = 0;
10957 unsigned HasTailCall = false;
10958 unsigned HasIndirectCall = false;
10959
10960 // parse optional fields
10961 while (EatIfPresent(lltok::comma)) {
10962 switch (Lex.getKind()) {
10963 case lltok::kw_hotness:
10964 Lex.Lex();
10965 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10966 return true;
10967 break;
10968 // Deprecated, keep in order to support old files.
10969 case lltok::kw_relbf:
10970 Lex.Lex();
10971 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10972 return true;
10973 break;
10974 case lltok::kw_tail:
10975 Lex.Lex();
10976 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10977 return true;
10978 break;
10979 case lltok::kw_indirect:
10980 Lex.Lex();
10981 if (parseToken(lltok::colon, "expected ':'") ||
10982 parseFlag(HasIndirectCall))
10983 return true;
10984 break;
10985 default:
10986 return error(Lex.getLoc(),
10987 "expected hotness, relbf, tail, or indirect");
10988 }
10989 }
10990 // Keep track of the Call array index needing a forward reference.
10991 // We will save the location of the ValueInfo needing an update, but
10992 // can only do so once the std::vector is finalized.
10993 if (VI.getRef() == FwdVIRef)
10994 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10996 VI, CalleeInfo(Hotness, HasTailCall, HasIndirectCall)});
10997
10998 if (parseToken(lltok::rparen, "expected ')' in call"))
10999 return true;
11000 } while (EatIfPresent(lltok::comma));
11001
11002 // Now that the Calls vector is finalized, it is safe to save the locations
11003 // of any forward GV references that need updating later.
11004 for (auto I : IdToIndexMap) {
11005 auto &Infos = ForwardRefValueInfos[I.first];
11006 for (auto P : I.second) {
11007 assert(Calls[P.first].first.getRef() == FwdVIRef &&
11008 "Forward referenced ValueInfo expected to be empty");
11009 Infos.emplace_back(&Calls[P.first].first, P.second);
11010 }
11011 }
11012
11013 if (parseToken(lltok::rparen, "expected ')' in calls"))
11014 return true;
11015
11016 return false;
11017}
11018
11019/// Hotness
11020/// := ('unknown'|'cold'|'none'|'hot'|'critical')
11021bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
11022 switch (Lex.getKind()) {
11023 case lltok::kw_unknown:
11025 break;
11026 case lltok::kw_cold:
11028 break;
11029 case lltok::kw_none:
11031 break;
11032 case lltok::kw_hot:
11034 break;
11035 case lltok::kw_critical:
11037 break;
11038 default:
11039 return error(Lex.getLoc(), "invalid call edge hotness");
11040 }
11041 Lex.Lex();
11042 return false;
11043}
11044
11045/// OptionalVTableFuncs
11046/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
11047/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
11048bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
11049 assert(Lex.getKind() == lltok::kw_vTableFuncs);
11050 Lex.Lex();
11051
11052 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
11053 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
11054 return true;
11055
11056 IdToIndexMapType IdToIndexMap;
11057 // parse each virtual function pair
11058 do {
11059 ValueInfo VI;
11060 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
11061 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
11062 parseToken(lltok::colon, "expected ':'"))
11063 return true;
11064
11065 LocTy Loc = Lex.getLoc();
11066 unsigned GVId;
11067 if (parseGVReference(VI, GVId))
11068 return true;
11069
11071 if (parseToken(lltok::comma, "expected comma") ||
11072 parseToken(lltok::kw_offset, "expected offset") ||
11073 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
11074 return true;
11075
11076 // Keep track of the VTableFuncs array index needing a forward reference.
11077 // We will save the location of the ValueInfo needing an update, but
11078 // can only do so once the std::vector is finalized.
11079 if (VI == EmptyVI)
11080 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
11081 VTableFuncs.push_back({VI, Offset});
11082
11083 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
11084 return true;
11085 } while (EatIfPresent(lltok::comma));
11086
11087 // Now that the VTableFuncs vector is finalized, it is safe to save the
11088 // locations of any forward GV references that need updating later.
11089 for (auto I : IdToIndexMap) {
11090 auto &Infos = ForwardRefValueInfos[I.first];
11091 for (auto P : I.second) {
11092 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
11093 "Forward referenced ValueInfo expected to be empty");
11094 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
11095 }
11096 }
11097
11098 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
11099 return true;
11100
11101 return false;
11102}
11103
11104/// ParamNo := 'param' ':' UInt64
11105bool LLParser::parseParamNo(uint64_t &ParamNo) {
11106 if (parseToken(lltok::kw_param, "expected 'param' here") ||
11107 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
11108 return true;
11109 return false;
11110}
11111
11112/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
11113bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
11114 APSInt Lower;
11115 APSInt Upper;
11116 auto ParseAPSInt = [&](APSInt &Val) {
11117 if (Lex.getKind() != lltok::APSInt)
11118 return tokError("expected integer");
11119 Val = Lex.getAPSIntVal();
11120 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
11121 Val.setIsSigned(true);
11122 Lex.Lex();
11123 return false;
11124 };
11125 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
11126 parseToken(lltok::colon, "expected ':' here") ||
11127 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
11128 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
11129 parseToken(lltok::rsquare, "expected ']' here"))
11130 return true;
11131
11132 ++Upper;
11133 Range =
11134 (Lower == Upper && !Lower.isMaxValue())
11135 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
11136 : ConstantRange(Lower, Upper);
11137
11138 return false;
11139}
11140
11141/// ParamAccessCall
11142/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
11143bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
11144 IdLocListType &IdLocList) {
11145 if (parseToken(lltok::lparen, "expected '(' here") ||
11146 parseToken(lltok::kw_callee, "expected 'callee' here") ||
11147 parseToken(lltok::colon, "expected ':' here"))
11148 return true;
11149
11150 unsigned GVId;
11151 ValueInfo VI;
11152 LocTy Loc = Lex.getLoc();
11153 if (parseGVReference(VI, GVId))
11154 return true;
11155
11156 Call.Callee = VI;
11157 IdLocList.emplace_back(GVId, Loc);
11158
11159 if (parseToken(lltok::comma, "expected ',' here") ||
11160 parseParamNo(Call.ParamNo) ||
11161 parseToken(lltok::comma, "expected ',' here") ||
11162 parseParamAccessOffset(Call.Offsets))
11163 return true;
11164
11165 if (parseToken(lltok::rparen, "expected ')' here"))
11166 return true;
11167
11168 return false;
11169}
11170
11171/// ParamAccess
11172/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
11173/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
11174bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
11175 IdLocListType &IdLocList) {
11176 if (parseToken(lltok::lparen, "expected '(' here") ||
11177 parseParamNo(Param.ParamNo) ||
11178 parseToken(lltok::comma, "expected ',' here") ||
11179 parseParamAccessOffset(Param.Use))
11180 return true;
11181
11182 if (EatIfPresent(lltok::comma)) {
11183 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
11184 parseToken(lltok::colon, "expected ':' here") ||
11185 parseToken(lltok::lparen, "expected '(' here"))
11186 return true;
11187 do {
11188 FunctionSummary::ParamAccess::Call Call;
11189 if (parseParamAccessCall(Call, IdLocList))
11190 return true;
11191 Param.Calls.push_back(Call);
11192 } while (EatIfPresent(lltok::comma));
11193
11194 if (parseToken(lltok::rparen, "expected ')' here"))
11195 return true;
11196 }
11197
11198 if (parseToken(lltok::rparen, "expected ')' here"))
11199 return true;
11200
11201 return false;
11202}
11203
11204/// OptionalParamAccesses
11205/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
11206bool LLParser::parseOptionalParamAccesses(
11207 std::vector<FunctionSummary::ParamAccess> &Params) {
11208 assert(Lex.getKind() == lltok::kw_params);
11209 Lex.Lex();
11210
11211 if (parseToken(lltok::colon, "expected ':' here") ||
11212 parseToken(lltok::lparen, "expected '(' here"))
11213 return true;
11214
11215 IdLocListType VContexts;
11216 size_t CallsNum = 0;
11217 do {
11218 FunctionSummary::ParamAccess ParamAccess;
11219 if (parseParamAccess(ParamAccess, VContexts))
11220 return true;
11221 CallsNum += ParamAccess.Calls.size();
11222 assert(VContexts.size() == CallsNum);
11223 (void)CallsNum;
11224 Params.emplace_back(std::move(ParamAccess));
11225 } while (EatIfPresent(lltok::comma));
11226
11227 if (parseToken(lltok::rparen, "expected ')' here"))
11228 return true;
11229
11230 // Now that the Params is finalized, it is safe to save the locations
11231 // of any forward GV references that need updating later.
11232 IdLocListType::const_iterator ItContext = VContexts.begin();
11233 for (auto &PA : Params) {
11234 for (auto &C : PA.Calls) {
11235 if (C.Callee.getRef() == FwdVIRef)
11236 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
11237 ItContext->second);
11238 ++ItContext;
11239 }
11240 }
11241 assert(ItContext == VContexts.end());
11242
11243 return false;
11244}
11245
11246/// OptionalRefs
11247/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
11248bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
11249 assert(Lex.getKind() == lltok::kw_refs);
11250 Lex.Lex();
11251
11252 if (parseToken(lltok::colon, "expected ':' in refs") ||
11253 parseToken(lltok::lparen, "expected '(' in refs"))
11254 return true;
11255
11256 struct ValueContext {
11257 ValueInfo VI;
11258 unsigned GVId;
11259 LocTy Loc;
11260 };
11261 std::vector<ValueContext> VContexts;
11262 // parse each ref edge
11263 do {
11264 ValueContext VC;
11265 VC.Loc = Lex.getLoc();
11266 if (parseGVReference(VC.VI, VC.GVId))
11267 return true;
11268 VContexts.push_back(VC);
11269 } while (EatIfPresent(lltok::comma));
11270
11271 // Sort value contexts so that ones with writeonly
11272 // and readonly ValueInfo are at the end of VContexts vector.
11273 // See FunctionSummary::specialRefCounts()
11274 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
11275 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
11276 });
11277
11278 IdToIndexMapType IdToIndexMap;
11279 for (auto &VC : VContexts) {
11280 // Keep track of the Refs array index needing a forward reference.
11281 // We will save the location of the ValueInfo needing an update, but
11282 // can only do so once the std::vector is finalized.
11283 if (VC.VI.getRef() == FwdVIRef)
11284 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
11285 Refs.push_back(VC.VI);
11286 }
11287
11288 // Now that the Refs vector is finalized, it is safe to save the locations
11289 // of any forward GV references that need updating later.
11290 for (auto I : IdToIndexMap) {
11291 auto &Infos = ForwardRefValueInfos[I.first];
11292 for (auto P : I.second) {
11293 assert(Refs[P.first].getRef() == FwdVIRef &&
11294 "Forward referenced ValueInfo expected to be empty");
11295 Infos.emplace_back(&Refs[P.first], P.second);
11296 }
11297 }
11298
11299 if (parseToken(lltok::rparen, "expected ')' in refs"))
11300 return true;
11301
11302 return false;
11303}
11304
11305/// OptionalTypeIdInfo
11306/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
11307/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
11308/// [',' TypeCheckedLoadConstVCalls]? ')'
11309bool LLParser::parseOptionalTypeIdInfo(
11310 FunctionSummary::TypeIdInfo &TypeIdInfo) {
11311 assert(Lex.getKind() == lltok::kw_typeIdInfo);
11312 Lex.Lex();
11313
11314 if (parseToken(lltok::colon, "expected ':' here") ||
11315 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
11316 return true;
11317
11318 do {
11319 switch (Lex.getKind()) {
11321 if (parseTypeTests(TypeIdInfo.TypeTests))
11322 return true;
11323 break;
11325 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
11326 TypeIdInfo.TypeTestAssumeVCalls))
11327 return true;
11328 break;
11330 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
11331 TypeIdInfo.TypeCheckedLoadVCalls))
11332 return true;
11333 break;
11335 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
11336 TypeIdInfo.TypeTestAssumeConstVCalls))
11337 return true;
11338 break;
11340 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
11341 TypeIdInfo.TypeCheckedLoadConstVCalls))
11342 return true;
11343 break;
11344 default:
11345 return error(Lex.getLoc(), "invalid typeIdInfo list type");
11346 }
11347 } while (EatIfPresent(lltok::comma));
11348
11349 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
11350 return true;
11351
11352 return false;
11353}
11354
11355/// TypeTests
11356/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
11357/// [',' (SummaryID | UInt64)]* ')'
11358bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
11359 assert(Lex.getKind() == lltok::kw_typeTests);
11360 Lex.Lex();
11361
11362 if (parseToken(lltok::colon, "expected ':' here") ||
11363 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
11364 return true;
11365
11366 IdToIndexMapType IdToIndexMap;
11367 do {
11369 if (Lex.getKind() == lltok::SummaryID) {
11370 unsigned ID = Lex.getUIntVal();
11371 LocTy Loc = Lex.getLoc();
11372 // Keep track of the TypeTests array index needing a forward reference.
11373 // We will save the location of the GUID needing an update, but
11374 // can only do so once the std::vector is finalized.
11375 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
11376 Lex.Lex();
11377 } else if (parseUInt64(GUID))
11378 return true;
11379 TypeTests.push_back(GUID);
11380 } while (EatIfPresent(lltok::comma));
11381
11382 // Now that the TypeTests vector is finalized, it is safe to save the
11383 // locations of any forward GV references that need updating later.
11384 for (auto I : IdToIndexMap) {
11385 auto &Ids = ForwardRefTypeIds[I.first];
11386 for (auto P : I.second) {
11387 assert(TypeTests[P.first] == 0 &&
11388 "Forward referenced type id GUID expected to be 0");
11389 Ids.emplace_back(&TypeTests[P.first], P.second);
11390 }
11391 }
11392
11393 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
11394 return true;
11395
11396 return false;
11397}
11398
11399/// VFuncIdList
11400/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
11401bool LLParser::parseVFuncIdList(
11402 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
11403 assert(Lex.getKind() == Kind);
11404 Lex.Lex();
11405
11406 if (parseToken(lltok::colon, "expected ':' here") ||
11407 parseToken(lltok::lparen, "expected '(' here"))
11408 return true;
11409
11410 IdToIndexMapType IdToIndexMap;
11411 do {
11412 FunctionSummary::VFuncId VFuncId;
11413 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
11414 return true;
11415 VFuncIdList.push_back(VFuncId);
11416 } while (EatIfPresent(lltok::comma));
11417
11418 if (parseToken(lltok::rparen, "expected ')' here"))
11419 return true;
11420
11421 // Now that the VFuncIdList vector is finalized, it is safe to save the
11422 // locations of any forward GV references that need updating later.
11423 for (auto I : IdToIndexMap) {
11424 auto &Ids = ForwardRefTypeIds[I.first];
11425 for (auto P : I.second) {
11426 assert(VFuncIdList[P.first].GUID == 0 &&
11427 "Forward referenced type id GUID expected to be 0");
11428 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
11429 }
11430 }
11431
11432 return false;
11433}
11434
11435/// ConstVCallList
11436/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
11437bool LLParser::parseConstVCallList(
11438 lltok::Kind Kind,
11439 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
11440 assert(Lex.getKind() == Kind);
11441 Lex.Lex();
11442
11443 if (parseToken(lltok::colon, "expected ':' here") ||
11444 parseToken(lltok::lparen, "expected '(' here"))
11445 return true;
11446
11447 IdToIndexMapType IdToIndexMap;
11448 do {
11449 FunctionSummary::ConstVCall ConstVCall;
11450 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11451 return true;
11452 ConstVCallList.push_back(ConstVCall);
11453 } while (EatIfPresent(lltok::comma));
11454
11455 if (parseToken(lltok::rparen, "expected ')' here"))
11456 return true;
11457
11458 // Now that the ConstVCallList vector is finalized, it is safe to save the
11459 // locations of any forward GV references that need updating later.
11460 for (auto I : IdToIndexMap) {
11461 auto &Ids = ForwardRefTypeIds[I.first];
11462 for (auto P : I.second) {
11463 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
11464 "Forward referenced type id GUID expected to be 0");
11465 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
11466 }
11467 }
11468
11469 return false;
11470}
11471
11472/// ConstVCall
11473/// ::= '(' VFuncId ',' Args ')'
11474bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11475 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11476 if (parseToken(lltok::lparen, "expected '(' here") ||
11477 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
11478 return true;
11479
11480 if (EatIfPresent(lltok::comma))
11481 if (parseArgs(ConstVCall.Args))
11482 return true;
11483
11484 if (parseToken(lltok::rparen, "expected ')' here"))
11485 return true;
11486
11487 return false;
11488}
11489
11490/// VFuncId
11491/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
11492/// 'offset' ':' UInt64 ')'
11493bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11494 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11495 assert(Lex.getKind() == lltok::kw_vFuncId);
11496 Lex.Lex();
11497
11498 if (parseToken(lltok::colon, "expected ':' here") ||
11499 parseToken(lltok::lparen, "expected '(' here"))
11500 return true;
11501
11502 if (Lex.getKind() == lltok::SummaryID) {
11503 VFuncId.GUID = 0;
11504 unsigned ID = Lex.getUIntVal();
11505 LocTy Loc = Lex.getLoc();
11506 // Keep track of the array index needing a forward reference.
11507 // We will save the location of the GUID needing an update, but
11508 // can only do so once the caller's std::vector is finalized.
11509 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
11510 Lex.Lex();
11511 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
11512 parseToken(lltok::colon, "expected ':' here") ||
11513 parseUInt64(VFuncId.GUID))
11514 return true;
11515
11516 if (parseToken(lltok::comma, "expected ',' here") ||
11517 parseToken(lltok::kw_offset, "expected 'offset' here") ||
11518 parseToken(lltok::colon, "expected ':' here") ||
11519 parseUInt64(VFuncId.Offset) ||
11520 parseToken(lltok::rparen, "expected ')' here"))
11521 return true;
11522
11523 return false;
11524}
11525
11526/// GVFlags
11527/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
11528/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
11529/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
11530/// 'canAutoHide' ':' Flag ',' ')'
11531bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11532 assert(Lex.getKind() == lltok::kw_flags);
11533 Lex.Lex();
11534
11535 if (parseToken(lltok::colon, "expected ':' here") ||
11536 parseToken(lltok::lparen, "expected '(' here"))
11537 return true;
11538
11539 do {
11540 unsigned Flag = 0;
11541 switch (Lex.getKind()) {
11542 case lltok::kw_linkage:
11543 Lex.Lex();
11544 if (parseToken(lltok::colon, "expected ':'"))
11545 return true;
11546 bool HasLinkage;
11547 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
11548 assert(HasLinkage && "Linkage not optional in summary entry");
11549 Lex.Lex();
11550 break;
11552 Lex.Lex();
11553 if (parseToken(lltok::colon, "expected ':'"))
11554 return true;
11555 parseOptionalVisibility(Flag);
11556 GVFlags.Visibility = Flag;
11557 break;
11559 Lex.Lex();
11560 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11561 return true;
11562 GVFlags.NotEligibleToImport = Flag;
11563 break;
11564 case lltok::kw_live:
11565 Lex.Lex();
11566 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11567 return true;
11568 GVFlags.Live = Flag;
11569 break;
11570 case lltok::kw_dsoLocal:
11571 Lex.Lex();
11572 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11573 return true;
11574 GVFlags.DSOLocal = Flag;
11575 break;
11577 Lex.Lex();
11578 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11579 return true;
11580 GVFlags.CanAutoHide = Flag;
11581 break;
11583 Lex.Lex();
11584 if (parseToken(lltok::colon, "expected ':'"))
11585 return true;
11587 if (parseOptionalImportType(Lex.getKind(), IK))
11588 return true;
11589 GVFlags.ImportType = static_cast<unsigned>(IK);
11590 Lex.Lex();
11591 break;
11593 Lex.Lex();
11594 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11595 return true;
11596 GVFlags.NoRenameOnPromotion = Flag;
11597 break;
11598 default:
11599 return error(Lex.getLoc(), "expected gv flag type");
11600 }
11601 } while (EatIfPresent(lltok::comma));
11602
11603 if (parseToken(lltok::rparen, "expected ')' here"))
11604 return true;
11605
11606 return false;
11607}
11608
11609/// GVarFlags
11610/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
11611/// ',' 'writeonly' ':' Flag
11612/// ',' 'constant' ':' Flag ')'
11613bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11614 assert(Lex.getKind() == lltok::kw_varFlags);
11615 Lex.Lex();
11616
11617 if (parseToken(lltok::colon, "expected ':' here") ||
11618 parseToken(lltok::lparen, "expected '(' here"))
11619 return true;
11620
11621 auto ParseRest = [this](unsigned int &Val) {
11622 Lex.Lex();
11623 if (parseToken(lltok::colon, "expected ':'"))
11624 return true;
11625 return parseFlag(Val);
11626 };
11627
11628 do {
11629 unsigned Flag = 0;
11630 switch (Lex.getKind()) {
11631 case lltok::kw_readonly:
11632 if (ParseRest(Flag))
11633 return true;
11634 GVarFlags.MaybeReadOnly = Flag;
11635 break;
11636 case lltok::kw_writeonly:
11637 if (ParseRest(Flag))
11638 return true;
11639 GVarFlags.MaybeWriteOnly = Flag;
11640 break;
11641 case lltok::kw_constant:
11642 if (ParseRest(Flag))
11643 return true;
11644 GVarFlags.Constant = Flag;
11645 break;
11647 if (ParseRest(Flag))
11648 return true;
11649 GVarFlags.VCallVisibility = Flag;
11650 break;
11651 default:
11652 return error(Lex.getLoc(), "expected gvar flag type");
11653 }
11654 } while (EatIfPresent(lltok::comma));
11655 return parseToken(lltok::rparen, "expected ')' here");
11656}
11657
11658/// ModuleReference
11659/// ::= 'module' ':' UInt
11660bool LLParser::parseModuleReference(StringRef &ModulePath) {
11661 // parse module id.
11662 if (parseToken(lltok::kw_module, "expected 'module' here") ||
11663 parseToken(lltok::colon, "expected ':' here") ||
11664 parseToken(lltok::SummaryID, "expected module ID"))
11665 return true;
11666
11667 unsigned ModuleID = Lex.getUIntVal();
11668 auto I = ModuleIdMap.find(ModuleID);
11669 // We should have already parsed all module IDs
11670 assert(I != ModuleIdMap.end());
11671 ModulePath = I->second;
11672 return false;
11673}
11674
11675/// GVReference
11676/// ::= SummaryID
11677bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11678 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
11679 if (!ReadOnly)
11680 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11681 if (parseToken(lltok::SummaryID, "expected GV ID"))
11682 return true;
11683
11684 GVId = Lex.getUIntVal();
11685 // Check if we already have a VI for this GV
11686 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11687 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11688 VI = NumberedValueInfos[GVId];
11689 } else
11690 // We will create a forward reference to the stored location.
11691 VI = ValueInfo(false, FwdVIRef);
11692
11693 if (ReadOnly)
11694 VI.setReadOnly();
11695 if (WriteOnly)
11696 VI.setWriteOnly();
11697 return false;
11698}
11699
11700/// OptionalAllocs
11701/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11702/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11703/// ',' MemProfs ')'
11704/// Version ::= UInt32
11705bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11706 assert(Lex.getKind() == lltok::kw_allocs);
11707 Lex.Lex();
11708
11709 if (parseToken(lltok::colon, "expected ':' in allocs") ||
11710 parseToken(lltok::lparen, "expected '(' in allocs"))
11711 return true;
11712
11713 // parse each alloc
11714 do {
11715 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
11716 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
11717 parseToken(lltok::colon, "expected ':'") ||
11718 parseToken(lltok::lparen, "expected '(' in versions"))
11719 return true;
11720
11721 SmallVector<uint8_t> Versions;
11722 do {
11723 uint8_t V = 0;
11724 if (parseAllocType(V))
11725 return true;
11726 Versions.push_back(V);
11727 } while (EatIfPresent(lltok::comma));
11728
11729 if (parseToken(lltok::rparen, "expected ')' in versions") ||
11730 parseToken(lltok::comma, "expected ',' in alloc"))
11731 return true;
11732
11733 std::vector<MIBInfo> MIBs;
11734 if (parseMemProfs(MIBs))
11735 return true;
11736
11737 Allocs.push_back({Versions, MIBs});
11738
11739 if (parseToken(lltok::rparen, "expected ')' in alloc"))
11740 return true;
11741 } while (EatIfPresent(lltok::comma));
11742
11743 if (parseToken(lltok::rparen, "expected ')' in allocs"))
11744 return true;
11745
11746 return false;
11747}
11748
11749/// MemProfs
11750/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11751/// MemProf ::= '(' 'type' ':' AllocType
11752/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11753/// StackId ::= UInt64
11754bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11755 assert(Lex.getKind() == lltok::kw_memProf);
11756 Lex.Lex();
11757
11758 if (parseToken(lltok::colon, "expected ':' in memprof") ||
11759 parseToken(lltok::lparen, "expected '(' in memprof"))
11760 return true;
11761
11762 // parse each MIB
11763 do {
11764 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
11765 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
11766 parseToken(lltok::colon, "expected ':'"))
11767 return true;
11768
11769 uint8_t AllocType;
11770 if (parseAllocType(AllocType))
11771 return true;
11772
11773 if (parseToken(lltok::comma, "expected ',' in memprof") ||
11774 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
11775 parseToken(lltok::colon, "expected ':'") ||
11776 parseToken(lltok::lparen, "expected '(' in stackIds"))
11777 return true;
11778
11779 SmallVector<unsigned> StackIdIndices;
11780 // Combined index alloc records may not have a stack id list.
11781 if (Lex.getKind() != lltok::rparen) {
11782 do {
11783 uint64_t StackId = 0;
11784 if (parseUInt64(StackId))
11785 return true;
11786 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11787 } while (EatIfPresent(lltok::comma));
11788 }
11789
11790 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11791 return true;
11792
11793 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11794
11795 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11796 return true;
11797 } while (EatIfPresent(lltok::comma));
11798
11799 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11800 return true;
11801
11802 return false;
11803}
11804
11805/// AllocType
11806/// := ('none'|'notcold'|'cold'|'hot'|'ambiguous')
11807bool LLParser::parseAllocType(uint8_t &AllocType) {
11808 switch (Lex.getKind()) {
11809 case lltok::kw_none:
11810 AllocType = (uint8_t)AllocationType::None;
11811 break;
11812 case lltok::kw_notcold:
11813 AllocType = (uint8_t)AllocationType::NotCold;
11814 break;
11816 // Both not cold and cold: the contexts reaching the allocation could not
11817 // be disambiguated.
11818 AllocType =
11820 break;
11821 case lltok::kw_cold:
11822 AllocType = (uint8_t)AllocationType::Cold;
11823 break;
11824 case lltok::kw_hot:
11825 AllocType = (uint8_t)AllocationType::Hot;
11826 break;
11827 default:
11828 return error(Lex.getLoc(), "invalid alloc type");
11829 }
11830 Lex.Lex();
11831 return false;
11832}
11833
11834/// OptionalCallsites
11835/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11836/// Callsite ::= '(' 'callee' ':' GVReference
11837/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11838/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11839/// Version ::= UInt32
11840/// StackId ::= UInt64
11841bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11842 assert(Lex.getKind() == lltok::kw_callsites);
11843 Lex.Lex();
11844
11845 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11846 parseToken(lltok::lparen, "expected '(' in callsites"))
11847 return true;
11848
11849 IdToIndexMapType IdToIndexMap;
11850 // parse each callsite
11851 do {
11852 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11853 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11854 parseToken(lltok::colon, "expected ':'"))
11855 return true;
11856
11857 ValueInfo VI;
11858 unsigned GVId = 0;
11859 LocTy Loc = Lex.getLoc();
11860 if (!EatIfPresent(lltok::kw_null)) {
11861 if (parseGVReference(VI, GVId))
11862 return true;
11863 }
11864
11865 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11866 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11867 parseToken(lltok::colon, "expected ':'") ||
11868 parseToken(lltok::lparen, "expected '(' in clones"))
11869 return true;
11870
11871 SmallVector<unsigned> Clones;
11872 do {
11873 unsigned V = 0;
11874 if (parseUInt32(V))
11875 return true;
11876 Clones.push_back(V);
11877 } while (EatIfPresent(lltok::comma));
11878
11879 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11880 parseToken(lltok::comma, "expected ',' in callsite") ||
11881 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11882 parseToken(lltok::colon, "expected ':'") ||
11883 parseToken(lltok::lparen, "expected '(' in stackIds"))
11884 return true;
11885
11886 SmallVector<unsigned> StackIdIndices;
11887 // Synthesized callsite records will not have a stack id list.
11888 if (Lex.getKind() != lltok::rparen) {
11889 do {
11890 uint64_t StackId = 0;
11891 if (parseUInt64(StackId))
11892 return true;
11893 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11894 } while (EatIfPresent(lltok::comma));
11895 }
11896
11897 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11898 return true;
11899
11900 // Keep track of the Callsites array index needing a forward reference.
11901 // We will save the location of the ValueInfo needing an update, but
11902 // can only do so once the SmallVector is finalized.
11903 if (VI.getRef() == FwdVIRef)
11904 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11905 Callsites.push_back({VI, Clones, StackIdIndices});
11906
11907 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11908 return true;
11909 } while (EatIfPresent(lltok::comma));
11910
11911 // Now that the Callsites vector is finalized, it is safe to save the
11912 // locations of any forward GV references that need updating later.
11913 for (auto I : IdToIndexMap) {
11914 auto &Infos = ForwardRefValueInfos[I.first];
11915 for (auto P : I.second) {
11916 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11917 "Forward referenced ValueInfo expected to be empty");
11918 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11919 }
11920 }
11921
11922 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11923 return true;
11924
11925 return false;
11926}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Function Alias Analysis false
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH
Definition Compiler.h:276
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_POP
Definition Compiler.h:277
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static uint64_t align(uint64_t Size)
dxil container globals
DXIL Finalize Linkage
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
@ Default
This file contains constants used for implementing Dwarf debug support.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
GlobalValue::SanitizerMetadata SanitizerMetadata
Definition Globals.cpp:317
Hexagon Common GEP
#define _
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
static cl::opt< bool > AllowIncompleteIR("allow-incomplete-ir", cl::init(false), cl::Hidden, cl::desc("Allow incomplete IR on a best effort basis (references to unknown " "metadata will be dropped)"))
static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV)
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
static bool blockCommentCrossesBoundary(SMLoc BeginLoc, SMLoc EndLoc, SMLoc BoundaryLoc)
Return whether skipped trivia contains a block comment that crosses the boundary between two metadata...
Definition LLParser.cpp:78
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
static SmallVector< MemoryEffects::Location, 2 > keywordToLoc(lltok::Kind Tok)
static std::optional< DenormalMode::DenormalModeKind > keywordToDenormalModeKind(lltok::Kind Tok)
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
static unsigned keywordToFPClassTest(lltok::Kind Tok)
#define CC_VLS_CASE(ABIVlen)
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
static bool isSanitizer(lltok::Kind Kind)
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
Definition LLParser.cpp:236
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
static ValueInfo EmptyVI
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
Definition LLParser.cpp:69
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
static bool isAtomic(MachineBasicBlock::iterator I)
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
RISCVCC::CondCode CC
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
dot regions Print regions of function to dot file(with no function bodies)"
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
static const char * name
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file provides utility classes that use RAII to save and restore values.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
FunctionLoweringInfo::StatepointRelocationRecord RecordType
DEMANGLE_NAMESPACE_BEGIN bool starts_with(std::string_view self, char C) noexcept
#define error(X)
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
Value * RHS
Value * LHS
static LLVM_ABI unsigned getSizeInBits(const fltSemantics &Sem)
Returns the size of the floating point number (in bits) in the given semantics.
Definition APFloat.cpp:673
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:305
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:395
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
APSInt extOrTrunc(uint32_t width) const
Definition APSInt.h:119
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:800
void setWeak(bool IsWeak)
static bool isValidFailureOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
static LLVM_ABI StringRef getOperationName(BinOp Op)
static LLVM_ABI AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static LLVM_ABI bool canUseAsRetAttr(AttrKind Kind)
static bool isTypeAttrKind(AttrKind Kind)
Definition Attributes.h:143
static LLVM_ABI bool canUseAsFnAttr(AttrKind Kind)
static LLVM_ABI bool canUseAsParamAttr(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
@ None
No attributes have been set.
Definition Attributes.h:127
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator end()
Definition BasicBlock.h:452
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:205
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 const char * areInvalidOperands(const Type *Ty, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitextract operation, otherwise return nu...
static BitExtractInst * Create(Type *Ty, Value *Src, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI const char * areInvalidOperands(Value *Base, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitinsert operation, otherwise return nul...
static BitInsertInst * Create(Value *Base, Value *Val, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
void setCallingConv(CallingConv::ID CC)
void setAttributes(AttributeList A)
Set the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
Definition ModRef.h:427
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void addSymbolWithThinLTOGUID(StringRef Name, GlobalValue::GUID GUID)
Add the function name and the GUID that ThinLTO uses for it.
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH 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:1477
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition Constants.h:1624
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static LLVM_ABI DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, Metadata *SizeInBits, uint32_t AlignInBits, Metadata *OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, std::optional< uint32_t > EnumKind, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations, Metadata *BitStride)
Build a DICompositeType with the given ODR identifier.
static LLVM_ABI std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
static LLVM_ABI std::optional< FixedPointKind > getFixedPointKind(StringRef Str)
static LLVM_ABI DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
LLVM_ABI void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static LLVM_ABI DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static LLVM_ABI DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static LLVM_ABI DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Kind
Subclass discriminator.
static LLVM_ABI DbgVariableRecord * createUnresolvedDbgVariableRecord(LocationType Type, Metadata *Val, MDNode *Variable, MDNode *Expression, MDNode *AssignID, Metadata *Address, MDNode *AddressExpression)
Used to create DbgVariableRecords during parsing, where some metadata references may still be unresol...
unsigned size() const
Definition DenseMap.h:717
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
bool any() const
Definition FMF.h:56
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static LLVM_ABI bool isValidArgumentType(Type *ArgTy)
Return true if the specified type is valid as an argument type.
Definition Type.cpp:452
Type::subtype_iterator param_iterator
static LLVM_ABI bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition Type.cpp:447
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:169
Argument * arg_iterator
Definition Function.h:73
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:826
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:451
arg_iterator arg_begin()
Definition Function.h:862
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1037
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:332
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
Definition Function.h:1049
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:277
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
static bool isValidLinkage(LinkageTypes L)
Definition GlobalAlias.h:98
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:695
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:752
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:348
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
std::pair< key_type, mapped_type > value_type
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
LLVM_ABI const SanitizerMetadata & getSanitizerMetadata() const
Definition Globals.cpp:318
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
Definition Globals.cpp:110
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
void setLinkage(LinkageTypes LT)
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition GlobalValue.h:74
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ DLLImportStorageClass
Function to be imported from DLL.
Definition GlobalValue.h:76
bool hasSanitizerMetadata() const
unsigned getAddressSpace() const
void setDSOLocal(bool Local)
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:158
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition GlobalValue.h:67
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:234
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:324
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
LLVM_ABI void setPartition(StringRef Part)
Definition Globals.cpp:301
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:613
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition Globals.cpp:663
void setExternallyInitialized(bool Val)
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition InlineAsm.cpp:43
static LLVM_ABI Error verify(FunctionType *Ty, StringRef Constraints)
This static method can be used by the parser to check to see if the specified constraint string is le...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI bool isValidOperands(const Value *Vec, const Value *NewElt, const Value *Idx)
Return true if an insertelement instruction can be formed with the specified operands.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
lltok::Kind Lex()
Definition LLLexer.h:68
lltok::Kind getKind() const
Definition LLLexer.h:73
const std::string & getStrVal() const
Definition LLLexer.h:74
LocTy getLoc() const
Definition LLLexer.h:71
LLVM_ABI bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:171
LLLexer::LocTy LocTy
Definition LLParser.h:111
LLVMContext & getContext()
Definition LLParser.h:243
LLVM_ABI bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:155
LLVM_ABI bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:142
LLVM_ABI bool parseMetadataDefinitions(SlotMapping &Slots, ArrayRef< SMLoc > DefinitionEnds)
Definition LLParser.cpp:186
LLVM_ABI bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:123
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...
Storage class for function-local metadata objects.
static LLVM_ABI MDFunctionLocalContext * getDistinct(LLVMContext &Context, bool NonDebug=false)
Metadata node.
Definition Metadata.h:1087
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1596
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
A single uniqued string.
Definition Metadata.h:734
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1545
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1534
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1554
static MemoryEffectsBase readOnly()
Definition ModRef.h:133
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition ModRef.h:224
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:143
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:149
bool isTargetMemLoc(IRMemLocation Loc) const
Whether location is target memory location.
Definition ModRef.h:279
static MemoryEffectsBase writeOnly()
Definition ModRef.h:138
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Definition ModRef.h:166
static MemoryEffectsBase none()
Definition ModRef.h:128
static MemoryEffectsBase unknown()
Definition ModRef.h:123
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:185
static LLVM_ABI MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition Metadata.cpp:105
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
StringMap< Comdat > ComdatSymTabType
The type of the comdat "symbol" table.
Definition Module.h:83
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:899
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
Represents a location in source code.
Definition SMLoc.h:22
constexpr const char * getPointer() const
Definition SMLoc.h:33
static LLVM_ABI const char * areInvalidOperands(Value *Cond, Value *True, Value *False)
Return a string if the specified operands are invalid for a select operation, otherwise return null.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator end()
Definition StringMap.h:214
iterator find(StringRef Key)
Definition StringMap.h:227
StringMapIterBase< Comdat, false > iterator
Definition StringMap.h:209
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:462
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:657
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:738
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:576
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Definition Type.cpp:937
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:274
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Definition Type.cpp:274
bool isLabelTy() const
Return true if this is 'label'.
Definition Type.h:225
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
static LLVM_ABI Type * getLabelTy(LLVMContext &C)
Definition Type.cpp:268
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
LLVM_ABI bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition Type.cpp:236
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:314
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:268
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:231
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:228
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:512
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
static constexpr uint64_t MaximumAlignment
Definition Value.h:801
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:103
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
CallInst * Call
LLVM_ABI unsigned getSourceLanguageName(StringRef SourceLanguageNameString)
Definition Dwarf.cpp:615
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:275
LLVM_ABI unsigned getLanguageDialect(StringRef LanguageDialectString)
Definition Dwarf.cpp:634
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:670
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
Definition Dwarf.cpp:424
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
Definition Dwarf.cpp:386
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
Definition Dwarf.cpp:405
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
Definition Dwarf.cpp:742
#define UINT64_MAX
Definition DataTypes.h:77
#define INT64_MIN
Definition DataTypes.h:74
#define INT64_MAX
Definition DataTypes.h:71
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
@ AVR_SIGNAL
Used for AVR signal routines.
@ Swift
Calling convention for Swift.
Definition CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
@ CHERIoT_CompartmentCall
Calling convention used for CHERIoT when crossing a protection boundary.
@ CFGuard_Check
Special calling convention on Windows for calling the Control Guard Check ICall funtion.
Definition CallingConv.h:82
@ AVR_INTR
Used for AVR interrupt routines.
@ PreserveMost
Used for runtime calls that preserves most registers.
Definition CallingConv.h:63
@ AnyReg
OBSOLETED - Used for stack based JavaScript calls.
Definition CallingConv.h:60
@ AMDGPU_Gfx
Used for AMD graphics targets.
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
@ CHERIoT_CompartmentCallee
Calling convention used for the callee of CHERIoT_CompartmentCall.
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ CHERIoT_LibraryCall
Calling convention used for CHERIoT for cross-library calls to a stateless compartment.
@ CXX_FAST_TLS
Used for access functions.
Definition CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
@ WASM_EmscriptenInvoke
For emscripten __invoke_* functions.
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
@ AVR_BUILTIN
Used for special AVR rtlib functions which have an "optimized" convention to preserve registers.
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X1
Preserve X1-X15, X19-X29, SP, Z0-Z31, P0-P15.
@ X86_ThisCall
Similar to X86_StdCall.
@ PTX_Device
Call to a PTX device function.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ PreserveAll
Used for runtime calls that preserves (almost) all registers.
Definition CallingConv.h:66
@ X86_StdCall
stdcall is mostly used by the Win32 API.
Definition CallingConv.h:99
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
@ PreserveNone
Used for runtime calls that preserves none general registers.
Definition CallingConv.h:90
@ AMDGPU_ES
Used for AMDPAL shader stage before geometry shader if geometry is in use.
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ Win64
The C convention as implemented on Windows/x86-64 and AArch64.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ GRAAL
Used by GraalVM. Two additional registers are reserved.
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
LLVM_ABI ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
LLVM_ABI bool isSignatureValid(Intrinsic::ID ID, FunctionType *FT, SmallVectorImpl< Type * > &OverloadTys, raw_ostream &OS=nulls())
Returns true if FT is a valid function type for intrinsic ID.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
constexpr bool isPacked(const T &...O)
Definition SIDefines.h:343
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:66
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
@ Init
Initialization function, sets up the coroutine frame.
Definition CodeView.h:644
@ DW_CC_hi_user
Definition Dwarf.h:856
@ DW_ATE_hi_user
Definition Dwarf.h:163
@ DW_LLVM_LANG_DIALECT_max
Definition Dwarf.h:212
@ DW_APPLE_ENUM_KIND_max
Definition Dwarf.h:206
@ DW_LANG_hi_user
Definition Dwarf.h:226
MacinfoRecordType
Definition Dwarf.h:918
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:924
@ DW_VIRTUALITY_max
Definition Dwarf.h:200
@ DW_TAG_hi_user
Definition Dwarf.h:109
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
Definition Dwarf.h:48
@ DW_MACINFO_invalid
Macinfo type for invalid results.
Definition Dwarf.h:50
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Definition Dwarf.h:49
@ kw_msp430_intrcc
Definition LLToken.h:155
@ kw_riscv_vls_cc
Definition LLToken.h:193
@ kw_cxx_fast_tlscc
Definition LLToken.h:175
@ kw_extractvalue
Definition LLToken.h:379
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:523
@ DwarfLangDialect
Definition LLToken.h:526
@ kw_arm_apcscc
Definition LLToken.h:147
@ kw_inteldialect
Definition LLToken.h:129
@ kw_x86_stdcallcc
Definition LLToken.h:142
@ kw_constant
Definition LLToken.h:48
@ kw_initialexec
Definition LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition LLToken.h:153
@ kw_provenance
Definition LLToken.h:227
@ kw_mustBeUnreachable
Definition LLToken.h:429
@ kw_internal
Definition LLToken.h:54
@ kw_wasm_emscripten_invokecc
Definition LLToken.h:190
@ kw_target_mem
Definition LLToken.h:213
@ kw_no_sanitize_hwaddress
Definition LLToken.h:501
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:470
@ kw_canAutoHide
Definition LLToken.h:412
@ kw_alwaysInline
Definition LLToken.h:425
@ kw_insertelement
Definition LLToken.h:376
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:196
@ kw_fmaximumnum
Definition LLToken.h:298
@ kw_inaccessiblememonly
Definition LLToken.h:220
@ kw_amdgpu_gfx
Definition LLToken.h:186
@ kw_getelementptr
Definition LLToken.h:373
@ FloatHexLiteral
Definition LLToken.h:543
@ kw_m68k_rtdcc
Definition LLToken.h:189
@ kw_preserve_nonecc
Definition LLToken.h:170
@ kw_x86_fastcallcc
Definition LLToken.h:143
@ kw_visibility
Definition LLToken.h:408
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:195
@ kw_positivezero
Definition LLToken.h:233
@ kw_unordered
Definition LLToken.h:96
@ kw_singleImpl
Definition LLToken.h:473
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:141
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:450
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:151
@ kw_amdgpu_kernel
Definition LLToken.h:185
@ kw_uselistorder
Definition LLToken.h:394
@ kw_blockcount
Definition LLToken.h:404
@ kw_notEligibleToImport
Definition LLToken.h:409
@ kw_linkonce_odr
Definition LLToken.h:56
@ kw_protected
Definition LLToken.h:66
@ kw_cfiFunctionDecls
Definition LLToken.h:406
@ kw_avr_builtincc
Definition LLToken.h:158
@ kw_dllexport
Definition LLToken.h:61
@ kw_x86_vectorcallcc
Definition LLToken.h:145
@ kw_ptx_device
Definition LLToken.h:160
@ kw_personality
Definition LLToken.h:348
@ DwarfEnumKind
Definition LLToken.h:537
@ kw_declaration
Definition LLToken.h:415
@ kw_elementwise
Definition LLToken.h:94
@ DwarfAttEncoding
Definition LLToken.h:522
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:161
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:428
@ kw_x86_intrcc
Definition LLToken.h:172
@ kw_addrspacecast
Definition LLToken.h:343
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:520
@ kw_x86_thiscallcc
Definition LLToken.h:144
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:194
@ kw_unnamed_addr
Definition LLToken.h:67
@ NameTableKind
Definition LLToken.h:529
@ kw_inlineBits
Definition LLToken.h:468
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:219
@ kw_blockaddress
Definition LLToken.h:381
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:187
@ kw_landingpad
Definition LLToken.h:347
@ kw_aarch64_vector_pcs
Definition LLToken.h:150
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:449
@ FixedPointKind
Definition LLToken.h:530
@ kw_target_mem1
Definition LLToken.h:215
@ kw_ptx_kernel
Definition LLToken.h:159
@ kw_extractelement
Definition LLToken.h:375
@ kw_branchFunnel
Definition LLToken.h:474
@ kw_typeidCompatibleVTable
Definition LLToken.h:455
@ kw_vTableFuncs
Definition LLToken.h:441
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:448
@ kw_no_sanitize_address
Definition LLToken.h:498
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:221
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:504
@ DwarfSourceLangName
Definition LLToken.h:525
@ kw_noRenameOnPromotion
Definition LLToken.h:416
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:184
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:361
@ kw_cfiFunctionDefs
Definition LLToken.h:405
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:148
@ kw_read_provenance
Definition LLToken.h:228
@ kw_cleanuppad
Definition LLToken.h:364
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:476
@ kw_target_mem0
Definition LLToken.h:214
@ kw_swifttailcc
Definition LLToken.h:167
@ kw_monotonic
Definition LLToken.h:97
@ kw_typeTestAssumeVCalls
Definition LLToken.h:447
@ kw_preservesign
Definition LLToken.h:232
@ kw_attributes
Definition LLToken.h:199
@ kw_code_model
Definition LLToken.h:123
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:479
@ kw_sideeffect
Definition LLToken.h:128
@ kw_sizeM1BitWidth
Definition LLToken.h:464
@ kw_nodeduplicate
Definition LLToken.h:263
@ kw_avr_signalcc
Definition LLToken.h:157
@ kw_bitextract
Definition LLToken.h:386
@ kw_exactmatch
Definition LLToken.h:261
@ kw_fminimumnum
Definition LLToken.h:299
@ kw_unreachable
Definition LLToken.h:359
@ kw_intel_ocl_bicc
Definition LLToken.h:140
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:423
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:152
@ kw_preserve_allcc
Definition LLToken.h:169
@ kw_importType
Definition LLToken.h:413
@ kw_cleanupret
Definition LLToken.h:360
@ kw_shufflevector
Definition LLToken.h:377
@ kw_riscv_vector_cc
Definition LLToken.h:192
@ kw_avr_intrcc
Definition LLToken.h:156
@ kw_definition
Definition LLToken.h:414
@ kw_virtualConstProp
Definition LLToken.h:481
@ kw_vcall_visibility
Definition LLToken.h:469
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:212
@ kw_preserve_mostcc
Definition LLToken.h:168
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:149
@ kw_typeTestRes
Definition LLToken.h:457
@ kw_hasEscapingBlockAddress
Definition LLToken.h:430
@ kw_x86_regcallcc
Definition LLToken.h:146
@ kw_typeIdInfo
Definition LLToken.h:445
@ kw_amdgpu_cs_chain
Definition LLToken.h:183
@ kw_dso_local_equivalent
Definition LLToken.h:382
@ kw_x86_64_sysvcc
Definition LLToken.h:163
@ DbgRecordType
Definition LLToken.h:536
@ kw_address_is_null
Definition LLToken.h:226
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:154
@ kw_uniqueRetVal
Definition LLToken.h:480
@ kw_insertvalue
Definition LLToken.h:380
@ kw_speculative
Definition LLToken.h:475
@ kw_indirectbr
Definition LLToken.h:356
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
LLVM_ABI void UpgradeSectionAttributes(Module &M)
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
SaveAndRestore(T &) -> SaveAndRestore< T >
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
DebugVariableAggregate VarID
A unique key that represents one instance of a debug variable.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
AllocFnKind
Definition Attributes.h:54
scope_exit(Callable) -> scope_exit< Callable >
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeInstructionMetadata(Module &M)
Discover metadata used by instructions in this module, and apply the suitable upgrade.
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:649
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
static void assign(DXContainerYAML::SourceInfo::SectionHeader &Dst, const dxbc::SourceInfo::SectionHeader &Src)
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
LLVM_ABI void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
UWTableKind
Definition CodeGen.h:362
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:365
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:364
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:376
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
CaptureComponents
Components of the pointer that may be captured.
Definition ModRef.h:365
iterator_range< SplittingIterator > split(StringRef Str, StringRef Separator)
Split the specified string over a separator and return a range-compatible iterable over its partition...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
IRMemLocation
The locations at which a function might access memory.
Definition ModRef.h:60
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
llvm::function_ref< std::optional< std::string >(StringRef, StringRef)> DataLayoutCallbackTy
Definition Parser.h:37
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
@ NearestTiesToEven
roundTiesToEven.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
PointerUnion< const Value *, const PseudoSourceValue * > ValueType
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
static int64_t upperBound(StackOffset Size)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
bool capturesNothing(CaptureComponents CC)
Definition ModRef.h:375
#define N
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
@ PositiveZero
Denormals are flushed to positive zero.
@ Dynamic
Denormals have unknown treatment.
@ IEEE
IEEE-754 denormal numbers preserved.
static constexpr DenormalMode getInvalid()
static constexpr DenormalMode getIEEE()
Unique FLMD, just a wrapper around a DILocalScope.
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
std::vector< ConstVCall > TypeCheckedLoadConstVCalls
std::vector< VFuncId > TypeCheckedLoadVCalls
std::vector< ConstVCall > TypeTestAssumeConstVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
std::vector< GlobalValue::GUID > TypeTests
List of type identifiers used by this function in llvm.type.test intrinsics referenced by something o...
std::vector< VFuncId > TypeTestAssumeVCalls
List of virtual calls made by this function using (respectively) llvm.assume(llvm....
unsigned NoRenameOnPromotion
This field is written by the ThinLTO prelink stage to decide whether a particular static global value...
unsigned DSOLocal
Indicates that the linker resolved the symbol to a definition from within the same linkage unit.
unsigned CanAutoHide
In the per-module summary, indicates that the global value is linkonce_odr and global unnamed addr (s...
unsigned ImportType
This field is written by the ThinLTO indexing step to postlink combined summary.
unsigned NotEligibleToImport
Indicate if the global value cannot be imported (e.g.
unsigned Linkage
The linkage type of the associated global value.
unsigned Visibility
Indicates the visibility.
unsigned Live
In per-module summary, indicate that the global value must be considered a live root for index-based ...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
LLVM_ABI bool set(StringRef Name, std::string Value)
Set a property using a string name.
Definition Module.cpp:1073
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition SlotMapping.h:32
std::map< unsigned, Type * > Types
Definition SlotMapping.h:36
StringMap< Type * > NamedTypes
Definition SlotMapping.h:35
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition SlotMapping.h:34
NumberedValues< GlobalValue * > GlobalValues
Definition SlotMapping.h:33
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
TypeTestResolution TTRes
@ Unknown
Unknown (analysis not performed, don't lower)
@ Single
Single element (last example in "Short Inline Bit Vectors")
@ Inline
Inlined bit vector ("Short Inline Bit Vectors")
@ Unsat
Unsatisfiable type (i.e. no global has this type metadata)
@ AllOnes
All-ones bit vector ("Eliminating Bit Vector Checks for All-Ones Bit Vectors")
@ ByteArray
Test a byte array (first example)
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Definition LLParser.h:55
@ t_PackedConstantStruct
Definition LLParser.h:73
@ t_ConstantStruct
Definition LLParser.h:72
@ t_ConstantSplat
Definition LLParser.h:70
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
unsigned UIntVal
Definition LLParser.h:77
FunctionType * FTy
Definition LLParser.h:78
LLLexer::LocTy Loc
Definition LLParser.h:76
std::string StrVal
Definition LLParser.h:79
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.
@ Speculative
Speculative devirtualization.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.