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"
34#include "llvm/IR/GlobalIFunc.h"
36#include "llvm/IR/InlineAsm.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/Metadata.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Operator.h"
45#include "llvm/IR/Value.h"
51#include "llvm/Support/ModRef.h"
54#include <algorithm>
55#include <cassert>
56#include <cstring>
57#include <optional>
58#include <vector>
59
60using namespace llvm;
61
63 "allow-incomplete-ir", cl::init(false), cl::Hidden,
65 "Allow incomplete IR on a best effort basis (references to unknown "
66 "metadata will be dropped)"));
67
68static std::string getTypeString(Type *T) {
69 std::string Result;
70 raw_string_ostream Tmp(Result);
71 Tmp << *T;
72 return Tmp.str();
73}
74
75/// Return whether skipped trivia contains a block comment that crosses the
76/// boundary between two metadata definitions.
77static bool blockCommentCrossesBoundary(SMLoc BeginLoc, SMLoc EndLoc,
78 SMLoc BoundaryLoc) {
79 const char *Begin = BeginLoc.getPointer();
80 const char *End = EndLoc.getPointer();
81 const char *Boundary = BoundaryLoc.getPointer();
82 const char *BlockCommentStart = nullptr;
83 bool InLineComment = false;
84
85 for (const char *Ptr = Begin; Ptr < End;) {
86 if (BlockCommentStart) {
87 if (Ptr + 1 < End && Ptr[0] == '*' && Ptr[1] == '/') {
88 Ptr += 2;
89 if (BlockCommentStart < Boundary && Ptr > Boundary)
90 return true;
91 BlockCommentStart = nullptr;
92 continue;
93 }
94 ++Ptr;
95 continue;
96 }
97
98 if (InLineComment) {
99 if (*Ptr == '\n' || *Ptr == '\r')
100 InLineComment = false;
101 ++Ptr;
102 continue;
103 }
104
105 if (*Ptr == ';') {
106 InLineComment = true;
107 ++Ptr;
108 continue;
109 }
110 if (Ptr + 1 < End && Ptr[0] == '/' && Ptr[1] == '*') {
111 BlockCommentStart = Ptr;
112 Ptr += 2;
113 continue;
114 }
115 ++Ptr;
116 }
117
118 return BlockCommentStart && BlockCommentStart < Boundary && End > Boundary;
119}
120
121/// Run: module ::= toplevelentity*
123 DataLayoutCallbackTy DataLayoutCallback) {
124 // Prime the lexer.
125 Lex.Lex();
126
127 if (Context.shouldDiscardValueNames())
128 return error(
129 Lex.getLoc(),
130 "Can't read textual IR with a Context that discards named Values");
131
132 if (M) {
133 if (parseTargetDefinitions(DataLayoutCallback))
134 return true;
135 }
136
137 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
138 validateEndOfIndex();
139}
140
142 const SlotMapping *Slots) {
143 restoreParsingState(Slots);
144 Lex.Lex();
145
146 Type *Ty = nullptr;
147 if (parseType(Ty) || parseConstantValue(Ty, C))
148 return true;
149 if (Lex.getKind() != lltok::Eof)
150 return error(Lex.getLoc(), "expected end of string");
151 return false;
152}
153
155 const SlotMapping *Slots) {
156 restoreParsingState(Slots);
157 Lex.Lex();
158
159 Read = 0;
160 SMLoc Start = Lex.getLoc();
161 Ty = nullptr;
162 if (parseType(Ty))
163 return true;
164 SMLoc End = Lex.getLoc();
165 Read = End.getPointer() - Start.getPointer();
166
167 return false;
168}
169
171 const SlotMapping *Slots) {
172 restoreParsingState(Slots);
173 Lex.Lex();
174
175 Read = 0;
176 SMLoc Start = Lex.getLoc();
177 Result = nullptr;
178 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
179 SMLoc End = Lex.getLoc();
180 Read = End.getPointer() - Start.getPointer();
181
182 return Status;
183}
184
186 ArrayRef<SMLoc> DefinitionEnds) {
187 restoreParsingState(&Slots);
188 Lex.Lex();
189
190 for (SMLoc End : DefinitionEnds) {
191 if (Lex.getLoc().getPointer() >= End.getPointer())
192 return error(End, "expected end of metadata definition");
193 if (Lex.getKind() != lltok::exclaim)
194 return tokError("expected a metadata definition");
195 if (parseStandaloneMetadata())
196 return true;
197 if (Lex.getPrevTokEndLoc().getPointer() > End.getPointer() ||
198 (Lex.getKind() != lltok::Eof &&
199 Lex.getLoc().getPointer() < End.getPointer()) ||
200 blockCommentCrossesBoundary(Lex.getPrevTokEndLoc(), Lex.getLoc(), End))
201 return error(End, "expected end of metadata definition");
202 }
203
204 if (Lex.getKind() != lltok::Eof)
205 return tokError("expected end of metadata definitions");
206
207 if (!ForwardRefMDNodes.empty())
208 return error(ForwardRefMDNodes.begin()->second.second,
209 "use of undefined metadata '!" +
210 Twine(ForwardRefMDNodes.begin()->first) + "'");
211
212 for (auto &[_, MD] : NumberedMetadata)
213 if (MD && !MD->isResolved())
214 MD->resolveCycles();
216 NewDistinctSPs.clear();
217
218 Slots.MetadataNodes = std::move(NumberedMetadata);
219 return false;
220}
221
222void LLParser::restoreParsingState(const SlotMapping *Slots) {
223 if (!Slots)
224 return;
225 NumberedVals = Slots->GlobalValues;
226 NumberedMetadata = Slots->MetadataNodes;
227 for (const auto &I : Slots->NamedTypes)
228 NamedTypes.insert(
229 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
230 for (const auto &I : Slots->Types)
231 NumberedTypes.insert(
232 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
233}
234
236 // White-list intrinsics that are safe to drop.
238 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
239 return;
240
242 for (Value *V : II->args())
243 if (auto *MV = dyn_cast<MetadataAsValue>(V))
244 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
245 if (MD->isTemporary())
246 MVs.push_back(MV);
247
248 if (!MVs.empty()) {
249 assert(II->use_empty() && "Cannot have uses");
250 II->eraseFromParent();
251
252 // Also remove no longer used MetadataAsValue wrappers.
253 for (MetadataAsValue *MV : MVs)
254 if (MV->use_empty())
255 delete MV;
256 }
257}
258
259void LLParser::dropUnknownMetadataReferences() {
260 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
261 for (Function &F : *M) {
262 F.eraseMetadataIf(Pred);
263 for (Instruction &I : make_early_inc_range(instructions(F))) {
264 I.eraseMetadataIf(Pred);
265
266 if (auto *II = dyn_cast<IntrinsicInst>(&I))
268 }
269 }
270
271 for (GlobalVariable &GV : M->globals())
272 GV.eraseMetadataIf(Pred);
273
274 llvm::erase_if(PendingDbgRecords,
275 [](const auto &E) { return std::get<2>(E)->isTemporary(); });
276 llvm::erase_if(PendingDbgInsts,
277 [](const auto &E) { return std::get<2>(E)->isTemporary(); });
278
279 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
280 // Check whether there is only a single use left, which would be in our
281 // own NumberedMetadata.
282 if (Info.first->getNumTemporaryUses() == 1) {
283 NumberedMetadata.erase(ID);
284 ForwardRefMDNodes.erase(ID);
285 }
286 }
287}
288
289/// validateEndOfModule - Do final validity and basic correctness checks at the
290/// end of the module.
291bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
292 if (!M)
293 return false;
294
295 // We should have already returned an error if we observed both intrinsics and
296 // records in this IR.
297 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
298 "Mixed debug intrinsics/records seen without a parsing error?");
299
300 // Handle any function attribute group forward references.
301 for (const auto &RAG : ForwardRefAttrGroups) {
302 Value *V = RAG.first;
303 const std::vector<unsigned> &Attrs = RAG.second;
304 AttrBuilder B(Context);
305
306 for (const auto &Attr : Attrs) {
307 auto R = NumberedAttrBuilders.find(Attr);
308 if (R != NumberedAttrBuilders.end())
309 B.merge(R->second);
310 }
311
312 if (Function *Fn = dyn_cast<Function>(V)) {
313 AttributeList AS = Fn->getAttributes();
314 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
315 AS = AS.removeFnAttributes(Context);
316
317 FnAttrs.merge(B);
318
319 // If the alignment was parsed as an attribute, move to the alignment
320 // field.
321 if (MaybeAlign A = FnAttrs.getAlignment()) {
322 Fn->setAlignment(*A);
323 FnAttrs.removeAttribute(Attribute::Alignment);
324 }
325
326 AS = AS.addFnAttributes(Context, FnAttrs);
327 Fn->setAttributes(AS);
328 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
329 AttributeList AS = CI->getAttributes();
330 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
331 AS = AS.removeFnAttributes(Context);
332 FnAttrs.merge(B);
333 AS = AS.addFnAttributes(Context, FnAttrs);
334 CI->setAttributes(AS);
335 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
336 AttributeList AS = II->getAttributes();
337 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
338 AS = AS.removeFnAttributes(Context);
339 FnAttrs.merge(B);
340 AS = AS.addFnAttributes(Context, FnAttrs);
341 II->setAttributes(AS);
342 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
343 AttributeList AS = CBI->getAttributes();
344 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
345 AS = AS.removeFnAttributes(Context);
346 FnAttrs.merge(B);
347 AS = AS.addFnAttributes(Context, FnAttrs);
348 CBI->setAttributes(AS);
349 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
350 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
351 Attrs.merge(B);
352 GV->setAttributes(AttributeSet::get(Context,Attrs));
353 } else {
354 llvm_unreachable("invalid object with forward attribute group reference");
355 }
356 }
357
358 // If there are entries in ForwardRefBlockAddresses at this point, the
359 // function was never defined.
360 if (!ForwardRefBlockAddresses.empty())
361 return error(ForwardRefBlockAddresses.begin()->first.Loc,
362 "expected function name in blockaddress");
363
364 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
365 GlobalValue *FwdRef) {
366 GlobalValue *GV = nullptr;
367 if (GVRef.Kind == ValID::t_GlobalName) {
368 GV = M->getNamedValue(GVRef.StrVal);
369 } else {
370 GV = NumberedVals.get(GVRef.UIntVal);
371 }
372
373 if (!GV)
374 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
375 "' referenced by dso_local_equivalent");
376
377 if (!GV->getValueType()->isFunctionTy())
378 return error(GVRef.Loc,
379 "expected a function, alias to function, or ifunc "
380 "in dso_local_equivalent");
381
382 auto *Equiv = DSOLocalEquivalent::get(GV);
383 FwdRef->replaceAllUsesWith(Equiv);
384 FwdRef->eraseFromParent();
385 return false;
386 };
387
388 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
389 // point, they are references after the function was defined. Resolve those
390 // now.
391 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
392 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
393 return true;
394 }
395 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
396 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
397 return true;
398 }
399 ForwardRefDSOLocalEquivalentIDs.clear();
400 ForwardRefDSOLocalEquivalentNames.clear();
401
402 for (const auto &NT : NumberedTypes)
403 if (NT.second.second.isValid())
404 return error(NT.second.second,
405 "use of undefined type '%" + Twine(NT.first) + "'");
406
407 for (const auto &[Name, TypeInfo] : NamedTypes)
408 if (TypeInfo.second.isValid())
409 return error(TypeInfo.second,
410 "use of undefined type named '" + Name + "'");
411
412 if (!ForwardRefComdats.empty())
413 return error(ForwardRefComdats.begin()->second,
414 "use of undefined comdat '$" +
415 ForwardRefComdats.begin()->first + "'");
416
417 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
418 dropUnknownMetadataReferences();
419
420 if (!ForwardRefMDNodes.empty())
421 return error(ForwardRefMDNodes.begin()->second.second,
422 "use of undefined metadata '!" +
423 Twine(ForwardRefMDNodes.begin()->first) + "'");
424
425 // Set debug locations.
426 for (auto [Loc, DR, MD] : PendingDbgRecords) {
427 if (auto *DI = dyn_cast<DILocation>(MD))
428 DR->setDebugLoc(DebugLoc(DI));
429 else
430 return error(Loc, "invalid debug location");
431 }
432 PendingDbgRecords.clear();
433 for (auto [Loc, I, MD] : PendingDbgInsts) {
434 if (auto *DI = dyn_cast<DILocation>(MD))
435 I->setDebugLoc(DebugLoc(DI));
436 else
437 return error(Loc, "invalid !dbg metadata");
438 }
439 PendingDbgInsts.clear();
440
441 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
442 if (StringRef(Name).starts_with("llvm.")) {
444 // Automatically create declarations for intrinsics. Intrinsics can only
445 // be called directly, so the call function type directly determines the
446 // declaration function type.
447 //
448 // Additionally, automatically add the required mangling suffix to the
449 // intrinsic name. This means that we may replace a single forward
450 // declaration with multiple functions here.
451 for (Use &U : make_early_inc_range(Info.first->uses())) {
452 auto *CB = dyn_cast<CallBase>(U.getUser());
453 if (!CB || !CB->isCallee(&U))
454 return error(Info.second, "intrinsic can only be used as callee");
455
456 std::string ErrorMsg;
457 raw_string_ostream ErrorOS(ErrorMsg);
458
459 SmallVector<Type *> OverloadTys;
460 if (IID != Intrinsic::not_intrinsic &&
461 Intrinsic::isSignatureValid(IID, CB->getFunctionType(), OverloadTys,
462 ErrorOS)) {
463 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
464 } else {
465 // Try to upgrade the intrinsic.
466 Function *TmpF = Function::Create(CB->getFunctionType(),
468 Function *NewF = nullptr;
469 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
470 if (IID == Intrinsic::not_intrinsic)
471 return error(Info.second, "unknown intrinsic '" + Name + "'");
472 return error(Info.second, ErrorMsg);
473 }
474
475 U.set(TmpF);
476 UpgradeIntrinsicCall(CB, NewF);
477 if (TmpF->use_empty())
478 TmpF->eraseFromParent();
479 }
480 }
481
482 Info.first->eraseFromParent();
483 ForwardRefVals.erase(Name);
484 continue;
485 }
486
487 // If incomplete IR is allowed, also add declarations for
488 // non-intrinsics.
490 continue;
491
492 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
493 FunctionType *FTy = nullptr;
494 for (Use &U : V->uses()) {
495 auto *CB = dyn_cast<CallBase>(U.getUser());
496 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
497 return nullptr;
498 FTy = CB->getFunctionType();
499 }
500 return FTy;
501 };
502
503 // First check whether this global is only used in calls with the same
504 // type, in which case we'll insert a function. Otherwise, fall back to
505 // using a dummy i8 type.
506 Type *Ty = GetCommonFunctionType(Info.first);
507 if (!Ty)
508 Ty = Type::getInt8Ty(Context);
509
510 GlobalValue *GV;
511 if (auto *FTy = dyn_cast<FunctionType>(Ty))
513 else
514 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
516 /*Initializer*/ nullptr, Name);
517 Info.first->replaceAllUsesWith(GV);
518 Info.first->eraseFromParent();
519 ForwardRefVals.erase(Name);
520 }
521
522 if (!ForwardRefVals.empty())
523 return error(ForwardRefVals.begin()->second.second,
524 "use of undefined value '@" + ForwardRefVals.begin()->first +
525 "'");
526
527 if (!ForwardRefValIDs.empty())
528 return error(ForwardRefValIDs.begin()->second.second,
529 "use of undefined value '@" +
530 Twine(ForwardRefValIDs.begin()->first) + "'");
531
532 // Resolve metadata cycles.
533 for (auto &N : NumberedMetadata) {
534 if (N.second && !N.second->isResolved())
535 N.second->resolveCycles();
536 }
537
539 NewDistinctSPs.clear();
540
541 // Look for intrinsic functions and CallInst that need to be upgraded. We use
542 // make_early_inc_range here because we may remove some functions.
545
548
555
556 if (!Slots)
557 return false;
558 // Initialize the slot mapping.
559 // Because by this point we've parsed and validated everything, we can "steal"
560 // the mapping from LLParser as it doesn't need it anymore.
561 Slots->GlobalValues = std::move(NumberedVals);
562 Slots->MetadataNodes = std::move(NumberedMetadata);
563 for (const auto &I : NamedTypes)
564 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
565 for (const auto &I : NumberedTypes)
566 Slots->Types.insert(std::make_pair(I.first, I.second.first));
567
568 return false;
569}
570
571/// Do final validity and basic correctness checks at the end of the index.
572bool LLParser::validateEndOfIndex() {
573 if (!Index)
574 return false;
575
576 if (!ForwardRefValueInfos.empty())
577 return error(ForwardRefValueInfos.begin()->second.front().second,
578 "use of undefined summary '^" +
579 Twine(ForwardRefValueInfos.begin()->first) + "'");
580
581 if (!ForwardRefAliasees.empty())
582 return error(ForwardRefAliasees.begin()->second.front().second,
583 "use of undefined summary '^" +
584 Twine(ForwardRefAliasees.begin()->first) + "'");
585
586 if (!ForwardRefTypeIds.empty())
587 return error(ForwardRefTypeIds.begin()->second.front().second,
588 "use of undefined type id summary '^" +
589 Twine(ForwardRefTypeIds.begin()->first) + "'");
590
591 return false;
592}
593
594//===----------------------------------------------------------------------===//
595// Top-Level Entities
596//===----------------------------------------------------------------------===//
597
598bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
599 // Delay parsing of the data layout string until the target triple is known.
600 // Then, pass both the the target triple and the tentative data layout string
601 // to DataLayoutCallback, allowing to override the DL string.
602 // This enables importing modules with invalid DL strings.
603 std::string TentativeDLStr = M->getDataLayoutStr();
604 LocTy DLStrLoc;
605
606 bool Done = false;
607 while (!Done) {
608 switch (Lex.getKind()) {
609 case lltok::kw_target:
610 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
611 return true;
612 break;
614 if (parseSourceFileName())
615 return true;
616 break;
617 default:
618 Done = true;
619 }
620 }
621 // Run the override callback to potentially change the data layout string, and
622 // parse the data layout string.
623 if (auto LayoutOverride =
624 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
625 TentativeDLStr = *LayoutOverride;
626 DLStrLoc = {};
627 }
628 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
629 if (!MaybeDL)
630 return error(DLStrLoc, toString(MaybeDL.takeError()));
631 M->setDataLayout(MaybeDL.get());
632 return false;
633}
634
635bool LLParser::parseTopLevelEntities() {
636 // If there is no Module, then parse just the summary index entries.
637 if (!M) {
638 while (true) {
639 switch (Lex.getKind()) {
640 case lltok::Eof:
641 return false;
642 case lltok::SummaryID:
643 if (parseSummaryEntry())
644 return true;
645 break;
647 if (parseSourceFileName())
648 return true;
649 break;
650 default:
651 // Skip everything else
652 Lex.Lex();
653 }
654 }
655 }
656 while (true) {
657 switch (Lex.getKind()) {
658 default:
659 return tokError("expected top-level entity");
660 case lltok::Eof: return false;
662 if (parseDeclare())
663 return true;
664 break;
665 case lltok::kw_define:
666 if (parseDefine())
667 return true;
668 break;
669 case lltok::kw_module:
670 if (parseModuleAsm())
671 return true;
672 break;
674 if (parseUnnamedType())
675 return true;
676 break;
677 case lltok::LocalVar:
678 if (parseNamedType())
679 return true;
680 break;
681 case lltok::GlobalID:
682 if (parseUnnamedGlobal())
683 return true;
684 break;
685 case lltok::GlobalVar:
686 if (parseNamedGlobal())
687 return true;
688 break;
689 case lltok::ComdatVar: if (parseComdat()) return true; break;
690 case lltok::exclaim:
691 if (parseStandaloneMetadata())
692 return true;
693 break;
694 case lltok::SummaryID:
695 if (parseSummaryEntry())
696 return true;
697 break;
699 if (parseNamedMetadata())
700 return true;
701 break;
703 if (parseUnnamedAttrGrp())
704 return true;
705 break;
707 if (parseUseListOrder())
708 return true;
709 break;
710 }
711 }
712}
713
714/// toplevelentity
715/// ::= 'module' 'asm' STRINGCONSTANT
716/// ::= 'module' 'asm' '(' 'property_name1:' STRINGCONSTANT ','
717/// 'property_name2:' STRINGCONSTANT ')'
718/// STRINGCONSTANT
719bool LLParser::parseModuleAsm() {
720 assert(Lex.getKind() == lltok::kw_module);
721 Lex.Lex();
722
723 std::string AsmStr;
724 if (parseToken(lltok::kw_asm, "expected 'module asm'"))
725 return true;
726
727 Module::GlobalAsmProperties Props;
728 if (EatIfPresent(lltok::lparen)) {
729 while (true) {
730 std::string Key, Value;
731 SMLoc Loc = Lex.getLoc();
732 if (Lex.getKind() != lltok::LabelStr)
733 return error(Loc, "expected property name followed by ':'");
734
735 Key = Lex.getStrVal();
736 Lex.Lex();
737
738 if (parseStringConstant(Value))
739 return true;
740
741 if (!Props.set(Key, Value))
742 return error(Loc, "unknown property name");
743
744 if (EatIfPresent(lltok::rparen))
745 break;
746 if (parseToken(lltok::comma, "expected ',' or ')'"))
747 return true;
748 }
749 }
750
751 do {
752 std::string AsmStrPart;
753 if (parseStringConstant(AsmStrPart))
754 return true;
755 AsmStr += AsmStrPart + "\n";
756 } while (Lex.getKind() == lltok::StringConstant);
757
758 M->appendModuleInlineAsm({AsmStr, Props});
759 return false;
760}
761
762/// toplevelentity
763/// ::= 'target' 'triple' '=' STRINGCONSTANT
764/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
765bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
766 LocTy &DLStrLoc) {
767 assert(Lex.getKind() == lltok::kw_target);
768 std::string Str;
769 switch (Lex.Lex()) {
770 default:
771 return tokError("unknown target property");
772 case lltok::kw_triple:
773 Lex.Lex();
774 if (parseToken(lltok::equal, "expected '=' after target triple") ||
775 parseStringConstant(Str))
776 return true;
777 M->setTargetTriple(Triple(std::move(Str)));
778 return false;
780 Lex.Lex();
781 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
782 return true;
783 DLStrLoc = Lex.getLoc();
784 if (parseStringConstant(TentativeDLStr))
785 return true;
786 return false;
787 }
788}
789
790/// toplevelentity
791/// ::= 'source_filename' '=' STRINGCONSTANT
792bool LLParser::parseSourceFileName() {
793 assert(Lex.getKind() == lltok::kw_source_filename);
794 Lex.Lex();
795 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
796 parseStringConstant(SourceFileName))
797 return true;
798 if (M)
799 M->setSourceFileName(SourceFileName);
800 return false;
801}
802
803/// parseUnnamedType:
804/// ::= LocalVarID '=' 'type' type
805bool LLParser::parseUnnamedType() {
806 LocTy TypeLoc = Lex.getLoc();
807 unsigned TypeID = Lex.getUIntVal();
808 Lex.Lex(); // eat LocalVarID;
809
810 if (parseToken(lltok::equal, "expected '=' after name") ||
811 parseToken(lltok::kw_type, "expected 'type' after '='"))
812 return true;
813
814 Type *Result = nullptr;
815 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
816 return true;
817
818 if (!isa<StructType>(Result)) {
819 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
820 if (Entry.first)
821 return error(TypeLoc, "non-struct types may not be recursive");
822 Entry.first = Result;
823 Entry.second = SMLoc();
824 }
825
826 return false;
827}
828
829/// toplevelentity
830/// ::= LocalVar '=' 'type' type
831bool LLParser::parseNamedType() {
832 std::string Name = Lex.getStrVal();
833 LocTy NameLoc = Lex.getLoc();
834 Lex.Lex(); // eat LocalVar.
835
836 if (parseToken(lltok::equal, "expected '=' after name") ||
837 parseToken(lltok::kw_type, "expected 'type' after name"))
838 return true;
839
840 Type *Result = nullptr;
841 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
842 return true;
843
844 if (!isa<StructType>(Result)) {
845 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
846 if (Entry.first)
847 return error(NameLoc, "non-struct types may not be recursive");
848 Entry.first = Result;
849 Entry.second = SMLoc();
850 }
851
852 return false;
853}
854
855/// toplevelentity
856/// ::= 'declare' FunctionHeader
857bool LLParser::parseDeclare() {
858 assert(Lex.getKind() == lltok::kw_declare);
859 Lex.Lex();
860
861 std::vector<std::pair<unsigned, MDNode *>> MDs;
862 while (Lex.getKind() == lltok::MetadataVar) {
863 unsigned MDK;
864 MDNode *N;
865 if (parseMetadataAttachment(MDK, N))
866 return true;
867 MDs.push_back({MDK, N});
868 }
869
870 Function *F;
871 unsigned FunctionNumber = -1;
872 SmallVector<unsigned> UnnamedArgNums;
873 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
874 return true;
875 for (auto &MD : MDs)
876 F->addMetadata(MD.first, *MD.second);
877 return false;
878}
879
880/// toplevelentity
881/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
882bool LLParser::parseDefine() {
883 assert(Lex.getKind() == lltok::kw_define);
884
885 FileLoc FunctionStart = getTokLineColumnPos();
886 Lex.Lex();
887
888 Function *F;
889 unsigned FunctionNumber = -1;
890 SmallVector<unsigned> UnnamedArgNums;
891 bool RetValue =
892 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
893 parseOptionalFunctionMetadata(*F) ||
894 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
895 if (ParserContext)
896 ParserContext->addFunctionLocation(
897 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
898
899 return RetValue;
900}
901
902/// parseGlobalType
903/// ::= 'constant'
904/// ::= 'global'
905bool LLParser::parseGlobalType(bool &IsConstant) {
906 if (Lex.getKind() == lltok::kw_constant)
907 IsConstant = true;
908 else if (Lex.getKind() == lltok::kw_global)
909 IsConstant = false;
910 else {
911 IsConstant = false;
912 return tokError("expected 'global' or 'constant'");
913 }
914 Lex.Lex();
915 return false;
916}
917
918bool LLParser::parseOptionalUnnamedAddr(
919 GlobalVariable::UnnamedAddr &UnnamedAddr) {
920 if (EatIfPresent(lltok::kw_unnamed_addr))
922 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
924 else
925 UnnamedAddr = GlobalValue::UnnamedAddr::None;
926 return false;
927}
928
929/// parseUnnamedGlobal:
930/// OptionalVisibility (ALIAS | IFUNC) ...
931/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
932/// OptionalDLLStorageClass
933/// ... -> global variable
934/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
935/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
936/// OptionalVisibility
937/// OptionalDLLStorageClass
938/// ... -> global variable
939bool LLParser::parseUnnamedGlobal() {
940 unsigned VarID;
941 std::string Name;
942 LocTy NameLoc = Lex.getLoc();
943
944 // Handle the GlobalID form.
945 if (Lex.getKind() == lltok::GlobalID) {
946 VarID = Lex.getUIntVal();
947 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
948 return true;
949
950 Lex.Lex(); // eat GlobalID;
951 if (parseToken(lltok::equal, "expected '=' after name"))
952 return true;
953 } else {
954 VarID = NumberedVals.getNext();
955 }
956
957 bool HasLinkage;
958 unsigned Linkage, Visibility, DLLStorageClass;
959 bool DSOLocal;
961 GlobalVariable::UnnamedAddr UnnamedAddr;
962 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
963 DSOLocal) ||
964 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
965 return true;
966
967 switch (Lex.getKind()) {
968 default:
969 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
970 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
971 case lltok::kw_alias:
972 case lltok::kw_ifunc:
973 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
974 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
975 }
976}
977
978/// parseNamedGlobal:
979/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
980/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
981/// OptionalVisibility OptionalDLLStorageClass
982/// ... -> global variable
983bool LLParser::parseNamedGlobal() {
984 assert(Lex.getKind() == lltok::GlobalVar);
985 LocTy NameLoc = Lex.getLoc();
986 std::string Name = Lex.getStrVal();
987 Lex.Lex();
988
989 bool HasLinkage;
990 unsigned Linkage, Visibility, DLLStorageClass;
991 bool DSOLocal;
993 GlobalVariable::UnnamedAddr UnnamedAddr;
994 if (parseToken(lltok::equal, "expected '=' in global variable") ||
995 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
996 DSOLocal) ||
997 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
998 return true;
999
1000 switch (Lex.getKind()) {
1001 default:
1002 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
1003 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1004 case lltok::kw_alias:
1005 case lltok::kw_ifunc:
1006 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
1007 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
1008 }
1009}
1010
1011bool LLParser::parseComdat() {
1012 assert(Lex.getKind() == lltok::ComdatVar);
1013 std::string Name = Lex.getStrVal();
1014 LocTy NameLoc = Lex.getLoc();
1015 Lex.Lex();
1016
1017 if (parseToken(lltok::equal, "expected '=' here"))
1018 return true;
1019
1020 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
1021 return tokError("expected comdat type");
1022
1024 switch (Lex.getKind()) {
1025 default:
1026 return tokError("unknown selection kind");
1027 case lltok::kw_any:
1028 SK = Comdat::Any;
1029 break;
1031 SK = Comdat::ExactMatch;
1032 break;
1033 case lltok::kw_largest:
1034 SK = Comdat::Largest;
1035 break;
1038 break;
1039 case lltok::kw_samesize:
1040 SK = Comdat::SameSize;
1041 break;
1042 }
1043 Lex.Lex();
1044
1045 // See if the comdat was forward referenced, if so, use the comdat.
1046 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1047 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1048 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
1049 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
1050
1051 Comdat *C;
1052 if (I != ComdatSymTab.end())
1053 C = &I->second;
1054 else
1055 C = M->getOrInsertComdat(Name);
1056 C->setSelectionKind(SK);
1057
1058 return false;
1059}
1060
1061// MDString:
1062// ::= '!' STRINGCONSTANT
1063bool LLParser::parseMDString(MDString *&Result) {
1064 std::string Str;
1065 if (parseStringConstant(Str))
1066 return true;
1067 Result = MDString::get(Context, Str);
1068 return false;
1069}
1070
1071// MDNode:
1072// ::= '!' MDNodeNumber
1073bool LLParser::parseMDNodeID(MDNode *&Result) {
1074 // !{ ..., !42, ... }
1075 LocTy IDLoc = Lex.getLoc();
1076 unsigned MID = 0;
1077 if (parseUInt32(MID))
1078 return true;
1079
1080 // If not a forward reference, just return it now.
1081 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
1082 if (!Inserted) {
1083 Result = It->second;
1084 return false;
1085 }
1086
1087 // Otherwise, create MDNode forward reference.
1088 auto &FwdRef = ForwardRefMDNodes[MID];
1089 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
1090
1091 Result = FwdRef.first.get();
1092 It->second.reset(Result);
1093 return false;
1094}
1095
1096/// parseNamedMetadata:
1097/// !foo = !{ !1, !2 }
1098bool LLParser::parseNamedMetadata() {
1099 assert(Lex.getKind() == lltok::MetadataVar);
1100 std::string Name = Lex.getStrVal();
1101 Lex.Lex();
1102
1103 if (parseToken(lltok::equal, "expected '=' here") ||
1104 parseToken(lltok::exclaim, "Expected '!' here") ||
1105 parseToken(lltok::lbrace, "Expected '{' here"))
1106 return true;
1107
1108 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
1109 if (Lex.getKind() != lltok::rbrace)
1110 do {
1111 MDNode *N = nullptr;
1112 // parse DIExpressions inline as a special case. They are still MDNodes,
1113 // so they can still appear in named metadata. Remove this logic if they
1114 // become plain Metadata.
1115 if (Lex.getKind() == lltok::MetadataVar &&
1116 Lex.getStrVal() == "DIExpression") {
1117 if (parseDIExpression(N, /*IsDistinct=*/false))
1118 return true;
1119 // DIArgLists should only appear inline in a function, as they may
1120 // contain LocalAsMetadata arguments which require a function context.
1121 } else if (Lex.getKind() == lltok::MetadataVar &&
1122 Lex.getStrVal() == "DIArgList") {
1123 return tokError("found DIArgList outside of function");
1124 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1125 parseMDNodeID(N)) {
1126 return true;
1127 }
1128 NMD->addOperand(N);
1129 } while (EatIfPresent(lltok::comma));
1130
1131 return parseToken(lltok::rbrace, "expected end of metadata node");
1132}
1133
1134/// parseStandaloneMetadata:
1135/// !42 = !{...}
1136bool LLParser::parseStandaloneMetadata() {
1137 assert(Lex.getKind() == lltok::exclaim);
1138 Lex.Lex();
1139 unsigned MetadataID = 0;
1140
1141 MDNode *Init;
1142 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1143 return true;
1144
1145 // Detect common error, from old metadata syntax.
1146 if (Lex.getKind() == lltok::Type)
1147 return tokError("unexpected type in metadata definition");
1148
1149 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1150 if (Lex.getKind() == lltok::MetadataVar) {
1151 if (parseSpecializedMDNode(Init, IsDistinct))
1152 return true;
1153 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1154 parseMDTuple(Init, IsDistinct))
1155 return true;
1156
1157 // See if this was forward referenced, if so, handle it.
1158 auto FI = ForwardRefMDNodes.find(MetadataID);
1159 if (FI != ForwardRefMDNodes.end()) {
1160 auto *ToReplace = FI->second.first.get();
1161 // DIAssignID has its own special forward-reference "replacement" for
1162 // attachments (the temporary attachments are never actually attached).
1163 if (isa<DIAssignID>(Init)) {
1164 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1165 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1166 "Inst unexpectedly already has DIAssignID attachment");
1167 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1168 }
1169 }
1170
1171 ToReplace->replaceAllUsesWith(Init);
1172 ForwardRefMDNodes.erase(FI);
1173
1174 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1175 } else {
1176 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1177 if (!Inserted)
1178 return tokError("Metadata id is already used");
1179 It->second.reset(Init);
1180 }
1181
1182 return false;
1183}
1184
1185// Skips a single module summary entry.
1186bool LLParser::skipModuleSummaryEntry() {
1187 // Each module summary entry consists of a tag for the entry
1188 // type, followed by a colon, then the fields which may be surrounded by
1189 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1190 // support is in place we will look for the tokens corresponding to the
1191 // expected tags.
1192 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1193 Lex.getKind() != lltok::kw_typeid &&
1194 Lex.getKind() != lltok::kw_typeidCompatibleVTable &&
1195 Lex.getKind() != lltok::kw_flags &&
1196 Lex.getKind() != lltok::kw_blockcount &&
1197 Lex.getKind() != lltok::kw_cfiFunctionDefs &&
1198 Lex.getKind() != lltok::kw_cfiFunctionDecls)
1199 return tokError("Expected 'gv', 'module', 'typeid', "
1200 "'typeidCompatibleVTable', 'flags', 'blockcount', "
1201 "'cfiFunctionDefs' or 'cfiFunctionDecls' at the start of "
1202 "summary entry");
1203 if (Lex.getKind() == lltok::kw_flags)
1204 return parseSummaryIndexFlags();
1205 if (Lex.getKind() == lltok::kw_blockcount)
1206 return parseBlockCount();
1207 Lex.Lex();
1208 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1209 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1210 return true;
1211 // Now walk through the parenthesized entry, until the number of open
1212 // parentheses goes back down to 0 (the first '(' was parsed above).
1213 unsigned NumOpenParen = 1;
1214 do {
1215 switch (Lex.getKind()) {
1216 case lltok::lparen:
1217 NumOpenParen++;
1218 break;
1219 case lltok::rparen:
1220 NumOpenParen--;
1221 break;
1222 case lltok::Eof:
1223 return tokError("found end of file while parsing summary entry");
1224 default:
1225 // Skip everything in between parentheses.
1226 break;
1227 }
1228 Lex.Lex();
1229 } while (NumOpenParen > 0);
1230 return false;
1231}
1232
1233/// SummaryEntry
1234/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1235bool LLParser::parseSummaryEntry() {
1236 assert(Lex.getKind() == lltok::SummaryID);
1237 unsigned SummaryID = Lex.getUIntVal();
1238
1239 // For summary entries, colons should be treated as distinct tokens,
1240 // not an indication of the end of a label token.
1241 Lex.setIgnoreColonInIdentifiers(true);
1242
1243 Lex.Lex();
1244 if (parseToken(lltok::equal, "expected '=' here"))
1245 return true;
1246
1247 // If we don't have an index object, skip the summary entry.
1248 if (!Index)
1249 return skipModuleSummaryEntry();
1250
1251 bool result = false;
1252 switch (Lex.getKind()) {
1253 case lltok::kw_gv:
1254 result = parseGVEntry(SummaryID);
1255 break;
1256 case lltok::kw_module:
1257 result = parseModuleEntry(SummaryID);
1258 break;
1259 case lltok::kw_typeid:
1260 result = parseTypeIdEntry(SummaryID);
1261 break;
1263 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1264 break;
1265 case lltok::kw_flags:
1266 result = parseSummaryIndexFlags();
1267 break;
1269 result = parseBlockCount();
1270 break;
1273 result = parseCfiFunctions();
1274 break;
1275 default:
1276 result = error(Lex.getLoc(), "unexpected summary kind");
1277 break;
1278 }
1279 Lex.setIgnoreColonInIdentifiers(false);
1280 return result;
1281}
1282
1291
1292// If there was an explicit dso_local, update GV. In the absence of an explicit
1293// dso_local we keep the default value.
1294static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1295 if (DSOLocal)
1296 GV.setDSOLocal(true);
1297}
1298
1299/// parseAliasOrIFunc:
1300/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1301/// OptionalVisibility OptionalDLLStorageClass
1302/// OptionalThreadLocal OptionalUnnamedAddr
1303/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1304///
1305/// AliaseeOrResolver
1306/// ::= TypeAndValue
1307///
1308/// SymbolAttrs
1309/// ::= ',' 'partition' StringConstant
1310///
1311/// Everything through OptionalUnnamedAddr has already been parsed.
1312///
1313bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1314 LocTy NameLoc, unsigned L, unsigned Visibility,
1315 unsigned DLLStorageClass, bool DSOLocal,
1317 GlobalVariable::UnnamedAddr UnnamedAddr) {
1318 bool IsAlias;
1319 if (Lex.getKind() == lltok::kw_alias)
1320 IsAlias = true;
1321 else if (Lex.getKind() == lltok::kw_ifunc)
1322 IsAlias = false;
1323 else
1324 llvm_unreachable("Not an alias or ifunc!");
1325 Lex.Lex();
1326
1328
1329 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1330 return error(NameLoc, "invalid linkage type for alias");
1331
1332 if (!isValidVisibilityForLinkage(Visibility, L))
1333 return error(NameLoc,
1334 "symbol with local linkage must have default visibility");
1335
1336 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1337 return error(NameLoc,
1338 "symbol with local linkage cannot have a DLL storage class");
1339
1340 Type *Ty;
1341 LocTy ExplicitTypeLoc = Lex.getLoc();
1342 if (parseType(Ty) ||
1343 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1344 return true;
1345
1346 Constant *Aliasee;
1347 LocTy AliaseeLoc = Lex.getLoc();
1348 if (Lex.getKind() != lltok::kw_bitcast &&
1349 Lex.getKind() != lltok::kw_getelementptr &&
1350 Lex.getKind() != lltok::kw_addrspacecast &&
1351 Lex.getKind() != lltok::kw_inttoptr) {
1352 if (parseGlobalTypeAndValue(Aliasee))
1353 return true;
1354 } else {
1355 // The bitcast dest type is not present, it is implied by the dest type.
1356 ValID ID;
1357 if (parseValID(ID, /*PFS=*/nullptr))
1358 return true;
1359 if (ID.Kind != ValID::t_Constant)
1360 return error(AliaseeLoc, "invalid aliasee");
1361 Aliasee = ID.ConstantVal;
1362 }
1363
1364 Type *AliaseeType = Aliasee->getType();
1365 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1366 if (!PTy)
1367 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1368 unsigned AddrSpace = PTy->getAddressSpace();
1369
1370 GlobalValue *GVal = nullptr;
1371
1372 // See if the alias was forward referenced, if so, prepare to replace the
1373 // forward reference.
1374 if (!Name.empty()) {
1375 auto I = ForwardRefVals.find(Name);
1376 if (I != ForwardRefVals.end()) {
1377 GVal = I->second.first;
1378 ForwardRefVals.erase(Name);
1379 } else if (M->getNamedValue(Name)) {
1380 return error(NameLoc, "redefinition of global '@" + Name + "'");
1381 }
1382 } else {
1383 auto I = ForwardRefValIDs.find(NameID);
1384 if (I != ForwardRefValIDs.end()) {
1385 GVal = I->second.first;
1386 ForwardRefValIDs.erase(I);
1387 }
1388 }
1389
1390 // Okay, create the alias/ifunc but do not insert it into the module yet.
1391 std::unique_ptr<GlobalAlias> GA;
1392 std::unique_ptr<GlobalIFunc> GI;
1393 GlobalValue *GV;
1394 if (IsAlias) {
1395 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1396 /*Parent=*/nullptr));
1397 GV = GA.get();
1398 } else {
1399 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1400 /*Parent=*/nullptr));
1401 GV = GI.get();
1402 }
1403 GV->setThreadLocalMode(TLM);
1406 GV->setUnnamedAddr(UnnamedAddr);
1407 maybeSetDSOLocal(DSOLocal, *GV);
1408
1409 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1410 // Now parse them if there are any.
1411 while (Lex.getKind() == lltok::comma) {
1412 Lex.Lex();
1413
1414 if (Lex.getKind() == lltok::kw_partition) {
1415 Lex.Lex();
1416 GV->setPartition(Lex.getStrVal());
1417 if (parseToken(lltok::StringConstant, "expected partition string"))
1418 return true;
1419 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1420 if (parseGlobalObjectMetadataAttachment(*GI))
1421 return true;
1422 } else {
1423 return tokError("unknown alias or ifunc property!");
1424 }
1425 }
1426
1427 if (Name.empty())
1428 NumberedVals.add(NameID, GV);
1429
1430 if (GVal) {
1431 // Verify that types agree.
1432 if (GVal->getType() != GV->getType())
1433 return error(
1434 ExplicitTypeLoc,
1435 "forward reference and definition of alias have different types");
1436
1437 // If they agree, just RAUW the old value with the alias and remove the
1438 // forward ref info.
1439 GVal->replaceAllUsesWith(GV);
1440 GVal->eraseFromParent();
1441 }
1442
1443 // Insert into the module, we know its name won't collide now.
1444 if (IsAlias)
1445 M->insertAlias(GA.release());
1446 else
1447 M->insertIFunc(GI.release());
1448 assert(GV->getName() == Name && "Should not be a name conflict!");
1449
1450 return false;
1451}
1452
1453static bool isSanitizer(lltok::Kind Kind) {
1454 switch (Kind) {
1457 case lltok::kw_sanitize_memtag:
1459 return true;
1460 default:
1461 return false;
1462 }
1463}
1464
1465bool LLParser::parseSanitizer(GlobalVariable *GV) {
1466 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1468 if (GV->hasSanitizerMetadata())
1469 Meta = GV->getSanitizerMetadata();
1470
1471 switch (Lex.getKind()) {
1473 Meta.NoAddress = true;
1474 break;
1476 Meta.NoHWAddress = true;
1477 break;
1478 case lltok::kw_sanitize_memtag:
1479 Meta.Memtag = true;
1480 break;
1482 Meta.IsDynInit = true;
1483 break;
1484 default:
1485 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1486 }
1487 GV->setSanitizerMetadata(Meta);
1488 Lex.Lex();
1489 return false;
1490}
1491
1492/// parseGlobal
1493/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1494/// OptionalVisibility OptionalDLLStorageClass
1495/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1496/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1497/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1498/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1499/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1500/// Const OptionalAttrs
1501///
1502/// Everything up to and including OptionalUnnamedAddr has been parsed
1503/// already.
1504///
1505bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1506 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1507 unsigned Visibility, unsigned DLLStorageClass,
1508 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1509 GlobalVariable::UnnamedAddr UnnamedAddr) {
1510 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1511 return error(NameLoc,
1512 "symbol with local linkage must have default visibility");
1513
1514 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1515 return error(NameLoc,
1516 "symbol with local linkage cannot have a DLL storage class");
1517
1518 unsigned AddrSpace;
1519 bool IsConstant, IsExternallyInitialized;
1520 LocTy IsExternallyInitializedLoc;
1521 LocTy TyLoc;
1522
1523 Type *Ty = nullptr;
1524 if (parseOptionalAddrSpace(AddrSpace) ||
1525 parseOptionalToken(lltok::kw_externally_initialized,
1526 IsExternallyInitialized,
1527 &IsExternallyInitializedLoc) ||
1528 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1529 return true;
1530
1531 // If the linkage is specified and is external, then no initializer is
1532 // present.
1533 Constant *Init = nullptr;
1534 if (!HasLinkage ||
1537 if (parseGlobalValue(Ty, Init))
1538 return true;
1539 }
1540
1542 return error(TyLoc, "invalid type for global variable");
1543
1544 GlobalValue *GVal = nullptr;
1545
1546 // See if the global was forward referenced, if so, use the global.
1547 if (!Name.empty()) {
1548 auto I = ForwardRefVals.find(Name);
1549 if (I != ForwardRefVals.end()) {
1550 GVal = I->second.first;
1551 ForwardRefVals.erase(I);
1552 } else if (M->getNamedValue(Name)) {
1553 return error(NameLoc, "redefinition of global '@" + Name + "'");
1554 }
1555 } else {
1556 // Handle @"", where a name is syntactically specified, but semantically
1557 // missing.
1558 if (NameID == (unsigned)-1)
1559 NameID = NumberedVals.getNext();
1560
1561 auto I = ForwardRefValIDs.find(NameID);
1562 if (I != ForwardRefValIDs.end()) {
1563 GVal = I->second.first;
1564 ForwardRefValIDs.erase(I);
1565 }
1566 }
1567
1568 GlobalVariable *GV = new GlobalVariable(
1569 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1571
1572 if (Name.empty())
1573 NumberedVals.add(NameID, GV);
1574
1575 // Set the parsed properties on the global.
1576 if (Init)
1577 GV->setInitializer(Init);
1578 GV->setConstant(IsConstant);
1580 maybeSetDSOLocal(DSOLocal, *GV);
1583 GV->setExternallyInitialized(IsExternallyInitialized);
1584 GV->setThreadLocalMode(TLM);
1585 GV->setUnnamedAddr(UnnamedAddr);
1586
1587 if (GVal) {
1588 if (GVal->getAddressSpace() != AddrSpace)
1589 return error(
1590 TyLoc,
1591 "forward reference and definition of global have different types");
1592
1593 GVal->replaceAllUsesWith(GV);
1594 GVal->eraseFromParent();
1595 }
1596
1597 // parse attributes on the global.
1598 while (Lex.getKind() == lltok::comma) {
1599 Lex.Lex();
1600
1601 if (Lex.getKind() == lltok::kw_section) {
1602 Lex.Lex();
1603 GV->setSection(Lex.getStrVal());
1604 if (parseToken(lltok::StringConstant, "expected global section string"))
1605 return true;
1606 } else if (Lex.getKind() == lltok::kw_partition) {
1607 Lex.Lex();
1608 GV->setPartition(Lex.getStrVal());
1609 if (parseToken(lltok::StringConstant, "expected partition string"))
1610 return true;
1611 } else if (Lex.getKind() == lltok::kw_align) {
1612 MaybeAlign Alignment;
1613 if (parseOptionalAlignment(Alignment))
1614 return true;
1615 if (Alignment)
1616 GV->setAlignment(*Alignment);
1617 } else if (Lex.getKind() == lltok::kw_code_model) {
1619 if (parseOptionalCodeModel(CodeModel))
1620 return true;
1621 GV->setCodeModel(CodeModel);
1622 } else if (Lex.getKind() == lltok::MetadataVar) {
1623 if (parseGlobalObjectMetadataAttachment(*GV))
1624 return true;
1625 } else if (isSanitizer(Lex.getKind())) {
1626 if (parseSanitizer(GV))
1627 return true;
1628 } else {
1629 Comdat *C;
1630 if (parseOptionalComdat(Name, C))
1631 return true;
1632 if (C)
1633 GV->setComdat(C);
1634 else
1635 return tokError("unknown global variable property!");
1636 }
1637 }
1638
1639 AttrBuilder Attrs(M->getContext());
1640 LocTy BuiltinLoc;
1641 std::vector<unsigned> FwdRefAttrGrps;
1642 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1643 return true;
1644 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1645 GV->setAttributes(AttributeSet::get(Context, Attrs));
1646 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1647 }
1648
1649 return false;
1650}
1651
1652/// parseUnnamedAttrGrp
1653/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1654bool LLParser::parseUnnamedAttrGrp() {
1655 assert(Lex.getKind() == lltok::kw_attributes);
1656 LocTy AttrGrpLoc = Lex.getLoc();
1657 Lex.Lex();
1658
1659 if (Lex.getKind() != lltok::AttrGrpID)
1660 return tokError("expected attribute group id");
1661
1662 unsigned VarID = Lex.getUIntVal();
1663 std::vector<unsigned> unused;
1664 LocTy BuiltinLoc;
1665 Lex.Lex();
1666
1667 if (parseToken(lltok::equal, "expected '=' here") ||
1668 parseToken(lltok::lbrace, "expected '{' here"))
1669 return true;
1670
1671 auto R = NumberedAttrBuilders.find(VarID);
1672 if (R == NumberedAttrBuilders.end())
1673 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1674
1675 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1676 parseToken(lltok::rbrace, "expected end of attribute group"))
1677 return true;
1678
1679 if (!R->second.hasAttributes())
1680 return error(AttrGrpLoc, "attribute group has no attributes");
1681
1682 return false;
1683}
1684
1686 switch (Kind) {
1687#define GET_ATTR_NAMES
1688#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1689 case lltok::kw_##DISPLAY_NAME: \
1690 return Attribute::ENUM_NAME;
1691#include "llvm/IR/Attributes.inc"
1692 default:
1693 return Attribute::None;
1694 }
1695}
1696
1697bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1698 bool InAttrGroup) {
1699 if (Attribute::isTypeAttrKind(Attr))
1700 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1701
1702 switch (Attr) {
1703 case Attribute::Alignment: {
1704 MaybeAlign Alignment;
1705 if (InAttrGroup) {
1706 uint32_t Value = 0;
1707 Lex.Lex();
1708 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1709 return true;
1711 } else {
1712 if (parseOptionalAlignment(Alignment, true))
1713 return true;
1714 }
1715 B.addAlignmentAttr(Alignment);
1716 return false;
1717 }
1718 case Attribute::StackAlignment: {
1719 unsigned Alignment;
1720 if (InAttrGroup) {
1721 Lex.Lex();
1722 if (parseToken(lltok::equal, "expected '=' here") ||
1723 parseUInt32(Alignment))
1724 return true;
1725 } else {
1726 if (parseOptionalStackAlignment(Alignment))
1727 return true;
1728 }
1729 B.addStackAlignmentAttr(Alignment);
1730 return false;
1731 }
1732 case Attribute::AllocSize: {
1733 unsigned ElemSizeArg;
1734 std::optional<unsigned> NumElemsArg;
1735 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1736 return true;
1737 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1738 return false;
1739 }
1740 case Attribute::VScaleRange: {
1741 unsigned MinValue, MaxValue;
1742 if (parseVScaleRangeArguments(MinValue, MaxValue))
1743 return true;
1744 B.addVScaleRangeAttr(MinValue,
1745 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1746 return false;
1747 }
1748 case Attribute::Dereferenceable: {
1749 std::optional<uint64_t> Bytes;
1750 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1751 return true;
1752 assert(Bytes.has_value());
1753 B.addDereferenceableAttr(Bytes.value());
1754 return false;
1755 }
1756 case Attribute::DeadOnReturn: {
1757 std::optional<uint64_t> Bytes;
1758 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1759 /*ErrorNoBytes=*/false))
1760 return true;
1761 if (Bytes.has_value()) {
1762 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1763 } else {
1764 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1765 }
1766 return false;
1767 }
1768 case Attribute::DereferenceableOrNull: {
1769 std::optional<uint64_t> Bytes;
1770 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1771 return true;
1772 assert(Bytes.has_value());
1773 B.addDereferenceableOrNullAttr(Bytes.value());
1774 return false;
1775 }
1776 case Attribute::UWTable: {
1778 if (parseOptionalUWTableKind(Kind))
1779 return true;
1780 B.addUWTableAttr(Kind);
1781 return false;
1782 }
1783 case Attribute::AllocKind: {
1785 if (parseAllocKind(Kind))
1786 return true;
1787 B.addAllocKindAttr(Kind);
1788 return false;
1789 }
1790 case Attribute::Memory: {
1791 std::optional<MemoryEffects> ME = parseMemoryAttr();
1792 if (!ME)
1793 return true;
1794 B.addMemoryAttr(*ME);
1795 return false;
1796 }
1797 case Attribute::DenormalFPEnv: {
1798 std::optional<DenormalFPEnv> Mode = parseDenormalFPEnvAttr();
1799 if (!Mode)
1800 return true;
1801
1802 B.addDenormalFPEnvAttr(*Mode);
1803 return false;
1804 }
1805 case Attribute::NoFPClass: {
1806 if (FPClassTest NoFPClass =
1807 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1808 B.addNoFPClassAttr(NoFPClass);
1809 return false;
1810 }
1811
1812 return true;
1813 }
1814 case Attribute::Range:
1815 return parseRangeAttr(B);
1816 case Attribute::Initializes:
1817 return parseInitializesAttr(B);
1818 case Attribute::Captures:
1819 return parseCapturesAttr(B);
1820 default:
1821 B.addAttribute(Attr);
1822 Lex.Lex();
1823 return false;
1824 }
1825}
1826
1828 switch (Kind) {
1829 case lltok::kw_readnone:
1830 ME &= MemoryEffects::none();
1831 return true;
1832 case lltok::kw_readonly:
1834 return true;
1835 case lltok::kw_writeonly:
1837 return true;
1840 return true;
1843 return true;
1846 return true;
1847 default:
1848 return false;
1849 }
1850}
1851
1852/// parseFnAttributeValuePairs
1853/// ::= <attr> | <attr> '=' <value>
1854bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1855 std::vector<unsigned> &FwdRefAttrGrps,
1856 bool InAttrGrp, LocTy &BuiltinLoc) {
1857 bool HaveError = false;
1858
1859 B.clear();
1860
1862 while (true) {
1863 lltok::Kind Token = Lex.getKind();
1864 if (Token == lltok::rbrace)
1865 break; // Finished.
1866
1867 if (Token == lltok::StringConstant) {
1868 if (parseStringAttribute(B))
1869 return true;
1870 continue;
1871 }
1872
1873 if (Token == lltok::AttrGrpID) {
1874 // Allow a function to reference an attribute group:
1875 //
1876 // define void @foo() #1 { ... }
1877 if (InAttrGrp) {
1878 HaveError |= error(
1879 Lex.getLoc(),
1880 "cannot have an attribute group reference in an attribute group");
1881 } else {
1882 // Save the reference to the attribute group. We'll fill it in later.
1883 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1884 }
1885 Lex.Lex();
1886 continue;
1887 }
1888
1889 SMLoc Loc = Lex.getLoc();
1890 if (Token == lltok::kw_builtin)
1891 BuiltinLoc = Loc;
1892
1893 if (upgradeMemoryAttr(ME, Token)) {
1894 Lex.Lex();
1895 continue;
1896 }
1897
1899 if (Attr == Attribute::None) {
1900 if (!InAttrGrp)
1901 break;
1902 return error(Lex.getLoc(), "unterminated attribute group");
1903 }
1904
1905 if (parseEnumAttribute(Attr, B, InAttrGrp))
1906 return true;
1907
1908 // As a hack, we allow function alignment to be initially parsed as an
1909 // attribute on a function declaration/definition or added to an attribute
1910 // group and later moved to the alignment field.
1911 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1912 HaveError |= error(Loc, "this attribute does not apply to functions");
1913 }
1914
1915 if (ME != MemoryEffects::unknown())
1916 B.addMemoryAttr(ME);
1917 return HaveError;
1918}
1919
1920//===----------------------------------------------------------------------===//
1921// GlobalValue Reference/Resolution Routines.
1922//===----------------------------------------------------------------------===//
1923
1925 // The used global type does not matter. We will later RAUW it with a
1926 // global/function of the correct type.
1927 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1930 PTy->getAddressSpace());
1931}
1932
1933Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1934 Value *Val) {
1935 Type *ValTy = Val->getType();
1936 if (ValTy == Ty)
1937 return Val;
1938 if (Ty->isLabelTy())
1939 error(Loc, "'" + Name + "' is not a basic block");
1940 else
1941 error(Loc, "'" + Name + "' defined with type '" +
1942 getTypeString(Val->getType()) + "' but expected '" +
1943 getTypeString(Ty) + "'");
1944 return nullptr;
1945}
1946
1947/// getGlobalVal - Get a value with the specified name or ID, creating a
1948/// forward reference record if needed. This can return null if the value
1949/// exists but does not have the right type.
1950GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1951 LocTy Loc) {
1953 if (!PTy) {
1954 error(Loc, "global variable reference must have pointer type");
1955 return nullptr;
1956 }
1957
1958 // Look this name up in the normal function symbol table.
1959 GlobalValue *Val =
1960 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1961
1962 // If this is a forward reference for the value, see if we already created a
1963 // forward ref record.
1964 if (!Val) {
1965 auto I = ForwardRefVals.find(Name);
1966 if (I != ForwardRefVals.end())
1967 Val = I->second.first;
1968 }
1969
1970 // If we have the value in the symbol table or fwd-ref table, return it.
1971 if (Val)
1973 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1974
1975 // Otherwise, create a new forward reference for this value and remember it.
1976 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1977 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1978 return FwdVal;
1979}
1980
1981GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1983 if (!PTy) {
1984 error(Loc, "global variable reference must have pointer type");
1985 return nullptr;
1986 }
1987
1988 GlobalValue *Val = NumberedVals.get(ID);
1989
1990 // If this is a forward reference for the value, see if we already created a
1991 // forward ref record.
1992 if (!Val) {
1993 auto I = ForwardRefValIDs.find(ID);
1994 if (I != ForwardRefValIDs.end())
1995 Val = I->second.first;
1996 }
1997
1998 // If we have the value in the symbol table or fwd-ref table, return it.
1999 if (Val)
2001 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
2002
2003 // Otherwise, create a new forward reference for this value and remember it.
2004 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
2005 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2006 return FwdVal;
2007}
2008
2009//===----------------------------------------------------------------------===//
2010// Comdat Reference/Resolution Routines.
2011//===----------------------------------------------------------------------===//
2012
2013Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
2014 // Look this name up in the comdat symbol table.
2015 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
2016 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
2017 if (I != ComdatSymTab.end())
2018 return &I->second;
2019
2020 // Otherwise, create a new forward reference for this value and remember it.
2021 Comdat *C = M->getOrInsertComdat(Name);
2022 ForwardRefComdats[Name] = Loc;
2023 return C;
2024}
2025
2026//===----------------------------------------------------------------------===//
2027// Helper Routines.
2028//===----------------------------------------------------------------------===//
2029
2030/// parseToken - If the current token has the specified kind, eat it and return
2031/// success. Otherwise, emit the specified error and return failure.
2032bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
2033 if (Lex.getKind() != T)
2034 return tokError(ErrMsg);
2035 Lex.Lex();
2036 return false;
2037}
2038
2039/// parseStringConstant
2040/// ::= StringConstant
2041bool LLParser::parseStringConstant(std::string &Result) {
2042 if (Lex.getKind() != lltok::StringConstant)
2043 return tokError("expected string constant");
2044 Result = Lex.getStrVal();
2045 Lex.Lex();
2046 return false;
2047}
2048
2049/// parseUInt32
2050/// ::= uint32
2051bool LLParser::parseUInt32(uint32_t &Val) {
2052 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2053 return tokError("expected integer");
2054 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
2055 if (Val64 != unsigned(Val64))
2056 return tokError("expected 32-bit integer (too large)");
2057 Val = Val64;
2058 Lex.Lex();
2059 return false;
2060}
2061
2062/// parseUInt64
2063/// ::= uint64
2064bool LLParser::parseUInt64(uint64_t &Val) {
2065 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
2066 return tokError("expected integer");
2067 Val = Lex.getAPSIntVal().getLimitedValue();
2068 Lex.Lex();
2069 return false;
2070}
2071
2072/// parseTLSModel
2073/// := 'localdynamic'
2074/// := 'initialexec'
2075/// := 'localexec'
2076bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
2077 switch (Lex.getKind()) {
2078 default:
2079 return tokError("expected localdynamic, initialexec or localexec");
2082 break;
2085 break;
2088 break;
2089 }
2090
2091 Lex.Lex();
2092 return false;
2093}
2094
2095/// parseOptionalThreadLocal
2096/// := /*empty*/
2097/// := 'thread_local'
2098/// := 'thread_local' '(' tlsmodel ')'
2099bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
2101 if (!EatIfPresent(lltok::kw_thread_local))
2102 return false;
2103
2105 if (Lex.getKind() == lltok::lparen) {
2106 Lex.Lex();
2107 return parseTLSModel(TLM) ||
2108 parseToken(lltok::rparen, "expected ')' after thread local model");
2109 }
2110 return false;
2111}
2112
2113/// parseOptionalAddrSpace
2114/// := /*empty*/
2115/// := 'addrspace' '(' uint32 ')'
2116bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
2117 AddrSpace = DefaultAS;
2118 if (!EatIfPresent(lltok::kw_addrspace))
2119 return false;
2120
2121 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
2122 if (Lex.getKind() == lltok::StringConstant) {
2123 const std::string &AddrSpaceStr = Lex.getStrVal();
2124 if (AddrSpaceStr == "A") {
2125 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
2126 } else if (AddrSpaceStr == "G") {
2127 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
2128 } else if (AddrSpaceStr == "P") {
2129 AddrSpace = M->getDataLayout().getProgramAddressSpace();
2130 } else if (std::optional<unsigned> AS =
2131 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2132 AddrSpace = *AS;
2133 } else {
2134 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
2135 }
2136 Lex.Lex();
2137 return false;
2138 }
2139 if (Lex.getKind() != lltok::APSInt)
2140 return tokError("expected integer or string constant");
2141 SMLoc Loc = Lex.getLoc();
2142 if (parseUInt32(AddrSpace))
2143 return true;
2144 if (!isUInt<24>(AddrSpace))
2145 return error(Loc, "invalid address space, must be a 24-bit integer");
2146 return false;
2147 };
2148
2149 return parseToken(lltok::lparen, "expected '(' in address space") ||
2150 ParseAddrspaceValue(AddrSpace) ||
2151 parseToken(lltok::rparen, "expected ')' in address space");
2152}
2153
2154/// parseStringAttribute
2155/// := StringConstant
2156/// := StringConstant '=' StringConstant
2157bool LLParser::parseStringAttribute(AttrBuilder &B) {
2158 std::string Attr = Lex.getStrVal();
2159 Lex.Lex();
2160 std::string Val;
2161 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
2162 return true;
2163 B.addAttribute(Attr, Val);
2164 return false;
2165}
2166
2167/// Parse a potentially empty list of parameter or return attributes.
2168bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2169 bool HaveError = false;
2170
2171 B.clear();
2172
2173 while (true) {
2174 lltok::Kind Token = Lex.getKind();
2175 if (Token == lltok::StringConstant) {
2176 if (parseStringAttribute(B))
2177 return true;
2178 continue;
2179 }
2180
2181 if (Token == lltok::kw_nocapture) {
2182 Lex.Lex();
2183 B.addCapturesAttr(CaptureInfo::none());
2184 continue;
2185 }
2186
2187 SMLoc Loc = Lex.getLoc();
2189 if (Attr == Attribute::None)
2190 return HaveError;
2191
2192 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2193 return true;
2194
2195 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2196 HaveError |= error(Loc, "this attribute does not apply to parameters");
2197 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2198 HaveError |= error(Loc, "this attribute does not apply to return values");
2199 }
2200}
2201
2202static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2203 HasLinkage = true;
2204 switch (Kind) {
2205 default:
2206 HasLinkage = false;
2208 case lltok::kw_private:
2210 case lltok::kw_internal:
2212 case lltok::kw_weak:
2214 case lltok::kw_weak_odr:
2216 case lltok::kw_linkonce:
2224 case lltok::kw_common:
2228 case lltok::kw_external:
2230 }
2231}
2232
2233/// parseOptionalLinkage
2234/// ::= /*empty*/
2235/// ::= 'private'
2236/// ::= 'internal'
2237/// ::= 'weak'
2238/// ::= 'weak_odr'
2239/// ::= 'linkonce'
2240/// ::= 'linkonce_odr'
2241/// ::= 'available_externally'
2242/// ::= 'appending'
2243/// ::= 'common'
2244/// ::= 'extern_weak'
2245/// ::= 'external'
2246bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2247 unsigned &Visibility,
2248 unsigned &DLLStorageClass, bool &DSOLocal) {
2249 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2250 if (HasLinkage)
2251 Lex.Lex();
2252 parseOptionalDSOLocal(DSOLocal);
2253 parseOptionalVisibility(Visibility);
2254 parseOptionalDLLStorageClass(DLLStorageClass);
2255
2256 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2257 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2258 }
2259
2260 return false;
2261}
2262
2263void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2264 switch (Lex.getKind()) {
2265 default:
2266 DSOLocal = false;
2267 break;
2269 DSOLocal = true;
2270 Lex.Lex();
2271 break;
2273 DSOLocal = false;
2274 Lex.Lex();
2275 break;
2276 }
2277}
2278
2279/// parseOptionalVisibility
2280/// ::= /*empty*/
2281/// ::= 'default'
2282/// ::= 'hidden'
2283/// ::= 'protected'
2284///
2285void LLParser::parseOptionalVisibility(unsigned &Res) {
2286 switch (Lex.getKind()) {
2287 default:
2289 return;
2290 case lltok::kw_default:
2292 break;
2293 case lltok::kw_hidden:
2295 break;
2298 break;
2299 }
2300 Lex.Lex();
2301}
2302
2303bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2305 switch (Kind) {
2306 default:
2307 return tokError("unknown import kind. Expect definition or declaration.");
2310 return false;
2313 return false;
2314 }
2315}
2316
2317/// parseOptionalDLLStorageClass
2318/// ::= /*empty*/
2319/// ::= 'dllimport'
2320/// ::= 'dllexport'
2321///
2322void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2323 switch (Lex.getKind()) {
2324 default:
2326 return;
2329 break;
2332 break;
2333 }
2334 Lex.Lex();
2335}
2336
2337/// parseOptionalCallingConv
2338/// ::= /*empty*/
2339/// ::= 'ccc'
2340/// ::= 'fastcc'
2341/// ::= 'intel_ocl_bicc'
2342/// ::= 'coldcc'
2343/// ::= 'cfguard_checkcc'
2344/// ::= 'x86_stdcallcc'
2345/// ::= 'x86_fastcallcc'
2346/// ::= 'x86_thiscallcc'
2347/// ::= 'x86_vectorcallcc'
2348/// ::= 'arm_apcscc'
2349/// ::= 'arm_aapcscc'
2350/// ::= 'arm_aapcs_vfpcc'
2351/// ::= 'aarch64_vector_pcs'
2352/// ::= 'aarch64_sve_vector_pcs'
2353/// ::= 'aarch64_sme_preservemost_from_x0'
2354/// ::= 'aarch64_sme_preservemost_from_x1'
2355/// ::= 'aarch64_sme_preservemost_from_x2'
2356/// ::= 'msp430_intrcc'
2357/// ::= 'avr_intrcc'
2358/// ::= 'avr_signalcc'
2359/// ::= 'ptx_kernel'
2360/// ::= 'ptx_device'
2361/// ::= 'spir_func'
2362/// ::= 'spir_kernel'
2363/// ::= 'x86_64_sysvcc'
2364/// ::= 'win64cc'
2365/// ::= 'anyregcc'
2366/// ::= 'preserve_mostcc'
2367/// ::= 'preserve_allcc'
2368/// ::= 'preserve_nonecc'
2369/// ::= 'ghccc'
2370/// ::= 'swiftcc'
2371/// ::= 'swifttailcc'
2372/// ::= 'x86_intrcc'
2373/// ::= 'hhvmcc'
2374/// ::= 'hhvm_ccc'
2375/// ::= 'cxx_fast_tlscc'
2376/// ::= 'amdgpu_vs'
2377/// ::= 'amdgpu_ls'
2378/// ::= 'amdgpu_hs'
2379/// ::= 'amdgpu_es'
2380/// ::= 'amdgpu_gs'
2381/// ::= 'amdgpu_ps'
2382/// ::= 'amdgpu_cs'
2383/// ::= 'amdgpu_cs_chain'
2384/// ::= 'amdgpu_cs_chain_preserve'
2385/// ::= 'amdgpu_kernel'
2386/// ::= 'tailcc'
2387/// ::= 'm68k_rtdcc'
2388/// ::= 'wasm_emscripten_invokecc'
2389/// ::= 'graalcc'
2390/// ::= 'riscv_vector_cc'
2391/// ::= 'riscv_vls_cc'
2392/// ::= 'cc' UINT
2393///
2394bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2395 switch (Lex.getKind()) {
2396 default: CC = CallingConv::C; return false;
2397 case lltok::kw_ccc: CC = CallingConv::C; break;
2398 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2399 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2412 break;
2415 break;
2418 break;
2421 break;
2436 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2440 case lltok::kw_hhvmcc:
2442 break;
2443 case lltok::kw_hhvm_ccc:
2445 break;
2457 break;
2460 break;
2464 break;
2465 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2469 break;
2473 break;
2475 // Default ABI_VLEN
2477 Lex.Lex();
2478 if (!EatIfPresent(lltok::lparen))
2479 break;
2480 uint32_t ABIVlen;
2481 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2482 return true;
2483 switch (ABIVlen) {
2484 default:
2485 return tokError("unknown RISC-V ABI VLEN");
2486#define CC_VLS_CASE(ABIVlen) \
2487 case ABIVlen: \
2488 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2489 break;
2490 CC_VLS_CASE(32)
2491 CC_VLS_CASE(64)
2492 CC_VLS_CASE(128)
2493 CC_VLS_CASE(256)
2494 CC_VLS_CASE(512)
2495 CC_VLS_CASE(1024)
2496 CC_VLS_CASE(2048)
2497 CC_VLS_CASE(4096)
2498 CC_VLS_CASE(8192)
2499 CC_VLS_CASE(16384)
2500 CC_VLS_CASE(32768)
2501 CC_VLS_CASE(65536)
2502#undef CC_VLS_CASE
2503 }
2504 return false;
2507 break;
2510 break;
2513 break;
2514 case lltok::kw_cc: {
2515 Lex.Lex();
2516 return parseUInt32(CC);
2517 }
2518 }
2519
2520 Lex.Lex();
2521 return false;
2522}
2523
2524/// parseMetadataAttachment
2525/// ::= !dbg !42
2526bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2527 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2528
2529 std::string Name = Lex.getStrVal();
2530 Kind = M->getMDKindID(Name);
2531 Lex.Lex();
2532
2533 return parseMDNode(MD);
2534}
2535
2536/// parseInstructionMetadata
2537/// ::= !dbg !42 (',' !dbg !57)*
2538bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2539 do {
2540 if (Lex.getKind() != lltok::MetadataVar)
2541 return tokError("expected metadata after comma");
2542
2543 unsigned MDK;
2544 MDNode *N;
2545 auto Loc = Lex.getLoc();
2546 if (parseMetadataAttachment(MDK, N))
2547 return true;
2548
2549 if (MDK == LLVMContext::MD_DIAssignID)
2550 TempDIAssignIDAttachments[N].push_back(&Inst);
2551 else if (MDK == LLVMContext::MD_dbg)
2552 PendingDbgInsts.emplace_back(Loc, &Inst, N);
2553 else
2554 Inst.setMetadata(MDK, N);
2555
2556 // If this is the end of the list, we're done.
2557 } while (EatIfPresent(lltok::comma));
2558 return false;
2559}
2560
2561/// parseGlobalObjectMetadataAttachment
2562/// ::= !dbg !57
2563bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2564 unsigned MDK;
2565 MDNode *N;
2566 if (parseMetadataAttachment(MDK, N))
2567 return true;
2568
2569 GO.addMetadata(MDK, *N);
2570 return false;
2571}
2572
2573/// parseOptionalFunctionMetadata
2574/// ::= (!dbg !57)*
2575bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2576 while (Lex.getKind() == lltok::MetadataVar)
2577 if (parseGlobalObjectMetadataAttachment(F))
2578 return true;
2579 return false;
2580}
2581
2582/// parseOptionalAlignment
2583/// ::= /* empty */
2584/// ::= 'align' 4
2585bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2586 Alignment = std::nullopt;
2587 if (!EatIfPresent(lltok::kw_align))
2588 return false;
2589 LocTy AlignLoc = Lex.getLoc();
2590 uint64_t Value = 0;
2591
2592 LocTy ParenLoc = Lex.getLoc();
2593 bool HaveParens = false;
2594 if (AllowParens) {
2595 if (EatIfPresent(lltok::lparen))
2596 HaveParens = true;
2597 }
2598
2599 if (parseUInt64(Value))
2600 return true;
2601
2602 if (HaveParens && !EatIfPresent(lltok::rparen))
2603 return error(ParenLoc, "expected ')'");
2604
2605 if (!isPowerOf2_64(Value))
2606 return error(AlignLoc, "alignment is not a power of two");
2608 return error(AlignLoc, "huge alignments are not supported yet");
2610 return false;
2611}
2612
2613/// parseOptionalPrefAlignment
2614/// ::= /* empty */
2615/// ::= 'prefalign' '(' 4 ')'
2616bool LLParser::parseOptionalPrefAlignment(MaybeAlign &Alignment) {
2617 Alignment = std::nullopt;
2618 if (!EatIfPresent(lltok::kw_prefalign))
2619 return false;
2620 LocTy AlignLoc = Lex.getLoc();
2621 uint64_t Value = 0;
2622
2623 LocTy ParenLoc = Lex.getLoc();
2624 if (!EatIfPresent(lltok::lparen))
2625 return error(ParenLoc, "expected '('");
2626
2627 if (parseUInt64(Value))
2628 return true;
2629
2630 ParenLoc = Lex.getLoc();
2631 if (!EatIfPresent(lltok::rparen))
2632 return error(ParenLoc, "expected ')'");
2633
2634 if (!isPowerOf2_64(Value))
2635 return error(AlignLoc, "alignment is not a power of two");
2637 return error(AlignLoc, "huge alignments are not supported yet");
2639 return false;
2640}
2641
2642/// parseOptionalCodeModel
2643/// ::= /* empty */
2644/// ::= 'code_model' "large"
2645bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2646 Lex.Lex();
2647 auto StrVal = Lex.getStrVal();
2648 auto ErrMsg = "expected global code model string";
2649 if (StrVal == "tiny")
2650 model = CodeModel::Tiny;
2651 else if (StrVal == "small")
2652 model = CodeModel::Small;
2653 else if (StrVal == "kernel")
2654 model = CodeModel::Kernel;
2655 else if (StrVal == "medium")
2656 model = CodeModel::Medium;
2657 else if (StrVal == "large")
2658 model = CodeModel::Large;
2659 else
2660 return tokError(ErrMsg);
2661 if (parseToken(lltok::StringConstant, ErrMsg))
2662 return true;
2663 return false;
2664}
2665
2666/// parseOptionalAttrBytes
2667/// ::= /* empty */
2668/// ::= AttrKind '(' 4 ')'
2669///
2670/// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or
2671/// 'dead_on_return'
2672bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind,
2673 std::optional<uint64_t> &Bytes,
2674 bool ErrorNoBytes) {
2675 assert((AttrKind == lltok::kw_dereferenceable ||
2676 AttrKind == lltok::kw_dereferenceable_or_null ||
2677 AttrKind == lltok::kw_dead_on_return) &&
2678 "contract!");
2679
2680 Bytes = 0;
2681 if (!EatIfPresent(AttrKind))
2682 return false;
2683 LocTy ParenLoc = Lex.getLoc();
2684 if (!EatIfPresent(lltok::lparen)) {
2685 if (ErrorNoBytes)
2686 return error(ParenLoc, "expected '('");
2687 Bytes = std::nullopt;
2688 return false;
2689 }
2690 LocTy DerefLoc = Lex.getLoc();
2691 if (parseUInt64(Bytes.value()))
2692 return true;
2693 ParenLoc = Lex.getLoc();
2694 if (!EatIfPresent(lltok::rparen))
2695 return error(ParenLoc, "expected ')'");
2696 if (!Bytes.value())
2697 return error(DerefLoc, "byte count specified must be non-zero");
2698 return false;
2699}
2700
2701bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2702 Lex.Lex();
2704 if (!EatIfPresent(lltok::lparen))
2705 return false;
2706 LocTy KindLoc = Lex.getLoc();
2707 if (Lex.getKind() == lltok::kw_sync)
2709 else if (Lex.getKind() == lltok::kw_async)
2711 else
2712 return error(KindLoc, "expected unwind table kind");
2713 Lex.Lex();
2714 return parseToken(lltok::rparen, "expected ')'");
2715}
2716
2717bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2718 Lex.Lex();
2719 LocTy ParenLoc = Lex.getLoc();
2720 if (!EatIfPresent(lltok::lparen))
2721 return error(ParenLoc, "expected '('");
2722 LocTy KindLoc = Lex.getLoc();
2723 std::string Arg;
2724 if (parseStringConstant(Arg))
2725 return error(KindLoc, "expected allockind value");
2726 for (StringRef A : llvm::split(Arg, ",")) {
2727 if (A == "alloc") {
2729 } else if (A == "realloc") {
2731 } else if (A == "free") {
2733 } else if (A == "uninitialized") {
2735 } else if (A == "zeroed") {
2737 } else if (A == "aligned") {
2739 } else {
2740 return error(KindLoc, Twine("unknown allockind ") + A);
2741 }
2742 }
2743 ParenLoc = Lex.getLoc();
2744 if (!EatIfPresent(lltok::rparen))
2745 return error(ParenLoc, "expected ')'");
2746 if (Kind == AllocFnKind::Unknown)
2747 return error(KindLoc, "expected allockind value");
2748 return false;
2749}
2750
2752 using Loc = IRMemLocation;
2753
2754 switch (Tok) {
2755 case lltok::kw_argmem:
2756 return {Loc::ArgMem};
2758 return {Loc::InaccessibleMem};
2759 case lltok::kw_errnomem:
2760 return {Loc::ErrnoMem};
2762 return {Loc::TargetMem0};
2764 return {Loc::TargetMem1};
2765 case lltok::kw_target_mem: {
2768 Targets.push_back(Loc);
2769 return Targets;
2770 }
2771 default:
2772 return {};
2773 }
2774}
2775
2776static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2777 switch (Tok) {
2778 case lltok::kw_none:
2779 return ModRefInfo::NoModRef;
2780 case lltok::kw_read:
2781 return ModRefInfo::Ref;
2782 case lltok::kw_write:
2783 return ModRefInfo::Mod;
2785 return ModRefInfo::ModRef;
2786 default:
2787 return std::nullopt;
2788 }
2789}
2790
2791static std::optional<DenormalMode::DenormalModeKind>
2793 switch (Tok) {
2794 case lltok::kw_ieee:
2795 return DenormalMode::IEEE;
2800 case lltok::kw_dynamic:
2801 return DenormalMode::Dynamic;
2802 default:
2803 return std::nullopt;
2804 }
2805}
2806
2807std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2809
2810 // We use syntax like memory(argmem: read), so the colon should not be
2811 // interpreted as a label terminator.
2812 Lex.setIgnoreColonInIdentifiers(true);
2813 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2814
2815 Lex.Lex();
2816 if (!EatIfPresent(lltok::lparen)) {
2817 tokError("expected '('");
2818 return std::nullopt;
2819 }
2820
2821 bool SeenLoc = false;
2822 bool SeenTargetLoc = false;
2823 do {
2824 SmallVector<IRMemLocation, 2> Locs = keywordToLoc(Lex.getKind());
2825 if (!Locs.empty()) {
2826 Lex.Lex();
2827 if (!EatIfPresent(lltok::colon)) {
2828 tokError("expected ':' after location");
2829 return std::nullopt;
2830 }
2831 }
2832
2833 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2834 if (!MR) {
2835 if (Locs.empty())
2836 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2837 "or access kind (none, read, write, readwrite)");
2838 else
2839 tokError("expected access kind (none, read, write, readwrite)");
2840 return std::nullopt;
2841 }
2842
2843 Lex.Lex();
2844 if (!Locs.empty()) {
2845 SeenLoc = true;
2846 for (IRMemLocation Loc : Locs) {
2847 ME = ME.getWithModRef(Loc, *MR);
2848 if (ME.isTargetMemLoc(Loc) && Locs.size() == 1)
2849 SeenTargetLoc = true;
2850 }
2851 if (Locs.size() > 1 && SeenTargetLoc) {
2852 tokError("target memory default access kind must be specified first");
2853 return std::nullopt;
2854 }
2855
2856 } else {
2857 if (SeenLoc) {
2858 tokError("default access kind must be specified first");
2859 return std::nullopt;
2860 }
2861 ME = MemoryEffects(*MR);
2862 }
2863
2864 if (EatIfPresent(lltok::rparen))
2865 return ME;
2866 } while (EatIfPresent(lltok::comma));
2867
2868 tokError("unterminated memory attribute");
2869 return std::nullopt;
2870}
2871
2872std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2873 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2874 keywordToDenormalModeKind(Lex.getKind());
2875 if (!OutputMode) {
2876 tokError("expected denormal behavior kind (ieee, preservesign, "
2877 "positivezero, dynamic)");
2878 return {};
2879 }
2880
2881 Lex.Lex();
2882
2883 std::optional<DenormalMode::DenormalModeKind> InputMode;
2884 if (EatIfPresent(lltok::bar)) {
2885 InputMode = keywordToDenormalModeKind(Lex.getKind());
2886 if (!InputMode) {
2887 tokError("expected denormal behavior kind (ieee, preservesign, "
2888 "positivezero, dynamic)");
2889 return {};
2890 }
2891
2892 Lex.Lex();
2893 } else {
2894 // Single item, input == output mode
2895 InputMode = OutputMode;
2896 }
2897
2898 return DenormalMode(*OutputMode, *InputMode);
2899}
2900
2901std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2902 // We use syntax like denormal_fpenv(float: preservesign), so the colon should
2903 // not be interpreted as a label terminator.
2904 Lex.setIgnoreColonInIdentifiers(true);
2905 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2906
2907 Lex.Lex();
2908
2909 if (parseToken(lltok::lparen, "expected '('"))
2910 return {};
2911
2912 DenormalMode DefaultMode = DenormalMode::getIEEE();
2913 DenormalMode F32Mode = DenormalMode::getInvalid();
2914
2915 bool HasDefaultSection = false;
2916 if (Lex.getKind() != lltok::Type) {
2917 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2918 if (!ParsedDefaultMode)
2919 return {};
2920 DefaultMode = *ParsedDefaultMode;
2921 HasDefaultSection = true;
2922 }
2923
2924 bool HasComma = EatIfPresent(lltok::comma);
2925 if (Lex.getKind() == lltok::Type) {
2926 if (HasDefaultSection && !HasComma) {
2927 tokError("expected ',' before float:");
2928 return {};
2929 }
2930
2931 Type *Ty = nullptr;
2932 if (parseType(Ty) || !Ty->isFloatTy()) {
2933 tokError("expected float:");
2934 return {};
2935 }
2936
2937 if (parseToken(lltok::colon, "expected ':' before float denormal_fpenv"))
2938 return {};
2939
2940 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2941 if (!ParsedF32Mode)
2942 return {};
2943
2944 F32Mode = *ParsedF32Mode;
2945 }
2946
2947 if (parseToken(lltok::rparen, "unterminated denormal_fpenv"))
2948 return {};
2949
2950 return DenormalFPEnv(DefaultMode, F32Mode);
2951}
2952
2953static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2954 switch (Tok) {
2955 case lltok::kw_all:
2956 return fcAllFlags;
2957 case lltok::kw_nan:
2958 return fcNan;
2959 case lltok::kw_snan:
2960 return fcSNan;
2961 case lltok::kw_qnan:
2962 return fcQNan;
2963 case lltok::kw_inf:
2964 return fcInf;
2965 case lltok::kw_ninf:
2966 return fcNegInf;
2967 case lltok::kw_pinf:
2968 return fcPosInf;
2969 case lltok::kw_norm:
2970 return fcNormal;
2971 case lltok::kw_nnorm:
2972 return fcNegNormal;
2973 case lltok::kw_pnorm:
2974 return fcPosNormal;
2975 case lltok::kw_sub:
2976 return fcSubnormal;
2977 case lltok::kw_nsub:
2978 return fcNegSubnormal;
2979 case lltok::kw_psub:
2980 return fcPosSubnormal;
2981 case lltok::kw_zero:
2982 return fcZero;
2983 case lltok::kw_nzero:
2984 return fcNegZero;
2985 case lltok::kw_pzero:
2986 return fcPosZero;
2987 default:
2988 return 0;
2989 }
2990}
2991
2992unsigned LLParser::parseNoFPClassAttr() {
2993 unsigned Mask = fcNone;
2994
2995 Lex.Lex();
2996 if (!EatIfPresent(lltok::lparen)) {
2997 tokError("expected '('");
2998 return 0;
2999 }
3000
3001 do {
3002 uint64_t Value = 0;
3003 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
3004 if (TestMask != 0) {
3005 Mask |= TestMask;
3006 // TODO: Disallow overlapping masks to avoid copy paste errors
3007 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
3008 !parseUInt64(Value)) {
3009 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
3010 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
3011 return 0;
3012 }
3013
3014 if (!EatIfPresent(lltok::rparen)) {
3015 error(Lex.getLoc(), "expected ')'");
3016 return 0;
3017 }
3018
3019 return Value;
3020 } else {
3021 error(Lex.getLoc(), "expected nofpclass test mask");
3022 return 0;
3023 }
3024
3025 Lex.Lex();
3026 if (EatIfPresent(lltok::rparen))
3027 return Mask;
3028 } while (1);
3029
3030 llvm_unreachable("unterminated nofpclass attribute");
3031}
3032
3033/// parseOptionalCommaAlign
3034/// ::=
3035/// ::= ',' align 4
3036///
3037/// This returns with AteExtraComma set to true if it ate an excess comma at the
3038/// end.
3039bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
3040 bool &AteExtraComma) {
3041 AteExtraComma = false;
3042 while (EatIfPresent(lltok::comma)) {
3043 // Metadata at the end is an early exit.
3044 if (Lex.getKind() == lltok::MetadataVar) {
3045 AteExtraComma = true;
3046 return false;
3047 }
3048
3049 if (Lex.getKind() != lltok::kw_align)
3050 return error(Lex.getLoc(), "expected metadata or 'align'");
3051
3052 if (parseOptionalAlignment(Alignment))
3053 return true;
3054 }
3055
3056 return false;
3057}
3058
3059/// parseOptionalCommaAddrSpace
3060/// ::=
3061/// ::= ',' addrspace(1)
3062///
3063/// This returns with AteExtraComma set to true if it ate an excess comma at the
3064/// end.
3065bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
3066 bool &AteExtraComma) {
3067 AteExtraComma = false;
3068 while (EatIfPresent(lltok::comma)) {
3069 // Metadata at the end is an early exit.
3070 if (Lex.getKind() == lltok::MetadataVar) {
3071 AteExtraComma = true;
3072 return false;
3073 }
3074
3075 Loc = Lex.getLoc();
3076 if (Lex.getKind() != lltok::kw_addrspace)
3077 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
3078
3079 if (parseOptionalAddrSpace(AddrSpace))
3080 return true;
3081 }
3082
3083 return false;
3084}
3085
3086bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
3087 std::optional<unsigned> &HowManyArg) {
3088 Lex.Lex();
3089
3090 auto StartParen = Lex.getLoc();
3091 if (!EatIfPresent(lltok::lparen))
3092 return error(StartParen, "expected '('");
3093
3094 if (parseUInt32(BaseSizeArg))
3095 return true;
3096
3097 if (EatIfPresent(lltok::comma)) {
3098 auto HowManyAt = Lex.getLoc();
3099 unsigned HowMany;
3100 if (parseUInt32(HowMany))
3101 return true;
3102 if (HowMany == BaseSizeArg)
3103 return error(HowManyAt,
3104 "'allocsize' indices can't refer to the same parameter");
3105 HowManyArg = HowMany;
3106 } else
3107 HowManyArg = std::nullopt;
3108
3109 auto EndParen = Lex.getLoc();
3110 if (!EatIfPresent(lltok::rparen))
3111 return error(EndParen, "expected ')'");
3112 return false;
3113}
3114
3115bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
3116 unsigned &MaxValue) {
3117 Lex.Lex();
3118
3119 auto StartParen = Lex.getLoc();
3120 if (!EatIfPresent(lltok::lparen))
3121 return error(StartParen, "expected '('");
3122
3123 if (parseUInt32(MinValue))
3124 return true;
3125
3126 if (EatIfPresent(lltok::comma)) {
3127 if (parseUInt32(MaxValue))
3128 return true;
3129 } else
3130 MaxValue = MinValue;
3131
3132 auto EndParen = Lex.getLoc();
3133 if (!EatIfPresent(lltok::rparen))
3134 return error(EndParen, "expected ')'");
3135 return false;
3136}
3137
3138/// parseScopeAndOrdering
3139/// if isAtomic: ::= SyncScope? AtomicOrdering
3140/// else: ::=
3141///
3142/// This sets Scope and Ordering to the parsed values.
3143bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
3144 AtomicOrdering &Ordering) {
3145 if (!IsAtomic)
3146 return false;
3147
3148 return parseScope(SSID) || parseOrdering(Ordering);
3149}
3150
3151/// parseScope
3152/// ::= syncscope("singlethread" | "<target scope>")?
3153///
3154/// This sets synchronization scope ID to the ID of the parsed value.
3155bool LLParser::parseScope(SyncScope::ID &SSID) {
3156 SSID = SyncScope::System;
3157 if (EatIfPresent(lltok::kw_syncscope)) {
3158 auto StartParenAt = Lex.getLoc();
3159 if (!EatIfPresent(lltok::lparen))
3160 return error(StartParenAt, "Expected '(' in syncscope");
3161
3162 std::string SSN;
3163 auto SSNAt = Lex.getLoc();
3164 if (parseStringConstant(SSN))
3165 return error(SSNAt, "Expected synchronization scope name");
3166
3167 auto EndParenAt = Lex.getLoc();
3168 if (!EatIfPresent(lltok::rparen))
3169 return error(EndParenAt, "Expected ')' in syncscope");
3170
3171 SSID = Context.getOrInsertSyncScopeID(SSN);
3172 }
3173
3174 return false;
3175}
3176
3177/// parseOrdering
3178/// ::= AtomicOrdering
3179///
3180/// This sets Ordering to the parsed value.
3181bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
3182 switch (Lex.getKind()) {
3183 default:
3184 return tokError("Expected ordering on atomic instruction");
3187 // Not specified yet:
3188 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
3192 case lltok::kw_seq_cst:
3194 break;
3195 }
3196 Lex.Lex();
3197 return false;
3198}
3199
3200/// parseOptionalStackAlignment
3201/// ::= /* empty */
3202/// ::= 'alignstack' '(' 4 ')'
3203bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
3204 Alignment = 0;
3205 if (!EatIfPresent(lltok::kw_alignstack))
3206 return false;
3207 LocTy ParenLoc = Lex.getLoc();
3208 if (!EatIfPresent(lltok::lparen))
3209 return error(ParenLoc, "expected '('");
3210 LocTy AlignLoc = Lex.getLoc();
3211 if (parseUInt32(Alignment))
3212 return true;
3213 ParenLoc = Lex.getLoc();
3214 if (!EatIfPresent(lltok::rparen))
3215 return error(ParenLoc, "expected ')'");
3216 if (!isPowerOf2_32(Alignment))
3217 return error(AlignLoc, "stack alignment is not a power of two");
3218 return false;
3219}
3220
3221/// parseIndexList - This parses the index list for an insert/extractvalue
3222/// instruction. This sets AteExtraComma in the case where we eat an extra
3223/// comma at the end of the line and find that it is followed by metadata.
3224/// Clients that don't allow metadata can call the version of this function that
3225/// only takes one argument.
3226///
3227/// parseIndexList
3228/// ::= (',' uint32)+
3229///
3230bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
3231 bool &AteExtraComma) {
3232 AteExtraComma = false;
3233
3234 if (Lex.getKind() != lltok::comma)
3235 return tokError("expected ',' as start of index list");
3236
3237 while (EatIfPresent(lltok::comma)) {
3238 if (Lex.getKind() == lltok::MetadataVar) {
3239 if (Indices.empty())
3240 return tokError("expected index");
3241 AteExtraComma = true;
3242 return false;
3243 }
3244 unsigned Idx = 0;
3245 if (parseUInt32(Idx))
3246 return true;
3247 Indices.push_back(Idx);
3248 }
3249
3250 return false;
3251}
3252
3253//===----------------------------------------------------------------------===//
3254// Type Parsing.
3255//===----------------------------------------------------------------------===//
3256
3257/// parseType - parse a type.
3258bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
3259 SMLoc TypeLoc = Lex.getLoc();
3260 switch (Lex.getKind()) {
3261 default:
3262 return tokError(Msg);
3263 case lltok::Type:
3264 // Type ::= 'float' | 'void' (etc)
3265 Result = Lex.getTyVal();
3266 Lex.Lex();
3267
3268 // Handle "ptr" opaque pointer type.
3269 //
3270 // Type ::= ptr ('addrspace' '(' uint32 ')')?
3271 if (Result->isPointerTy()) {
3272 unsigned AddrSpace;
3273 if (parseOptionalAddrSpace(AddrSpace))
3274 return true;
3275 Result = PointerType::get(getContext(), AddrSpace);
3276
3277 // Give a nice error for 'ptr*'.
3278 if (Lex.getKind() == lltok::star)
3279 return tokError("ptr* is invalid - use ptr instead");
3280
3281 // Fall through to parsing the type suffixes only if this 'ptr' is a
3282 // function return. Otherwise, return success, implicitly rejecting other
3283 // suffixes.
3284 if (Lex.getKind() != lltok::lparen)
3285 return false;
3286 }
3287 break;
3288 case lltok::kw_target: {
3289 // Type ::= TargetExtType
3290 if (parseTargetExtType(Result))
3291 return true;
3292 break;
3293 }
3294 case lltok::lbrace:
3295 // Type ::= StructType
3296 if (parseAnonStructType(Result, false))
3297 return true;
3298 break;
3299 case lltok::lsquare:
3300 // Type ::= '[' ... ']'
3301 Lex.Lex(); // eat the lsquare.
3302 if (parseArrayVectorType(Result, false))
3303 return true;
3304 break;
3305 case lltok::less: // Either vector or packed struct.
3306 // Type ::= '<' ... '>'
3307 Lex.Lex();
3308 if (Lex.getKind() == lltok::lbrace) {
3309 if (parseAnonStructType(Result, true) ||
3310 parseToken(lltok::greater, "expected '>' at end of packed struct"))
3311 return true;
3312 } else if (parseArrayVectorType(Result, true))
3313 return true;
3314 break;
3315 case lltok::LocalVar: {
3316 // Type ::= %foo
3317 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3318
3319 // If the type hasn't been defined yet, create a forward definition and
3320 // remember where that forward def'n was seen (in case it never is defined).
3321 if (!Entry.first) {
3322 Entry.first = StructType::create(Context, Lex.getStrVal());
3323 Entry.second = Lex.getLoc();
3324 }
3325 Result = Entry.first;
3326 Lex.Lex();
3327 break;
3328 }
3329
3330 case lltok::LocalVarID: {
3331 // Type ::= %4
3332 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3333
3334 // If the type hasn't been defined yet, create a forward definition and
3335 // remember where that forward def'n was seen (in case it never is defined).
3336 if (!Entry.first) {
3337 Entry.first = StructType::create(Context);
3338 Entry.second = Lex.getLoc();
3339 }
3340 Result = Entry.first;
3341 Lex.Lex();
3342 break;
3343 }
3344 }
3345
3346 // parse the type suffixes.
3347 while (true) {
3348 switch (Lex.getKind()) {
3349 // End of type.
3350 default:
3351 if (!AllowVoid && Result->isVoidTy())
3352 return error(TypeLoc, "void type only allowed for function results");
3353 return false;
3354
3355 // Type ::= Type '*'
3356 case lltok::star:
3357 if (Result->isLabelTy())
3358 return tokError("basic block pointers are invalid");
3359 if (Result->isVoidTy())
3360 return tokError("pointers to void are invalid - use i8* instead");
3362 return tokError("pointer to this type is invalid");
3363 Result = PointerType::getUnqual(Context);
3364 Lex.Lex();
3365 break;
3366
3367 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3368 case lltok::kw_addrspace: {
3369 if (Result->isLabelTy())
3370 return tokError("basic block pointers are invalid");
3371 if (Result->isVoidTy())
3372 return tokError("pointers to void are invalid; use i8* instead");
3374 return tokError("pointer to this type is invalid");
3375 unsigned AddrSpace;
3376 if (parseOptionalAddrSpace(AddrSpace) ||
3377 parseToken(lltok::star, "expected '*' in address space"))
3378 return true;
3379
3380 Result = PointerType::get(Context, AddrSpace);
3381 break;
3382 }
3383
3384 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3385 case lltok::lparen:
3386 if (parseFunctionType(Result))
3387 return true;
3388 break;
3389 }
3390 }
3391}
3392
3393/// parseParameterList
3394/// ::= '(' ')'
3395/// ::= '(' Arg (',' Arg)* ')'
3396/// Arg
3397/// ::= Type OptionalAttributes Value OptionalAttributes
3398bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3399 PerFunctionState &PFS, bool IsMustTailCall,
3400 bool InVarArgsFunc) {
3401 if (parseToken(lltok::lparen, "expected '(' in call"))
3402 return true;
3403
3404 while (Lex.getKind() != lltok::rparen) {
3405 // If this isn't the first argument, we need a comma.
3406 if (!ArgList.empty() &&
3407 parseToken(lltok::comma, "expected ',' in argument list"))
3408 return true;
3409
3410 // parse an ellipsis if this is a musttail call in a variadic function.
3411 if (Lex.getKind() == lltok::dotdotdot) {
3412 const char *Msg = "unexpected ellipsis in argument list for ";
3413 if (!IsMustTailCall)
3414 return tokError(Twine(Msg) + "non-musttail call");
3415 if (!InVarArgsFunc)
3416 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3417 Lex.Lex(); // Lex the '...', it is purely for readability.
3418 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3419 }
3420
3421 // parse the argument.
3422 LocTy ArgLoc;
3423 Type *ArgTy = nullptr;
3424 Value *V;
3425 if (parseType(ArgTy, ArgLoc))
3426 return true;
3428 return error(ArgLoc, "invalid type for function argument");
3429
3430 AttrBuilder ArgAttrs(M->getContext());
3431
3432 if (ArgTy->isMetadataTy()) {
3433 if (parseMetadataAsValue(V, PFS))
3434 return true;
3435 } else {
3436 // Otherwise, handle normal operands.
3437 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3438 return true;
3439 }
3440 ArgList.push_back(ParamInfo(
3441 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3442 }
3443
3444 if (IsMustTailCall && InVarArgsFunc)
3445 return tokError("expected '...' at end of argument list for musttail call "
3446 "in varargs function");
3447
3448 Lex.Lex(); // Lex the ')'.
3449 return false;
3450}
3451
3452/// parseRequiredTypeAttr
3453/// ::= attrname(<ty>)
3454bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3455 Attribute::AttrKind AttrKind) {
3456 Type *Ty = nullptr;
3457 if (!EatIfPresent(AttrToken))
3458 return true;
3459 if (!EatIfPresent(lltok::lparen))
3460 return error(Lex.getLoc(), "expected '('");
3461 if (parseType(Ty))
3462 return true;
3463 if (!EatIfPresent(lltok::rparen))
3464 return error(Lex.getLoc(), "expected ')'");
3465
3466 B.addTypeAttr(AttrKind, Ty);
3467 return false;
3468}
3469
3470/// parseRangeAttr
3471/// ::= range(<ty> <n>,<n>)
3472bool LLParser::parseRangeAttr(AttrBuilder &B) {
3473 Lex.Lex();
3474
3475 APInt Lower;
3476 APInt Upper;
3477 Type *Ty = nullptr;
3478 LocTy TyLoc;
3479
3480 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3481 if (Lex.getKind() != lltok::APSInt)
3482 return tokError("expected integer");
3483 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3484 return tokError(
3485 "integer is too large for the bit width of specified type");
3486 Val = Lex.getAPSIntVal().extend(BitWidth);
3487 Lex.Lex();
3488 return false;
3489 };
3490
3491 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3492 return true;
3493 if (!Ty->isIntegerTy())
3494 return error(TyLoc, "the range must have integer type!");
3495
3496 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3497
3498 if (ParseAPSInt(BitWidth, Lower) ||
3499 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3500 return true;
3501 if (Lower == Upper && !Lower.isZero())
3502 return tokError("the range represent the empty set but limits aren't 0!");
3503
3504 if (parseToken(lltok::rparen, "expected ')'"))
3505 return true;
3506
3507 B.addRangeAttr(ConstantRange(Lower, Upper));
3508 return false;
3509}
3510
3511/// parseInitializesAttr
3512/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3513bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3514 Lex.Lex();
3515
3516 auto ParseAPSInt = [&](APInt &Val) {
3517 if (Lex.getKind() != lltok::APSInt)
3518 return tokError("expected integer");
3519 Val = Lex.getAPSIntVal().extend(64);
3520 Lex.Lex();
3521 return false;
3522 };
3523
3524 if (parseToken(lltok::lparen, "expected '('"))
3525 return true;
3526
3528 // Parse each constant range.
3529 do {
3530 APInt Lower, Upper;
3531 if (parseToken(lltok::lparen, "expected '('"))
3532 return true;
3533
3534 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3535 ParseAPSInt(Upper))
3536 return true;
3537
3538 if (Lower == Upper)
3539 return tokError("the range should not represent the full or empty set!");
3540
3541 if (parseToken(lltok::rparen, "expected ')'"))
3542 return true;
3543
3544 RangeList.push_back(ConstantRange(Lower, Upper));
3545 } while (EatIfPresent(lltok::comma));
3546
3547 if (parseToken(lltok::rparen, "expected ')'"))
3548 return true;
3549
3550 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3551 if (!CRLOrNull.has_value())
3552 return tokError("Invalid (unordered or overlapping) range list");
3553 B.addInitializesAttr(*CRLOrNull);
3554 return false;
3555}
3556
3557bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3559 std::optional<CaptureComponents> Ret;
3560
3561 // We use syntax like captures(ret: address, provenance), so the colon
3562 // should not be interpreted as a label terminator.
3563 Lex.setIgnoreColonInIdentifiers(true);
3564 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
3565
3566 Lex.Lex();
3567 if (parseToken(lltok::lparen, "expected '('"))
3568 return true;
3569
3570 CaptureComponents *Current = &Other;
3571 bool SeenComponent = false;
3572 while (true) {
3573 if (EatIfPresent(lltok::kw_ret)) {
3574 if (parseToken(lltok::colon, "expected ':'"))
3575 return true;
3576 if (Ret)
3577 return tokError("duplicate 'ret' location");
3579 Current = &*Ret;
3580 SeenComponent = false;
3581 }
3582
3583 if (EatIfPresent(lltok::kw_none)) {
3584 if (SeenComponent)
3585 return tokError("cannot use 'none' with other component");
3586 *Current = CaptureComponents::None;
3587 } else {
3588 if (SeenComponent && capturesNothing(*Current))
3589 return tokError("cannot use 'none' with other component");
3590
3591 if (EatIfPresent(lltok::kw_address_is_null))
3593 else if (EatIfPresent(lltok::kw_address))
3594 *Current |= CaptureComponents::Address;
3595 else if (EatIfPresent(lltok::kw_provenance))
3597 else if (EatIfPresent(lltok::kw_read_provenance))
3599 else
3600 return tokError("expected one of 'none', 'address', 'address_is_null', "
3601 "'provenance' or 'read_provenance'");
3602 }
3603
3604 SeenComponent = true;
3605 if (EatIfPresent(lltok::rparen))
3606 break;
3607
3608 if (parseToken(lltok::comma, "expected ',' or ')'"))
3609 return true;
3610 }
3611
3612 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3613 return false;
3614}
3615
3616/// parseOptionalOperandBundles
3617/// ::= /*empty*/
3618/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3619///
3620/// OperandBundle
3621/// ::= bundle-tag '(' ')'
3622/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3623///
3624/// bundle-tag ::= String Constant
3625bool LLParser::parseOptionalOperandBundles(
3626 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3627 LocTy BeginLoc = Lex.getLoc();
3628 if (!EatIfPresent(lltok::lsquare))
3629 return false;
3630
3631 while (Lex.getKind() != lltok::rsquare) {
3632 // If this isn't the first operand bundle, we need a comma.
3633 if (!BundleList.empty() &&
3634 parseToken(lltok::comma, "expected ',' in input list"))
3635 return true;
3636
3637 std::string Tag;
3638 if (parseStringConstant(Tag))
3639 return true;
3640
3641 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3642 return true;
3643
3644 std::vector<Value *> Inputs;
3645 while (Lex.getKind() != lltok::rparen) {
3646 // If this isn't the first input, we need a comma.
3647 if (!Inputs.empty() &&
3648 parseToken(lltok::comma, "expected ',' in input list"))
3649 return true;
3650
3651 Type *Ty = nullptr;
3652 Value *Input = nullptr;
3653 if (parseType(Ty))
3654 return true;
3655 if (Ty->isMetadataTy()) {
3656 if (parseMetadataAsValue(Input, PFS))
3657 return true;
3658 } else if (parseValue(Ty, Input, PFS)) {
3659 return true;
3660 }
3661 Inputs.push_back(Input);
3662 }
3663
3664 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3665
3666 Lex.Lex(); // Lex the ')'.
3667 }
3668
3669 if (BundleList.empty())
3670 return error(BeginLoc, "operand bundle set must not be empty");
3671
3672 Lex.Lex(); // Lex the ']'.
3673 return false;
3674}
3675
3676bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3677 unsigned NextID, unsigned ID) {
3678 if (ID < NextID)
3679 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3680 Twine(NextID) + "' or greater");
3681
3682 return false;
3683}
3684
3685/// parseArgumentList - parse the argument list for a function type or function
3686/// prototype.
3687/// ::= '(' ArgTypeListI ')'
3688/// ArgTypeListI
3689/// ::= /*empty*/
3690/// ::= '...'
3691/// ::= ArgTypeList ',' '...'
3692/// ::= ArgType (',' ArgType)*
3693///
3694bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3695 SmallVectorImpl<unsigned> &UnnamedArgNums,
3696 bool &IsVarArg) {
3697 unsigned CurValID = 0;
3698 IsVarArg = false;
3699 assert(Lex.getKind() == lltok::lparen);
3700 Lex.Lex(); // eat the (.
3701
3702 if (Lex.getKind() != lltok::rparen) {
3703 do {
3704 // Handle ... at end of arg list.
3705 if (EatIfPresent(lltok::dotdotdot)) {
3706 IsVarArg = true;
3707 break;
3708 }
3709
3710 // Otherwise must be an argument type.
3711 LocTy TypeLoc = Lex.getLoc();
3712 Type *ArgTy = nullptr;
3713 AttrBuilder Attrs(M->getContext());
3714 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3715 return true;
3716
3717 if (ArgTy->isVoidTy())
3718 return error(TypeLoc, "argument can not have void type");
3719
3720 std::string Name;
3721 FileLoc IdentStart;
3722 FileLoc IdentEnd;
3723 bool Unnamed = false;
3724 if (Lex.getKind() == lltok::LocalVar) {
3725 Name = Lex.getStrVal();
3726 IdentStart = getTokLineColumnPos();
3727 Lex.Lex();
3728 IdentEnd = getPrevTokEndLineColumnPos();
3729 } else {
3730 unsigned ArgID;
3731 if (Lex.getKind() == lltok::LocalVarID) {
3732 ArgID = Lex.getUIntVal();
3733 IdentStart = getTokLineColumnPos();
3734 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3735 return true;
3736 Lex.Lex();
3737 IdentEnd = getPrevTokEndLineColumnPos();
3738 } else {
3739 ArgID = CurValID;
3740 Unnamed = true;
3741 }
3742 UnnamedArgNums.push_back(ArgID);
3743 CurValID = ArgID + 1;
3744 }
3745
3747 return error(TypeLoc, "invalid type for function argument");
3748
3749 ArgList.emplace_back(
3750 TypeLoc, ArgTy,
3751 Unnamed ? std::nullopt
3752 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3753 AttributeSet::get(ArgTy->getContext(), Attrs), std::move(Name));
3754 } while (EatIfPresent(lltok::comma));
3755 }
3756
3757 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3758}
3759
3760/// parseFunctionType
3761/// ::= Type ArgumentList OptionalAttrs
3762bool LLParser::parseFunctionType(Type *&Result) {
3763 assert(Lex.getKind() == lltok::lparen);
3764
3766 return tokError("invalid function return type");
3767
3769 bool IsVarArg;
3770 SmallVector<unsigned> UnnamedArgNums;
3771 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3772 return true;
3773
3774 // Reject names on the arguments lists.
3775 for (const ArgInfo &Arg : ArgList) {
3776 if (!Arg.Name.empty())
3777 return error(Arg.Loc, "argument name invalid in function type");
3778 if (Arg.Attrs.hasAttributes())
3779 return error(Arg.Loc, "argument attributes invalid in function type");
3780 }
3781
3782 SmallVector<Type*, 16> ArgListTy;
3783 for (const ArgInfo &Arg : ArgList)
3784 ArgListTy.push_back(Arg.Ty);
3785
3786 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3787 return false;
3788}
3789
3790/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3791/// other structs.
3792bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3794 if (parseStructBody(Elts))
3795 return true;
3796
3797 Result = StructType::get(Context, Elts, Packed);
3798 return false;
3799}
3800
3801/// parseStructDefinition - parse a struct in a 'type' definition.
3802bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3803 std::pair<Type *, LocTy> &Entry,
3804 Type *&ResultTy) {
3805 // If the type was already defined, diagnose the redefinition.
3806 if (Entry.first && !Entry.second.isValid())
3807 return error(TypeLoc, "redefinition of type");
3808
3809 // If we have opaque, just return without filling in the definition for the
3810 // struct. This counts as a definition as far as the .ll file goes.
3811 if (EatIfPresent(lltok::kw_opaque)) {
3812 // This type is being defined, so clear the location to indicate this.
3813 Entry.second = SMLoc();
3814
3815 // If this type number has never been uttered, create it.
3816 if (!Entry.first)
3817 Entry.first = StructType::create(Context, Name);
3818 ResultTy = Entry.first;
3819 return false;
3820 }
3821
3822 // If the type starts with '<', then it is either a packed struct or a vector.
3823 bool isPacked = EatIfPresent(lltok::less);
3824
3825 // If we don't have a struct, then we have a random type alias, which we
3826 // accept for compatibility with old files. These types are not allowed to be
3827 // forward referenced and not allowed to be recursive.
3828 if (Lex.getKind() != lltok::lbrace) {
3829 if (Entry.first)
3830 return error(TypeLoc, "forward references to non-struct type");
3831
3832 ResultTy = nullptr;
3833 if (isPacked)
3834 return parseArrayVectorType(ResultTy, true);
3835 return parseType(ResultTy);
3836 }
3837
3838 // This type is being defined, so clear the location to indicate this.
3839 Entry.second = SMLoc();
3840
3841 // If this type number has never been uttered, create it.
3842 if (!Entry.first)
3843 Entry.first = StructType::create(Context, Name);
3844
3845 StructType *STy = cast<StructType>(Entry.first);
3846
3848 if (parseStructBody(Body) ||
3849 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3850 return true;
3851
3852 if (auto E = STy->setBodyOrError(Body, isPacked))
3853 return tokError(toString(std::move(E)));
3854
3855 ResultTy = STy;
3856 return false;
3857}
3858
3859/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3860/// StructType
3861/// ::= '{' '}'
3862/// ::= '{' Type (',' Type)* '}'
3863/// ::= '<' '{' '}' '>'
3864/// ::= '<' '{' Type (',' Type)* '}' '>'
3865bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3866 assert(Lex.getKind() == lltok::lbrace);
3867 Lex.Lex(); // Consume the '{'
3868
3869 // Handle the empty struct.
3870 if (EatIfPresent(lltok::rbrace))
3871 return false;
3872
3873 LocTy EltTyLoc = Lex.getLoc();
3874 Type *Ty = nullptr;
3875 if (parseType(Ty))
3876 return true;
3877 Body.push_back(Ty);
3878
3880 return error(EltTyLoc, "invalid element type for struct");
3881
3882 while (EatIfPresent(lltok::comma)) {
3883 EltTyLoc = Lex.getLoc();
3884 if (parseType(Ty))
3885 return true;
3886
3888 return error(EltTyLoc, "invalid element type for struct");
3889
3890 Body.push_back(Ty);
3891 }
3892
3893 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3894}
3895
3896/// parseArrayVectorType - parse an array or vector type, assuming the first
3897/// token has already been consumed.
3898/// Type
3899/// ::= '[' APSINTVAL 'x' Types ']'
3900/// ::= '<' APSINTVAL 'x' Types '>'
3901/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3902bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3903 bool Scalable = false;
3904
3905 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3906 Lex.Lex(); // consume the 'vscale'
3907 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3908 return true;
3909
3910 Scalable = true;
3911 }
3912
3913 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3914 Lex.getAPSIntVal().getBitWidth() > 64)
3915 return tokError("expected number in address space");
3916
3917 LocTy SizeLoc = Lex.getLoc();
3918 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3919 Lex.Lex();
3920
3921 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3922 return true;
3923
3924 LocTy TypeLoc = Lex.getLoc();
3925 Type *EltTy = nullptr;
3926 if (parseType(EltTy))
3927 return true;
3928
3929 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3930 "expected end of sequential type"))
3931 return true;
3932
3933 if (IsVector) {
3934 if (Size == 0)
3935 return error(SizeLoc, "zero element vector is illegal");
3936 if ((unsigned)Size != Size)
3937 return error(SizeLoc, "size too large for vector");
3939 return error(TypeLoc, "invalid vector element type");
3940 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3941 } else {
3943 return error(TypeLoc, "invalid array element type");
3944 Result = ArrayType::get(EltTy, Size);
3945 }
3946 return false;
3947}
3948
3949/// parseTargetExtType - handle target extension type syntax
3950/// TargetExtType
3951/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3952///
3953/// TargetExtTypeParams
3954/// ::= /*empty*/
3955/// ::= ',' Type TargetExtTypeParams
3956///
3957/// TargetExtIntParams
3958/// ::= /*empty*/
3959/// ::= ',' uint32 TargetExtIntParams
3960bool LLParser::parseTargetExtType(Type *&Result) {
3961 Lex.Lex(); // Eat the 'target' keyword.
3962
3963 // Get the mandatory type name.
3964 std::string TypeName;
3965 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3966 parseStringConstant(TypeName))
3967 return true;
3968
3969 // Parse all of the integer and type parameters at the same time; the use of
3970 // SeenInt will allow us to catch cases where type parameters follow integer
3971 // parameters.
3972 SmallVector<Type *> TypeParams;
3973 SmallVector<unsigned> IntParams;
3974 bool SeenInt = false;
3975 while (Lex.getKind() == lltok::comma) {
3976 Lex.Lex(); // Eat the comma.
3977
3978 if (Lex.getKind() == lltok::APSInt) {
3979 SeenInt = true;
3980 unsigned IntVal;
3981 if (parseUInt32(IntVal))
3982 return true;
3983 IntParams.push_back(IntVal);
3984 } else if (SeenInt) {
3985 // The only other kind of parameter we support is type parameters, which
3986 // must precede the integer parameters. This is therefore an error.
3987 return tokError("expected uint32 param");
3988 } else {
3989 Type *TypeParam;
3990 if (parseType(TypeParam, /*AllowVoid=*/true))
3991 return true;
3992 TypeParams.push_back(TypeParam);
3993 }
3994 }
3995
3996 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3997 return true;
3998
3999 auto TTy =
4000 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
4001 if (auto E = TTy.takeError())
4002 return tokError(toString(std::move(E)));
4003
4004 Result = *TTy;
4005 return false;
4006}
4007
4008//===----------------------------------------------------------------------===//
4009// Function Semantic Analysis.
4010//===----------------------------------------------------------------------===//
4011
4012LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
4013 int functionNumber,
4014 ArrayRef<unsigned> UnnamedArgNums)
4015 : P(p), F(f), FunctionNumber(functionNumber) {
4016
4017 // Insert unnamed arguments into the NumberedVals list.
4018 auto It = UnnamedArgNums.begin();
4019 for (Argument &A : F.args()) {
4020 if (!A.hasName()) {
4021 unsigned ArgNum = *It++;
4022 NumberedVals.add(ArgNum, &A);
4023 }
4024 }
4025}
4026
4027LLParser::PerFunctionState::~PerFunctionState() {
4028 // If there were any forward referenced non-basicblock values, delete them.
4029
4030 for (const auto &P : ForwardRefVals) {
4031 if (isa<BasicBlock>(P.second.first))
4032 continue;
4033 P.second.first->replaceAllUsesWith(
4034 PoisonValue::get(P.second.first->getType()));
4035 P.second.first->deleteValue();
4036 }
4037
4038 for (const auto &P : ForwardRefValIDs) {
4039 if (isa<BasicBlock>(P.second.first))
4040 continue;
4041 P.second.first->replaceAllUsesWith(
4042 PoisonValue::get(P.second.first->getType()));
4043 P.second.first->deleteValue();
4044 }
4045}
4046
4047bool LLParser::PerFunctionState::finishFunction() {
4048 if (!ForwardRefVals.empty())
4049 return P.error(ForwardRefVals.begin()->second.second,
4050 "use of undefined value '%" + ForwardRefVals.begin()->first +
4051 "'");
4052 if (!ForwardRefValIDs.empty())
4053 return P.error(ForwardRefValIDs.begin()->second.second,
4054 "use of undefined value '%" +
4055 Twine(ForwardRefValIDs.begin()->first) + "'");
4056 return false;
4057}
4058
4059/// getVal - Get a value with the specified name or ID, creating a
4060/// forward reference record if needed. This can return null if the value
4061/// exists but does not have the right type.
4062Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
4063 LocTy Loc) {
4064 // Look this name up in the normal function symbol table.
4065 Value *Val = F.getValueSymbolTable()->lookup(Name);
4066
4067 // If this is a forward reference for the value, see if we already created a
4068 // forward ref record.
4069 if (!Val) {
4070 auto I = ForwardRefVals.find(Name);
4071 if (I != ForwardRefVals.end())
4072 Val = I->second.first;
4073 }
4074
4075 // If we have the value in the symbol table or fwd-ref table, return it.
4076 if (Val)
4077 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
4078
4079 // Don't make placeholders with invalid type.
4080 if (!Ty->isFirstClassType()) {
4081 P.error(Loc, "invalid use of a non-first-class type");
4082 return nullptr;
4083 }
4084
4085 // Otherwise, create a new forward reference for this value and remember it.
4086 Value *FwdVal;
4087 if (Ty->isLabelTy()) {
4088 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
4089 } else {
4090 FwdVal = new Argument(Ty, Name);
4091 }
4092 if (FwdVal->getName() != Name) {
4093 P.error(Loc, "name is too long which can result in name collisions, "
4094 "consider making the name shorter or "
4095 "increasing -non-global-value-max-name-size");
4096 return nullptr;
4097 }
4098
4099 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
4100 return FwdVal;
4101}
4102
4103Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
4104 // Look this name up in the normal function symbol table.
4105 Value *Val = NumberedVals.get(ID);
4106
4107 // If this is a forward reference for the value, see if we already created a
4108 // forward ref record.
4109 if (!Val) {
4110 auto I = ForwardRefValIDs.find(ID);
4111 if (I != ForwardRefValIDs.end())
4112 Val = I->second.first;
4113 }
4114
4115 // If we have the value in the symbol table or fwd-ref table, return it.
4116 if (Val)
4117 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
4118
4119 if (!Ty->isFirstClassType()) {
4120 P.error(Loc, "invalid use of a non-first-class type");
4121 return nullptr;
4122 }
4123
4124 // Otherwise, create a new forward reference for this value and remember it.
4125 Value *FwdVal;
4126 if (Ty->isLabelTy()) {
4127 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
4128 } else {
4129 FwdVal = new Argument(Ty);
4130 }
4131
4132 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
4133 return FwdVal;
4134}
4135
4136/// setInstName - After an instruction is parsed and inserted into its
4137/// basic block, this installs its name.
4138bool LLParser::PerFunctionState::setInstName(int NameID,
4139 const std::string &NameStr,
4140 LocTy NameLoc, Instruction *Inst) {
4141 // If this instruction has void type, it cannot have a name or ID specified.
4142 if (Inst->getType()->isVoidTy()) {
4143 if (NameID != -1 || !NameStr.empty())
4144 return P.error(NameLoc, "instructions returning void cannot have a name");
4145 return false;
4146 }
4147
4148 // If this was a numbered instruction, verify that the instruction is the
4149 // expected value and resolve any forward references.
4150 if (NameStr.empty()) {
4151 // If neither a name nor an ID was specified, just use the next ID.
4152 if (NameID == -1)
4153 NameID = NumberedVals.getNext();
4154
4155 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
4156 NameID))
4157 return true;
4158
4159 auto FI = ForwardRefValIDs.find(NameID);
4160 if (FI != ForwardRefValIDs.end()) {
4161 Value *Sentinel = FI->second.first;
4162 if (Sentinel->getType() != Inst->getType())
4163 return P.error(NameLoc, "instruction forward referenced with type '" +
4164 getTypeString(FI->second.first->getType()) +
4165 "'");
4166
4167 Sentinel->replaceAllUsesWith(Inst);
4168 Sentinel->deleteValue();
4169 ForwardRefValIDs.erase(FI);
4170 }
4171
4172 NumberedVals.add(NameID, Inst);
4173 return false;
4174 }
4175
4176 // Otherwise, the instruction had a name. Resolve forward refs and set it.
4177 auto FI = ForwardRefVals.find(NameStr);
4178 if (FI != ForwardRefVals.end()) {
4179 Value *Sentinel = FI->second.first;
4180 if (Sentinel->getType() != Inst->getType())
4181 return P.error(NameLoc, "instruction forward referenced with type '" +
4182 getTypeString(FI->second.first->getType()) +
4183 "'");
4184
4185 Sentinel->replaceAllUsesWith(Inst);
4186 Sentinel->deleteValue();
4187 ForwardRefVals.erase(FI);
4188 }
4189
4190 // Set the name on the instruction.
4191 Inst->setName(NameStr);
4192
4193 if (Inst->getName() != NameStr)
4194 return P.error(NameLoc, "multiple definition of local value named '" +
4195 NameStr + "'");
4196 return false;
4197}
4198
4199/// getBB - Get a basic block with the specified name or ID, creating a
4200/// forward reference record if needed.
4201BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
4202 LocTy Loc) {
4204 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
4205}
4206
4207BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
4209 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
4210}
4211
4212/// defineBB - Define the specified basic block, which is either named or
4213/// unnamed. If there is an error, this returns null otherwise it returns
4214/// the block being defined.
4215BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
4216 int NameID, LocTy Loc) {
4217 BasicBlock *BB;
4218 if (Name.empty()) {
4219 if (NameID != -1) {
4220 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
4221 return nullptr;
4222 } else {
4223 NameID = NumberedVals.getNext();
4224 }
4225 BB = getBB(NameID, Loc);
4226 if (!BB) {
4227 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
4228 return nullptr;
4229 }
4230 } else {
4231 BB = getBB(Name, Loc);
4232 if (!BB) {
4233 P.error(Loc, "unable to create block named '" + Name + "'");
4234 return nullptr;
4235 }
4236 }
4237
4238 // Move the block to the end of the function. Forward ref'd blocks are
4239 // inserted wherever they happen to be referenced.
4240 F.splice(F.end(), &F, BB->getIterator());
4241
4242 // Remove the block from forward ref sets.
4243 if (Name.empty()) {
4244 ForwardRefValIDs.erase(NameID);
4245 NumberedVals.add(NameID, BB);
4246 } else {
4247 // BB forward references are already in the function symbol table.
4248 ForwardRefVals.erase(Name);
4249 }
4250
4251 return BB;
4252}
4253
4254//===----------------------------------------------------------------------===//
4255// Constants.
4256//===----------------------------------------------------------------------===//
4257
4258/// parseValID - parse an abstract value that doesn't necessarily have a
4259/// type implied. For example, if we parse "4" we don't know what integer type
4260/// it has. The value will later be combined with its type and checked for
4261/// basic correctness. PFS is used to convert function-local operands of
4262/// metadata (since metadata operands are not just parsed here but also
4263/// converted to values). PFS can be null when we are not parsing metadata
4264/// values inside a function.
4265bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
4266 ID.Loc = Lex.getLoc();
4267 switch (Lex.getKind()) {
4268 default:
4269 return tokError("expected value token");
4270 case lltok::GlobalID: // @42
4271 ID.UIntVal = Lex.getUIntVal();
4272 ID.Kind = ValID::t_GlobalID;
4273 break;
4274 case lltok::GlobalVar: // @foo
4275 ID.StrVal = Lex.getStrVal();
4276 ID.Kind = ValID::t_GlobalName;
4277 break;
4278 case lltok::LocalVarID: // %42
4279 ID.UIntVal = Lex.getUIntVal();
4280 ID.Kind = ValID::t_LocalID;
4281 break;
4282 case lltok::LocalVar: // %foo
4283 ID.StrVal = Lex.getStrVal();
4284 ID.Kind = ValID::t_LocalName;
4285 break;
4286 case lltok::APSInt:
4287 ID.APSIntVal = Lex.getAPSIntVal();
4288 ID.Kind = ValID::t_APSInt;
4289 break;
4290 case lltok::APFloat: {
4291 ID.APFloatVal = Lex.getAPFloatVal();
4292 ID.Kind = ValID::t_APFloat;
4293 break;
4294 }
4295 case lltok::FloatLiteral: {
4296 if (!ExpectedTy)
4297 return error(ID.Loc, "unexpected floating-point literal");
4298 if (!ExpectedTy->isFloatingPointTy())
4299 return error(ID.Loc, "floating-point constant invalid for type");
4300 ID.APFloatVal = APFloat(ExpectedTy->getFltSemantics());
4301 APFloat::opStatus Except =
4302 cantFail(ID.APFloatVal.convertFromString(
4303 Lex.getStrVal(), RoundingMode::NearestTiesToEven),
4304 "Invalid float strings should be caught by the lexer");
4305 // Forbid overflowing and underflowing literals, but permit inexact
4306 // literals. Underflow is thrown when the result is denormal, so to allow
4307 // denormals, only reject underflowing literals that resulted in a zero.
4308 if (Except & APFloat::opOverflow)
4309 return error(ID.Loc, "floating-point constant overflowed type");
4310 if ((Except & APFloat::opUnderflow) && ID.APFloatVal.isZero())
4311 return error(ID.Loc, "floating-point constant underflowed type");
4312 ID.Kind = ValID::t_APFloat;
4313 break;
4314 }
4316 if (!ExpectedTy)
4317 return error(ID.Loc, "unexpected floating-point literal");
4318 const auto &Semantics = ExpectedTy->getFltSemantics();
4319 const APInt &Bits = Lex.getAPSIntVal();
4320 if (APFloat::getSizeInBits(Semantics) != Bits.getBitWidth())
4321 return error(ID.Loc, "float hex literal has incorrect number of bits");
4322 ID.APFloatVal = APFloat(Semantics, Bits);
4323 ID.Kind = ValID::t_APFloat;
4324 break;
4325 }
4326 case lltok::kw_true:
4327 ID.ConstantVal = ConstantInt::getTrue(Context);
4328 ID.Kind = ValID::t_Constant;
4329 break;
4330 case lltok::kw_false:
4331 ID.ConstantVal = ConstantInt::getFalse(Context);
4332 ID.Kind = ValID::t_Constant;
4333 break;
4334 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
4335 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
4336 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
4337 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
4338 case lltok::kw_none: ID.Kind = ValID::t_None; break;
4339
4340 case lltok::lbrace: {
4341 // ValID ::= '{' ConstVector '}'
4342 Lex.Lex();
4344 if (parseGlobalValueVector(Elts) ||
4345 parseToken(lltok::rbrace, "expected end of struct constant"))
4346 return true;
4347
4348 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4349 ID.UIntVal = Elts.size();
4350 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4351 Elts.size() * sizeof(Elts[0]));
4353 return false;
4354 }
4355 case lltok::less: {
4356 // ValID ::= '<' ConstVector '>' --> Vector.
4357 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
4358 Lex.Lex();
4359 bool isPackedStruct = EatIfPresent(lltok::lbrace);
4360
4362 LocTy FirstEltLoc = Lex.getLoc();
4363 if (parseGlobalValueVector(Elts) ||
4364 (isPackedStruct &&
4365 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4366 parseToken(lltok::greater, "expected end of constant"))
4367 return true;
4368
4369 if (isPackedStruct) {
4370 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4371 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4372 Elts.size() * sizeof(Elts[0]));
4373 ID.UIntVal = Elts.size();
4375 return false;
4376 }
4377
4378 if (Elts.empty())
4379 return error(ID.Loc, "constant vector must not be empty");
4380
4381 if (!Elts[0]->getType()->isIntegerTy() && !Elts[0]->getType()->isByteTy() &&
4382 !Elts[0]->getType()->isFloatingPointTy() &&
4383 !Elts[0]->getType()->isPointerTy())
4384 return error(
4385 FirstEltLoc,
4386 "vector elements must have integer, byte, pointer or floating point "
4387 "type");
4388
4389 // Verify that all the vector elements have the same type.
4390 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4391 if (Elts[i]->getType() != Elts[0]->getType())
4392 return error(FirstEltLoc, "vector element #" + Twine(i) +
4393 " is not of type '" +
4394 getTypeString(Elts[0]->getType()));
4395
4396 ID.ConstantVal = ConstantVector::get(Elts);
4397 ID.Kind = ValID::t_Constant;
4398 return false;
4399 }
4400 case lltok::lsquare: { // Array Constant
4401 Lex.Lex();
4403 LocTy FirstEltLoc = Lex.getLoc();
4404 if (parseGlobalValueVector(Elts) ||
4405 parseToken(lltok::rsquare, "expected end of array constant"))
4406 return true;
4407
4408 // Handle empty element.
4409 if (Elts.empty()) {
4410 // Use undef instead of an array because it's inconvenient to determine
4411 // the element type at this point, there being no elements to examine.
4412 ID.Kind = ValID::t_EmptyArray;
4413 return false;
4414 }
4415
4416 if (!Elts[0]->getType()->isFirstClassType())
4417 return error(FirstEltLoc, "invalid array element type: " +
4418 getTypeString(Elts[0]->getType()));
4419
4420 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4421
4422 // Verify all elements are correct type!
4423 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4424 if (Elts[i]->getType() != Elts[0]->getType())
4425 return error(FirstEltLoc, "array element #" + Twine(i) +
4426 " is not of type '" +
4427 getTypeString(Elts[0]->getType()));
4428 }
4429
4430 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4431 ID.Kind = ValID::t_Constant;
4432 return false;
4433 }
4434 case lltok::kw_c: { // c "foo"
4435 Lex.Lex();
4436 ArrayType *ATy = cast<ArrayType>(ExpectedTy);
4437 ID.ConstantVal = ConstantDataArray::getString(
4438 Context, Lex.getStrVal(), false, ATy->getElementType()->isByteTy());
4439 if (parseToken(lltok::StringConstant, "expected string"))
4440 return true;
4441 ID.Kind = ValID::t_Constant;
4442 return false;
4443 }
4444 case lltok::kw_asm: {
4445 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4446 // STRINGCONSTANT
4447 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4448 Lex.Lex();
4449 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4450 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4451 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4452 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4453 parseStringConstant(ID.StrVal) ||
4454 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4455 parseToken(lltok::StringConstant, "expected constraint string"))
4456 return true;
4457 ID.StrVal2 = Lex.getStrVal();
4458 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4459 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4460 ID.Kind = ValID::t_InlineAsm;
4461 return false;
4462 }
4463
4465 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4466 Lex.Lex();
4467
4468 ValID Fn, Label;
4469
4470 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4471 parseValID(Fn, PFS) ||
4472 parseToken(lltok::comma,
4473 "expected comma in block address expression") ||
4474 parseValID(Label, PFS) ||
4475 parseToken(lltok::rparen, "expected ')' in block address expression"))
4476 return true;
4477
4479 return error(Fn.Loc, "expected function name in blockaddress");
4480 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4481 return error(Label.Loc, "expected basic block name in blockaddress");
4482
4483 // Try to find the function (but skip it if it's forward-referenced).
4484 GlobalValue *GV = nullptr;
4485 if (Fn.Kind == ValID::t_GlobalID) {
4486 GV = NumberedVals.get(Fn.UIntVal);
4487 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4488 GV = M->getNamedValue(Fn.StrVal);
4489 }
4490 Function *F = nullptr;
4491 if (GV) {
4492 // Confirm that it's actually a function with a definition.
4493 if (!isa<Function>(GV))
4494 return error(Fn.Loc, "expected function name in blockaddress");
4495 F = cast<Function>(GV);
4496 if (F->isDeclaration())
4497 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4498 }
4499
4500 if (!F) {
4501 // Make a global variable as a placeholder for this reference.
4502 GlobalValue *&FwdRef =
4503 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4504 if (!FwdRef) {
4505 unsigned FwdDeclAS;
4506 if (ExpectedTy) {
4507 // If we know the type that the blockaddress is being assigned to,
4508 // we can use the address space of that type.
4509 if (!ExpectedTy->isPointerTy())
4510 return error(ID.Loc,
4511 "type of blockaddress must be a pointer and not '" +
4512 getTypeString(ExpectedTy) + "'");
4513 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4514 } else if (PFS) {
4515 // Otherwise, we default the address space of the current function.
4516 FwdDeclAS = PFS->getFunction().getAddressSpace();
4517 } else {
4518 llvm_unreachable("Unknown address space for blockaddress");
4519 }
4520 FwdRef = new GlobalVariable(
4521 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4522 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4523 }
4524
4525 ID.ConstantVal = FwdRef;
4526 ID.Kind = ValID::t_Constant;
4527 return false;
4528 }
4529
4530 // We found the function; now find the basic block. Don't use PFS, since we
4531 // might be inside a constant expression.
4532 BasicBlock *BB;
4533 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4534 if (Label.Kind == ValID::t_LocalID)
4535 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4536 else
4537 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4538 if (!BB)
4539 return error(Label.Loc, "referenced value is not a basic block");
4540 } else {
4541 if (Label.Kind == ValID::t_LocalID)
4542 return error(Label.Loc, "cannot take address of numeric label after "
4543 "the function is defined");
4545 F->getValueSymbolTable()->lookup(Label.StrVal));
4546 if (!BB)
4547 return error(Label.Loc, "referenced value is not a basic block");
4548 }
4549
4550 ID.ConstantVal = BlockAddress::get(F, BB);
4551 ID.Kind = ValID::t_Constant;
4552 return false;
4553 }
4554
4556 // ValID ::= 'dso_local_equivalent' @foo
4557 Lex.Lex();
4558
4559 ValID Fn;
4560
4561 if (parseValID(Fn, PFS))
4562 return true;
4563
4565 return error(Fn.Loc,
4566 "expected global value name in dso_local_equivalent");
4567
4568 // Try to find the function (but skip it if it's forward-referenced).
4569 GlobalValue *GV = nullptr;
4570 if (Fn.Kind == ValID::t_GlobalID) {
4571 GV = NumberedVals.get(Fn.UIntVal);
4572 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4573 GV = M->getNamedValue(Fn.StrVal);
4574 }
4575
4576 if (!GV) {
4577 // Make a placeholder global variable as a placeholder for this reference.
4578 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4579 ? ForwardRefDSOLocalEquivalentIDs
4580 : ForwardRefDSOLocalEquivalentNames;
4581 GlobalValue *&FwdRef = FwdRefMap[Fn];
4582 if (!FwdRef) {
4583 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4584 GlobalValue::InternalLinkage, nullptr, "",
4586 }
4587
4588 ID.ConstantVal = FwdRef;
4589 ID.Kind = ValID::t_Constant;
4590 return false;
4591 }
4592
4593 if (!GV->getValueType()->isFunctionTy())
4594 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4595 "in dso_local_equivalent");
4596
4597 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4598 ID.Kind = ValID::t_Constant;
4599 return false;
4600 }
4601
4602 case lltok::kw_no_cfi: {
4603 // ValID ::= 'no_cfi' @foo
4604 Lex.Lex();
4605
4606 if (parseValID(ID, PFS))
4607 return true;
4608
4609 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4610 return error(ID.Loc, "expected global value name in no_cfi");
4611
4612 ID.NoCFI = true;
4613 return false;
4614 }
4615 case lltok::kw_ptrauth: {
4616 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4617 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4618 // )? )? ')'
4619 Lex.Lex();
4620
4621 Constant *Ptr, *Key;
4622 Constant *Disc = nullptr, *AddrDisc = nullptr,
4623 *DeactivationSymbol = nullptr;
4624
4625 if (parseToken(lltok::lparen,
4626 "expected '(' in constant ptrauth expression") ||
4627 parseGlobalTypeAndValue(Ptr) ||
4628 parseToken(lltok::comma,
4629 "expected comma in constant ptrauth expression") ||
4630 parseGlobalTypeAndValue(Key))
4631 return true;
4632 // If present, parse the optional disc/addrdisc/ds.
4633 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(Disc))
4634 return true;
4635 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4636 return true;
4637 if (EatIfPresent(lltok::comma) &&
4638 parseGlobalTypeAndValue(DeactivationSymbol))
4639 return true;
4640 if (parseToken(lltok::rparen,
4641 "expected ')' in constant ptrauth expression"))
4642 return true;
4643
4644 if (!Ptr->getType()->isPointerTy())
4645 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4646
4647 auto *KeyC = dyn_cast<ConstantInt>(Key);
4648 if (!KeyC || KeyC->getBitWidth() != 32)
4649 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4650
4651 ConstantInt *DiscC = nullptr;
4652 if (Disc) {
4653 DiscC = dyn_cast<ConstantInt>(Disc);
4654 if (!DiscC || DiscC->getBitWidth() != 64)
4655 return error(
4656 ID.Loc,
4657 "constant ptrauth integer discriminator must be i64 constant");
4658 } else {
4659 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4660 }
4661
4662 if (AddrDisc) {
4663 if (!AddrDisc->getType()->isPointerTy())
4664 return error(
4665 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4666 } else {
4667 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4668 }
4669
4670 if (!DeactivationSymbol)
4671 DeactivationSymbol =
4673 if (!DeactivationSymbol->getType()->isPointerTy())
4674 return error(ID.Loc,
4675 "constant ptrauth deactivation symbol must be a pointer");
4676
4677 ID.ConstantVal =
4678 ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc, DeactivationSymbol);
4679 ID.Kind = ValID::t_Constant;
4680 return false;
4681 }
4682
4683 case lltok::kw_trunc:
4684 case lltok::kw_bitcast:
4686 case lltok::kw_inttoptr:
4688 case lltok::kw_ptrtoint: {
4689 unsigned Opc = Lex.getUIntVal();
4690 Type *DestTy = nullptr;
4691 Constant *SrcVal;
4692 Lex.Lex();
4693 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4694 parseGlobalTypeAndValue(SrcVal) ||
4695 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4696 parseType(DestTy) ||
4697 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4698 return true;
4699 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4700 return error(ID.Loc, "invalid cast opcode for cast from '" +
4701 getTypeString(SrcVal->getType()) + "' to '" +
4702 getTypeString(DestTy) + "'");
4704 SrcVal, DestTy);
4705 ID.Kind = ValID::t_Constant;
4706 return false;
4707 }
4709 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4711 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4712 case lltok::kw_udiv:
4713 return error(ID.Loc, "udiv constexprs are no longer supported");
4714 case lltok::kw_sdiv:
4715 return error(ID.Loc, "sdiv constexprs are no longer supported");
4716 case lltok::kw_urem:
4717 return error(ID.Loc, "urem constexprs are no longer supported");
4718 case lltok::kw_srem:
4719 return error(ID.Loc, "srem constexprs are no longer supported");
4720 case lltok::kw_fadd:
4721 return error(ID.Loc, "fadd constexprs are no longer supported");
4722 case lltok::kw_fsub:
4723 return error(ID.Loc, "fsub constexprs are no longer supported");
4724 case lltok::kw_fmul:
4725 return error(ID.Loc, "fmul constexprs are no longer supported");
4726 case lltok::kw_fdiv:
4727 return error(ID.Loc, "fdiv constexprs are no longer supported");
4728 case lltok::kw_frem:
4729 return error(ID.Loc, "frem constexprs are no longer supported");
4730 case lltok::kw_and:
4731 return error(ID.Loc, "and constexprs are no longer supported");
4732 case lltok::kw_or:
4733 return error(ID.Loc, "or constexprs are no longer supported");
4734 case lltok::kw_lshr:
4735 return error(ID.Loc, "lshr constexprs are no longer supported");
4736 case lltok::kw_ashr:
4737 return error(ID.Loc, "ashr constexprs are no longer supported");
4738 case lltok::kw_shl:
4739 return error(ID.Loc, "shl constexprs are no longer supported");
4740 case lltok::kw_mul:
4741 return error(ID.Loc, "mul constexprs are no longer supported");
4742 case lltok::kw_fneg:
4743 return error(ID.Loc, "fneg constexprs are no longer supported");
4744 case lltok::kw_select:
4745 return error(ID.Loc, "select constexprs are no longer supported");
4746 case lltok::kw_zext:
4747 return error(ID.Loc, "zext constexprs are no longer supported");
4748 case lltok::kw_sext:
4749 return error(ID.Loc, "sext constexprs are no longer supported");
4750 case lltok::kw_fptrunc:
4751 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4752 case lltok::kw_fpext:
4753 return error(ID.Loc, "fpext constexprs are no longer supported");
4754 case lltok::kw_uitofp:
4755 return error(ID.Loc, "uitofp constexprs are no longer supported");
4756 case lltok::kw_sitofp:
4757 return error(ID.Loc, "sitofp constexprs are no longer supported");
4758 case lltok::kw_fptoui:
4759 return error(ID.Loc, "fptoui constexprs are no longer supported");
4760 case lltok::kw_fptosi:
4761 return error(ID.Loc, "fptosi constexprs are no longer supported");
4762 case lltok::kw_icmp:
4763 return error(ID.Loc, "icmp constexprs are no longer supported");
4764 case lltok::kw_fcmp:
4765 return error(ID.Loc, "fcmp constexprs are no longer supported");
4766
4767 // Binary Operators.
4768 case lltok::kw_add:
4769 case lltok::kw_sub:
4770 case lltok::kw_xor: {
4771 bool NUW = false;
4772 bool NSW = false;
4773 unsigned Opc = Lex.getUIntVal();
4774 Constant *Val0, *Val1;
4775 Lex.Lex();
4776 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4777 Opc == Instruction::Mul) {
4778 if (EatIfPresent(lltok::kw_nuw))
4779 NUW = true;
4780 if (EatIfPresent(lltok::kw_nsw)) {
4781 NSW = true;
4782 if (EatIfPresent(lltok::kw_nuw))
4783 NUW = true;
4784 }
4785 }
4786 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4787 parseGlobalTypeAndValue(Val0) ||
4788 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4789 parseGlobalTypeAndValue(Val1) ||
4790 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4791 return true;
4792 if (Val0->getType() != Val1->getType())
4793 return error(ID.Loc, "operands of constexpr must have same type");
4794 // Check that the type is valid for the operator.
4795 if (!Val0->getType()->isIntOrIntVectorTy())
4796 return error(ID.Loc,
4797 "constexpr requires integer or integer vector operands");
4798 unsigned Flags = 0;
4801 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4802 ID.Kind = ValID::t_Constant;
4803 return false;
4804 }
4805
4806 case lltok::kw_splat: {
4807 Lex.Lex();
4808 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4809 return true;
4810 Constant *C;
4811 if (parseGlobalTypeAndValue(C))
4812 return true;
4813 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4814 return true;
4815
4816 ID.ConstantVal = C;
4818 return false;
4819 }
4820
4825 unsigned Opc = Lex.getUIntVal();
4827 GEPNoWrapFlags NW;
4828 bool HasInRange = false;
4829 APSInt InRangeStart;
4830 APSInt InRangeEnd;
4831 Type *Ty;
4832 Lex.Lex();
4833
4834 if (Opc == Instruction::GetElementPtr) {
4835 while (true) {
4836 if (EatIfPresent(lltok::kw_inbounds))
4838 else if (EatIfPresent(lltok::kw_nusw))
4840 else if (EatIfPresent(lltok::kw_nuw))
4842 else
4843 break;
4844 }
4845
4846 if (EatIfPresent(lltok::kw_inrange)) {
4847 if (parseToken(lltok::lparen, "expected '('"))
4848 return true;
4849 if (Lex.getKind() != lltok::APSInt)
4850 return tokError("expected integer");
4851 InRangeStart = Lex.getAPSIntVal();
4852 Lex.Lex();
4853 if (parseToken(lltok::comma, "expected ','"))
4854 return true;
4855 if (Lex.getKind() != lltok::APSInt)
4856 return tokError("expected integer");
4857 InRangeEnd = Lex.getAPSIntVal();
4858 Lex.Lex();
4859 if (parseToken(lltok::rparen, "expected ')'"))
4860 return true;
4861 HasInRange = true;
4862 }
4863 }
4864
4865 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4866 return true;
4867
4868 if (Opc == Instruction::GetElementPtr) {
4869 if (parseType(Ty) ||
4870 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4871 return true;
4872 }
4873
4874 if (parseGlobalValueVector(Elts) ||
4875 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4876 return true;
4877
4878 if (Opc == Instruction::GetElementPtr) {
4879 if (Elts.size() == 0 ||
4880 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4881 return error(ID.Loc, "base of getelementptr must be a pointer");
4882
4883 Type *BaseType = Elts[0]->getType();
4884 std::optional<ConstantRange> InRange;
4885 if (HasInRange) {
4886 unsigned IndexWidth =
4887 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4888 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4889 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4890 if (InRangeStart.sge(InRangeEnd))
4891 return error(ID.Loc, "expected end to be larger than start");
4892 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4893 }
4894
4895 unsigned GEPWidth =
4896 BaseType->isVectorTy()
4897 ? cast<FixedVectorType>(BaseType)->getNumElements()
4898 : 0;
4899
4900 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4901 for (Constant *Val : Indices) {
4902 Type *ValTy = Val->getType();
4903 if (!ValTy->isIntOrIntVectorTy())
4904 return error(ID.Loc, "getelementptr index must be an integer");
4905 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4906 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4907 if (GEPWidth && (ValNumEl != GEPWidth))
4908 return error(
4909 ID.Loc,
4910 "getelementptr vector index has a wrong number of elements");
4911 // GEPWidth may have been unknown because the base is a scalar,
4912 // but it is known now.
4913 GEPWidth = ValNumEl;
4914 }
4915 }
4916
4917 if (!Indices.empty() && !Ty->isSized())
4918 return error(ID.Loc, "base element of getelementptr must be sized");
4919
4921 return error(ID.Loc, "invalid base element for constant getelementptr");
4922
4923 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4924 return error(ID.Loc, "invalid getelementptr indices");
4925
4927 ID.ConstantVal =
4928 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4930 } else if (Opc == Instruction::ShuffleVector) {
4931 if (Elts.size() != 3)
4932 return error(ID.Loc, "expected three operands to shufflevector");
4933 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4934 return error(ID.Loc, "invalid operands to shufflevector");
4935 SmallVector<int, 16> Mask;
4937 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4938 } else if (Opc == Instruction::ExtractElement) {
4939 if (Elts.size() != 2)
4940 return error(ID.Loc, "expected two operands to extractelement");
4941 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4942 return error(ID.Loc, "invalid extractelement operands");
4943 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4944 } else {
4945 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4946 if (Elts.size() != 3)
4947 return error(ID.Loc, "expected three operands to insertelement");
4948 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4949 return error(ID.Loc, "invalid insertelement operands");
4950 ID.ConstantVal =
4951 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4952 }
4953
4954 ID.Kind = ValID::t_Constant;
4955 return false;
4956 }
4957 }
4958
4959 Lex.Lex();
4960 return false;
4961}
4962
4963/// parseGlobalValue - parse a global value with the specified type.
4964bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4965 C = nullptr;
4966 ValID ID;
4967 Value *V = nullptr;
4968 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4969 convertValIDToValue(Ty, ID, V, nullptr);
4970 if (V && !(C = dyn_cast<Constant>(V)))
4971 return error(ID.Loc, "global values must be constants");
4972 return Parsed;
4973}
4974
4975bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4976 Type *Ty = nullptr;
4977 return parseType(Ty) || parseGlobalValue(Ty, V);
4978}
4979
4980bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4981 C = nullptr;
4982
4983 LocTy KwLoc = Lex.getLoc();
4984 if (!EatIfPresent(lltok::kw_comdat))
4985 return false;
4986
4987 if (EatIfPresent(lltok::lparen)) {
4988 if (Lex.getKind() != lltok::ComdatVar)
4989 return tokError("expected comdat variable");
4990 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4991 Lex.Lex();
4992 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4993 return true;
4994 } else {
4995 if (GlobalName.empty())
4996 return tokError("comdat cannot be unnamed");
4997 C = getComdat(std::string(GlobalName), KwLoc);
4998 }
4999
5000 return false;
5001}
5002
5003/// parseGlobalValueVector
5004/// ::= /*empty*/
5005/// ::= TypeAndValue (',' TypeAndValue)*
5006bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
5007 // Empty list.
5008 if (Lex.getKind() == lltok::rbrace ||
5009 Lex.getKind() == lltok::rsquare ||
5010 Lex.getKind() == lltok::greater ||
5011 Lex.getKind() == lltok::rparen)
5012 return false;
5013
5014 do {
5015 // Let the caller deal with inrange.
5016 if (Lex.getKind() == lltok::kw_inrange)
5017 return false;
5018
5019 Constant *C;
5020 if (parseGlobalTypeAndValue(C))
5021 return true;
5022 Elts.push_back(C);
5023 } while (EatIfPresent(lltok::comma));
5024
5025 return false;
5026}
5027
5028bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
5030 if (parseMDNodeVector(Elts))
5031 return true;
5032
5033 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
5034 return false;
5035}
5036
5037/// MDNode:
5038/// ::= !{ ... }
5039/// ::= !7
5040/// ::= !DILocation(...)
5041bool LLParser::parseMDNode(MDNode *&N) {
5042 if (Lex.getKind() == lltok::MetadataVar)
5043 return parseSpecializedMDNode(N);
5044
5045 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
5046}
5047
5048bool LLParser::parseMDNodeTail(MDNode *&N) {
5049 // !{ ... }
5050 if (Lex.getKind() == lltok::lbrace)
5051 return parseMDTuple(N);
5052
5053 // !42
5054 return parseMDNodeID(N);
5055}
5056
5057namespace {
5058
5059/// Structure to represent an optional metadata field.
5060template <class FieldTy> struct MDFieldImpl {
5061 typedef MDFieldImpl ImplTy;
5062 FieldTy Val;
5063 bool Seen;
5064
5065 void assign(FieldTy Val) {
5066 Seen = true;
5067 this->Val = std::move(Val);
5068 }
5069
5070 explicit MDFieldImpl(FieldTy Default)
5071 : Val(std::move(Default)), Seen(false) {}
5072};
5073
5074/// Structure to represent an optional metadata field that
5075/// can be of either type (A or B) and encapsulates the
5076/// MD<typeofA>Field and MD<typeofB>Field structs, so not
5077/// to reimplement the specifics for representing each Field.
5078template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
5079 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
5080 FieldTypeA A;
5081 FieldTypeB B;
5082 bool Seen;
5083
5084 enum {
5085 IsInvalid = 0,
5086 IsTypeA = 1,
5087 IsTypeB = 2
5088 } WhatIs;
5089
5090 void assign(FieldTypeA A) {
5091 Seen = true;
5092 this->A = std::move(A);
5093 WhatIs = IsTypeA;
5094 }
5095
5096 void assign(FieldTypeB B) {
5097 Seen = true;
5098 this->B = std::move(B);
5099 WhatIs = IsTypeB;
5100 }
5101
5102 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
5103 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
5104 WhatIs(IsInvalid) {}
5105};
5106
5107struct MDUnsignedField : public MDFieldImpl<uint64_t> {
5108 uint64_t Max;
5109
5110 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
5111 : ImplTy(Default), Max(Max) {}
5112};
5113
5114struct LineField : public MDUnsignedField {
5115 LineField() : MDUnsignedField(0, UINT32_MAX) {}
5116};
5117
5118struct ColumnField : public MDUnsignedField {
5119 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
5120};
5121
5122struct DwarfTagField : public MDUnsignedField {
5123 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
5124 DwarfTagField(dwarf::Tag DefaultTag)
5125 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
5126};
5127
5128struct DwarfMacinfoTypeField : public MDUnsignedField {
5129 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
5130 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
5131 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
5132};
5133
5134struct DwarfAttEncodingField : public MDUnsignedField {
5135 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
5136};
5137
5138struct DwarfVirtualityField : public MDUnsignedField {
5139 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
5140};
5141
5142struct DwarfLangField : public MDUnsignedField {
5143 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
5144};
5145
5146struct DwarfSourceLangNameField : public MDUnsignedField {
5147 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5148};
5149
5150struct DwarfLangDialectField : public MDUnsignedField {
5151 DwarfLangDialectField()
5152 : MDUnsignedField(0, dwarf::DW_LLVM_LANG_DIALECT_max) {}
5153};
5154
5155struct DwarfCCField : public MDUnsignedField {
5156 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
5157};
5158
5159struct DwarfEnumKindField : public MDUnsignedField {
5160 DwarfEnumKindField()
5161 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
5162 dwarf::DW_APPLE_ENUM_KIND_max) {}
5163};
5164
5165struct EmissionKindField : public MDUnsignedField {
5166 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5167};
5168
5169struct FixedPointKindField : public MDUnsignedField {
5170 FixedPointKindField()
5171 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5172};
5173
5174struct NameTableKindField : public MDUnsignedField {
5175 NameTableKindField()
5176 : MDUnsignedField(
5177 0, (unsigned)
5178 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5179};
5180
5181struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
5182 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5183};
5184
5185struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
5186 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5187};
5188
5189struct MDAPSIntField : public MDFieldImpl<APSInt> {
5190 MDAPSIntField() : ImplTy(APSInt()) {}
5191};
5192
5193struct MDSignedField : public MDFieldImpl<int64_t> {
5194 int64_t Min = INT64_MIN;
5195 int64_t Max = INT64_MAX;
5196
5197 MDSignedField(int64_t Default = 0)
5198 : ImplTy(Default) {}
5199 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
5200 : ImplTy(Default), Min(Min), Max(Max) {}
5201};
5202
5203struct MDBoolField : public MDFieldImpl<bool> {
5204 MDBoolField(bool Default = false) : ImplTy(Default) {}
5205};
5206
5207struct MDField : public MDFieldImpl<Metadata *> {
5208 bool AllowNull;
5209
5210 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5211};
5212
5213struct MDStringField : public MDFieldImpl<MDString *> {
5214 enum class EmptyIs {
5215 Null, //< Allow empty input string, map to nullptr
5216 Empty, //< Allow empty input string, map to an empty MDString
5217 Error, //< Disallow empty string, map to an error
5218 } EmptyIs;
5219 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
5220 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5221};
5222
5223struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
5224 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
5225};
5226
5227struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
5228 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
5229};
5230
5231struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5232 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
5233 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
5234
5235 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
5236 bool AllowNull = true)
5237 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
5238
5239 bool isMDSignedField() const { return WhatIs == IsTypeA; }
5240 bool isMDField() const { return WhatIs == IsTypeB; }
5241 int64_t getMDSignedValue() const {
5242 assert(isMDSignedField() && "Wrong field type");
5243 return A.Val;
5244 }
5245 Metadata *getMDFieldValue() const {
5246 assert(isMDField() && "Wrong field type");
5247 return B.Val;
5248 }
5249};
5250
5251struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5252 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
5253 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
5254
5255 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
5256 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
5257
5258 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
5259 bool isMDField() const { return WhatIs == IsTypeB; }
5260 uint64_t getMDUnsignedValue() const {
5261 assert(isMDUnsignedField() && "Wrong field type");
5262 return A.Val;
5263 }
5264 Metadata *getMDFieldValue() const {
5265 assert(isMDField() && "Wrong field type");
5266 return B.Val;
5267 }
5268
5269 Metadata *getValueAsMetadata(LLVMContext &Context) const {
5270 if (isMDUnsignedField())
5272 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
5273 if (isMDField())
5274 return getMDFieldValue();
5275 return nullptr;
5276 }
5277};
5278
5279} // end anonymous namespace
5280
5281namespace llvm {
5282
5283template <>
5284bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
5285 if (Lex.getKind() != lltok::APSInt)
5286 return tokError("expected integer");
5287
5288 Result.assign(Lex.getAPSIntVal());
5289 Lex.Lex();
5290 return false;
5291}
5292
5293template <>
5294bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5295 MDUnsignedField &Result) {
5296 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5297 return tokError("expected unsigned integer");
5298
5299 auto &U = Lex.getAPSIntVal();
5300 if (U.ugt(Result.Max))
5301 return tokError("value for '" + Name + "' too large, limit is " +
5302 Twine(Result.Max));
5303 Result.assign(U.getZExtValue());
5304 assert(Result.Val <= Result.Max && "Expected value in range");
5305 Lex.Lex();
5306 return false;
5307}
5308
5309template <>
5310bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
5311 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5312}
5313template <>
5314bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
5315 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5316}
5317
5318template <>
5319bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
5320 if (Lex.getKind() == lltok::APSInt)
5321 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5322
5323 if (Lex.getKind() != lltok::DwarfTag)
5324 return tokError("expected DWARF tag");
5325
5326 unsigned Tag = dwarf::getTag(Lex.getStrVal());
5328 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
5329 assert(Tag <= Result.Max && "Expected valid DWARF tag");
5330
5331 Result.assign(Tag);
5332 Lex.Lex();
5333 return false;
5334}
5335
5336template <>
5337bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5338 DwarfMacinfoTypeField &Result) {
5339 if (Lex.getKind() == lltok::APSInt)
5340 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5341
5342 if (Lex.getKind() != lltok::DwarfMacinfo)
5343 return tokError("expected DWARF macinfo type");
5344
5345 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
5346 if (Macinfo == dwarf::DW_MACINFO_invalid)
5347 return tokError("invalid DWARF macinfo type" + Twine(" '") +
5348 Lex.getStrVal() + "'");
5349 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
5350
5351 Result.assign(Macinfo);
5352 Lex.Lex();
5353 return false;
5354}
5355
5356template <>
5357bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5358 DwarfVirtualityField &Result) {
5359 if (Lex.getKind() == lltok::APSInt)
5360 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5361
5362 if (Lex.getKind() != lltok::DwarfVirtuality)
5363 return tokError("expected DWARF virtuality code");
5364
5365 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
5366 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5367 return tokError("invalid DWARF virtuality code" + Twine(" '") +
5368 Lex.getStrVal() + "'");
5369 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5370 Result.assign(Virtuality);
5371 Lex.Lex();
5372 return false;
5373}
5374
5375template <>
5376bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5377 DwarfEnumKindField &Result) {
5378 if (Lex.getKind() == lltok::APSInt)
5379 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5380
5381 if (Lex.getKind() != lltok::DwarfEnumKind)
5382 return tokError("expected DWARF enum kind code");
5383
5384 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5385 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5386 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5387 Lex.getStrVal() + "'");
5388 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5389 Result.assign(EnumKind);
5390 Lex.Lex();
5391 return false;
5392}
5393
5394template <>
5395bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5396 if (Lex.getKind() == lltok::APSInt)
5397 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5398
5399 if (Lex.getKind() != lltok::DwarfLang)
5400 return tokError("expected DWARF language");
5401
5402 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5403 if (!Lang)
5404 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5405 "'");
5406 assert(Lang <= Result.Max && "Expected valid DWARF language");
5407 Result.assign(Lang);
5408 Lex.Lex();
5409 return false;
5410}
5411
5412template <>
5413bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5414 DwarfSourceLangNameField &Result) {
5415 if (Lex.getKind() == lltok::APSInt)
5416 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5417
5418 if (Lex.getKind() != lltok::DwarfSourceLangName)
5419 return tokError("expected DWARF source language name");
5420
5421 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5422 if (!Lang)
5423 return tokError("invalid DWARF source language name" + Twine(" '") +
5424 Lex.getStrVal() + "'");
5425 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5426 Result.assign(Lang);
5427 Lex.Lex();
5428 return false;
5429}
5430
5431template <>
5432bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5433 DwarfLangDialectField &Result) {
5434 // Specifying the dialect field requires a recognized dialect: simt or
5435 // tile (numerically 1 or 2). Omitting the field is the only way to
5436 // express "no dialect specified".
5437 if (Lex.getKind() == lltok::APSInt) {
5438 if (Lex.getAPSIntVal() == 0)
5439 return tokError("value for 'dialect' must be a known DWARF language "
5440 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5441 "DW_LLVM_LANG_DIALECT_tile)");
5442 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5443 }
5444
5445 if (Lex.getKind() != lltok::DwarfLangDialect)
5446 return tokError("expected DWARF language dialect");
5447
5448 StringRef DialectString = Lex.getStrVal();
5449 // getLanguageDialect returns a sentinel above Result.Max for unknown
5450 // spellings; only simt and tile are registered, so any unrecognized
5451 // DW_LLVM_LANG_DIALECT_* token is rejected here.
5452 unsigned Dialect = dwarf::getLanguageDialect(DialectString);
5453 if (Dialect > Result.Max)
5454 return tokError("invalid DWARF language dialect" + Twine(" '") +
5455 DialectString + "'");
5456 Result.assign(Dialect);
5457 Lex.Lex();
5458 return false;
5459}
5460
5461template <>
5462bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5463 if (Lex.getKind() == lltok::APSInt)
5464 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5465
5466 if (Lex.getKind() != lltok::DwarfCC)
5467 return tokError("expected DWARF calling convention");
5468
5469 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5470 if (!CC)
5471 return tokError("invalid DWARF calling convention" + Twine(" '") +
5472 Lex.getStrVal() + "'");
5473 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5474 Result.assign(CC);
5475 Lex.Lex();
5476 return false;
5477}
5478
5479template <>
5480bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5481 EmissionKindField &Result) {
5482 if (Lex.getKind() == lltok::APSInt)
5483 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5484
5485 if (Lex.getKind() != lltok::EmissionKind)
5486 return tokError("expected emission kind");
5487
5488 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5489 if (!Kind)
5490 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5491 "'");
5492 assert(*Kind <= Result.Max && "Expected valid emission kind");
5493 Result.assign(*Kind);
5494 Lex.Lex();
5495 return false;
5496}
5497
5498template <>
5499bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5500 FixedPointKindField &Result) {
5501 if (Lex.getKind() == lltok::APSInt)
5502 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5503
5504 if (Lex.getKind() != lltok::FixedPointKind)
5505 return tokError("expected fixed-point kind");
5506
5507 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5508 if (!Kind)
5509 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5510 "'");
5511 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5512 Result.assign(*Kind);
5513 Lex.Lex();
5514 return false;
5515}
5516
5517template <>
5518bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5519 NameTableKindField &Result) {
5520 if (Lex.getKind() == lltok::APSInt)
5521 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5522
5523 if (Lex.getKind() != lltok::NameTableKind)
5524 return tokError("expected nameTable kind");
5525
5526 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5527 if (!Kind)
5528 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5529 "'");
5530 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5531 Result.assign((unsigned)*Kind);
5532 Lex.Lex();
5533 return false;
5534}
5535
5536template <>
5537bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5538 DwarfAttEncodingField &Result) {
5539 if (Lex.getKind() == lltok::APSInt)
5540 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5541
5542 if (Lex.getKind() != lltok::DwarfAttEncoding)
5543 return tokError("expected DWARF type attribute encoding");
5544
5545 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5546 if (!Encoding)
5547 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5548 Lex.getStrVal() + "'");
5549 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5550 Result.assign(Encoding);
5551 Lex.Lex();
5552 return false;
5553}
5554
5555/// DIFlagField
5556/// ::= uint32
5557/// ::= DIFlagVector
5558/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5559template <>
5560bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5561
5562 // parser for a single flag.
5563 auto parseFlag = [&](DINode::DIFlags &Val) {
5564 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5565 uint32_t TempVal = static_cast<uint32_t>(Val);
5566 bool Res = parseUInt32(TempVal);
5567 Val = static_cast<DINode::DIFlags>(TempVal);
5568 return Res;
5569 }
5570
5571 if (Lex.getKind() != lltok::DIFlag)
5572 return tokError("expected debug info flag");
5573
5574 Val = DINode::getFlag(Lex.getStrVal());
5575 if (!Val)
5576 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5577 "'");
5578 Lex.Lex();
5579 return false;
5580 };
5581
5582 // parse the flags and combine them together.
5583 DINode::DIFlags Combined = DINode::FlagZero;
5584 do {
5585 DINode::DIFlags Val;
5586 if (parseFlag(Val))
5587 return true;
5588 Combined |= Val;
5589 } while (EatIfPresent(lltok::bar));
5590
5591 Result.assign(Combined);
5592 return false;
5593}
5594
5595/// DISPFlagField
5596/// ::= uint32
5597/// ::= DISPFlagVector
5598/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5599template <>
5600bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5601
5602 // parser for a single flag.
5603 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5604 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5605 uint32_t TempVal = static_cast<uint32_t>(Val);
5606 bool Res = parseUInt32(TempVal);
5607 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5608 return Res;
5609 }
5610
5611 if (Lex.getKind() != lltok::DISPFlag)
5612 return tokError("expected debug info flag");
5613
5614 Val = DISubprogram::getFlag(Lex.getStrVal());
5615 if (!Val)
5616 return tokError(Twine("invalid subprogram debug info flag '") +
5617 Lex.getStrVal() + "'");
5618 Lex.Lex();
5619 return false;
5620 };
5621
5622 // parse the flags and combine them together.
5623 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5624 do {
5626 if (parseFlag(Val))
5627 return true;
5628 Combined |= Val;
5629 } while (EatIfPresent(lltok::bar));
5630
5631 Result.assign(Combined);
5632 return false;
5633}
5634
5635template <>
5636bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5637 if (Lex.getKind() != lltok::APSInt)
5638 return tokError("expected signed integer");
5639
5640 auto &S = Lex.getAPSIntVal();
5641 if (S < Result.Min)
5642 return tokError("value for '" + Name + "' too small, limit is " +
5643 Twine(Result.Min));
5644 if (S > Result.Max)
5645 return tokError("value for '" + Name + "' too large, limit is " +
5646 Twine(Result.Max));
5647 Result.assign(S.getExtValue());
5648 assert(Result.Val >= Result.Min && "Expected value in range");
5649 assert(Result.Val <= Result.Max && "Expected value in range");
5650 Lex.Lex();
5651 return false;
5652}
5653
5654template <>
5655bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5656 switch (Lex.getKind()) {
5657 default:
5658 return tokError("expected 'true' or 'false'");
5659 case lltok::kw_true:
5660 Result.assign(true);
5661 break;
5662 case lltok::kw_false:
5663 Result.assign(false);
5664 break;
5665 }
5666 Lex.Lex();
5667 return false;
5668}
5669
5670template <>
5671bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5672 if (Lex.getKind() == lltok::kw_null) {
5673 if (!Result.AllowNull)
5674 return tokError("'" + Name + "' cannot be null");
5675 Lex.Lex();
5676 Result.assign(nullptr);
5677 return false;
5678 }
5679
5680 Metadata *MD;
5681 if (parseMetadata(MD, nullptr))
5682 return true;
5683
5684 Result.assign(MD);
5685 return false;
5686}
5687
5688template <>
5689bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5690 MDSignedOrMDField &Result) {
5691 // Try to parse a signed int.
5692 if (Lex.getKind() == lltok::APSInt) {
5693 MDSignedField Res = Result.A;
5694 if (!parseMDField(Loc, Name, Res)) {
5695 Result.assign(Res);
5696 return false;
5697 }
5698 return true;
5699 }
5700
5701 // Otherwise, try to parse as an MDField.
5702 MDField Res = Result.B;
5703 if (!parseMDField(Loc, Name, Res)) {
5704 Result.assign(Res);
5705 return false;
5706 }
5707
5708 return true;
5709}
5710
5711template <>
5712bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5713 MDUnsignedOrMDField &Result) {
5714 // Try to parse an unsigned int.
5715 if (Lex.getKind() == lltok::APSInt) {
5716 MDUnsignedField Res = Result.A;
5717 if (!parseMDField(Loc, Name, Res)) {
5718 Result.assign(Res);
5719 return false;
5720 }
5721 return true;
5722 }
5723
5724 // Otherwise, try to parse as an MDField.
5725 MDField Res = Result.B;
5726 if (!parseMDField(Loc, Name, Res)) {
5727 Result.assign(Res);
5728 return false;
5729 }
5730
5731 return true;
5732}
5733
5734template <>
5735bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5736 LocTy ValueLoc = Lex.getLoc();
5737 std::string S;
5738 if (parseStringConstant(S))
5739 return true;
5740
5741 if (S.empty()) {
5742 switch (Result.EmptyIs) {
5743 case MDStringField::EmptyIs::Null:
5744 Result.assign(nullptr);
5745 return false;
5746 case MDStringField::EmptyIs::Empty:
5747 break;
5748 case MDStringField::EmptyIs::Error:
5749 return error(ValueLoc, "'" + Name + "' cannot be empty");
5750 }
5751 }
5752
5753 Result.assign(MDString::get(Context, S));
5754 return false;
5755}
5756
5757template <>
5758bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5760 if (parseMDNodeVector(MDs))
5761 return true;
5762
5763 Result.assign(std::move(MDs));
5764 return false;
5765}
5766
5767template <>
5768bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5769 ChecksumKindField &Result) {
5770 std::optional<DIFile::ChecksumKind> CSKind =
5771 DIFile::getChecksumKind(Lex.getStrVal());
5772
5773 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5774 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5775 "'");
5776
5777 Result.assign(*CSKind);
5778 Lex.Lex();
5779 return false;
5780}
5781
5782} // end namespace llvm
5783
5784template <class ParserTy>
5785bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5786 do {
5787 if (Lex.getKind() != lltok::LabelStr)
5788 return tokError("expected field label here");
5789
5790 if (ParseField())
5791 return true;
5792 } while (EatIfPresent(lltok::comma));
5793
5794 return false;
5795}
5796
5797template <class ParserTy>
5798bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5799 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5800 Lex.Lex();
5801
5802 if (parseToken(lltok::lparen, "expected '(' here"))
5803 return true;
5804 if (Lex.getKind() != lltok::rparen)
5805 if (parseMDFieldsImplBody(ParseField))
5806 return true;
5807
5808 ClosingLoc = Lex.getLoc();
5809 return parseToken(lltok::rparen, "expected ')' here");
5810}
5811
5812template <class FieldTy>
5813bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5814 if (Result.Seen)
5815 return tokError("field '" + Name + "' cannot be specified more than once");
5816
5817 LocTy Loc = Lex.getLoc();
5818 Lex.Lex();
5819 return parseMDField(Loc, Name, Result);
5820}
5821
5822bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5823 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5824
5825#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5826 if (Lex.getStrVal() == #CLASS) \
5827 return parse##CLASS(N, IsDistinct);
5828#include "llvm/IR/Metadata.def"
5829
5830 return tokError("expected metadata type");
5831}
5832
5833#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5834#define NOP_FIELD(NAME, TYPE, INIT)
5835#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5836 if (!NAME.Seen) \
5837 return error(ClosingLoc, "missing required field '" #NAME "'");
5838#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5839 if (Lex.getStrVal() == #NAME) \
5840 return parseMDField(#NAME, NAME);
5841#define PARSE_MD_FIELDS() \
5842 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5843 do { \
5844 LocTy ClosingLoc; \
5845 if (parseMDFieldsImpl( \
5846 [&]() -> bool { \
5847 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5848 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5849 "'"); \
5850 }, \
5851 ClosingLoc)) \
5852 return true; \
5853 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5854 } while (false)
5855#define GET_OR_DISTINCT(CLASS, ARGS) \
5856 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5857
5858bool LLParser::parseMDFunctionLocalContext(MDNode *&Result, bool IsDistinct) {
5859 return tokError("!MDFunctionLocalContext parsing not yet implemented");
5860}
5861
5862/// parseDILocationFields:
5863/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5864/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5865bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5866#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5867 OPTIONAL(line, LineField, ); \
5868 OPTIONAL(column, ColumnField, ); \
5869 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5870 OPTIONAL(inlinedAt, MDField, ); \
5871 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5872 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5873 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX)); \
5874 OPTIONAL(irlayers, MDField, );
5876#undef VISIT_MD_FIELDS
5877
5878 Result =
5879 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
5880 inlinedAt.Val, isImplicitCode.Val,
5881 atomGroup.Val, atomRank.Val, irlayers.Val));
5882 return false;
5883}
5884
5885bool LLParser::parseDILayerLoc(MDNode *&Result, bool IsDistinct) {
5886#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5887 OPTIONAL(line, LineField, ); \
5888 OPTIONAL(column, ColumnField, ); \
5889 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5890 REQUIRED(kind, MDStringField, );
5892#undef VISIT_MD_FIELDS
5893
5894 Result = GET_OR_DISTINCT(DILayerLoc,
5895 (Context, kind.Val, file.Val, line.Val, column.Val));
5896 return false;
5897}
5898
5899bool LLParser::parseDILayerLocList(MDNode *&Result, bool IsDistinct) {
5900 // ::= !DILayerLocList(!a, !b, ...)
5901 Lex.Lex(); // eat the '!DILayerLocList' type name
5902 if (parseToken(lltok::lparen, "expected '(' here"))
5903 return true;
5905 if (!EatIfPresent(lltok::rparen)) {
5906 do {
5907 Metadata *MD;
5908 if (parseMetadata(MD, nullptr))
5909 return true;
5910 Layers.push_back(MD);
5911 } while (EatIfPresent(lltok::comma));
5912 if (parseToken(lltok::rparen, "expected ')' here"))
5913 return true;
5914 }
5915 Result = GET_OR_DISTINCT(DILayerLocList, (Context, Layers));
5916 return false;
5917}
5918
5919/// parseDIAssignID:
5920/// ::= distinct !DIAssignID()
5921bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5922 if (!IsDistinct)
5923 return tokError("missing 'distinct', required for !DIAssignID()");
5924
5925 Lex.Lex();
5926
5927 // Now eat the parens.
5928 if (parseToken(lltok::lparen, "expected '(' here"))
5929 return true;
5930 if (parseToken(lltok::rparen, "expected ')' here"))
5931 return true;
5932
5934 return false;
5935}
5936
5937/// parseGenericDINode:
5938/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5939bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5940#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5941 REQUIRED(tag, DwarfTagField, ); \
5942 OPTIONAL(header, MDStringField, ); \
5943 OPTIONAL(operands, MDFieldList, );
5945#undef VISIT_MD_FIELDS
5946
5947 Result = GET_OR_DISTINCT(GenericDINode,
5948 (Context, tag.Val, header.Val, operands.Val));
5949 return false;
5950}
5951
5952/// parseDISubrangeType:
5953/// ::= !DISubrangeType(name: "whatever", file: !0,
5954/// line: 7, scope: !1, baseType: !2, size: 32,
5955/// align: 32, flags: 0, lowerBound: !3
5956/// upperBound: !4, stride: !5, bias: !6)
5957bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5958#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5959 OPTIONAL(name, MDStringField, ); \
5960 OPTIONAL(file, MDField, ); \
5961 OPTIONAL(line, LineField, ); \
5962 OPTIONAL(scope, MDField, ); \
5963 OPTIONAL(baseType, MDField, ); \
5964 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5965 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5966 OPTIONAL(flags, DIFlagField, ); \
5967 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5968 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5969 OPTIONAL(stride, MDSignedOrMDField, ); \
5970 OPTIONAL(bias, MDSignedOrMDField, );
5972#undef VISIT_MD_FIELDS
5973
5974 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5975 if (Bound.isMDSignedField())
5977 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5978 if (Bound.isMDField())
5979 return Bound.getMDFieldValue();
5980 return nullptr;
5981 };
5982
5983 Metadata *LowerBound = convToMetadata(lowerBound);
5984 Metadata *UpperBound = convToMetadata(upperBound);
5985 Metadata *Stride = convToMetadata(stride);
5986 Metadata *Bias = convToMetadata(bias);
5987
5989 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5990 size.getValueAsMetadata(Context), align.Val, flags.Val,
5991 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5992
5993 return false;
5994}
5995
5996/// parseDISubrange:
5997/// ::= !DISubrange(count: 30, lowerBound: 2)
5998/// ::= !DISubrange(count: !node, lowerBound: 2)
5999/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
6000bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
6001#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6002 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
6003 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6004 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6005 OPTIONAL(stride, MDSignedOrMDField, );
6007#undef VISIT_MD_FIELDS
6008
6009 Metadata *Count = nullptr;
6010 Metadata *LowerBound = nullptr;
6011 Metadata *UpperBound = nullptr;
6012 Metadata *Stride = nullptr;
6013
6014 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
6015 if (Bound.isMDSignedField())
6017 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
6018 if (Bound.isMDField())
6019 return Bound.getMDFieldValue();
6020 return nullptr;
6021 };
6022
6023 Count = convToMetadata(count);
6024 LowerBound = convToMetadata(lowerBound);
6025 UpperBound = convToMetadata(upperBound);
6026 Stride = convToMetadata(stride);
6027
6028 Result = GET_OR_DISTINCT(DISubrange,
6029 (Context, Count, LowerBound, UpperBound, Stride));
6030
6031 return false;
6032}
6033
6034/// parseDIGenericSubrange:
6035/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
6036/// !node3)
6037bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
6038#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6039 OPTIONAL(count, MDSignedOrMDField, ); \
6040 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
6041 OPTIONAL(upperBound, MDSignedOrMDField, ); \
6042 OPTIONAL(stride, MDSignedOrMDField, );
6044#undef VISIT_MD_FIELDS
6045
6046 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
6047 if (Bound.isMDSignedField())
6048 return DIExpression::get(
6049 Context, {dwarf::DW_OP_consts,
6050 static_cast<uint64_t>(Bound.getMDSignedValue())});
6051 if (Bound.isMDField())
6052 return Bound.getMDFieldValue();
6053 return nullptr;
6054 };
6055
6056 Metadata *Count = ConvToMetadata(count);
6057 Metadata *LowerBound = ConvToMetadata(lowerBound);
6058 Metadata *UpperBound = ConvToMetadata(upperBound);
6059 Metadata *Stride = ConvToMetadata(stride);
6060
6061 Result = GET_OR_DISTINCT(DIGenericSubrange,
6062 (Context, Count, LowerBound, UpperBound, Stride));
6063
6064 return false;
6065}
6066
6067/// parseDIEnumerator:
6068/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
6069bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
6070#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6071 REQUIRED(name, MDStringField, ); \
6072 REQUIRED(value, MDAPSIntField, ); \
6073 OPTIONAL(isUnsigned, MDBoolField, (false));
6075#undef VISIT_MD_FIELDS
6076
6077 if (isUnsigned.Val && value.Val.isNegative())
6078 return tokError("unsigned enumerator with negative value");
6079
6080 APSInt Value(value.Val);
6081 // Add a leading zero so that unsigned values with the msb set are not
6082 // mistaken for negative values when used for signed enumerators.
6083 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
6084 Value = Value.zext(Value.getBitWidth() + 1);
6085
6086 Result =
6087 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
6088
6089 return false;
6090}
6091
6092/// parseDIBasicType:
6093/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
6094/// encoding: DW_ATE_encoding, flags: 0)
6095bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
6096#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6097 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6098 OPTIONAL(name, MDStringField, ); \
6099 OPTIONAL(file, MDField, ); \
6100 OPTIONAL(line, LineField, ); \
6101 OPTIONAL(scope, MDField, ); \
6102 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6103 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6104 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
6105 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6106 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6107 OPTIONAL(flags, DIFlagField, );
6109#undef VISIT_MD_FIELDS
6110
6112 DIBasicType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6113 size.getValueAsMetadata(Context), align.Val, encoding.Val,
6114 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
6115 return false;
6116}
6117
6118/// parseDIFixedPointType:
6119/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
6120/// align: 32, encoding: DW_ATE_signed_fixed,
6121/// flags: 0, kind: Rational, factor: 3, numerator: 1,
6122/// denominator: 8)
6123bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
6124#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6125 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
6126 OPTIONAL(name, MDStringField, ); \
6127 OPTIONAL(file, MDField, ); \
6128 OPTIONAL(line, LineField, ); \
6129 OPTIONAL(scope, MDField, ); \
6130 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6131 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6132 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6133 OPTIONAL(flags, DIFlagField, ); \
6134 OPTIONAL(kind, FixedPointKindField, ); \
6135 OPTIONAL(factor, MDSignedField, ); \
6136 OPTIONAL(numerator, MDAPSIntField, ); \
6137 OPTIONAL(denominator, MDAPSIntField, );
6139#undef VISIT_MD_FIELDS
6140
6141 Result = GET_OR_DISTINCT(DIFixedPointType,
6142 (Context, tag.Val, name.Val, file.Val, line.Val,
6143 scope.Val, size.getValueAsMetadata(Context),
6144 align.Val, encoding.Val, flags.Val, kind.Val,
6145 factor.Val, numerator.Val, denominator.Val));
6146 return false;
6147}
6148
6149/// parseDIStringType:
6150/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
6151bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
6152#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6153 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
6154 OPTIONAL(name, MDStringField, ); \
6155 OPTIONAL(stringLength, MDField, ); \
6156 OPTIONAL(stringLengthExpression, MDField, ); \
6157 OPTIONAL(stringLocationExpression, MDField, ); \
6158 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6159 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6160 OPTIONAL(encoding, DwarfAttEncodingField, ); \
6161 OPTIONAL(charType, MDField, );
6163#undef VISIT_MD_FIELDS
6164
6166 DIStringType,
6167 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
6168 stringLocationExpression.Val, size.getValueAsMetadata(Context),
6169 align.Val, encoding.Val, charType.Val));
6170 return false;
6171}
6172
6173/// parseDIDerivedType:
6174/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
6175/// line: 7, scope: !1, baseType: !2, size: 32,
6176/// align: 32, offset: 0, flags: 0, extraData: !3,
6177/// dwarfAddressSpace: 3, ptrAuthKey: 1,
6178/// ptrAuthIsAddressDiscriminated: true,
6179/// ptrAuthExtraDiscriminator: 0x1234,
6180/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
6181/// )
6182bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
6183#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6184 REQUIRED(tag, DwarfTagField, ); \
6185 OPTIONAL(name, MDStringField, ); \
6186 OPTIONAL(file, MDField, ); \
6187 OPTIONAL(line, LineField, ); \
6188 OPTIONAL(scope, MDField, ); \
6189 REQUIRED(baseType, MDField, ); \
6190 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6191 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6192 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6193 OPTIONAL(flags, DIFlagField, ); \
6194 OPTIONAL(extraData, MDField, ); \
6195 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6196 OPTIONAL(annotations, MDField, ); \
6197 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6198 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6199 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6200 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6201 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6203#undef VISIT_MD_FIELDS
6204
6205 std::optional<unsigned> DWARFAddressSpace;
6206 if (dwarfAddressSpace.Val != UINT32_MAX)
6207 DWARFAddressSpace = dwarfAddressSpace.Val;
6208 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6209 if (ptrAuthKey.Val)
6210 PtrAuthData.emplace(
6211 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6212 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6213 ptrAuthAuthenticatesNullValues.Val);
6214
6216 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6217 baseType.Val, size.getValueAsMetadata(Context), align.Val,
6218 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6219 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6220 return false;
6221}
6222
6223bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
6224#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6225 REQUIRED(tag, DwarfTagField, ); \
6226 OPTIONAL(name, MDStringField, ); \
6227 OPTIONAL(file, MDField, ); \
6228 OPTIONAL(line, LineField, ); \
6229 OPTIONAL(scope, MDField, ); \
6230 OPTIONAL(baseType, MDField, ); \
6231 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6232 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6233 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6234 OPTIONAL(flags, DIFlagField, ); \
6235 OPTIONAL(elements, MDField, ); \
6236 OPTIONAL(runtimeLang, DwarfLangField, ); \
6237 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6238 OPTIONAL(vtableHolder, MDField, ); \
6239 OPTIONAL(templateParams, MDField, ); \
6240 OPTIONAL(identifier, MDStringField, ); \
6241 OPTIONAL(discriminator, MDField, ); \
6242 OPTIONAL(dataLocation, MDField, ); \
6243 OPTIONAL(associated, MDField, ); \
6244 OPTIONAL(allocated, MDField, ); \
6245 OPTIONAL(rank, MDSignedOrMDField, ); \
6246 OPTIONAL(annotations, MDField, ); \
6247 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6248 OPTIONAL(specification, MDField, ); \
6249 OPTIONAL(bitStride, MDField, );
6251#undef VISIT_MD_FIELDS
6252
6253 Metadata *Rank = nullptr;
6254 if (rank.isMDSignedField())
6256 Type::getInt64Ty(Context), rank.getMDSignedValue()));
6257 else if (rank.isMDField())
6258 Rank = rank.getMDFieldValue();
6259
6260 std::optional<unsigned> EnumKind;
6261 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
6262 EnumKind = enumKind.Val;
6263
6264 // If this has an identifier try to build an ODR type.
6265 if (identifier.Val)
6266 if (auto *CT = DICompositeType::buildODRType(
6267 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
6268 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
6269 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6270 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6271 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6272 dataLocation.Val, associated.Val, allocated.Val, Rank,
6273 annotations.Val, bitStride.Val)) {
6274 Result = CT;
6275 return false;
6276 }
6277
6278 // Create a new node, and save it in the context if it belongs in the type
6279 // map.
6281 DICompositeType,
6282 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
6283 size.getValueAsMetadata(Context), align.Val,
6284 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6285 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6286 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6287 allocated.Val, Rank, annotations.Val, specification.Val,
6288 num_extra_inhabitants.Val, bitStride.Val));
6289 return false;
6290}
6291
6292bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
6293#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6294 OPTIONAL(flags, DIFlagField, ); \
6295 OPTIONAL(cc, DwarfCCField, ); \
6296 REQUIRED(types, MDField, );
6298#undef VISIT_MD_FIELDS
6299
6300 Result = GET_OR_DISTINCT(DISubroutineType,
6301 (Context, flags.Val, cc.Val, types.Val));
6302 return false;
6303}
6304
6305/// parseDIFileType:
6306/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
6307/// checksumkind: CSK_MD5,
6308/// checksum: "000102030405060708090a0b0c0d0e0f",
6309/// source: "source file contents")
6310bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
6311 // The default constructed value for checksumkind is required, but will never
6312 // be used, as the parser checks if the field was actually Seen before using
6313 // the Val.
6314#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6315 REQUIRED(filename, MDStringField, ); \
6316 REQUIRED(directory, MDStringField, ); \
6317 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6318 OPTIONAL(checksum, MDStringField, ); \
6319 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6321#undef VISIT_MD_FIELDS
6322
6323 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6324 if (checksumkind.Seen && checksum.Seen)
6325 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6326 else if (checksumkind.Seen || checksum.Seen)
6327 return tokError("'checksumkind' and 'checksum' must be provided together");
6328
6329 MDString *Source = nullptr;
6330 if (source.Seen)
6331 Source = source.Val;
6333 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
6334 return false;
6335}
6336
6337/// parseDICompileUnit:
6338/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
6339/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
6340/// splitDebugFilename: "abc.debug",
6341/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
6342/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
6343/// sysroot: "/", sdk: "MacOSX.sdk",
6344/// dialect: DW_LLVM_LANG_DIALECT_simt)
6345bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
6346 if (!IsDistinct)
6347 return tokError("missing 'distinct', required for !DICompileUnit");
6348
6349 LocTy Loc = Lex.getLoc();
6350
6351#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6352 REQUIRED(file, MDField, (/* AllowNull */ false)); \
6353 OPTIONAL(language, DwarfLangField, ); \
6354 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6355 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6356 OPTIONAL(producer, MDStringField, ); \
6357 OPTIONAL(isOptimized, MDBoolField, ); \
6358 OPTIONAL(flags, MDStringField, ); \
6359 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6360 OPTIONAL(splitDebugFilename, MDStringField, ); \
6361 OPTIONAL(emissionKind, EmissionKindField, ); \
6362 OPTIONAL(enums, MDField, ); \
6363 OPTIONAL(retainedTypes, MDField, ); \
6364 OPTIONAL(globals, MDField, ); \
6365 OPTIONAL(imports, MDField, ); \
6366 OPTIONAL(macros, MDField, ); \
6367 OPTIONAL(dwoId, MDUnsignedField, ); \
6368 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6369 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6370 OPTIONAL(nameTableKind, NameTableKindField, ); \
6371 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6372 OPTIONAL(sysroot, MDStringField, ); \
6373 OPTIONAL(sdk, MDStringField, ); \
6374 OPTIONAL(dialect, DwarfLangDialectField, );
6376#undef VISIT_MD_FIELDS
6377
6378 if (!language.Seen && !sourceLanguageName.Seen)
6379 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
6380 "required for !DICompileUnit");
6381
6382 if (language.Seen && sourceLanguageName.Seen)
6383 return error(Loc, "can only specify one of 'language' and "
6384 "'sourceLanguageName' on !DICompileUnit");
6385
6386 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6387 return error(Loc, "'sourceLanguageVersion' requires an associated "
6388 "'sourceLanguageName' on !DICompileUnit");
6389
6390 uint16_t Dialect = static_cast<uint16_t>(dialect.Val);
6391 DISourceLanguageName SourceLanguage =
6392 language.Seen
6393 ? DISourceLanguageName(static_cast<uint16_t>(language.Val), Dialect)
6394 : DISourceLanguageName(
6395 static_cast<uint16_t>(sourceLanguageName.Val),
6396 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6397
6399 Context, SourceLanguage, file.Val, producer.Val, isOptimized.Val,
6400 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6401 enums.Val, retainedTypes.Val, globals.Val, imports.Val, macros.Val,
6402 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6403 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6404 return false;
6405}
6406
6407/// parseDISubprogram:
6408/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
6409/// file: !1, line: 7, type: !2, isLocal: false,
6410/// isDefinition: true, scopeLine: 8, containingType: !3,
6411/// virtuality: DW_VIRTUALTIY_pure_virtual,
6412/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
6413/// spFlags: 10, isOptimized: false, templateParams: !4,
6414/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
6415/// annotations: !8)
6416bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
6417 auto Loc = Lex.getLoc();
6418#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6419 OPTIONAL(scope, MDField, ); \
6420 OPTIONAL(name, MDStringField, ); \
6421 OPTIONAL(linkageName, MDStringField, ); \
6422 OPTIONAL(file, MDField, ); \
6423 OPTIONAL(line, LineField, ); \
6424 REQUIRED(type, MDField, (/* AllowNull */ false)); \
6425 OPTIONAL(isLocal, MDBoolField, ); \
6426 OPTIONAL(isDefinition, MDBoolField, (true)); \
6427 OPTIONAL(scopeLine, LineField, ); \
6428 OPTIONAL(containingType, MDField, ); \
6429 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6430 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6431 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6432 OPTIONAL(flags, DIFlagField, ); \
6433 OPTIONAL(spFlags, DISPFlagField, ); \
6434 OPTIONAL(isOptimized, MDBoolField, ); \
6435 OPTIONAL(unit, MDField, ); \
6436 OPTIONAL(templateParams, MDField, ); \
6437 OPTIONAL(declaration, MDField, ); \
6438 OPTIONAL(retainedNodes, MDField, ); \
6439 OPTIONAL(thrownTypes, MDField, ); \
6440 OPTIONAL(annotations, MDField, ); \
6441 OPTIONAL(targetFuncName, MDStringField, ); \
6442 OPTIONAL(keyInstructions, MDBoolField, );
6444#undef VISIT_MD_FIELDS
6445
6446 // An explicit spFlags field takes precedence over individual fields in
6447 // older IR versions.
6448 DISubprogram::DISPFlags SPFlags =
6449 spFlags.Seen ? spFlags.Val
6450 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
6451 isOptimized.Val, virtuality.Val);
6452 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6453 return error(
6454 Loc,
6455 "missing 'distinct', required for !DISubprogram that is a Definition");
6457 DISubprogram,
6458 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6459 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6460 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6461 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6462 targetFuncName.Val, keyInstructions.Val));
6463
6464 if (IsDistinct)
6465 NewDistinctSPs.push_back(cast<DISubprogram>(Result));
6466
6467 return false;
6468}
6469
6470/// parseDILexicalBlock:
6471/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6472bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6473#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6474 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6475 OPTIONAL(file, MDField, ); \
6476 OPTIONAL(line, LineField, ); \
6477 OPTIONAL(column, ColumnField, );
6479#undef VISIT_MD_FIELDS
6480
6482 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6483 return false;
6484}
6485
6486/// parseDILexicalBlockFile:
6487/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6488bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6489#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6490 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6491 OPTIONAL(file, MDField, ); \
6492 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6494#undef VISIT_MD_FIELDS
6495
6496 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6497 (Context, scope.Val, file.Val, discriminator.Val));
6498 return false;
6499}
6500
6501/// parseDICommonBlock:
6502/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6503bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6504#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6505 REQUIRED(scope, MDField, ); \
6506 OPTIONAL(declaration, MDField, ); \
6507 OPTIONAL(name, MDStringField, ); \
6508 OPTIONAL(file, MDField, ); \
6509 OPTIONAL(line, LineField, );
6511#undef VISIT_MD_FIELDS
6512
6513 Result = GET_OR_DISTINCT(DICommonBlock,
6514 (Context, scope.Val, declaration.Val, name.Val,
6515 file.Val, line.Val));
6516 return false;
6517}
6518
6519/// parseDINamespace:
6520/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6521bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6522#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6523 REQUIRED(scope, MDField, ); \
6524 OPTIONAL(name, MDStringField, ); \
6525 OPTIONAL(exportSymbols, MDBoolField, );
6527#undef VISIT_MD_FIELDS
6528
6529 Result = GET_OR_DISTINCT(DINamespace,
6530 (Context, scope.Val, name.Val, exportSymbols.Val));
6531 return false;
6532}
6533
6534/// parseDIMacro:
6535/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6536/// "SomeValue")
6537bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6538#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6539 REQUIRED(type, DwarfMacinfoTypeField, ); \
6540 OPTIONAL(line, LineField, ); \
6541 REQUIRED(name, MDStringField, ); \
6542 OPTIONAL(value, MDStringField, );
6544#undef VISIT_MD_FIELDS
6545
6546 Result = GET_OR_DISTINCT(DIMacro,
6547 (Context, type.Val, line.Val, name.Val, value.Val));
6548 return false;
6549}
6550
6551/// parseDIMacroFile:
6552/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6553bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6554#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6555 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6556 OPTIONAL(line, LineField, ); \
6557 REQUIRED(file, MDField, ); \
6558 OPTIONAL(nodes, MDField, );
6560#undef VISIT_MD_FIELDS
6561
6562 Result = GET_OR_DISTINCT(DIMacroFile,
6563 (Context, type.Val, line.Val, file.Val, nodes.Val));
6564 return false;
6565}
6566
6567/// parseDIModule:
6568/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6569/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6570/// file: !1, line: 4, isDecl: false)
6571bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6572#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6573 REQUIRED(scope, MDField, ); \
6574 REQUIRED(name, MDStringField, ); \
6575 OPTIONAL(configMacros, MDStringField, ); \
6576 OPTIONAL(includePath, MDStringField, ); \
6577 OPTIONAL(apinotes, MDStringField, ); \
6578 OPTIONAL(file, MDField, ); \
6579 OPTIONAL(line, LineField, ); \
6580 OPTIONAL(isDecl, MDBoolField, );
6582#undef VISIT_MD_FIELDS
6583
6584 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6585 configMacros.Val, includePath.Val,
6586 apinotes.Val, line.Val, isDecl.Val));
6587 return false;
6588}
6589
6590/// parseDITemplateTypeParameter:
6591/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6592bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6593#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6594 OPTIONAL(name, MDStringField, ); \
6595 REQUIRED(type, MDField, ); \
6596 OPTIONAL(defaulted, MDBoolField, );
6598#undef VISIT_MD_FIELDS
6599
6600 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6601 (Context, name.Val, type.Val, defaulted.Val));
6602 return false;
6603}
6604
6605/// parseDITemplateValueParameter:
6606/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6607/// name: "V", type: !1, defaulted: false,
6608/// value: i32 7)
6609bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6610#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6611 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6612 OPTIONAL(name, MDStringField, ); \
6613 OPTIONAL(type, MDField, ); \
6614 OPTIONAL(defaulted, MDBoolField, ); \
6615 REQUIRED(value, MDField, );
6616
6618#undef VISIT_MD_FIELDS
6619
6621 DITemplateValueParameter,
6622 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6623 return false;
6624}
6625
6626/// parseDIGlobalVariable:
6627/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6628/// file: !1, line: 7, type: !2, isLocal: false,
6629/// isDefinition: true, templateParams: !3,
6630/// declaration: !4, align: 8)
6631bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6632#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6633 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6634 OPTIONAL(scope, MDField, ); \
6635 OPTIONAL(linkageName, MDStringField, ); \
6636 OPTIONAL(file, MDField, ); \
6637 OPTIONAL(line, LineField, ); \
6638 OPTIONAL(type, MDField, ); \
6639 OPTIONAL(isLocal, MDBoolField, ); \
6640 OPTIONAL(isDefinition, MDBoolField, (true)); \
6641 OPTIONAL(templateParams, MDField, ); \
6642 OPTIONAL(declaration, MDField, ); \
6643 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6644 OPTIONAL(annotations, MDField, );
6646#undef VISIT_MD_FIELDS
6647
6648 Result =
6649 GET_OR_DISTINCT(DIGlobalVariable,
6650 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6651 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6652 declaration.Val, templateParams.Val, align.Val,
6653 annotations.Val));
6654 return false;
6655}
6656
6657/// parseDILocalVariable:
6658/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6659/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6660/// align: 8)
6661/// ::= !DILocalVariable(scope: !0, name: "foo",
6662/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6663/// align: 8)
6664bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6665#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6666 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6667 OPTIONAL(name, MDStringField, ); \
6668 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6669 OPTIONAL(file, MDField, ); \
6670 OPTIONAL(line, LineField, ); \
6671 OPTIONAL(type, MDField, ); \
6672 OPTIONAL(flags, DIFlagField, ); \
6673 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6674 OPTIONAL(annotations, MDField, );
6676#undef VISIT_MD_FIELDS
6677
6678 Result = GET_OR_DISTINCT(DILocalVariable,
6679 (Context, scope.Val, name.Val, file.Val, line.Val,
6680 type.Val, arg.Val, flags.Val, align.Val,
6681 annotations.Val));
6682 return false;
6683}
6684
6685/// parseDILabel:
6686/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6687bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6688#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6689 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6690 REQUIRED(name, MDStringField, ); \
6691 REQUIRED(file, MDField, ); \
6692 REQUIRED(line, LineField, ); \
6693 OPTIONAL(column, ColumnField, ); \
6694 OPTIONAL(isArtificial, MDBoolField, ); \
6695 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6697#undef VISIT_MD_FIELDS
6698
6699 std::optional<unsigned> CoroSuspendIdx =
6700 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6701 : std::nullopt;
6702
6703 Result = GET_OR_DISTINCT(DILabel,
6704 (Context, scope.Val, name.Val, file.Val, line.Val,
6705 column.Val, isArtificial.Val, CoroSuspendIdx));
6706 return false;
6707}
6708
6709/// parseDIExpressionBody:
6710/// ::= (0, 7, -1)
6711bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6712 if (parseToken(lltok::lparen, "expected '(' here"))
6713 return true;
6714
6715 SmallVector<uint64_t, 8> Elements;
6716 if (Lex.getKind() != lltok::rparen)
6717 do {
6718 if (Lex.getKind() == lltok::DwarfOp) {
6719 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6720 Lex.Lex();
6721 Elements.push_back(Op);
6722 continue;
6723 }
6724 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6725 }
6726
6727 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6728 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6729 Lex.Lex();
6730 Elements.push_back(Op);
6731 continue;
6732 }
6733 return tokError(Twine("invalid DWARF attribute encoding '") +
6734 Lex.getStrVal() + "'");
6735 }
6736
6737 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6738 return tokError("expected unsigned integer");
6739
6740 auto &U = Lex.getAPSIntVal();
6741 if (U.ugt(UINT64_MAX))
6742 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6743 Elements.push_back(U.getZExtValue());
6744 Lex.Lex();
6745 } while (EatIfPresent(lltok::comma));
6746
6747 if (parseToken(lltok::rparen, "expected ')' here"))
6748 return true;
6749
6750 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6751 return false;
6752}
6753
6754/// parseDIExpression:
6755/// ::= !DIExpression(0, 7, -1)
6756bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6757 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6758 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6759 Lex.Lex();
6760
6761 return parseDIExpressionBody(Result, IsDistinct);
6762}
6763
6764/// ParseDIArgList:
6765/// ::= !DIArgList(i32 7, i64 %0)
6766bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6767 assert(PFS && "Expected valid function state");
6768 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6769 Lex.Lex();
6770
6771 if (parseToken(lltok::lparen, "expected '(' here"))
6772 return true;
6773
6775 if (Lex.getKind() != lltok::rparen)
6776 do {
6777 Metadata *MD;
6778 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6779 return true;
6780 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6781 } while (EatIfPresent(lltok::comma));
6782
6783 if (parseToken(lltok::rparen, "expected ')' here"))
6784 return true;
6785
6786 MD = DIArgList::get(Context, Args);
6787 return false;
6788}
6789
6790/// parseDIGlobalVariableExpression:
6791/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6792bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6793 bool IsDistinct) {
6794#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6795 REQUIRED(var, MDField, ); \
6796 REQUIRED(expr, MDField, );
6798#undef VISIT_MD_FIELDS
6799
6800 Result =
6801 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6802 return false;
6803}
6804
6805/// parseDIObjCProperty:
6806/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6807/// getter: "getFoo", attributes: 7, type: !2)
6808bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6809#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6810 OPTIONAL(name, MDStringField, ); \
6811 OPTIONAL(file, MDField, ); \
6812 OPTIONAL(line, LineField, ); \
6813 OPTIONAL(setter, MDStringField, ); \
6814 OPTIONAL(getter, MDStringField, ); \
6815 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6816 OPTIONAL(type, MDField, );
6818#undef VISIT_MD_FIELDS
6819
6820 Result = GET_OR_DISTINCT(DIObjCProperty,
6821 (Context, name.Val, file.Val, line.Val, getter.Val,
6822 setter.Val, attributes.Val, type.Val));
6823 return false;
6824}
6825
6826/// parseDIProperty:
6827/// ::= !DIProperty(name: "x", file: !1, line: 7, type: !2,
6828/// backing_storage: !3)
6829bool LLParser::parseDIProperty(MDNode *&Result, bool IsDistinct) {
6830#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6831 OPTIONAL(name, MDStringField, ); \
6832 OPTIONAL(file, MDField, ); \
6833 OPTIONAL(line, LineField, ); \
6834 OPTIONAL(type, MDField, ); \
6835 OPTIONAL(backing_storage, MDField, );
6837#undef VISIT_MD_FIELDS
6838
6839 Result = GET_OR_DISTINCT(DIProperty, (Context, name.Val, file.Val, line.Val,
6840 type.Val, backing_storage.Val));
6841 return false;
6842}
6843
6844/// parseDIImportedEntity:
6845/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6846/// line: 7, name: "foo", elements: !2)
6847bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6848#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6849 REQUIRED(tag, DwarfTagField, ); \
6850 REQUIRED(scope, MDField, ); \
6851 OPTIONAL(entity, MDField, ); \
6852 OPTIONAL(file, MDField, ); \
6853 OPTIONAL(line, LineField, ); \
6854 OPTIONAL(name, MDStringField, ); \
6855 OPTIONAL(elements, MDField, );
6857#undef VISIT_MD_FIELDS
6858
6859 Result = GET_OR_DISTINCT(DIImportedEntity,
6860 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6861 line.Val, name.Val, elements.Val));
6862 return false;
6863}
6864
6865#undef PARSE_MD_FIELD
6866#undef NOP_FIELD
6867#undef REQUIRE_FIELD
6868#undef DECLARE_FIELD
6869
6870/// parseMetadataAsValue
6871/// ::= metadata i32 %local
6872/// ::= metadata i32 @global
6873/// ::= metadata i32 7
6874/// ::= metadata !0
6875/// ::= metadata !{...}
6876/// ::= metadata !"string"
6877bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6878 // Note: the type 'metadata' has already been parsed.
6879 Metadata *MD;
6880 if (parseMetadata(MD, &PFS))
6881 return true;
6882
6883 V = MetadataAsValue::get(Context, MD);
6884 return false;
6885}
6886
6887/// parseValueAsMetadata
6888/// ::= i32 %local
6889/// ::= i32 @global
6890/// ::= i32 7
6891bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6892 PerFunctionState *PFS) {
6893 Type *Ty;
6894 LocTy Loc;
6895 if (parseType(Ty, TypeMsg, Loc))
6896 return true;
6897 if (Ty->isMetadataTy())
6898 return error(Loc, "invalid metadata-value-metadata roundtrip");
6899
6900 Value *V;
6901 if (parseValue(Ty, V, PFS))
6902 return true;
6903
6904 MD = ValueAsMetadata::get(V);
6905 return false;
6906}
6907
6908/// parseMetadata
6909/// ::= i32 %local
6910/// ::= i32 @global
6911/// ::= i32 7
6912/// ::= !42
6913/// ::= !{...}
6914/// ::= !"string"
6915/// ::= !DILocation(...)
6916bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6917 if (Lex.getKind() == lltok::MetadataVar) {
6918 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6919 // so parsing this requires a Function State.
6920 if (Lex.getStrVal() == "DIArgList") {
6921 Metadata *AL;
6922 if (parseDIArgList(AL, PFS))
6923 return true;
6924 MD = AL;
6925 return false;
6926 }
6927 MDNode *N;
6928 if (parseSpecializedMDNode(N)) {
6929 return true;
6930 }
6931 MD = N;
6932 return false;
6933 }
6934
6935 // ValueAsMetadata:
6936 // <type> <value>
6937 if (Lex.getKind() != lltok::exclaim)
6938 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6939
6940 // '!'.
6941 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6942 Lex.Lex();
6943
6944 // MDString:
6945 // ::= '!' STRINGCONSTANT
6946 if (Lex.getKind() == lltok::StringConstant) {
6947 MDString *S;
6948 if (parseMDString(S))
6949 return true;
6950 MD = S;
6951 return false;
6952 }
6953
6954 // MDNode:
6955 // !{ ... }
6956 // !7
6957 MDNode *N;
6958 if (parseMDNodeTail(N))
6959 return true;
6960 MD = N;
6961 return false;
6962}
6963
6964//===----------------------------------------------------------------------===//
6965// Function Parsing.
6966//===----------------------------------------------------------------------===//
6967
6968bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6969 PerFunctionState *PFS) {
6970 if (Ty->isFunctionTy())
6971 return error(ID.Loc, "functions are not values, refer to them as pointers");
6972
6973 switch (ID.Kind) {
6974 case ValID::t_LocalID:
6975 if (!PFS)
6976 return error(ID.Loc, "invalid use of function-local name");
6977 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6978 return V == nullptr;
6979 case ValID::t_LocalName:
6980 if (!PFS)
6981 return error(ID.Loc, "invalid use of function-local name");
6982 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6983 return V == nullptr;
6984 case ValID::t_InlineAsm: {
6985 if (!ID.FTy)
6986 return error(ID.Loc, "invalid type for inline asm constraint string");
6987 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6988 return error(ID.Loc, toString(std::move(Err)));
6989 V = InlineAsm::get(
6990 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6991 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6992 return false;
6993 }
6995 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6996 if (V && ID.NoCFI)
6998 return V == nullptr;
6999 case ValID::t_GlobalID:
7000 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
7001 if (V && ID.NoCFI)
7003 return V == nullptr;
7004 case ValID::t_APSInt:
7005 if (!Ty->isIntegerTy() && !Ty->isByteTy())
7006 return error(ID.Loc, "integer/byte constant must have integer/byte type");
7007 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
7008 Ty->isIntegerTy() ? V = ConstantInt::get(Context, ID.APSIntVal)
7009 : V = ConstantByte::get(Context, ID.APSIntVal);
7010 return false;
7011 case ValID::t_APFloat:
7012 if (!Ty->isFloatingPointTy() ||
7013 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
7014 return error(ID.Loc, "floating point constant invalid for type");
7015
7016 // The lexer has no type info, so builds all half, bfloat, float, and double
7017 // FP constants as double. Fix this here. Long double does not need this.
7018 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
7019 // Check for signaling before potentially converting and losing that info.
7020 bool IsSNAN = ID.APFloatVal.isSignaling();
7021 bool Ignored;
7022 if (Ty->isHalfTy())
7023 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
7024 &Ignored);
7025 else if (Ty->isBFloatTy())
7026 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
7027 &Ignored);
7028 else if (Ty->isFloatTy())
7029 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
7030 &Ignored);
7031 if (IsSNAN) {
7032 // The convert call above may quiet an SNaN, so manufacture another
7033 // SNaN. The bitcast works because the payload (significand) parameter
7034 // is truncated to fit.
7035 APInt Payload = ID.APFloatVal.bitcastToAPInt();
7036 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
7037 ID.APFloatVal.isNegative(), &Payload);
7038 }
7039 }
7040 V = ConstantFP::get(Context, ID.APFloatVal);
7041
7042 if (V->getType() != Ty)
7043 return error(ID.Loc, "floating point constant does not have type '" +
7044 getTypeString(Ty) + "'");
7045
7046 return false;
7047 case ValID::t_Null:
7048 if (!Ty->isPointerTy())
7049 return error(ID.Loc, "null must be a pointer type");
7051 return false;
7052 case ValID::t_Undef:
7053 // FIXME: LabelTy should not be a first-class type.
7054 if (!Ty->isFirstClassType() || Ty->isLabelTy())
7055 return error(ID.Loc, "invalid type for undef constant");
7056 V = UndefValue::get(Ty);
7057 return false;
7059 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
7060 return error(ID.Loc, "invalid empty array initializer");
7061 V = PoisonValue::get(Ty);
7062 return false;
7063 case ValID::t_Zero:
7064 // FIXME: LabelTy should not be a first-class type.
7065 if (!Ty->isFirstClassType() || Ty->isLabelTy())
7066 return error(ID.Loc, "invalid type for null constant");
7067 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
7068 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
7069 return error(ID.Loc, "invalid type for null constant");
7071 return false;
7072 case ValID::t_None:
7073 if (!Ty->isTokenTy())
7074 return error(ID.Loc, "invalid type for none constant");
7076 return false;
7077 case ValID::t_Poison:
7078 // FIXME: LabelTy should not be a first-class type.
7079 if (!Ty->isFirstClassType() || Ty->isLabelTy())
7080 return error(ID.Loc, "invalid type for poison constant");
7081 V = PoisonValue::get(Ty);
7082 return false;
7083 case ValID::t_Constant:
7084 if (ID.ConstantVal->getType() != Ty)
7085 return error(ID.Loc, "constant expression type mismatch: got type '" +
7086 getTypeString(ID.ConstantVal->getType()) +
7087 "' but expected '" + getTypeString(Ty) + "'");
7088 V = ID.ConstantVal;
7089 return false;
7091 if (!Ty->isVectorTy())
7092 return error(ID.Loc, "vector constant must have vector type");
7093 if (ID.ConstantVal->getType() != Ty->getScalarType())
7094 return error(ID.Loc, "constant expression type mismatch: got type '" +
7095 getTypeString(ID.ConstantVal->getType()) +
7096 "' but expected '" +
7097 getTypeString(Ty->getScalarType()) + "'");
7098 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
7099 ID.ConstantVal);
7100 return false;
7103 if (StructType *ST = dyn_cast<StructType>(Ty)) {
7104 if (ST->getNumElements() != ID.UIntVal)
7105 return error(ID.Loc,
7106 "initializer with struct type has wrong # elements");
7107 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
7108 return error(ID.Loc, "packed'ness of initializer and type don't match");
7109
7110 // Verify that the elements are compatible with the structtype.
7111 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
7112 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
7113 return error(
7114 ID.Loc,
7115 "element " + Twine(i) +
7116 " of struct initializer doesn't match struct element type");
7117
7119 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
7120 } else
7121 return error(ID.Loc, "constant expression type mismatch");
7122 return false;
7123 }
7124 llvm_unreachable("Invalid ValID");
7125}
7126
7127bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
7128 C = nullptr;
7129 ValID ID;
7130 auto Loc = Lex.getLoc();
7131 if (parseValID(ID, /*PFS=*/nullptr, /*ExpectedTy=*/Ty))
7132 return true;
7133 switch (ID.Kind) {
7134 case ValID::t_APSInt:
7135 case ValID::t_APFloat:
7136 case ValID::t_Undef:
7137 case ValID::t_Poison:
7138 case ValID::t_Zero:
7139 case ValID::t_Constant:
7143 Value *V;
7144 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
7145 return true;
7146 assert(isa<Constant>(V) && "Expected a constant value");
7147 C = cast<Constant>(V);
7148 return false;
7149 }
7150 case ValID::t_Null:
7152 return false;
7153 default:
7154 return error(Loc, "expected a constant value");
7155 }
7156}
7157
7158bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
7159 V = nullptr;
7160 ValID ID;
7161
7162 FileLoc Start = getTokLineColumnPos();
7163 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
7164 if (!Ret && ParserContext) {
7165 FileLoc End = getPrevTokEndLineColumnPos();
7166 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
7167 }
7168 return Ret;
7169}
7170
7171bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
7172 Type *Ty = nullptr;
7173 return parseType(Ty) || parseValue(Ty, V, PFS);
7174}
7175
7176bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
7177 PerFunctionState &PFS) {
7178 Value *V;
7179 Loc = Lex.getLoc();
7180 if (parseTypeAndValue(V, PFS))
7181 return true;
7182 if (!isa<BasicBlock>(V))
7183 return error(Loc, "expected a basic block");
7184 BB = cast<BasicBlock>(V);
7185 return false;
7186}
7187
7189 // Exit early for the common (non-debug-intrinsic) case.
7190 // We can make this the only check when we begin supporting all "llvm.dbg"
7191 // intrinsics in the new debug info format.
7192 if (!Name.starts_with("llvm.dbg."))
7193 return false;
7195 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7196 FnID == Intrinsic::dbg_assign;
7197}
7198
7199/// FunctionHeader
7200/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
7201/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
7202/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
7203/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
7204bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
7205 unsigned &FunctionNumber,
7206 SmallVectorImpl<unsigned> &UnnamedArgNums) {
7207 // parse the linkage.
7208 LocTy LinkageLoc = Lex.getLoc();
7209 unsigned Linkage;
7210 unsigned Visibility;
7211 unsigned DLLStorageClass;
7212 bool DSOLocal;
7213 AttrBuilder RetAttrs(M->getContext());
7214 unsigned CC;
7215 bool HasLinkage;
7216 Type *RetType = nullptr;
7217 LocTy RetTypeLoc = Lex.getLoc();
7218 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
7219 DSOLocal) ||
7220 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7221 parseType(RetType, RetTypeLoc, true /*void allowed*/))
7222 return true;
7223
7224 // Verify that the linkage is ok.
7227 break; // always ok.
7229 if (IsDefine)
7230 return error(LinkageLoc, "invalid linkage for function definition");
7231 break;
7239 if (!IsDefine)
7240 return error(LinkageLoc, "invalid linkage for function declaration");
7241 break;
7244 return error(LinkageLoc, "invalid function linkage type");
7245 }
7246
7247 if (!isValidVisibilityForLinkage(Visibility, Linkage))
7248 return error(LinkageLoc,
7249 "symbol with local linkage must have default visibility");
7250
7251 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
7252 return error(LinkageLoc,
7253 "symbol with local linkage cannot have a DLL storage class");
7254
7255 if (!FunctionType::isValidReturnType(RetType))
7256 return error(RetTypeLoc, "invalid function return type");
7257
7258 LocTy NameLoc = Lex.getLoc();
7259
7260 std::string FunctionName;
7261 if (Lex.getKind() == lltok::GlobalVar) {
7262 FunctionName = Lex.getStrVal();
7263 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
7264 FunctionNumber = Lex.getUIntVal();
7265 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
7266 FunctionNumber))
7267 return true;
7268 } else {
7269 return tokError("expected function name");
7270 }
7271
7272 Lex.Lex();
7273
7274 if (Lex.getKind() != lltok::lparen)
7275 return tokError("expected '(' in function argument list");
7276
7278 bool IsVarArg;
7279 AttrBuilder FuncAttrs(M->getContext());
7280 std::vector<unsigned> FwdRefAttrGrps;
7281 LocTy BuiltinLoc;
7282 std::string Section;
7283 std::string Partition;
7284 MaybeAlign Alignment, PrefAlignment;
7285 std::string GC;
7287 unsigned AddrSpace = 0;
7288 Constant *Prefix = nullptr;
7289 Constant *Prologue = nullptr;
7290 Constant *PersonalityFn = nullptr;
7291 Comdat *C;
7292
7293 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7294 parseOptionalUnnamedAddr(UnnamedAddr) ||
7295 parseOptionalProgramAddrSpace(AddrSpace) ||
7296 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
7297 BuiltinLoc) ||
7298 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
7299 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
7300 parseOptionalComdat(FunctionName, C) ||
7301 parseOptionalAlignment(Alignment) ||
7302 parseOptionalPrefAlignment(PrefAlignment) ||
7303 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
7304 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
7305 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
7306 (EatIfPresent(lltok::kw_personality) &&
7307 parseGlobalTypeAndValue(PersonalityFn)))
7308 return true;
7309
7310 if (FuncAttrs.contains(Attribute::Builtin))
7311 return error(BuiltinLoc, "'builtin' attribute not valid on function");
7312
7313 // If the alignment was parsed as an attribute, move to the alignment field.
7314 if (MaybeAlign A = FuncAttrs.getAlignment()) {
7315 Alignment = A;
7316 FuncAttrs.removeAttribute(Attribute::Alignment);
7317 }
7318
7319 // Okay, if we got here, the function is syntactically valid. Convert types
7320 // and do semantic checks.
7321 std::vector<Type*> ParamTypeList;
7323
7324 for (const ArgInfo &Arg : ArgList) {
7325 ParamTypeList.push_back(Arg.Ty);
7326 Attrs.push_back(Arg.Attrs);
7327 }
7328
7329 AttributeList PAL =
7330 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
7331 AttributeSet::get(Context, RetAttrs), Attrs);
7332
7333 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
7334 return error(RetTypeLoc, "functions with 'sret' argument must return void");
7335
7336 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
7337 PointerType *PFT = PointerType::get(Context, AddrSpace);
7338
7339 Fn = nullptr;
7340 GlobalValue *FwdFn = nullptr;
7341 if (!FunctionName.empty()) {
7342 // If this was a definition of a forward reference, remove the definition
7343 // from the forward reference table and fill in the forward ref.
7344 auto FRVI = ForwardRefVals.find(FunctionName);
7345 if (FRVI != ForwardRefVals.end()) {
7346 FwdFn = FRVI->second.first;
7347 if (FwdFn->getType() != PFT)
7348 return error(FRVI->second.second,
7349 "invalid forward reference to "
7350 "function '" +
7351 FunctionName +
7352 "' with wrong type: "
7353 "expected '" +
7354 getTypeString(PFT) + "' but was '" +
7355 getTypeString(FwdFn->getType()) + "'");
7356 ForwardRefVals.erase(FRVI);
7357 } else if ((Fn = M->getFunction(FunctionName))) {
7358 // Reject redefinitions.
7359 return error(NameLoc,
7360 "invalid redefinition of function '" + FunctionName + "'");
7361 } else if (M->getNamedValue(FunctionName)) {
7362 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
7363 }
7364
7365 } else {
7366 // Handle @"", where a name is syntactically specified, but semantically
7367 // missing.
7368 if (FunctionNumber == (unsigned)-1)
7369 FunctionNumber = NumberedVals.getNext();
7370
7371 // If this is a definition of a forward referenced function, make sure the
7372 // types agree.
7373 auto I = ForwardRefValIDs.find(FunctionNumber);
7374 if (I != ForwardRefValIDs.end()) {
7375 FwdFn = I->second.first;
7376 if (FwdFn->getType() != PFT)
7377 return error(NameLoc, "type of definition and forward reference of '@" +
7378 Twine(FunctionNumber) +
7379 "' disagree: "
7380 "expected '" +
7381 getTypeString(PFT) + "' but was '" +
7382 getTypeString(FwdFn->getType()) + "'");
7383 ForwardRefValIDs.erase(I);
7384 }
7385 }
7386
7388 FunctionName, M);
7389
7390 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
7391
7392 if (FunctionName.empty())
7393 NumberedVals.add(FunctionNumber, Fn);
7394
7396 maybeSetDSOLocal(DSOLocal, *Fn);
7399 Fn->setCallingConv(CC);
7400 Fn->setAttributes(PAL);
7401 Fn->setUnnamedAddr(UnnamedAddr);
7402 if (Alignment)
7403 Fn->setAlignment(*Alignment);
7404 Fn->setPreferredAlignment(PrefAlignment);
7405 Fn->setSection(Section);
7406 Fn->setPartition(Partition);
7407 Fn->setComdat(C);
7408 Fn->setPersonalityFn(PersonalityFn);
7409 if (!GC.empty()) Fn->setGC(GC);
7410 Fn->setPrefixData(Prefix);
7411 Fn->setPrologueData(Prologue);
7412 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7413
7414 // Add all of the arguments we parsed to the function.
7415 Function::arg_iterator ArgIt = Fn->arg_begin();
7416 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7417 if (ParserContext && ArgList[i].IdentLoc)
7418 ParserContext->addInstructionOrArgumentLocation(
7419 &*ArgIt, ArgList[i].IdentLoc.value());
7420 // If the argument has a name, insert it into the argument symbol table.
7421 if (ArgList[i].Name.empty()) continue;
7422
7423 // Set the name, if it conflicted, it will be auto-renamed.
7424 ArgIt->setName(ArgList[i].Name);
7425
7426 if (ArgIt->getName() != ArgList[i].Name)
7427 return error(ArgList[i].Loc,
7428 "redefinition of argument '%" + ArgList[i].Name + "'");
7429 }
7430
7431 if (FwdFn) {
7432 FwdFn->replaceAllUsesWith(Fn);
7433 FwdFn->eraseFromParent();
7434 }
7435
7436 if (IsDefine)
7437 return false;
7438
7439 // Check the declaration has no block address forward references.
7440 ValID ID;
7441 if (FunctionName.empty()) {
7442 ID.Kind = ValID::t_GlobalID;
7443 ID.UIntVal = FunctionNumber;
7444 } else {
7445 ID.Kind = ValID::t_GlobalName;
7446 ID.StrVal = FunctionName;
7447 }
7448 auto Blocks = ForwardRefBlockAddresses.find(ID);
7449 if (Blocks != ForwardRefBlockAddresses.end())
7450 return error(Blocks->first.Loc,
7451 "cannot take blockaddress inside a declaration");
7452 return false;
7453}
7454
7455bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7456 ValID ID;
7457 if (FunctionNumber == -1) {
7458 ID.Kind = ValID::t_GlobalName;
7459 ID.StrVal = std::string(F.getName());
7460 } else {
7461 ID.Kind = ValID::t_GlobalID;
7462 ID.UIntVal = FunctionNumber;
7463 }
7464
7465 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7466 if (Blocks == P.ForwardRefBlockAddresses.end())
7467 return false;
7468
7469 for (const auto &I : Blocks->second) {
7470 const ValID &BBID = I.first;
7471 GlobalValue *GV = I.second;
7472
7473 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7474 "Expected local id or name");
7475 BasicBlock *BB;
7476 if (BBID.Kind == ValID::t_LocalName)
7477 BB = getBB(BBID.StrVal, BBID.Loc);
7478 else
7479 BB = getBB(BBID.UIntVal, BBID.Loc);
7480 if (!BB)
7481 return P.error(BBID.Loc, "referenced value is not a basic block");
7482
7483 Value *ResolvedVal = BlockAddress::get(&F, BB);
7484 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7485 ResolvedVal);
7486 if (!ResolvedVal)
7487 return true;
7488 GV->replaceAllUsesWith(ResolvedVal);
7489 GV->eraseFromParent();
7490 }
7491
7492 P.ForwardRefBlockAddresses.erase(Blocks);
7493 return false;
7494}
7495
7496/// parseFunctionBody
7497/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7498bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7499 ArrayRef<unsigned> UnnamedArgNums) {
7500 if (Lex.getKind() != lltok::lbrace)
7501 return tokError("expected '{' in function body");
7502 Lex.Lex(); // eat the {.
7503
7504 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7505
7506 // Resolve block addresses and allow basic blocks to be forward-declared
7507 // within this function.
7508 if (PFS.resolveForwardRefBlockAddresses())
7509 return true;
7510 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7511
7512 // We need at least one basic block.
7513 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7514 return tokError("function body requires at least one basic block");
7515
7516 while (Lex.getKind() != lltok::rbrace &&
7517 Lex.getKind() != lltok::kw_uselistorder)
7518 if (parseBasicBlock(PFS))
7519 return true;
7520
7521 while (Lex.getKind() != lltok::rbrace)
7522 if (parseUseListOrder(&PFS))
7523 return true;
7524
7525 // Eat the }.
7526 Lex.Lex();
7527
7528 // Verify function is ok.
7529 return PFS.finishFunction();
7530}
7531
7532/// parseBasicBlock
7533/// ::= (LabelStr|LabelID)? Instruction*
7534bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7535 FileLoc BBStart = getTokLineColumnPos();
7536
7537 // If this basic block starts out with a name, remember it.
7538 std::string Name;
7539 int NameID = -1;
7540 LocTy NameLoc = Lex.getLoc();
7541 if (Lex.getKind() == lltok::LabelStr) {
7542 Name = Lex.getStrVal();
7543 Lex.Lex();
7544 } else if (Lex.getKind() == lltok::LabelID) {
7545 NameID = Lex.getUIntVal();
7546 Lex.Lex();
7547 }
7548
7549 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7550 if (!BB)
7551 return true;
7552
7553 std::string NameStr;
7554
7555 // Parse the instructions and debug values in this block until we get a
7556 // terminator.
7557 Instruction *Inst;
7558 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7559 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7560 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7561 do {
7562 // Handle debug records first - there should always be an instruction
7563 // following the debug records, i.e. they cannot appear after the block
7564 // terminator.
7565 while (Lex.getKind() == lltok::hash) {
7566 if (SeenOldDbgInfoFormat)
7567 return error(Lex.getLoc(), "debug record should not appear in a module "
7568 "containing debug info intrinsics");
7569 SeenNewDbgInfoFormat = true;
7570 Lex.Lex();
7571
7572 DbgRecord *DR;
7573 if (parseDebugRecord(DR, PFS))
7574 return true;
7575 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7576 }
7577
7578 FileLoc InstStart = getTokLineColumnPos();
7579 // This instruction may have three possibilities for a name: a) none
7580 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7581 LocTy NameLoc = Lex.getLoc();
7582 int NameID = -1;
7583 NameStr = "";
7584
7585 if (Lex.getKind() == lltok::LocalVarID) {
7586 NameID = Lex.getUIntVal();
7587 Lex.Lex();
7588 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7589 return true;
7590 } else if (Lex.getKind() == lltok::LocalVar) {
7591 NameStr = Lex.getStrVal();
7592 Lex.Lex();
7593 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7594 return true;
7595 }
7596
7597 switch (parseInstruction(Inst, BB, PFS)) {
7598 default:
7599 llvm_unreachable("Unknown parseInstruction result!");
7600 case InstError: return true;
7601 case InstNormal:
7602 Inst->insertInto(BB, BB->end());
7603
7604 // With a normal result, we check to see if the instruction is followed by
7605 // a comma and metadata.
7606 if (EatIfPresent(lltok::comma))
7607 if (parseInstructionMetadata(*Inst))
7608 return true;
7609 break;
7610 case InstExtraComma:
7611 Inst->insertInto(BB, BB->end());
7612
7613 // If the instruction parser ate an extra comma at the end of it, it
7614 // *must* be followed by metadata.
7615 if (parseInstructionMetadata(*Inst))
7616 return true;
7617 break;
7618 }
7619
7620 // Set the name on the instruction.
7621 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7622 return true;
7623
7624 // Attach any preceding debug values to this instruction.
7625 for (DbgRecordPtr &DR : TrailingDbgRecord)
7626 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7627 TrailingDbgRecord.clear();
7628 if (ParserContext) {
7629 ParserContext->addInstructionOrArgumentLocation(
7630 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7631 }
7632 } while (!Inst->isTerminator());
7633
7634 if (ParserContext)
7635 ParserContext->addBlockLocation(
7636 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7637
7638 assert(TrailingDbgRecord.empty() &&
7639 "All debug values should have been attached to an instruction.");
7640
7641 return false;
7642}
7643
7644/// parseDebugRecord
7645/// ::= #dbg_label '(' MDNode ')'
7646/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7647/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7648bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7649 using RecordKind = DbgRecord::Kind;
7650 using LocType = DbgVariableRecord::LocationType;
7651 LocTy DVRLoc = Lex.getLoc();
7652 if (Lex.getKind() != lltok::DbgRecordType)
7653 return error(DVRLoc, "expected debug record type here");
7654 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7655 .Case("declare", RecordKind::ValueKind)
7656 .Case("value", RecordKind::ValueKind)
7657 .Case("assign", RecordKind::ValueKind)
7658 .Case("label", RecordKind::LabelKind)
7659 .Case("declare_value", RecordKind::ValueKind);
7660
7661 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7662 // full DbgVariableRecord processing stage.
7663 if (RecordType == RecordKind::LabelKind) {
7664 Lex.Lex();
7665 if (parseToken(lltok::lparen, "Expected '(' here"))
7666 return true;
7667 MDNode *Label;
7668 if (parseMDNode(Label))
7669 return true;
7670 if (parseToken(lltok::comma, "Expected ',' here"))
7671 return true;
7672 MDNode *DbgLoc;
7673 if (parseMDNode(DbgLoc))
7674 return true;
7675 if (parseToken(lltok::rparen, "Expected ')' here"))
7676 return true;
7678 PendingDbgRecords.emplace_back(DVRLoc, DR, DbgLoc);
7679 return false;
7680 }
7681
7682 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7683 .Case("declare", LocType::Declare)
7684 .Case("value", LocType::Value)
7685 .Case("assign", LocType::Assign)
7686 .Case("declare_value", LocType::DeclareValue);
7687
7688 Lex.Lex();
7689 if (parseToken(lltok::lparen, "Expected '(' here"))
7690 return true;
7691
7692 // Parse Value field.
7693 Metadata *ValLocMD;
7694 if (parseMetadata(ValLocMD, &PFS))
7695 return true;
7696 if (parseToken(lltok::comma, "Expected ',' here"))
7697 return true;
7698
7699 // Parse Variable field.
7700 MDNode *Variable;
7701 if (parseMDNode(Variable))
7702 return true;
7703 if (parseToken(lltok::comma, "Expected ',' here"))
7704 return true;
7705
7706 // Parse Expression field.
7707 MDNode *Expression;
7708 if (parseMDNode(Expression))
7709 return true;
7710 if (parseToken(lltok::comma, "Expected ',' here"))
7711 return true;
7712
7713 // Parse additional fields for #dbg_assign.
7714 MDNode *AssignID = nullptr;
7715 Metadata *AddressLocation = nullptr;
7716 MDNode *AddressExpression = nullptr;
7717 if (ValueType == LocType::Assign) {
7718 // Parse DIAssignID.
7719 if (parseMDNode(AssignID))
7720 return true;
7721 if (parseToken(lltok::comma, "Expected ',' here"))
7722 return true;
7723
7724 // Parse address ValueAsMetadata.
7725 if (parseMetadata(AddressLocation, &PFS))
7726 return true;
7727 if (parseToken(lltok::comma, "Expected ',' here"))
7728 return true;
7729
7730 // Parse address DIExpression.
7731 if (parseMDNode(AddressExpression))
7732 return true;
7733 if (parseToken(lltok::comma, "Expected ',' here"))
7734 return true;
7735 }
7736
7737 /// Parse DILocation.
7738 MDNode *DebugLoc;
7739 if (parseMDNode(DebugLoc))
7740 return true;
7741
7742 if (parseToken(lltok::rparen, "Expected ')' here"))
7743 return true;
7745 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7746 AddressExpression);
7747 PendingDbgRecords.emplace_back(DVRLoc, DR, DebugLoc);
7748 return false;
7749}
7750//===----------------------------------------------------------------------===//
7751// Instruction Parsing.
7752//===----------------------------------------------------------------------===//
7753
7754/// parseInstruction - parse one of the many different instructions.
7755///
7756int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7757 PerFunctionState &PFS) {
7758 lltok::Kind Token = Lex.getKind();
7759 if (Token == lltok::Eof)
7760 return tokError("found end of file when expecting more instructions");
7761 LocTy Loc = Lex.getLoc();
7762 unsigned KeywordVal = Lex.getUIntVal();
7763 Lex.Lex(); // Eat the keyword.
7764
7765 switch (Token) {
7766 default:
7767 return error(Loc, "expected instruction opcode");
7768 // Terminator Instructions.
7769 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7770 case lltok::kw_ret:
7771 return parseRet(Inst, BB, PFS);
7772 case lltok::kw_br:
7773 return parseBr(Inst, PFS);
7774 case lltok::kw_switch:
7775 return parseSwitch(Inst, PFS);
7777 return parseIndirectBr(Inst, PFS);
7778 case lltok::kw_invoke:
7779 return parseInvoke(Inst, PFS);
7780 case lltok::kw_resume:
7781 return parseResume(Inst, PFS);
7783 return parseCleanupRet(Inst, PFS);
7784 case lltok::kw_catchret:
7785 return parseCatchRet(Inst, PFS);
7787 return parseCatchSwitch(Inst, PFS);
7788 case lltok::kw_catchpad:
7789 return parseCatchPad(Inst, PFS);
7791 return parseCleanupPad(Inst, PFS);
7792 case lltok::kw_callbr:
7793 return parseCallBr(Inst, PFS);
7794 // Unary Operators.
7795 case lltok::kw_fneg: {
7796 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7797 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7798 if (Res != 0)
7799 return Res;
7800 if (FMF.any())
7801 Inst->setFastMathFlags(FMF);
7802 return false;
7803 }
7804 // Binary Operators.
7805 case lltok::kw_add:
7806 case lltok::kw_sub:
7807 case lltok::kw_mul:
7808 case lltok::kw_shl: {
7809 bool NUW = EatIfPresent(lltok::kw_nuw);
7810 bool NSW = EatIfPresent(lltok::kw_nsw);
7811 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7812
7813 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7814 return true;
7815
7816 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7817 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7818 return false;
7819 }
7820 case lltok::kw_fadd:
7821 case lltok::kw_fsub:
7822 case lltok::kw_fmul:
7823 case lltok::kw_fdiv:
7824 case lltok::kw_frem: {
7825 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7826 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7827 if (Res != 0)
7828 return Res;
7829 if (FMF.any())
7830 Inst->setFastMathFlags(FMF);
7831 return 0;
7832 }
7833
7834 case lltok::kw_sdiv:
7835 case lltok::kw_udiv:
7836 case lltok::kw_lshr:
7837 case lltok::kw_ashr: {
7838 bool Exact = EatIfPresent(lltok::kw_exact);
7839
7840 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7841 return true;
7842 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7843 return false;
7844 }
7845
7846 case lltok::kw_urem:
7847 case lltok::kw_srem:
7848 return parseArithmetic(Inst, PFS, KeywordVal,
7849 /*IsFP*/ false);
7850 case lltok::kw_or: {
7851 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7852 if (parseLogical(Inst, PFS, KeywordVal))
7853 return true;
7854 if (Disjoint)
7855 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7856 return false;
7857 }
7858 case lltok::kw_and:
7859 case lltok::kw_xor:
7860 return parseLogical(Inst, PFS, KeywordVal);
7861 case lltok::kw_icmp: {
7862 bool SameSign = EatIfPresent(lltok::kw_samesign);
7863 if (parseCompare(Inst, PFS, KeywordVal))
7864 return true;
7865 if (SameSign)
7866 cast<ICmpInst>(Inst)->setSameSign();
7867 return false;
7868 }
7869 case lltok::kw_fcmp: {
7870 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7871 int Res = parseCompare(Inst, PFS, KeywordVal);
7872 if (Res != 0)
7873 return Res;
7874 if (FMF.any())
7875 Inst->setFastMathFlags(FMF);
7876 return 0;
7877 }
7878
7879 // Casts.
7880 case lltok::kw_uitofp: {
7881 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7882 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7883 bool Res = parseCast(Inst, PFS, KeywordVal);
7884 if (Res != 0)
7885 return Res;
7886 if (NonNeg)
7887 Inst->setNonNeg();
7888 Inst->setFastMathFlags(FMF);
7889 return 0;
7890 }
7891 case lltok::kw_zext: {
7892 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7893 bool Res = parseCast(Inst, PFS, KeywordVal);
7894 if (Res != 0)
7895 return Res;
7896 if (NonNeg)
7897 Inst->setNonNeg();
7898 return 0;
7899 }
7900 case lltok::kw_trunc: {
7901 bool NUW = EatIfPresent(lltok::kw_nuw);
7902 bool NSW = EatIfPresent(lltok::kw_nsw);
7903 if (!NUW)
7904 NUW = EatIfPresent(lltok::kw_nuw);
7905 if (parseCast(Inst, PFS, KeywordVal))
7906 return true;
7907 if (NUW)
7908 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7909 if (NSW)
7910 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7911 return false;
7912 }
7914 bool NonNull = EatIfPresent(lltok::kw_nonnull);
7915 if (parseCast(Inst, PFS, KeywordVal))
7916 return true;
7917 if (NonNull)
7918 cast<AddrSpaceCastInst>(Inst)->setNonNull();
7919 return false;
7920 }
7921 case lltok::kw_sext:
7922 case lltok::kw_bitcast:
7923 case lltok::kw_fptoui:
7924 case lltok::kw_fptosi:
7925 case lltok::kw_inttoptr:
7927 case lltok::kw_ptrtoint:
7928 return parseCast(Inst, PFS, KeywordVal);
7929 case lltok::kw_fptrunc:
7930 case lltok::kw_fpext:
7931 case lltok::kw_sitofp: {
7932 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7933 if (parseCast(Inst, PFS, KeywordVal))
7934 return true;
7935 if (FMF.any())
7936 Inst->setFastMathFlags(FMF);
7937 return false;
7938 }
7939
7940 // Other.
7941 case lltok::kw_select: {
7942 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7943 int Res = parseSelect(Inst, PFS);
7944 if (Res != 0)
7945 return Res;
7946 if (FMF.any()) {
7947 if (!isa<FPMathOperator>(Inst)) {
7948 Inst->deleteValue();
7949 return error(Loc, "fast-math-flags specified for select without "
7950 "floating-point scalar or vector return type");
7951 }
7952 Inst->setFastMathFlags(FMF);
7953 }
7954 return 0;
7955 }
7956 case lltok::kw_va_arg:
7957 return parseVAArg(Inst, PFS);
7959 return parseExtractElement(Inst, PFS);
7961 return parseInsertElement(Inst, PFS);
7963 return parseShuffleVector(Inst, PFS);
7964 case lltok::kw_phi: {
7965 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7966 int Res = parsePHI(Inst, PFS);
7967 if (Res != 0)
7968 return Res;
7969 if (FMF.any()) {
7970 if (!isa<FPMathOperator>(Inst)) {
7971 Inst->deleteValue();
7972 return error(Loc, "fast-math-flags specified for phi without "
7973 "floating-point scalar or vector return type");
7974 }
7975 Inst->setFastMathFlags(FMF);
7976 }
7977 return 0;
7978 }
7980 return parseLandingPad(Inst, PFS);
7981 case lltok::kw_freeze:
7982 return parseFreeze(Inst, PFS);
7984 return parseBitInsert(Inst, PFS);
7986 return parseBitExtract(Inst, PFS);
7987 // Call.
7988 case lltok::kw_call:
7989 return parseCall(Inst, PFS, CallInst::TCK_None);
7990 case lltok::kw_tail:
7991 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7992 case lltok::kw_musttail:
7993 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7994 case lltok::kw_notail:
7995 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7996 // Memory.
7997 case lltok::kw_alloca:
7998 return parseAlloc(Inst, PFS);
7999 case lltok::kw_load:
8000 return parseLoad(Inst, PFS);
8001 case lltok::kw_store:
8002 return parseStore(Inst, PFS);
8003 case lltok::kw_cmpxchg:
8004 return parseCmpXchg(Inst, PFS);
8006 return parseAtomicRMW(Inst, PFS);
8007 case lltok::kw_fence:
8008 return parseFence(Inst, PFS);
8010 return parseGetElementPtr(Inst, PFS);
8012 return parseExtractValue(Inst, PFS);
8014 return parseInsertValue(Inst, PFS);
8015 }
8016}
8017
8018/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
8019bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
8020 if (Opc == Instruction::FCmp) {
8021 switch (Lex.getKind()) {
8022 default:
8023 return tokError("expected fcmp predicate (e.g. 'oeq')");
8024 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
8025 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
8026 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
8027 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
8028 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
8029 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
8030 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
8031 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
8032 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
8033 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
8034 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
8035 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
8036 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
8037 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
8038 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
8039 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
8040 }
8041 } else {
8042 switch (Lex.getKind()) {
8043 default:
8044 return tokError("expected icmp predicate (e.g. 'eq')");
8045 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
8046 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
8047 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
8048 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
8049 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
8050 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
8051 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
8052 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
8053 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
8054 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
8055 }
8056 }
8057 Lex.Lex();
8058 return false;
8059}
8060
8061//===----------------------------------------------------------------------===//
8062// Terminator Instructions.
8063//===----------------------------------------------------------------------===//
8064
8065/// parseRet - parse a return instruction.
8066/// ::= 'ret' void (',' !dbg, !1)*
8067/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
8068bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
8069 PerFunctionState &PFS) {
8070 SMLoc TypeLoc = Lex.getLoc();
8071 Type *Ty = nullptr;
8072 if (parseType(Ty, true /*void allowed*/))
8073 return true;
8074
8075 Type *ResType = PFS.getFunction().getReturnType();
8076
8077 if (Ty->isVoidTy()) {
8078 if (!ResType->isVoidTy())
8079 return error(TypeLoc, "value doesn't match function result type '" +
8080 getTypeString(ResType) + "'");
8081
8082 Inst = ReturnInst::Create(Context);
8083 return false;
8084 }
8085
8086 Value *RV;
8087 if (parseValue(Ty, RV, PFS))
8088 return true;
8089
8090 if (ResType != RV->getType())
8091 return error(TypeLoc, "value doesn't match function result type '" +
8092 getTypeString(ResType) + "'");
8093
8094 Inst = ReturnInst::Create(Context, RV);
8095 return false;
8096}
8097
8098/// parseBr
8099/// ::= 'br' TypeAndValue
8100/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8101bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
8102 LocTy Loc, Loc2;
8103 Value *Op0;
8104 BasicBlock *Op1, *Op2;
8105 if (parseTypeAndValue(Op0, Loc, PFS))
8106 return true;
8107
8108 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
8109 Inst = UncondBrInst::Create(BB);
8110 return false;
8111 }
8112
8113 if (Op0->getType() != Type::getInt1Ty(Context))
8114 return error(Loc, "branch condition must have 'i1' type");
8115
8116 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
8117 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
8118 parseToken(lltok::comma, "expected ',' after true destination") ||
8119 parseTypeAndBasicBlock(Op2, Loc2, PFS))
8120 return true;
8121
8122 Inst = CondBrInst::Create(Op0, Op1, Op2);
8123 return false;
8124}
8125
8126/// parseSwitch
8127/// Instruction
8128/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
8129/// JumpTable
8130/// ::= (TypeAndValue ',' TypeAndValue)*
8131bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8132 LocTy CondLoc, BBLoc;
8133 Value *Cond;
8134 BasicBlock *DefaultBB;
8135 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
8136 parseToken(lltok::comma, "expected ',' after switch condition") ||
8137 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
8138 parseToken(lltok::lsquare, "expected '[' with switch table"))
8139 return true;
8140
8141 if (!Cond->getType()->isIntegerTy())
8142 return error(CondLoc, "switch condition must have integer type");
8143
8144 // parse the jump table pairs.
8145 SmallPtrSet<Value*, 32> SeenCases;
8147 while (Lex.getKind() != lltok::rsquare) {
8148 Value *Constant;
8149 BasicBlock *DestBB;
8150
8151 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
8152 parseToken(lltok::comma, "expected ',' after case value") ||
8153 parseTypeAndBasicBlock(DestBB, PFS))
8154 return true;
8155
8156 if (!SeenCases.insert(Constant).second)
8157 return error(CondLoc, "duplicate case value in switch");
8158 if (!isa<ConstantInt>(Constant))
8159 return error(CondLoc, "case value is not a constant integer");
8160
8161 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
8162 }
8163
8164 Lex.Lex(); // Eat the ']'.
8165
8166 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
8167 for (const auto &[OnVal, Dest] : Table)
8168 SI->addCase(OnVal, Dest);
8169 Inst = SI;
8170 return false;
8171}
8172
8173/// parseIndirectBr
8174/// Instruction
8175/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
8176bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
8177 LocTy AddrLoc;
8178 Value *Address;
8179 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
8180 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
8181 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
8182 return true;
8183
8184 if (!Address->getType()->isPointerTy())
8185 return error(AddrLoc, "indirectbr address must have pointer type");
8186
8187 // parse the destination list.
8188 SmallVector<BasicBlock*, 16> DestList;
8189
8190 if (Lex.getKind() != lltok::rsquare) {
8191 BasicBlock *DestBB;
8192 if (parseTypeAndBasicBlock(DestBB, PFS))
8193 return true;
8194 DestList.push_back(DestBB);
8195
8196 while (EatIfPresent(lltok::comma)) {
8197 if (parseTypeAndBasicBlock(DestBB, PFS))
8198 return true;
8199 DestList.push_back(DestBB);
8200 }
8201 }
8202
8203 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8204 return true;
8205
8206 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
8207 for (BasicBlock *Dest : DestList)
8208 IBI->addDestination(Dest);
8209 Inst = IBI;
8210 return false;
8211}
8212
8213// If RetType is a non-function pointer type, then this is the short syntax
8214// for the call, which means that RetType is just the return type. Infer the
8215// rest of the function argument types from the arguments that are present.
8216bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
8217 FunctionType *&FuncTy) {
8218 FuncTy = dyn_cast<FunctionType>(RetType);
8219 if (!FuncTy) {
8220 // Pull out the types of all of the arguments...
8221 SmallVector<Type *, 8> ParamTypes;
8222 ParamTypes.reserve(ArgList.size());
8223 for (const ParamInfo &Arg : ArgList)
8224 ParamTypes.push_back(Arg.V->getType());
8225
8226 if (!FunctionType::isValidReturnType(RetType))
8227 return true;
8228
8229 FuncTy = FunctionType::get(RetType, ParamTypes, false);
8230 }
8231 return false;
8232}
8233
8234/// parseInvoke
8235/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
8236/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
8237bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8238 LocTy CallLoc = Lex.getLoc();
8239 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8240 std::vector<unsigned> FwdRefAttrGrps;
8241 LocTy NoBuiltinLoc;
8242 unsigned CC;
8243 unsigned InvokeAddrSpace;
8244 Type *RetType = nullptr;
8245 LocTy RetTypeLoc;
8246 ValID CalleeID;
8249
8250 BasicBlock *NormalBB, *UnwindBB;
8251 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8252 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8253 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8254 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8255 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8256 NoBuiltinLoc) ||
8257 parseOptionalOperandBundles(BundleList, PFS) ||
8258 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
8259 parseTypeAndBasicBlock(NormalBB, PFS) ||
8260 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
8261 parseTypeAndBasicBlock(UnwindBB, PFS))
8262 return true;
8263
8264 // If RetType is a non-function pointer type, then this is the short syntax
8265 // for the call, which means that RetType is just the return type. Infer the
8266 // rest of the function argument types from the arguments that are present.
8267 FunctionType *Ty;
8268 if (resolveFunctionType(RetType, ArgList, Ty))
8269 return error(RetTypeLoc, "Invalid result type for LLVM function");
8270
8271 CalleeID.FTy = Ty;
8272
8273 // Look up the callee.
8274 Value *Callee;
8275 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
8276 Callee, &PFS))
8277 return true;
8278
8279 // Set up the Attribute for the function.
8280 SmallVector<Value *, 8> Args;
8282
8283 // Loop through FunctionType's arguments and ensure they are specified
8284 // correctly. Also, gather any parameter attributes.
8285 FunctionType::param_iterator I = Ty->param_begin();
8286 FunctionType::param_iterator E = Ty->param_end();
8287 for (const ParamInfo &Arg : ArgList) {
8288 Type *ExpectedTy = nullptr;
8289 if (I != E) {
8290 ExpectedTy = *I++;
8291 } else if (!Ty->isVarArg()) {
8292 return error(Arg.Loc, "too many arguments specified");
8293 }
8294
8295 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8296 return error(Arg.Loc, "argument is not of expected type '" +
8297 getTypeString(ExpectedTy) + "'");
8298 Args.push_back(Arg.V);
8299 ArgAttrs.push_back(Arg.Attrs);
8300 }
8301
8302 if (I != E)
8303 return error(CallLoc, "not enough parameters specified for call");
8304
8305 // Finish off the Attribute and check them
8306 AttributeList PAL =
8307 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8308 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8309
8310 InvokeInst *II =
8311 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
8312 II->setCallingConv(CC);
8313 II->setAttributes(PAL);
8314 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
8315 Inst = II;
8316 return false;
8317}
8318
8319/// parseResume
8320/// ::= 'resume' TypeAndValue
8321bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8322 Value *Exn; LocTy ExnLoc;
8323 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8324 return true;
8325
8326 ResumeInst *RI = ResumeInst::Create(Exn);
8327 Inst = RI;
8328 return false;
8329}
8330
8331bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8332 PerFunctionState &PFS) {
8333 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
8334 return true;
8335
8336 while (Lex.getKind() != lltok::rsquare) {
8337 // If this isn't the first argument, we need a comma.
8338 if (!Args.empty() &&
8339 parseToken(lltok::comma, "expected ',' in argument list"))
8340 return true;
8341
8342 // parse the argument.
8343 LocTy ArgLoc;
8344 Type *ArgTy = nullptr;
8345 if (parseType(ArgTy, ArgLoc))
8346 return true;
8347
8348 Value *V;
8349 if (ArgTy->isMetadataTy()) {
8350 if (parseMetadataAsValue(V, PFS))
8351 return true;
8352 } else {
8353 if (parseValue(ArgTy, V, PFS))
8354 return true;
8355 }
8356 Args.push_back(V);
8357 }
8358
8359 Lex.Lex(); // Lex the ']'.
8360 return false;
8361}
8362
8363/// parseCleanupRet
8364/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
8365bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8366 Value *CleanupPad = nullptr;
8367
8368 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
8369 return true;
8370
8371 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
8372 return true;
8373
8374 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
8375 return true;
8376
8377 BasicBlock *UnwindBB = nullptr;
8378 if (Lex.getKind() == lltok::kw_to) {
8379 Lex.Lex();
8380 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
8381 return true;
8382 } else {
8383 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8384 return true;
8385 }
8386 }
8387
8388 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
8389 return false;
8390}
8391
8392/// parseCatchRet
8393/// ::= 'catchret' from Parent Value 'to' TypeAndValue
8394bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8395 Value *CatchPad = nullptr;
8396
8397 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
8398 return true;
8399
8400 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
8401 return true;
8402
8403 BasicBlock *BB;
8404 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
8405 parseTypeAndBasicBlock(BB, PFS))
8406 return true;
8407
8408 Inst = CatchReturnInst::Create(CatchPad, BB);
8409 return false;
8410}
8411
8412/// parseCatchSwitch
8413/// ::= 'catchswitch' within Parent
8414bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8415 Value *ParentPad;
8416
8417 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
8418 return true;
8419
8420 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8421 Lex.getKind() != lltok::LocalVarID)
8422 return tokError("expected scope value for catchswitch");
8423
8424 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8425 return true;
8426
8427 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
8428 return true;
8429
8431 do {
8432 BasicBlock *DestBB;
8433 if (parseTypeAndBasicBlock(DestBB, PFS))
8434 return true;
8435 Table.push_back(DestBB);
8436 } while (EatIfPresent(lltok::comma));
8437
8438 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
8439 return true;
8440
8441 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
8442 return true;
8443
8444 BasicBlock *UnwindBB = nullptr;
8445 if (EatIfPresent(lltok::kw_to)) {
8446 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
8447 return true;
8448 } else {
8449 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8450 return true;
8451 }
8452
8453 auto *CatchSwitch =
8454 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
8455 for (BasicBlock *DestBB : Table)
8456 CatchSwitch->addHandler(DestBB);
8457 Inst = CatchSwitch;
8458 return false;
8459}
8460
8461/// parseCatchPad
8462/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
8463bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8464 Value *CatchSwitch = nullptr;
8465
8466 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
8467 return true;
8468
8469 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
8470 return tokError("expected scope value for catchpad");
8471
8472 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
8473 return true;
8474
8475 SmallVector<Value *, 8> Args;
8476 if (parseExceptionArgs(Args, PFS))
8477 return true;
8478
8479 Inst = CatchPadInst::Create(CatchSwitch, Args);
8480 return false;
8481}
8482
8483/// parseCleanupPad
8484/// ::= 'cleanuppad' within Parent ParamList
8485bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8486 Value *ParentPad = nullptr;
8487
8488 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
8489 return true;
8490
8491 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8492 Lex.getKind() != lltok::LocalVarID)
8493 return tokError("expected scope value for cleanuppad");
8494
8495 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8496 return true;
8497
8498 SmallVector<Value *, 8> Args;
8499 if (parseExceptionArgs(Args, PFS))
8500 return true;
8501
8502 Inst = CleanupPadInst::Create(ParentPad, Args);
8503 return false;
8504}
8505
8506//===----------------------------------------------------------------------===//
8507// Unary Operators.
8508//===----------------------------------------------------------------------===//
8509
8510/// parseUnaryOp
8511/// ::= UnaryOp TypeAndValue ',' Value
8512///
8513/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8514/// operand is allowed.
8515bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8516 unsigned Opc, bool IsFP) {
8517 LocTy Loc; Value *LHS;
8518 if (parseTypeAndValue(LHS, Loc, PFS))
8519 return true;
8520
8521 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8523
8524 if (!Valid)
8525 return error(Loc, "invalid operand type for instruction");
8526
8528 return false;
8529}
8530
8531/// parseCallBr
8532/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8533/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8534/// '[' LabelList ']'
8535bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8536 LocTy CallLoc = Lex.getLoc();
8537 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8538 std::vector<unsigned> FwdRefAttrGrps;
8539 LocTy NoBuiltinLoc;
8540 unsigned CC;
8541 Type *RetType = nullptr;
8542 LocTy RetTypeLoc;
8543 ValID CalleeID;
8546
8547 BasicBlock *DefaultDest;
8548 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8549 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8550 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8551 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8552 NoBuiltinLoc) ||
8553 parseOptionalOperandBundles(BundleList, PFS) ||
8554 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8555 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8556 parseToken(lltok::lsquare, "expected '[' in callbr"))
8557 return true;
8558
8559 // parse the destination list.
8560 SmallVector<BasicBlock *, 16> IndirectDests;
8561
8562 if (Lex.getKind() != lltok::rsquare) {
8563 BasicBlock *DestBB;
8564 if (parseTypeAndBasicBlock(DestBB, PFS))
8565 return true;
8566 IndirectDests.push_back(DestBB);
8567
8568 while (EatIfPresent(lltok::comma)) {
8569 if (parseTypeAndBasicBlock(DestBB, PFS))
8570 return true;
8571 IndirectDests.push_back(DestBB);
8572 }
8573 }
8574
8575 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8576 return true;
8577
8578 // If RetType is a non-function pointer type, then this is the short syntax
8579 // for the call, which means that RetType is just the return type. Infer the
8580 // rest of the function argument types from the arguments that are present.
8581 FunctionType *Ty;
8582 if (resolveFunctionType(RetType, ArgList, Ty))
8583 return error(RetTypeLoc, "Invalid result type for LLVM function");
8584
8585 CalleeID.FTy = Ty;
8586
8587 // Look up the callee.
8588 Value *Callee;
8589 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8590 &PFS))
8591 return true;
8592
8593 // Set up the Attribute for the function.
8594 SmallVector<Value *, 8> Args;
8596
8597 // Loop through FunctionType's arguments and ensure they are specified
8598 // correctly. Also, gather any parameter attributes.
8599 FunctionType::param_iterator I = Ty->param_begin();
8600 FunctionType::param_iterator E = Ty->param_end();
8601 for (const ParamInfo &Arg : ArgList) {
8602 Type *ExpectedTy = nullptr;
8603 if (I != E) {
8604 ExpectedTy = *I++;
8605 } else if (!Ty->isVarArg()) {
8606 return error(Arg.Loc, "too many arguments specified");
8607 }
8608
8609 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8610 return error(Arg.Loc, "argument is not of expected type '" +
8611 getTypeString(ExpectedTy) + "'");
8612 Args.push_back(Arg.V);
8613 ArgAttrs.push_back(Arg.Attrs);
8614 }
8615
8616 if (I != E)
8617 return error(CallLoc, "not enough parameters specified for call");
8618
8619 // Finish off the Attribute and check them
8620 AttributeList PAL =
8621 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8622 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8623
8624 CallBrInst *CBI =
8625 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8626 BundleList);
8627 CBI->setCallingConv(CC);
8628 CBI->setAttributes(PAL);
8629 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8630 Inst = CBI;
8631 return false;
8632}
8633
8634//===----------------------------------------------------------------------===//
8635// Binary Operators.
8636//===----------------------------------------------------------------------===//
8637
8638/// parseArithmetic
8639/// ::= ArithmeticOps TypeAndValue ',' Value
8640///
8641/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8642/// operand is allowed.
8643bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8644 unsigned Opc, bool IsFP) {
8645 LocTy Loc; Value *LHS, *RHS;
8646 if (parseTypeAndValue(LHS, Loc, PFS) ||
8647 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8648 parseValue(LHS->getType(), RHS, PFS))
8649 return true;
8650
8651 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8653
8654 if (!Valid)
8655 return error(Loc, "invalid operand type for instruction");
8656
8658 return false;
8659}
8660
8661/// parseLogical
8662/// ::= ArithmeticOps TypeAndValue ',' Value {
8663bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8664 unsigned Opc) {
8665 LocTy Loc; Value *LHS, *RHS;
8666 if (parseTypeAndValue(LHS, Loc, PFS) ||
8667 parseToken(lltok::comma, "expected ',' in logical operation") ||
8668 parseValue(LHS->getType(), RHS, PFS))
8669 return true;
8670
8671 if (!LHS->getType()->isIntOrIntVectorTy())
8672 return error(Loc,
8673 "instruction requires integer or integer vector operands");
8674
8676 return false;
8677}
8678
8679/// parseCompare
8680/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8681/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8682bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8683 unsigned Opc) {
8684 // parse the integer/fp comparison predicate.
8685 LocTy Loc;
8686 unsigned Pred;
8687 Value *LHS, *RHS;
8688 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8689 parseToken(lltok::comma, "expected ',' after compare value") ||
8690 parseValue(LHS->getType(), RHS, PFS))
8691 return true;
8692
8693 if (Opc == Instruction::FCmp) {
8694 if (!LHS->getType()->isFPOrFPVectorTy())
8695 return error(Loc, "fcmp requires floating point operands");
8696 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8697 } else {
8698 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8699 if (!LHS->getType()->isIntOrIntVectorTy() &&
8701 return error(Loc, "icmp requires integer operands");
8702 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8703 }
8704 return false;
8705}
8706
8707//===----------------------------------------------------------------------===//
8708// Other Instructions.
8709//===----------------------------------------------------------------------===//
8710
8711/// parseCast
8712/// ::= CastOpc TypeAndValue 'to' Type
8713bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8714 unsigned Opc) {
8715 LocTy Loc;
8716 Value *Op;
8717 Type *DestTy = nullptr;
8718 if (parseTypeAndValue(Op, Loc, PFS) ||
8719 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8720 parseType(DestTy))
8721 return true;
8722
8724 return error(Loc, "invalid cast opcode for cast from '" +
8725 getTypeString(Op->getType()) + "' to '" +
8726 getTypeString(DestTy) + "'");
8727 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8728 return false;
8729}
8730
8731/// parseSelect
8732/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8733bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8734 LocTy Loc;
8735 Value *Op0, *Op1, *Op2;
8736 if (parseTypeAndValue(Op0, Loc, PFS) ||
8737 parseToken(lltok::comma, "expected ',' after select condition") ||
8738 parseTypeAndValue(Op1, PFS) ||
8739 parseToken(lltok::comma, "expected ',' after select value") ||
8740 parseTypeAndValue(Op2, PFS))
8741 return true;
8742
8743 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8744 return error(Loc, Reason);
8745
8746 Inst = SelectInst::Create(Op0, Op1, Op2);
8747 return false;
8748}
8749
8750/// parseVAArg
8751/// ::= 'va_arg' TypeAndValue ',' Type
8752bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8753 Value *Op;
8754 Type *EltTy = nullptr;
8755 LocTy TypeLoc;
8756 if (parseTypeAndValue(Op, PFS) ||
8757 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8758 parseType(EltTy, TypeLoc))
8759 return true;
8760
8761 if (!EltTy->isFirstClassType())
8762 return error(TypeLoc, "va_arg requires operand with first class type");
8763
8764 Inst = new VAArgInst(Op, EltTy);
8765 return false;
8766}
8767
8768/// parseExtractElement
8769/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8770bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8771 LocTy Loc;
8772 Value *Op0, *Op1;
8773 if (parseTypeAndValue(Op0, Loc, PFS) ||
8774 parseToken(lltok::comma, "expected ',' after extract value") ||
8775 parseTypeAndValue(Op1, PFS))
8776 return true;
8777
8779 return error(Loc, "invalid extractelement operands");
8780
8781 Inst = ExtractElementInst::Create(Op0, Op1);
8782 return false;
8783}
8784
8785/// parseInsertElement
8786/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8787bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8788 LocTy Loc;
8789 Value *Op0, *Op1, *Op2;
8790 if (parseTypeAndValue(Op0, Loc, PFS) ||
8791 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8792 parseTypeAndValue(Op1, PFS) ||
8793 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8794 parseTypeAndValue(Op2, PFS))
8795 return true;
8796
8797 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8798 return error(Loc, "invalid insertelement operands");
8799
8800 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8801 return false;
8802}
8803
8804// parseBitExtract
8805// ::= 'bitextract' Type ',' TypeAndValue ',' TypeAndValue
8806bool LLParser::parseBitExtract(Instruction *&Inst, PerFunctionState &PFS) {
8807 LocTy Loc;
8808 Type *Ty = nullptr;
8809 Value *Op0, *Op1;
8810 if (parseType(Ty, Loc) ||
8811 parseToken(lltok::comma, "expected ',' after bitextract type") ||
8812 parseTypeAndValue(Op0, Loc, PFS) ||
8813 parseToken(lltok::comma, "expected ',' after bitextract source value") ||
8814 parseTypeAndValue(Op1, PFS))
8815 return true;
8816
8817 if (const char *Reason = BitExtractInst::areInvalidOperands(Ty, Op0, Op1))
8818 return error(Loc, Reason);
8819
8820 Inst = BitExtractInst::Create(Ty, Op0, Op1);
8821 return false;
8822}
8823
8824// parseBitInsert
8825// ::= 'bitinsert' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8826bool LLParser::parseBitInsert(Instruction *&Inst, PerFunctionState &PFS) {
8827 LocTy Loc;
8828 Value *Op0, *Op1, *Op2;
8829 if (parseTypeAndValue(Op0, Loc, PFS) ||
8830 parseToken(lltok::comma, "expected ',' after bitinsert source value") ||
8831 parseTypeAndValue(Op1, PFS) ||
8832 parseToken(lltok::comma, "expected ',' after bitinsert insert value") ||
8833 parseTypeAndValue(Op2, PFS))
8834 return true;
8835
8836 if (const char *Reason = BitInsertInst::areInvalidOperands(Op0, Op1, Op2))
8837 return error(Loc, Reason);
8838
8839 Inst = BitInsertInst::Create(Op0, Op1, Op2);
8840 return false;
8841}
8842
8843/// parseShuffleVector
8844/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8845bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8846 LocTy Loc;
8847 Value *Op0, *Op1, *Op2;
8848 if (parseTypeAndValue(Op0, Loc, PFS) ||
8849 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8850 parseTypeAndValue(Op1, PFS) ||
8851 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8852 parseTypeAndValue(Op2, PFS))
8853 return true;
8854
8855 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8856 return error(Loc, "invalid shufflevector operands");
8857
8858 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8859 return false;
8860}
8861
8862/// parsePHI
8863/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8864int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8865 Type *Ty = nullptr; LocTy TypeLoc;
8866 Value *Op0, *Op1;
8867
8868 if (parseType(Ty, TypeLoc))
8869 return true;
8870
8871 if (!Ty->isFirstClassType())
8872 return error(TypeLoc, "phi node must have first class type");
8873
8874 bool First = true;
8875 bool AteExtraComma = false;
8877
8878 while (true) {
8879 if (First) {
8880 if (Lex.getKind() != lltok::lsquare)
8881 break;
8882 First = false;
8883 } else if (!EatIfPresent(lltok::comma))
8884 break;
8885
8886 if (Lex.getKind() == lltok::MetadataVar) {
8887 AteExtraComma = true;
8888 break;
8889 }
8890
8891 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8892 parseValue(Ty, Op0, PFS) ||
8893 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8894 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8895 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8896 return true;
8897
8898 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8899 }
8900
8901 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8902 for (const auto &[Val, BB] : PHIVals)
8903 PN->addIncoming(Val, BB);
8904 Inst = PN;
8905 return AteExtraComma ? InstExtraComma : InstNormal;
8906}
8907
8908/// parseLandingPad
8909/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8910/// Clause
8911/// ::= 'catch' TypeAndValue
8912/// ::= 'filter'
8913/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8914bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8915 Type *Ty = nullptr; LocTy TyLoc;
8916
8917 if (parseType(Ty, TyLoc))
8918 return true;
8919
8920 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8921 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8922
8923 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8925 if (EatIfPresent(lltok::kw_catch))
8927 else if (EatIfPresent(lltok::kw_filter))
8929 else
8930 return tokError("expected 'catch' or 'filter' clause type");
8931
8932 Value *V;
8933 LocTy VLoc;
8934 if (parseTypeAndValue(V, VLoc, PFS))
8935 return true;
8936
8937 // A 'catch' type expects a non-array constant. A filter clause expects an
8938 // array constant.
8939 if (CT == LandingPadInst::Catch) {
8940 if (isa<ArrayType>(V->getType()))
8941 return error(VLoc, "'catch' clause has an invalid type");
8942 } else {
8943 if (!isa<ArrayType>(V->getType()))
8944 return error(VLoc, "'filter' clause has an invalid type");
8945 }
8946
8948 if (!CV)
8949 return error(VLoc, "clause argument must be a constant");
8950 LP->addClause(CV);
8951 }
8952
8953 Inst = LP.release();
8954 return false;
8955}
8956
8957/// parseFreeze
8958/// ::= 'freeze' Type Value
8959bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8960 LocTy Loc;
8961 Value *Op;
8962 if (parseTypeAndValue(Op, Loc, PFS))
8963 return true;
8964
8965 Inst = new FreezeInst(Op);
8966 return false;
8967}
8968
8969/// parseCall
8970/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8971/// OptionalAttrs Type Value ParameterList OptionalAttrs
8972/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8973/// OptionalAttrs Type Value ParameterList OptionalAttrs
8974/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8975/// OptionalAttrs Type Value ParameterList OptionalAttrs
8976/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8977/// OptionalAttrs Type Value ParameterList OptionalAttrs
8978bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8980 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8981 std::vector<unsigned> FwdRefAttrGrps;
8982 LocTy BuiltinLoc;
8983 unsigned CallAddrSpace;
8984 unsigned CC;
8985 Type *RetType = nullptr;
8986 LocTy RetTypeLoc;
8987 ValID CalleeID;
8990 LocTy CallLoc = Lex.getLoc();
8991
8992 if (TCK != CallInst::TCK_None &&
8993 parseToken(lltok::kw_call,
8994 "expected 'tail call', 'musttail call', or 'notail call'"))
8995 return true;
8996
8997 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8998
8999 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
9000 parseOptionalProgramAddrSpace(CallAddrSpace) ||
9001 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
9002 parseValID(CalleeID, &PFS) ||
9003 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
9004 PFS.getFunction().isVarArg()) ||
9005 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
9006 parseOptionalOperandBundles(BundleList, PFS))
9007 return true;
9008
9009 // If RetType is a non-function pointer type, then this is the short syntax
9010 // for the call, which means that RetType is just the return type. Infer the
9011 // rest of the function argument types from the arguments that are present.
9012 FunctionType *Ty;
9013 if (resolveFunctionType(RetType, ArgList, Ty))
9014 return error(RetTypeLoc, "Invalid result type for LLVM function");
9015
9016 CalleeID.FTy = Ty;
9017
9018 // Look up the callee.
9019 Value *Callee;
9020 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
9021 Callee, &PFS))
9022 return true;
9023
9024 // Set up the Attribute for the function.
9026
9027 SmallVector<Value*, 8> Args;
9028
9029 // Loop through FunctionType's arguments and ensure they are specified
9030 // correctly. Also, gather any parameter attributes.
9031 FunctionType::param_iterator I = Ty->param_begin();
9032 FunctionType::param_iterator E = Ty->param_end();
9033 for (const ParamInfo &Arg : ArgList) {
9034 Type *ExpectedTy = nullptr;
9035 if (I != E) {
9036 ExpectedTy = *I++;
9037 } else if (!Ty->isVarArg()) {
9038 return error(Arg.Loc, "too many arguments specified");
9039 }
9040
9041 if (ExpectedTy && ExpectedTy != Arg.V->getType())
9042 return error(Arg.Loc, "argument is not of expected type '" +
9043 getTypeString(ExpectedTy) + "'");
9044 Args.push_back(Arg.V);
9045 Attrs.push_back(Arg.Attrs);
9046 }
9047
9048 if (I != E)
9049 return error(CallLoc, "not enough parameters specified for call");
9050
9051 // Finish off the Attribute and check them
9052 AttributeList PAL =
9053 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
9054 AttributeSet::get(Context, RetAttrs), Attrs);
9055
9056 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
9057 CI->setTailCallKind(TCK);
9058 CI->setCallingConv(CC);
9059 if (FMF.any()) {
9060 if (!isa<FPMathOperator>(CI)) {
9061 CI->deleteValue();
9062 return error(CallLoc, "fast-math-flags specified for call without "
9063 "floating-point scalar or vector return type");
9064 }
9065 CI->setFastMathFlags(FMF);
9066 }
9067
9068 if (CalleeID.Kind == ValID::t_GlobalName &&
9069 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
9070 if (SeenNewDbgInfoFormat) {
9071 CI->deleteValue();
9072 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
9073 "using non-intrinsic debug info");
9074 }
9075 SeenOldDbgInfoFormat = true;
9076 }
9077 CI->setAttributes(PAL);
9078 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
9079 Inst = CI;
9080 return false;
9081}
9082
9083//===----------------------------------------------------------------------===//
9084// Memory Instructions.
9085//===----------------------------------------------------------------------===//
9086
9087/// parseAlloc
9088/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
9089/// (',' 'align' i32)? (',', 'addrspace(n))?
9090int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
9091 Value *Size = nullptr;
9092 LocTy SizeLoc, TyLoc, ASLoc;
9093 MaybeAlign Alignment;
9094 unsigned AddrSpace = 0;
9095 Type *Ty = nullptr;
9096
9097 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
9098 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
9099
9100 if (parseType(Ty, TyLoc))
9101 return true;
9102
9104 return error(TyLoc, "invalid type for alloca");
9105
9106 bool AteExtraComma = false;
9107 if (EatIfPresent(lltok::comma)) {
9108 if (Lex.getKind() == lltok::kw_align) {
9109 if (parseOptionalAlignment(Alignment))
9110 return true;
9111 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9112 return true;
9113 } else if (Lex.getKind() == lltok::kw_addrspace) {
9114 ASLoc = Lex.getLoc();
9115 if (parseOptionalAddrSpace(AddrSpace))
9116 return true;
9117 } else if (Lex.getKind() == lltok::MetadataVar) {
9118 AteExtraComma = true;
9119 } else {
9120 if (parseTypeAndValue(Size, SizeLoc, PFS))
9121 return true;
9122 if (EatIfPresent(lltok::comma)) {
9123 if (Lex.getKind() == lltok::kw_align) {
9124 if (parseOptionalAlignment(Alignment))
9125 return true;
9126 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
9127 return true;
9128 } else if (Lex.getKind() == lltok::kw_addrspace) {
9129 ASLoc = Lex.getLoc();
9130 if (parseOptionalAddrSpace(AddrSpace))
9131 return true;
9132 } else if (Lex.getKind() == lltok::MetadataVar) {
9133 AteExtraComma = true;
9134 }
9135 }
9136 }
9137 }
9138
9139 if (Size && !Size->getType()->isIntegerTy())
9140 return error(SizeLoc, "element count must have integer type");
9141
9142 if (!Alignment && !Ty->isSized())
9143 return error(TyLoc, "Cannot allocate unsized type");
9144 if (!Alignment)
9145 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
9146 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
9147 AI->setUsedWithInAlloca(IsInAlloca);
9148 AI->setSwiftError(IsSwiftError);
9149 Inst = AI;
9150 return AteExtraComma ? InstExtraComma : InstNormal;
9151}
9152
9153/// parseLoad
9154/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
9155/// ::= 'load' 'atomic' 'volatile'? 'elementwise'? TypeAndValue
9156/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
9157int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
9158 Value *Val; LocTy Loc;
9159 MaybeAlign Alignment;
9160 bool AteExtraComma = false;
9161 bool isAtomic = false;
9164
9165 if (Lex.getKind() == lltok::kw_atomic) {
9166 isAtomic = true;
9167 Lex.Lex();
9168 }
9169
9170 bool isVolatile = false;
9171 if (Lex.getKind() == lltok::kw_volatile) {
9172 isVolatile = true;
9173 Lex.Lex();
9174 }
9175
9176 bool IsElementwise = false;
9177 if (Lex.getKind() == lltok::kw_elementwise) {
9178 IsElementwise = true;
9179 Lex.Lex();
9180 }
9181
9182 Type *Ty;
9183 LocTy ExplicitTypeLoc = Lex.getLoc();
9184 if (parseType(Ty) ||
9185 parseToken(lltok::comma, "expected comma after load's type") ||
9186 parseTypeAndValue(Val, Loc, PFS) ||
9187 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9188 parseOptionalCommaAlign(Alignment, AteExtraComma))
9189 return true;
9190
9191 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
9192 return error(Loc, "load operand must be a pointer to a first class type");
9193
9194 if (IsElementwise && !isAtomic)
9195 return error(Loc, "elementwise load must be atomic");
9196
9197 if (IsElementwise && !isa<FixedVectorType>(Ty))
9198 return error(ExplicitTypeLoc,
9199 "atomic elementwise load operand must have fixed vector type");
9200
9201 if (isAtomic && !Alignment)
9202 return error(Loc, "atomic load must have explicit non-zero alignment");
9203
9204 if (Ordering == AtomicOrdering::Release ||
9206 return error(Loc, "atomic load cannot use Release ordering");
9207 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9208 return error(Loc,
9209 "atomic elementwise load cannot be sequentially consistent");
9210
9211 if (!Alignment && !Ty->isSized())
9212 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
9213 if (!Alignment)
9214 Alignment = M->getDataLayout().getABITypeAlign(Ty);
9215 Inst = new LoadInst(Ty, Val, "",
9216 LoadStoreInstProperties{isVolatile, *Alignment, Ordering,
9217 SSID, IsElementwise},
9218 /*InsertBefore=*/nullptr);
9219 return AteExtraComma ? InstExtraComma : InstNormal;
9220}
9221
9222/// parseStore
9223
9224/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
9225/// ::= 'store' 'atomic' 'volatile'? 'elementwise'? TypeAndValue ','
9226/// TypeAndValue 'singlethread'? AtomicOrdering (',' 'align' i32)?
9227int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
9228 Value *Val, *Ptr;
9229 LocTy Loc, PtrLoc;
9230 MaybeAlign Alignment;
9231 bool AteExtraComma = false;
9232 bool isAtomic = false;
9235
9236 if (Lex.getKind() == lltok::kw_atomic) {
9237 isAtomic = true;
9238 Lex.Lex();
9239 }
9240
9241 bool isVolatile = false;
9242 if (Lex.getKind() == lltok::kw_volatile) {
9243 isVolatile = true;
9244 Lex.Lex();
9245 }
9246
9247 bool IsElementwise = false;
9248 if (Lex.getKind() == lltok::kw_elementwise) {
9249 IsElementwise = true;
9250 Lex.Lex();
9251 }
9252
9253 if (parseTypeAndValue(Val, Loc, PFS) ||
9254 parseToken(lltok::comma, "expected ',' after store operand") ||
9255 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9256 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
9257 parseOptionalCommaAlign(Alignment, AteExtraComma))
9258 return true;
9259
9260 if (!Ptr->getType()->isPointerTy())
9261 return error(PtrLoc, "store operand must be a pointer");
9262 if (!Val->getType()->isFirstClassType())
9263 return error(Loc, "store operand must be a first class value");
9264 if (isAtomic && !Alignment)
9265 return error(Loc, "atomic store must have explicit non-zero alignment");
9266 if (Ordering == AtomicOrdering::Acquire ||
9268 return error(Loc, "atomic store cannot use Acquire ordering");
9269
9270 if (IsElementwise && !isAtomic)
9271 return error(Loc, "elementwise store must be atomic");
9272
9273 if (IsElementwise && !isa<FixedVectorType>(Val->getType()))
9274 return error(
9275 Loc, "atomic elementwise store operand must have fixed vector type");
9276
9277 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9278 return error(Loc,
9279 "atomic elementwise store cannot be sequentially consistent");
9280
9281 if (!Alignment && !Val->getType()->isSized())
9282 return error(Loc, "storing unsized types is not allowed");
9283 if (!Alignment)
9284 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
9285
9286 Inst = new StoreInst(Val, Ptr,
9287 LoadStoreInstProperties{isVolatile, *Alignment, Ordering,
9288 SSID, IsElementwise},
9289 /*InsertBefore=*/nullptr);
9290 return AteExtraComma ? InstExtraComma : InstNormal;
9291}
9292
9293/// parseCmpXchg
9294/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
9295/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
9296/// 'Align'?
9297int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
9298 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
9299 bool AteExtraComma = false;
9300 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
9301 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
9303 bool isVolatile = false;
9304 bool isWeak = false;
9305 MaybeAlign Alignment;
9306
9307 if (EatIfPresent(lltok::kw_weak))
9308 isWeak = true;
9309
9310 if (EatIfPresent(lltok::kw_volatile))
9311 isVolatile = true;
9312
9313 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9314 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
9315 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9316 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
9317 parseTypeAndValue(New, NewLoc, PFS) ||
9318 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
9319 parseOrdering(FailureOrdering) ||
9320 parseOptionalCommaAlign(Alignment, AteExtraComma))
9321 return true;
9322
9323 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
9324 return tokError("invalid cmpxchg success ordering");
9325 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
9326 return tokError("invalid cmpxchg failure ordering");
9327 if (!Ptr->getType()->isPointerTy())
9328 return error(PtrLoc, "cmpxchg operand must be a pointer");
9329 if (Cmp->getType() != New->getType())
9330 return error(NewLoc, "compare value and new value type do not match");
9331 if (!New->getType()->isFirstClassType())
9332 return error(NewLoc, "cmpxchg operand must be a first class value");
9333
9334 const Align DefaultAlignment(
9335 PFS.getFunction().getDataLayout().getTypeStoreSize(
9336 Cmp->getType()));
9337
9338 AtomicCmpXchgInst *CXI =
9339 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
9340 SuccessOrdering, FailureOrdering, SSID);
9341 CXI->setVolatile(isVolatile);
9342 CXI->setWeak(isWeak);
9343
9344 Inst = CXI;
9345 return AteExtraComma ? InstExtraComma : InstNormal;
9346}
9347
9348/// parseAtomicRMW
9349/// ::= 'atomicrmw' 'volatile'? 'elementwise'? BinOp TypeAndValue ','
9350/// TypeAndValue
9351/// 'singlethread'? AtomicOrdering
9352int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9353 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
9354 bool AteExtraComma = false;
9357 bool IsVolatile = false;
9358 bool IsElementwise = false;
9359 bool IsFP = false;
9361 MaybeAlign Alignment;
9362
9363 if (EatIfPresent(lltok::kw_volatile))
9364 IsVolatile = true;
9365 if (EatIfPresent(lltok::kw_elementwise))
9366 IsElementwise = true;
9367
9368 switch (Lex.getKind()) {
9369 default:
9370 return tokError("expected binary operation in atomicrmw");
9384 break;
9387 break;
9390 break;
9391 case lltok::kw_usub_sat:
9393 break;
9394 case lltok::kw_fadd:
9396 IsFP = true;
9397 break;
9398 case lltok::kw_fsub:
9400 IsFP = true;
9401 break;
9402 case lltok::kw_fmax:
9404 IsFP = true;
9405 break;
9406 case lltok::kw_fmin:
9408 IsFP = true;
9409 break;
9410 case lltok::kw_fmaximum:
9412 IsFP = true;
9413 break;
9414 case lltok::kw_fminimum:
9416 IsFP = true;
9417 break;
9420 IsFP = true;
9421 break;
9424 IsFP = true;
9425 break;
9426 }
9427 Lex.Lex(); // Eat the operation.
9428
9429 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9430 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
9431 parseTypeAndValue(Val, ValLoc, PFS) ||
9432 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
9433 parseOptionalCommaAlign(Alignment, AteExtraComma))
9434 return true;
9435
9436 if (Ordering == AtomicOrdering::Unordered)
9437 return tokError("atomicrmw cannot be unordered");
9438 if (IsElementwise && Ordering == AtomicOrdering::SequentiallyConsistent)
9439 return tokError("atomicrmw elementwise cannot be sequentially consistent");
9440 if (!Ptr->getType()->isPointerTy())
9441 return error(PtrLoc, "atomicrmw operand must be a pointer");
9442 if (Val->getType()->isScalableTy())
9443 return error(ValLoc, "atomicrmw operand may not be scalable");
9444
9445 Type *ValTy = Val->getType();
9446 if (IsElementwise) {
9447 if (!isa<FixedVectorType>(Val->getType()))
9448 return error(ValLoc,
9449 "atomicrmw elementwise operand must be a fixed vector type");
9450 }
9451
9453 if (!ValTy->isIntOrIntVectorTy() && !ValTy->isFPOrFPVectorTy() &&
9454 !ValTy->isPtrOrPtrVectorTy()) {
9455 return error(
9456 ValLoc,
9458 " operand must be an integer type, a floating-point type, a "
9459 "pointer type, or a fixed vector of any of these types");
9460 }
9461 } else if (IsFP) {
9462 if (!ValTy->isFPOrFPVectorTy()) {
9463 return error(ValLoc, "atomicrmw " +
9465 " operand must be a floating point or fixed "
9466 "vector of floating point type");
9467 }
9468 } else {
9469 if (!ValTy->isIntOrIntVectorTy()) {
9470 return error(
9471 ValLoc,
9473 " operand must be an integer or fixed vector of integer type");
9474 }
9475 }
9476
9477 unsigned Size =
9478 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(ValTy);
9479 if (Size < 8 || (Size & (Size - 1)))
9480 return error(ValLoc,
9481 "atomicrmw operand must have a power-of-two byte size");
9482 const Align DefaultAlignment(
9483 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->getType()));
9484 AtomicRMWInst *RMWI = new AtomicRMWInst(Operation, Ptr, Val,
9485 Alignment.value_or(DefaultAlignment),
9486 Ordering, SSID, IsElementwise);
9487 RMWI->setVolatile(IsVolatile);
9488 Inst = RMWI;
9489 return AteExtraComma ? InstExtraComma : InstNormal;
9490}
9491
9492/// parseFence
9493/// ::= 'fence' 'singlethread'? AtomicOrdering
9494int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9497 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
9498 return true;
9499
9500 if (Ordering == AtomicOrdering::Unordered)
9501 return tokError("fence cannot be unordered");
9502 if (Ordering == AtomicOrdering::Monotonic)
9503 return tokError("fence cannot be monotonic");
9504
9505 Inst = new FenceInst(Context, Ordering, SSID);
9506 return InstNormal;
9507}
9508
9509/// parseGetElementPtr
9510/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9511int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9512 Value *Ptr = nullptr;
9513 Value *Val = nullptr;
9514 LocTy Loc, EltLoc;
9515 GEPNoWrapFlags NW;
9516
9517 while (true) {
9518 if (EatIfPresent(lltok::kw_inbounds))
9520 else if (EatIfPresent(lltok::kw_nusw))
9522 else if (EatIfPresent(lltok::kw_nuw))
9524 else
9525 break;
9526 }
9527
9528 Type *Ty = nullptr;
9529 if (parseType(Ty) ||
9530 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
9531 parseTypeAndValue(Ptr, Loc, PFS))
9532 return true;
9533
9534 Type *BaseType = Ptr->getType();
9535 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
9536 if (!BasePointerType)
9537 return error(Loc, "base of getelementptr must be a pointer");
9538
9539 SmallVector<Value*, 16> Indices;
9540 bool AteExtraComma = false;
9541 // GEP returns a vector of pointers if at least one of parameters is a vector.
9542 // All vector parameters should have the same vector width.
9543 ElementCount GEPWidth = BaseType->isVectorTy()
9544 ? cast<VectorType>(BaseType)->getElementCount()
9546
9547 while (EatIfPresent(lltok::comma)) {
9548 if (Lex.getKind() == lltok::MetadataVar) {
9549 AteExtraComma = true;
9550 break;
9551 }
9552 if (parseTypeAndValue(Val, EltLoc, PFS))
9553 return true;
9554 if (!Val->getType()->isIntOrIntVectorTy())
9555 return error(EltLoc, "getelementptr index must be an integer");
9556
9557 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
9558 ElementCount ValNumEl = ValVTy->getElementCount();
9559 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
9560 return error(
9561 EltLoc,
9562 "getelementptr vector index has a wrong number of elements");
9563 GEPWidth = ValNumEl;
9564 }
9565 Indices.push_back(Val);
9566 }
9567
9568 if (!Indices.empty() && !Ty->isSized())
9569 return error(Loc, "base element of getelementptr must be sized");
9570
9571 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
9572 return error(Loc, "invalid getelementptr indices");
9573 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
9574 Inst = GEP;
9575 GEP->setNoWrapFlags(NW);
9576 return AteExtraComma ? InstExtraComma : InstNormal;
9577}
9578
9579/// parseExtractValue
9580/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9581int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9582 Value *Val; LocTy Loc;
9583 SmallVector<unsigned, 4> Indices;
9584 bool AteExtraComma;
9585 if (parseTypeAndValue(Val, Loc, PFS) ||
9586 parseIndexList(Indices, AteExtraComma))
9587 return true;
9588
9589 if (!Val->getType()->isAggregateType())
9590 return error(Loc, "extractvalue operand must be aggregate type");
9591
9592 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9593 return error(Loc, "invalid indices for extractvalue");
9594 Inst = ExtractValueInst::Create(Val, Indices);
9595 return AteExtraComma ? InstExtraComma : InstNormal;
9596}
9597
9598/// parseInsertValue
9599/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9600int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9601 Value *Val0, *Val1; LocTy Loc0, Loc1;
9602 SmallVector<unsigned, 4> Indices;
9603 bool AteExtraComma;
9604 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9605 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9606 parseTypeAndValue(Val1, Loc1, PFS) ||
9607 parseIndexList(Indices, AteExtraComma))
9608 return true;
9609
9610 if (!Val0->getType()->isAggregateType())
9611 return error(Loc0, "insertvalue operand must be aggregate type");
9612
9613 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9614 if (!IndexedType)
9615 return error(Loc0, "invalid indices for insertvalue");
9616 if (IndexedType != Val1->getType())
9617 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9618 getTypeString(Val1->getType()) + "' instead of '" +
9619 getTypeString(IndexedType) + "'");
9620 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9621 return AteExtraComma ? InstExtraComma : InstNormal;
9622}
9623
9624//===----------------------------------------------------------------------===//
9625// Embedded metadata.
9626//===----------------------------------------------------------------------===//
9627
9628/// parseMDNodeVector
9629/// ::= { Element (',' Element)* }
9630/// Element
9631/// ::= 'null' | Metadata
9632bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9633 if (parseToken(lltok::lbrace, "expected '{' here"))
9634 return true;
9635
9636 // Check for an empty list.
9637 if (EatIfPresent(lltok::rbrace))
9638 return false;
9639
9640 do {
9641 if (EatIfPresent(lltok::kw_null)) {
9642 Elts.push_back(nullptr);
9643 continue;
9644 }
9645
9646 Metadata *MD;
9647 if (parseMetadata(MD, nullptr))
9648 return true;
9649 Elts.push_back(MD);
9650 } while (EatIfPresent(lltok::comma));
9651
9652 return parseToken(lltok::rbrace, "expected end of metadata node");
9653}
9654
9655//===----------------------------------------------------------------------===//
9656// Use-list order directives.
9657//===----------------------------------------------------------------------===//
9658bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9659 SMLoc Loc) {
9660 if (!V->hasUseList())
9661 return false;
9662 if (V->use_empty())
9663 return error(Loc, "value has no uses");
9664
9665 unsigned NumUses = 0;
9666 SmallDenseMap<const Use *, unsigned, 16> Order;
9667 for (const Use &U : V->uses()) {
9668 if (++NumUses > Indexes.size())
9669 break;
9670 Order[&U] = Indexes[NumUses - 1];
9671 }
9672 if (NumUses < 2)
9673 return error(Loc, "value only has one use");
9674 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9675 return error(Loc,
9676 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9677
9678 V->sortUseList([&](const Use &L, const Use &R) {
9679 return Order.lookup(&L) < Order.lookup(&R);
9680 });
9681 return false;
9682}
9683
9684/// parseUseListOrderIndexes
9685/// ::= '{' uint32 (',' uint32)+ '}'
9686bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9687 SMLoc Loc = Lex.getLoc();
9688 if (parseToken(lltok::lbrace, "expected '{' here"))
9689 return true;
9690 if (Lex.getKind() == lltok::rbrace)
9691 return tokError("expected non-empty list of uselistorder indexes");
9692
9693 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9694 // indexes should be distinct numbers in the range [0, size-1], and should
9695 // not be in order.
9696 unsigned Offset = 0;
9697 unsigned Max = 0;
9698 bool IsOrdered = true;
9699 assert(Indexes.empty() && "Expected empty order vector");
9700 do {
9701 unsigned Index;
9702 if (parseUInt32(Index))
9703 return true;
9704
9705 // Update consistency checks.
9706 Offset += Index - Indexes.size();
9707 Max = std::max(Max, Index);
9708 IsOrdered &= Index == Indexes.size();
9709
9710 Indexes.push_back(Index);
9711 } while (EatIfPresent(lltok::comma));
9712
9713 if (parseToken(lltok::rbrace, "expected '}' here"))
9714 return true;
9715
9716 if (Indexes.size() < 2)
9717 return error(Loc, "expected >= 2 uselistorder indexes");
9718 if (Offset != 0 || Max >= Indexes.size())
9719 return error(Loc,
9720 "expected distinct uselistorder indexes in range [0, size)");
9721 if (IsOrdered)
9722 return error(Loc, "expected uselistorder indexes to change the order");
9723
9724 return false;
9725}
9726
9727/// parseUseListOrder
9728/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9729bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9730 SMLoc Loc = Lex.getLoc();
9731 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9732 return true;
9733
9734 Value *V;
9735 SmallVector<unsigned, 16> Indexes;
9736 if (parseTypeAndValue(V, PFS) ||
9737 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9738 parseUseListOrderIndexes(Indexes))
9739 return true;
9740
9741 return sortUseListOrder(V, Indexes, Loc);
9742}
9743
9744/// ModuleEntry
9745/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9746/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9747bool LLParser::parseModuleEntry(unsigned ID) {
9748 assert(Lex.getKind() == lltok::kw_module);
9749 Lex.Lex();
9750
9751 std::string Path;
9752 if (parseToken(lltok::colon, "expected ':' here") ||
9753 parseToken(lltok::lparen, "expected '(' here") ||
9754 parseToken(lltok::kw_path, "expected 'path' here") ||
9755 parseToken(lltok::colon, "expected ':' here") ||
9756 parseStringConstant(Path) ||
9757 parseToken(lltok::comma, "expected ',' here") ||
9758 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9759 parseToken(lltok::colon, "expected ':' here") ||
9760 parseToken(lltok::lparen, "expected '(' here"))
9761 return true;
9762
9763 ModuleHash Hash;
9764 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9765 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9766 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9767 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9768 parseUInt32(Hash[4]))
9769 return true;
9770
9771 if (parseToken(lltok::rparen, "expected ')' here") ||
9772 parseToken(lltok::rparen, "expected ')' here"))
9773 return true;
9774
9775 auto ModuleEntry = Index->addModule(Path, Hash);
9776 ModuleIdMap[ID] = ModuleEntry->first();
9777
9778 return false;
9779}
9780
9781/// TypeIdEntry
9782/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9783bool LLParser::parseTypeIdEntry(unsigned ID) {
9784 assert(Lex.getKind() == lltok::kw_typeid);
9785 Lex.Lex();
9786
9787 std::string Name;
9788 if (parseToken(lltok::colon, "expected ':' here") ||
9789 parseToken(lltok::lparen, "expected '(' here") ||
9790 parseToken(lltok::kw_name, "expected 'name' here") ||
9791 parseToken(lltok::colon, "expected ':' here") ||
9792 parseStringConstant(Name))
9793 return true;
9794
9795 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9796 if (parseToken(lltok::comma, "expected ',' here") ||
9797 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9798 return true;
9799
9800 // Check if this ID was forward referenced, and if so, update the
9801 // corresponding GUIDs.
9802 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9803 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9804 for (auto TIDRef : FwdRefTIDs->second) {
9805 assert(!*TIDRef.first &&
9806 "Forward referenced type id GUID expected to be 0");
9807 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9808 }
9809 ForwardRefTypeIds.erase(FwdRefTIDs);
9810 }
9811
9812 return false;
9813}
9814
9815/// TypeIdSummary
9816/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9817bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9818 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9819 parseToken(lltok::colon, "expected ':' here") ||
9820 parseToken(lltok::lparen, "expected '(' here") ||
9821 parseTypeTestResolution(TIS.TTRes))
9822 return true;
9823
9824 if (EatIfPresent(lltok::comma)) {
9825 // Expect optional wpdResolutions field
9826 if (parseOptionalWpdResolutions(TIS.WPDRes))
9827 return true;
9828 }
9829
9830 if (parseToken(lltok::rparen, "expected ')' here"))
9831 return true;
9832
9833 return false;
9834}
9835
9838
9839/// TypeIdCompatibleVtableEntry
9840/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9841/// TypeIdCompatibleVtableInfo
9842/// ')'
9843bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9845 Lex.Lex();
9846
9847 std::string Name;
9848 if (parseToken(lltok::colon, "expected ':' here") ||
9849 parseToken(lltok::lparen, "expected '(' here") ||
9850 parseToken(lltok::kw_name, "expected 'name' here") ||
9851 parseToken(lltok::colon, "expected ':' here") ||
9852 parseStringConstant(Name))
9853 return true;
9854
9856 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9857 if (parseToken(lltok::comma, "expected ',' here") ||
9858 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9859 parseToken(lltok::colon, "expected ':' here") ||
9860 parseToken(lltok::lparen, "expected '(' here"))
9861 return true;
9862
9863 IdToIndexMapType IdToIndexMap;
9864 // parse each call edge
9865 do {
9867 if (parseToken(lltok::lparen, "expected '(' here") ||
9868 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9869 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9870 parseToken(lltok::comma, "expected ',' here"))
9871 return true;
9872
9873 LocTy Loc = Lex.getLoc();
9874 unsigned GVId;
9875 ValueInfo VI;
9876 if (parseGVReference(VI, GVId))
9877 return true;
9878
9879 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9880 // forward reference. We will save the location of the ValueInfo needing an
9881 // update, but can only do so once the std::vector is finalized.
9882 if (VI == EmptyVI)
9883 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9884 TI.push_back({Offset, VI});
9885
9886 if (parseToken(lltok::rparen, "expected ')' in call"))
9887 return true;
9888 } while (EatIfPresent(lltok::comma));
9889
9890 // Now that the TI vector is finalized, it is safe to save the locations
9891 // of any forward GV references that need updating later.
9892 for (auto I : IdToIndexMap) {
9893 auto &Infos = ForwardRefValueInfos[I.first];
9894 for (auto P : I.second) {
9895 assert(TI[P.first].VTableVI == EmptyVI &&
9896 "Forward referenced ValueInfo expected to be empty");
9897 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9898 }
9899 }
9900
9901 if (parseToken(lltok::rparen, "expected ')' here") ||
9902 parseToken(lltok::rparen, "expected ')' here"))
9903 return true;
9904
9905 // Check if this ID was forward referenced, and if so, update the
9906 // corresponding GUIDs.
9907 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9908 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9909 for (auto TIDRef : FwdRefTIDs->second) {
9910 assert(!*TIDRef.first &&
9911 "Forward referenced type id GUID expected to be 0");
9912 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9913 }
9914 ForwardRefTypeIds.erase(FwdRefTIDs);
9915 }
9916
9917 return false;
9918}
9919
9920/// TypeTestResolution
9921/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9922/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9923/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9924/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9925/// [',' 'inlinesBits' ':' UInt64]? ')'
9926bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9927 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9928 parseToken(lltok::colon, "expected ':' here") ||
9929 parseToken(lltok::lparen, "expected '(' here") ||
9930 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9931 parseToken(lltok::colon, "expected ':' here"))
9932 return true;
9933
9934 switch (Lex.getKind()) {
9935 case lltok::kw_unknown:
9937 break;
9938 case lltok::kw_unsat:
9940 break;
9943 break;
9944 case lltok::kw_inline:
9946 break;
9947 case lltok::kw_single:
9949 break;
9950 case lltok::kw_allOnes:
9952 break;
9953 default:
9954 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9955 }
9956 Lex.Lex();
9957
9958 if (parseToken(lltok::comma, "expected ',' here") ||
9959 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9960 parseToken(lltok::colon, "expected ':' here") ||
9961 parseUInt32(TTRes.SizeM1BitWidth))
9962 return true;
9963
9964 // parse optional fields
9965 while (EatIfPresent(lltok::comma)) {
9966 switch (Lex.getKind()) {
9968 Lex.Lex();
9969 if (parseToken(lltok::colon, "expected ':'") ||
9970 parseUInt64(TTRes.AlignLog2))
9971 return true;
9972 break;
9973 case lltok::kw_sizeM1:
9974 Lex.Lex();
9975 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9976 return true;
9977 break;
9978 case lltok::kw_bitMask: {
9979 unsigned Val;
9980 Lex.Lex();
9981 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9982 return true;
9983 assert(Val <= 0xff);
9984 TTRes.BitMask = (uint8_t)Val;
9985 break;
9986 }
9988 Lex.Lex();
9989 if (parseToken(lltok::colon, "expected ':'") ||
9990 parseUInt64(TTRes.InlineBits))
9991 return true;
9992 break;
9993 default:
9994 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9995 }
9996 }
9997
9998 if (parseToken(lltok::rparen, "expected ')' here"))
9999 return true;
10000
10001 return false;
10002}
10003
10004/// OptionalWpdResolutions
10005/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
10006/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
10007bool LLParser::parseOptionalWpdResolutions(
10008 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
10009 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
10010 parseToken(lltok::colon, "expected ':' here") ||
10011 parseToken(lltok::lparen, "expected '(' here"))
10012 return true;
10013
10014 do {
10016 WholeProgramDevirtResolution WPDRes;
10017 if (parseToken(lltok::lparen, "expected '(' here") ||
10018 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10019 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
10020 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
10021 parseToken(lltok::rparen, "expected ')' here"))
10022 return true;
10023 WPDResMap[Offset] = WPDRes;
10024 } while (EatIfPresent(lltok::comma));
10025
10026 if (parseToken(lltok::rparen, "expected ')' here"))
10027 return true;
10028
10029 return false;
10030}
10031
10032/// WpdRes
10033/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
10034/// [',' OptionalResByArg]? ')'
10035/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
10036/// ',' 'singleImplName' ':' STRINGCONSTANT ','
10037/// [',' OptionalResByArg]? ')'
10038/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
10039/// [',' OptionalResByArg]? ')'
10040bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
10041 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
10042 parseToken(lltok::colon, "expected ':' here") ||
10043 parseToken(lltok::lparen, "expected '(' here") ||
10044 parseToken(lltok::kw_kind, "expected 'kind' here") ||
10045 parseToken(lltok::colon, "expected ':' here"))
10046 return true;
10047
10048 switch (Lex.getKind()) {
10049 case lltok::kw_indir:
10051 break;
10054 break;
10057 break;
10060 break;
10061 default:
10062 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
10063 }
10064 Lex.Lex();
10065
10066 // parse optional fields
10067 while (EatIfPresent(lltok::comma)) {
10068 switch (Lex.getKind()) {
10070 Lex.Lex();
10071 if (parseToken(lltok::colon, "expected ':' here") ||
10072 parseStringConstant(WPDRes.SingleImplName))
10073 return true;
10074 break;
10075 case lltok::kw_resByArg:
10076 if (parseOptionalResByArg(WPDRes.ResByArg))
10077 return true;
10078 break;
10079 default:
10080 return error(Lex.getLoc(),
10081 "expected optional WholeProgramDevirtResolution field");
10082 }
10083 }
10084
10085 if (parseToken(lltok::rparen, "expected ')' here"))
10086 return true;
10087
10088 return false;
10089}
10090
10091/// OptionalResByArg
10092/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
10093/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
10094/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
10095/// 'virtualConstProp' )
10096/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
10097/// [',' 'bit' ':' UInt32]? ')'
10098bool LLParser::parseOptionalResByArg(
10099 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
10100 &ResByArg) {
10101 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
10102 parseToken(lltok::colon, "expected ':' here") ||
10103 parseToken(lltok::lparen, "expected '(' here"))
10104 return true;
10105
10106 do {
10107 std::vector<uint64_t> Args;
10108 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
10109 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
10110 parseToken(lltok::colon, "expected ':' here") ||
10111 parseToken(lltok::lparen, "expected '(' here") ||
10112 parseToken(lltok::kw_kind, "expected 'kind' here") ||
10113 parseToken(lltok::colon, "expected ':' here"))
10114 return true;
10115
10116 WholeProgramDevirtResolution::ByArg ByArg;
10117 switch (Lex.getKind()) {
10118 case lltok::kw_indir:
10120 break;
10123 break;
10126 break;
10129 break;
10130 default:
10131 return error(Lex.getLoc(),
10132 "unexpected WholeProgramDevirtResolution::ByArg kind");
10133 }
10134 Lex.Lex();
10135
10136 // parse optional fields
10137 while (EatIfPresent(lltok::comma)) {
10138 switch (Lex.getKind()) {
10139 case lltok::kw_info:
10140 Lex.Lex();
10141 if (parseToken(lltok::colon, "expected ':' here") ||
10142 parseUInt64(ByArg.Info))
10143 return true;
10144 break;
10145 case lltok::kw_byte:
10146 Lex.Lex();
10147 if (parseToken(lltok::colon, "expected ':' here") ||
10148 parseUInt32(ByArg.Byte))
10149 return true;
10150 break;
10151 case lltok::kw_bit:
10152 Lex.Lex();
10153 if (parseToken(lltok::colon, "expected ':' here") ||
10154 parseUInt32(ByArg.Bit))
10155 return true;
10156 break;
10157 default:
10158 return error(Lex.getLoc(),
10159 "expected optional whole program devirt field");
10160 }
10161 }
10162
10163 if (parseToken(lltok::rparen, "expected ')' here"))
10164 return true;
10165
10166 ResByArg[Args] = ByArg;
10167 } while (EatIfPresent(lltok::comma));
10168
10169 if (parseToken(lltok::rparen, "expected ')' here"))
10170 return true;
10171
10172 return false;
10173}
10174
10175/// OptionalResByArg
10176/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
10177bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
10178 if (parseToken(lltok::kw_args, "expected 'args' here") ||
10179 parseToken(lltok::colon, "expected ':' here") ||
10180 parseToken(lltok::lparen, "expected '(' here"))
10181 return true;
10182
10183 do {
10184 uint64_t Val;
10185 if (parseUInt64(Val))
10186 return true;
10187 Args.push_back(Val);
10188 } while (EatIfPresent(lltok::comma));
10189
10190 if (parseToken(lltok::rparen, "expected ')' here"))
10191 return true;
10192
10193 return false;
10194}
10195
10197
10198static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
10199 bool ReadOnly = Fwd->isReadOnly();
10200 bool WriteOnly = Fwd->isWriteOnly();
10201 assert(!(ReadOnly && WriteOnly));
10202 *Fwd = Resolved;
10203 if (ReadOnly)
10204 Fwd->setReadOnly();
10205 if (WriteOnly)
10206 Fwd->setWriteOnly();
10207}
10208
10209/// Stores the given Name/GUID and associated summary into the Index.
10210/// Also updates any forward references to the associated entry ID.
10211bool LLParser::addGlobalValueToIndex(
10212 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
10213 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
10214 // First create the ValueInfo utilizing the Name or GUID.
10215 ValueInfo VI;
10216 if (GUID != 0) {
10217 assert(Name.empty());
10218 VI = Index->getOrInsertValueInfo(GUID);
10219 } else {
10220 assert(!Name.empty());
10221 if (M) {
10222 auto *GV = M->getNamedValue(Name);
10223 if (!GV)
10224 return error(Loc, "Reference to undefined global \"" + Name + "\"");
10225
10226 // Be a little lenient here, to accomodate older files without GUIDs
10227 // already computed and assigned as metadata.
10228 GUID = GV->getGUIDOrFallback();
10229
10230 VI = Index->getOrInsertValueInfo(GV, GUID);
10231 } else {
10232 assert(
10233 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
10234 "Need a source_filename to compute GUID for local");
10236 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
10237 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
10238 }
10239 }
10240
10241 // Resolve forward references from calls/refs
10242 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
10243 if (FwdRefVIs != ForwardRefValueInfos.end()) {
10244 for (auto VIRef : FwdRefVIs->second) {
10245 assert(VIRef.first->getRef() == FwdVIRef &&
10246 "Forward referenced ValueInfo expected to be empty");
10247 resolveFwdRef(VIRef.first, VI);
10248 }
10249 ForwardRefValueInfos.erase(FwdRefVIs);
10250 }
10251
10252 // Resolve forward references from aliases
10253 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10254 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10255 for (auto AliaseeRef : FwdRefAliasees->second) {
10256 assert(!AliaseeRef.first->hasAliasee() &&
10257 "Forward referencing alias already has aliasee");
10258 assert(Summary && "Aliasee must be a definition");
10259 AliaseeRef.first->setAliasee(VI, Summary.get());
10260 }
10261 ForwardRefAliasees.erase(FwdRefAliasees);
10262 }
10263
10264 // Add the summary if one was provided.
10265 if (Summary)
10266 Index->addGlobalValueSummary(VI, std::move(Summary));
10267
10268 // Save the associated ValueInfo for use in later references by ID.
10269 if (ID == NumberedValueInfos.size())
10270 NumberedValueInfos.push_back(VI);
10271 else {
10272 // Handle non-continuous numbers (to make test simplification easier).
10273 if (ID > NumberedValueInfos.size())
10274 NumberedValueInfos.resize(ID + 1);
10275 NumberedValueInfos[ID] = VI;
10276 }
10277
10278 return false;
10279}
10280
10281/// parseSummaryIndexFlags
10282/// ::= 'flags' ':' UInt64
10283bool LLParser::parseSummaryIndexFlags() {
10284 assert(Lex.getKind() == lltok::kw_flags);
10285 Lex.Lex();
10286
10287 if (parseToken(lltok::colon, "expected ':' here"))
10288 return true;
10290 if (parseUInt64(Flags))
10291 return true;
10292 if (Index)
10293 Index->setFlags(Flags);
10294 return false;
10295}
10296
10297/// parseBlockCount
10298/// ::= 'blockcount' ':' UInt64
10299bool LLParser::parseBlockCount() {
10300 assert(Lex.getKind() == lltok::kw_blockcount);
10301 Lex.Lex();
10302
10303 if (parseToken(lltok::colon, "expected ':' here"))
10304 return true;
10305 uint64_t BlockCount;
10306 if (parseUInt64(BlockCount))
10307 return true;
10308 if (Index)
10309 Index->setBlockCount(BlockCount);
10310 return false;
10311}
10312
10313/// parseCfiFunctions
10314/// ::= ('cfiFunctionDefs' | 'cfiFunctionDecls') ':' '(' CfiFunction
10315/// [',' CfiFunction]* ')'
10316/// CfiFunction ::= '(' 'guid' ':' UInt64 ',' 'name' ':' STRINGCONSTANT ')'
10317bool LLParser::parseCfiFunctions() {
10318 assert(Lex.getKind() == lltok::kw_cfiFunctionDefs ||
10319 Lex.getKind() == lltok::kw_cfiFunctionDecls);
10320 CfiFunctionIndex &CfiIndex = Lex.getKind() == lltok::kw_cfiFunctionDefs
10321 ? Index->cfiFunctionDefs()
10322 : Index->cfiFunctionDecls();
10323 Lex.Lex();
10324
10325 if (parseToken(lltok::colon, "expected ':' here") ||
10326 parseToken(lltok::lparen, "expected '(' here"))
10327 return true;
10328
10329 do {
10331 std::string Name;
10332 if (parseToken(lltok::lparen, "expected '(' here") ||
10333 parseToken(lltok::kw_guid, "expected 'guid' here") ||
10334 parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID) ||
10335 parseToken(lltok::comma, "expected ',' here") ||
10336 parseToken(lltok::kw_name, "expected 'name' here") ||
10337 parseToken(lltok::colon, "expected ':' here") ||
10338 parseStringConstant(Name) ||
10339 parseToken(lltok::rparen, "expected ')' here"))
10340 return true;
10341 CfiIndex.addSymbolWithThinLTOGUID(Name, GUID);
10342 } while (EatIfPresent(lltok::comma));
10343
10344 return parseToken(lltok::rparen, "expected ')' here");
10345}
10346
10347/// parseGVEntry
10348/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
10349/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
10350/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
10351bool LLParser::parseGVEntry(unsigned ID) {
10352 assert(Lex.getKind() == lltok::kw_gv);
10353 Lex.Lex();
10354
10355 if (parseToken(lltok::colon, "expected ':' here") ||
10356 parseToken(lltok::lparen, "expected '(' here"))
10357 return true;
10358
10359 LocTy Loc = Lex.getLoc();
10360 std::string Name;
10362 switch (Lex.getKind()) {
10363 case lltok::kw_name:
10364 Lex.Lex();
10365 if (parseToken(lltok::colon, "expected ':' here") ||
10366 parseStringConstant(Name))
10367 return true;
10368 // Can't create GUID/ValueInfo until we have the linkage.
10369 break;
10370 case lltok::kw_guid:
10371 Lex.Lex();
10372 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
10373 return true;
10374 break;
10375 default:
10376 return error(Lex.getLoc(), "expected name or guid tag");
10377 }
10378
10379 if (!EatIfPresent(lltok::comma)) {
10380 // No summaries. Wrap up.
10381 if (parseToken(lltok::rparen, "expected ')' here"))
10382 return true;
10383 // This was created for a call to an external or indirect target.
10384 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
10385 // created for indirect calls with VP. A Name with no GUID came from
10386 // an external definition. We pass ExternalLinkage since that is only
10387 // used when the GUID must be computed from Name, and in that case
10388 // the symbol must have external linkage.
10389 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
10390 nullptr, Loc);
10391 }
10392
10393 // Have a list of summaries
10394 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
10395 parseToken(lltok::colon, "expected ':' here") ||
10396 parseToken(lltok::lparen, "expected '(' here"))
10397 return true;
10398 do {
10399 switch (Lex.getKind()) {
10400 case lltok::kw_function:
10401 if (parseFunctionSummary(Name, GUID, ID))
10402 return true;
10403 break;
10404 case lltok::kw_variable:
10405 if (parseVariableSummary(Name, GUID, ID))
10406 return true;
10407 break;
10408 case lltok::kw_alias:
10409 if (parseAliasSummary(Name, GUID, ID))
10410 return true;
10411 break;
10412 default:
10413 return error(Lex.getLoc(), "expected summary type");
10414 }
10415 } while (EatIfPresent(lltok::comma));
10416
10417 if (parseToken(lltok::rparen, "expected ')' here") ||
10418 parseToken(lltok::rparen, "expected ')' here"))
10419 return true;
10420
10421 return false;
10422}
10423
10424/// FunctionSummary
10425/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10426/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10427/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10428/// [',' OptionalRefs]? ')'
10429bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10430 unsigned ID) {
10431 LocTy Loc = Lex.getLoc();
10432 assert(Lex.getKind() == lltok::kw_function);
10433 Lex.Lex();
10434
10435 StringRef ModulePath;
10436 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10438 /*NotEligibleToImport=*/false,
10439 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10440 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10441 unsigned InstCount;
10443 FunctionSummary::TypeIdInfo TypeIdInfo;
10444 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10446 std::vector<CallsiteInfo> Callsites;
10447 std::vector<AllocInfo> Allocs;
10448 // Default is all-zeros (conservative values).
10449 FunctionSummary::FFlags FFlags = {};
10450 if (parseToken(lltok::colon, "expected ':' here") ||
10451 parseToken(lltok::lparen, "expected '(' here") ||
10452 parseModuleReference(ModulePath) ||
10453 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10454 parseToken(lltok::comma, "expected ',' here") ||
10455 parseToken(lltok::kw_insts, "expected 'insts' here") ||
10456 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
10457 return true;
10458
10459 // parse optional fields
10460 while (EatIfPresent(lltok::comma)) {
10461 switch (Lex.getKind()) {
10463 if (parseOptionalFFlags(FFlags))
10464 return true;
10465 break;
10466 case lltok::kw_calls:
10467 if (parseOptionalCalls(Calls))
10468 return true;
10469 break;
10471 if (parseOptionalTypeIdInfo(TypeIdInfo))
10472 return true;
10473 break;
10474 case lltok::kw_refs:
10475 if (parseOptionalRefs(Refs))
10476 return true;
10477 break;
10478 case lltok::kw_params:
10479 if (parseOptionalParamAccesses(ParamAccesses))
10480 return true;
10481 break;
10482 case lltok::kw_allocs:
10483 if (parseOptionalAllocs(Allocs))
10484 return true;
10485 break;
10487 if (parseOptionalCallsites(Callsites))
10488 return true;
10489 break;
10490 default:
10491 return error(Lex.getLoc(), "expected optional function summary field");
10492 }
10493 }
10494
10495 if (parseToken(lltok::rparen, "expected ')' here"))
10496 return true;
10497
10498 auto FS = std::make_unique<FunctionSummary>(
10499 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10500 std::move(TypeIdInfo.TypeTests),
10501 std::move(TypeIdInfo.TypeTestAssumeVCalls),
10502 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10503 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10504 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10505 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10506
10507 FS->setModulePath(ModulePath);
10508
10509 return addGlobalValueToIndex(Name, GUID,
10511 std::move(FS), Loc);
10512}
10513
10514/// VariableSummary
10515/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10516/// [',' OptionalRefs]? ')'
10517bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10518 unsigned ID) {
10519 LocTy Loc = Lex.getLoc();
10520 assert(Lex.getKind() == lltok::kw_variable);
10521 Lex.Lex();
10522
10523 StringRef ModulePath;
10524 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10526 /*NotEligibleToImport=*/false,
10527 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10528 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10529 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10530 /* WriteOnly */ false,
10531 /* Constant */ false,
10534 VTableFuncList VTableFuncs;
10535 if (parseToken(lltok::colon, "expected ':' here") ||
10536 parseToken(lltok::lparen, "expected '(' here") ||
10537 parseModuleReference(ModulePath) ||
10538 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10539 parseToken(lltok::comma, "expected ',' here") ||
10540 parseGVarFlags(GVarFlags))
10541 return true;
10542
10543 // parse optional fields
10544 while (EatIfPresent(lltok::comma)) {
10545 switch (Lex.getKind()) {
10547 if (parseOptionalVTableFuncs(VTableFuncs))
10548 return true;
10549 break;
10550 case lltok::kw_refs:
10551 if (parseOptionalRefs(Refs))
10552 return true;
10553 break;
10554 default:
10555 return error(Lex.getLoc(), "expected optional variable summary field");
10556 }
10557 }
10558
10559 if (parseToken(lltok::rparen, "expected ')' here"))
10560 return true;
10561
10562 auto GS =
10563 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10564
10565 GS->setModulePath(ModulePath);
10566 GS->setVTableFuncs(std::move(VTableFuncs));
10567
10568 return addGlobalValueToIndex(Name, GUID,
10570 std::move(GS), Loc);
10571}
10572
10573/// AliasSummary
10574/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10575/// 'aliasee' ':' GVReference ')'
10576bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10577 unsigned ID) {
10578 assert(Lex.getKind() == lltok::kw_alias);
10579 LocTy Loc = Lex.getLoc();
10580 Lex.Lex();
10581
10582 StringRef ModulePath;
10583 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10585 /*NotEligibleToImport=*/false,
10586 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10587 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10588 if (parseToken(lltok::colon, "expected ':' here") ||
10589 parseToken(lltok::lparen, "expected '(' here") ||
10590 parseModuleReference(ModulePath) ||
10591 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10592 parseToken(lltok::comma, "expected ',' here") ||
10593 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10594 parseToken(lltok::colon, "expected ':' here"))
10595 return true;
10596
10597 ValueInfo AliaseeVI;
10598 unsigned GVId;
10599 auto AS = std::make_unique<AliasSummary>(GVFlags);
10600 AS->setModulePath(ModulePath);
10601
10602 if (!EatIfPresent(lltok::kw_null)) {
10603 if (parseGVReference(AliaseeVI, GVId))
10604 return true;
10605
10606 // Record forward reference if the aliasee is not parsed yet.
10607 if (AliaseeVI.getRef() == FwdVIRef) {
10608 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10609 } else {
10610 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10611 assert(Summary && "Aliasee must be a definition");
10612 AS->setAliasee(AliaseeVI, Summary);
10613 }
10614 }
10615
10616 if (parseToken(lltok::rparen, "expected ')' here"))
10617 return true;
10618
10619 return addGlobalValueToIndex(Name, GUID,
10621 std::move(AS), Loc);
10622}
10623
10624/// Flag
10625/// ::= [0|1]
10626bool LLParser::parseFlag(unsigned &Val) {
10627 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10628 return tokError("expected integer");
10629 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10630 Lex.Lex();
10631 return false;
10632}
10633
10634/// OptionalFFlags
10635/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10636/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10637/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10638/// [',' 'noInline' ':' Flag]? ')'
10639/// [',' 'alwaysInline' ':' Flag]? ')'
10640/// [',' 'noUnwind' ':' Flag]? ')'
10641/// [',' 'mayThrow' ':' Flag]? ')'
10642/// [',' 'hasUnknownCall' ':' Flag]? ')'
10643/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10644
10645bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10646 assert(Lex.getKind() == lltok::kw_funcFlags);
10647 Lex.Lex();
10648
10649 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10650 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10651 return true;
10652
10653 do {
10654 unsigned Val = 0;
10655 switch (Lex.getKind()) {
10656 case lltok::kw_readNone:
10657 Lex.Lex();
10658 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10659 return true;
10660 FFlags.ReadNone = Val;
10661 break;
10662 case lltok::kw_readOnly:
10663 Lex.Lex();
10664 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10665 return true;
10666 FFlags.ReadOnly = Val;
10667 break;
10669 Lex.Lex();
10670 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10671 return true;
10672 FFlags.NoRecurse = Val;
10673 break;
10675 Lex.Lex();
10676 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10677 return true;
10678 FFlags.ReturnDoesNotAlias = Val;
10679 break;
10680 case lltok::kw_noInline:
10681 Lex.Lex();
10682 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10683 return true;
10684 FFlags.NoInline = Val;
10685 break;
10687 Lex.Lex();
10688 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10689 return true;
10690 FFlags.AlwaysInline = Val;
10691 break;
10692 case lltok::kw_noUnwind:
10693 Lex.Lex();
10694 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10695 return true;
10696 FFlags.NoUnwind = Val;
10697 break;
10698 case lltok::kw_mayThrow:
10699 Lex.Lex();
10700 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10701 return true;
10702 FFlags.MayThrow = Val;
10703 break;
10705 Lex.Lex();
10706 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10707 return true;
10708 FFlags.HasUnknownCall = Val;
10709 break;
10711 Lex.Lex();
10712 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10713 return true;
10714 FFlags.MustBeUnreachable = Val;
10715 break;
10716 default:
10717 return error(Lex.getLoc(), "expected function flag type");
10718 }
10719 } while (EatIfPresent(lltok::comma));
10720
10721 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10722 return true;
10723
10724 return false;
10725}
10726
10727/// OptionalCalls
10728/// := 'calls' ':' '(' Call [',' Call]* ')'
10729/// Call ::= '(' 'callee' ':' GVReference
10730/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10731/// [ ',' 'tail' ]? ')'
10732bool LLParser::parseOptionalCalls(
10733 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10734 assert(Lex.getKind() == lltok::kw_calls);
10735 Lex.Lex();
10736
10737 if (parseToken(lltok::colon, "expected ':' in calls") ||
10738 parseToken(lltok::lparen, "expected '(' in calls"))
10739 return true;
10740
10741 IdToIndexMapType IdToIndexMap;
10742 // parse each call edge
10743 do {
10744 ValueInfo VI;
10745 if (parseToken(lltok::lparen, "expected '(' in call") ||
10746 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10747 parseToken(lltok::colon, "expected ':'"))
10748 return true;
10749
10750 LocTy Loc = Lex.getLoc();
10751 unsigned GVId;
10752 if (parseGVReference(VI, GVId))
10753 return true;
10754
10756 unsigned RelBF = 0;
10757 unsigned HasTailCall = false;
10758 unsigned HasIndirectCall = false;
10759
10760 // parse optional fields
10761 while (EatIfPresent(lltok::comma)) {
10762 switch (Lex.getKind()) {
10763 case lltok::kw_hotness:
10764 Lex.Lex();
10765 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10766 return true;
10767 break;
10768 // Deprecated, keep in order to support old files.
10769 case lltok::kw_relbf:
10770 Lex.Lex();
10771 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10772 return true;
10773 break;
10774 case lltok::kw_tail:
10775 Lex.Lex();
10776 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10777 return true;
10778 break;
10779 case lltok::kw_indirect:
10780 Lex.Lex();
10781 if (parseToken(lltok::colon, "expected ':'") ||
10782 parseFlag(HasIndirectCall))
10783 return true;
10784 break;
10785 default:
10786 return error(Lex.getLoc(),
10787 "expected hotness, relbf, tail, or indirect");
10788 }
10789 }
10790 // Keep track of the Call array index needing a forward reference.
10791 // We will save the location of the ValueInfo needing an update, but
10792 // can only do so once the std::vector is finalized.
10793 if (VI.getRef() == FwdVIRef)
10794 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10796 VI, CalleeInfo(Hotness, HasTailCall, HasIndirectCall)});
10797
10798 if (parseToken(lltok::rparen, "expected ')' in call"))
10799 return true;
10800 } while (EatIfPresent(lltok::comma));
10801
10802 // Now that the Calls vector is finalized, it is safe to save the locations
10803 // of any forward GV references that need updating later.
10804 for (auto I : IdToIndexMap) {
10805 auto &Infos = ForwardRefValueInfos[I.first];
10806 for (auto P : I.second) {
10807 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10808 "Forward referenced ValueInfo expected to be empty");
10809 Infos.emplace_back(&Calls[P.first].first, P.second);
10810 }
10811 }
10812
10813 if (parseToken(lltok::rparen, "expected ')' in calls"))
10814 return true;
10815
10816 return false;
10817}
10818
10819/// Hotness
10820/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10821bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10822 switch (Lex.getKind()) {
10823 case lltok::kw_unknown:
10825 break;
10826 case lltok::kw_cold:
10828 break;
10829 case lltok::kw_none:
10831 break;
10832 case lltok::kw_hot:
10834 break;
10835 case lltok::kw_critical:
10837 break;
10838 default:
10839 return error(Lex.getLoc(), "invalid call edge hotness");
10840 }
10841 Lex.Lex();
10842 return false;
10843}
10844
10845/// OptionalVTableFuncs
10846/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10847/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10848bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10849 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10850 Lex.Lex();
10851
10852 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10853 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10854 return true;
10855
10856 IdToIndexMapType IdToIndexMap;
10857 // parse each virtual function pair
10858 do {
10859 ValueInfo VI;
10860 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10861 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10862 parseToken(lltok::colon, "expected ':'"))
10863 return true;
10864
10865 LocTy Loc = Lex.getLoc();
10866 unsigned GVId;
10867 if (parseGVReference(VI, GVId))
10868 return true;
10869
10871 if (parseToken(lltok::comma, "expected comma") ||
10872 parseToken(lltok::kw_offset, "expected offset") ||
10873 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10874 return true;
10875
10876 // Keep track of the VTableFuncs array index needing a forward reference.
10877 // We will save the location of the ValueInfo needing an update, but
10878 // can only do so once the std::vector is finalized.
10879 if (VI == EmptyVI)
10880 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10881 VTableFuncs.push_back({VI, Offset});
10882
10883 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10884 return true;
10885 } while (EatIfPresent(lltok::comma));
10886
10887 // Now that the VTableFuncs vector is finalized, it is safe to save the
10888 // locations of any forward GV references that need updating later.
10889 for (auto I : IdToIndexMap) {
10890 auto &Infos = ForwardRefValueInfos[I.first];
10891 for (auto P : I.second) {
10892 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10893 "Forward referenced ValueInfo expected to be empty");
10894 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10895 }
10896 }
10897
10898 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10899 return true;
10900
10901 return false;
10902}
10903
10904/// ParamNo := 'param' ':' UInt64
10905bool LLParser::parseParamNo(uint64_t &ParamNo) {
10906 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10907 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10908 return true;
10909 return false;
10910}
10911
10912/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10913bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10914 APSInt Lower;
10915 APSInt Upper;
10916 auto ParseAPSInt = [&](APSInt &Val) {
10917 if (Lex.getKind() != lltok::APSInt)
10918 return tokError("expected integer");
10919 Val = Lex.getAPSIntVal();
10920 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10921 Val.setIsSigned(true);
10922 Lex.Lex();
10923 return false;
10924 };
10925 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10926 parseToken(lltok::colon, "expected ':' here") ||
10927 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10928 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10929 parseToken(lltok::rsquare, "expected ']' here"))
10930 return true;
10931
10932 ++Upper;
10933 Range =
10934 (Lower == Upper && !Lower.isMaxValue())
10935 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10936 : ConstantRange(Lower, Upper);
10937
10938 return false;
10939}
10940
10941/// ParamAccessCall
10942/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10943bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10944 IdLocListType &IdLocList) {
10945 if (parseToken(lltok::lparen, "expected '(' here") ||
10946 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10947 parseToken(lltok::colon, "expected ':' here"))
10948 return true;
10949
10950 unsigned GVId;
10951 ValueInfo VI;
10952 LocTy Loc = Lex.getLoc();
10953 if (parseGVReference(VI, GVId))
10954 return true;
10955
10956 Call.Callee = VI;
10957 IdLocList.emplace_back(GVId, Loc);
10958
10959 if (parseToken(lltok::comma, "expected ',' here") ||
10960 parseParamNo(Call.ParamNo) ||
10961 parseToken(lltok::comma, "expected ',' here") ||
10962 parseParamAccessOffset(Call.Offsets))
10963 return true;
10964
10965 if (parseToken(lltok::rparen, "expected ')' here"))
10966 return true;
10967
10968 return false;
10969}
10970
10971/// ParamAccess
10972/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10973/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10974bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10975 IdLocListType &IdLocList) {
10976 if (parseToken(lltok::lparen, "expected '(' here") ||
10977 parseParamNo(Param.ParamNo) ||
10978 parseToken(lltok::comma, "expected ',' here") ||
10979 parseParamAccessOffset(Param.Use))
10980 return true;
10981
10982 if (EatIfPresent(lltok::comma)) {
10983 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10984 parseToken(lltok::colon, "expected ':' here") ||
10985 parseToken(lltok::lparen, "expected '(' here"))
10986 return true;
10987 do {
10988 FunctionSummary::ParamAccess::Call Call;
10989 if (parseParamAccessCall(Call, IdLocList))
10990 return true;
10991 Param.Calls.push_back(Call);
10992 } while (EatIfPresent(lltok::comma));
10993
10994 if (parseToken(lltok::rparen, "expected ')' here"))
10995 return true;
10996 }
10997
10998 if (parseToken(lltok::rparen, "expected ')' here"))
10999 return true;
11000
11001 return false;
11002}
11003
11004/// OptionalParamAccesses
11005/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
11006bool LLParser::parseOptionalParamAccesses(
11007 std::vector<FunctionSummary::ParamAccess> &Params) {
11008 assert(Lex.getKind() == lltok::kw_params);
11009 Lex.Lex();
11010
11011 if (parseToken(lltok::colon, "expected ':' here") ||
11012 parseToken(lltok::lparen, "expected '(' here"))
11013 return true;
11014
11015 IdLocListType VContexts;
11016 size_t CallsNum = 0;
11017 do {
11018 FunctionSummary::ParamAccess ParamAccess;
11019 if (parseParamAccess(ParamAccess, VContexts))
11020 return true;
11021 CallsNum += ParamAccess.Calls.size();
11022 assert(VContexts.size() == CallsNum);
11023 (void)CallsNum;
11024 Params.emplace_back(std::move(ParamAccess));
11025 } while (EatIfPresent(lltok::comma));
11026
11027 if (parseToken(lltok::rparen, "expected ')' here"))
11028 return true;
11029
11030 // Now that the Params is finalized, it is safe to save the locations
11031 // of any forward GV references that need updating later.
11032 IdLocListType::const_iterator ItContext = VContexts.begin();
11033 for (auto &PA : Params) {
11034 for (auto &C : PA.Calls) {
11035 if (C.Callee.getRef() == FwdVIRef)
11036 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
11037 ItContext->second);
11038 ++ItContext;
11039 }
11040 }
11041 assert(ItContext == VContexts.end());
11042
11043 return false;
11044}
11045
11046/// OptionalRefs
11047/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
11048bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
11049 assert(Lex.getKind() == lltok::kw_refs);
11050 Lex.Lex();
11051
11052 if (parseToken(lltok::colon, "expected ':' in refs") ||
11053 parseToken(lltok::lparen, "expected '(' in refs"))
11054 return true;
11055
11056 struct ValueContext {
11057 ValueInfo VI;
11058 unsigned GVId;
11059 LocTy Loc;
11060 };
11061 std::vector<ValueContext> VContexts;
11062 // parse each ref edge
11063 do {
11064 ValueContext VC;
11065 VC.Loc = Lex.getLoc();
11066 if (parseGVReference(VC.VI, VC.GVId))
11067 return true;
11068 VContexts.push_back(VC);
11069 } while (EatIfPresent(lltok::comma));
11070
11071 // Sort value contexts so that ones with writeonly
11072 // and readonly ValueInfo are at the end of VContexts vector.
11073 // See FunctionSummary::specialRefCounts()
11074 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
11075 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
11076 });
11077
11078 IdToIndexMapType IdToIndexMap;
11079 for (auto &VC : VContexts) {
11080 // Keep track of the Refs array index needing a forward reference.
11081 // We will save the location of the ValueInfo needing an update, but
11082 // can only do so once the std::vector is finalized.
11083 if (VC.VI.getRef() == FwdVIRef)
11084 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
11085 Refs.push_back(VC.VI);
11086 }
11087
11088 // Now that the Refs vector is finalized, it is safe to save the locations
11089 // of any forward GV references that need updating later.
11090 for (auto I : IdToIndexMap) {
11091 auto &Infos = ForwardRefValueInfos[I.first];
11092 for (auto P : I.second) {
11093 assert(Refs[P.first].getRef() == FwdVIRef &&
11094 "Forward referenced ValueInfo expected to be empty");
11095 Infos.emplace_back(&Refs[P.first], P.second);
11096 }
11097 }
11098
11099 if (parseToken(lltok::rparen, "expected ')' in refs"))
11100 return true;
11101
11102 return false;
11103}
11104
11105/// OptionalTypeIdInfo
11106/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
11107/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
11108/// [',' TypeCheckedLoadConstVCalls]? ')'
11109bool LLParser::parseOptionalTypeIdInfo(
11110 FunctionSummary::TypeIdInfo &TypeIdInfo) {
11111 assert(Lex.getKind() == lltok::kw_typeIdInfo);
11112 Lex.Lex();
11113
11114 if (parseToken(lltok::colon, "expected ':' here") ||
11115 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
11116 return true;
11117
11118 do {
11119 switch (Lex.getKind()) {
11121 if (parseTypeTests(TypeIdInfo.TypeTests))
11122 return true;
11123 break;
11125 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
11126 TypeIdInfo.TypeTestAssumeVCalls))
11127 return true;
11128 break;
11130 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
11131 TypeIdInfo.TypeCheckedLoadVCalls))
11132 return true;
11133 break;
11135 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
11136 TypeIdInfo.TypeTestAssumeConstVCalls))
11137 return true;
11138 break;
11140 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
11141 TypeIdInfo.TypeCheckedLoadConstVCalls))
11142 return true;
11143 break;
11144 default:
11145 return error(Lex.getLoc(), "invalid typeIdInfo list type");
11146 }
11147 } while (EatIfPresent(lltok::comma));
11148
11149 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
11150 return true;
11151
11152 return false;
11153}
11154
11155/// TypeTests
11156/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
11157/// [',' (SummaryID | UInt64)]* ')'
11158bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
11159 assert(Lex.getKind() == lltok::kw_typeTests);
11160 Lex.Lex();
11161
11162 if (parseToken(lltok::colon, "expected ':' here") ||
11163 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
11164 return true;
11165
11166 IdToIndexMapType IdToIndexMap;
11167 do {
11169 if (Lex.getKind() == lltok::SummaryID) {
11170 unsigned ID = Lex.getUIntVal();
11171 LocTy Loc = Lex.getLoc();
11172 // Keep track of the TypeTests array index needing a forward reference.
11173 // We will save the location of the GUID needing an update, but
11174 // can only do so once the std::vector is finalized.
11175 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
11176 Lex.Lex();
11177 } else if (parseUInt64(GUID))
11178 return true;
11179 TypeTests.push_back(GUID);
11180 } while (EatIfPresent(lltok::comma));
11181
11182 // Now that the TypeTests vector is finalized, it is safe to save the
11183 // locations of any forward GV references that need updating later.
11184 for (auto I : IdToIndexMap) {
11185 auto &Ids = ForwardRefTypeIds[I.first];
11186 for (auto P : I.second) {
11187 assert(TypeTests[P.first] == 0 &&
11188 "Forward referenced type id GUID expected to be 0");
11189 Ids.emplace_back(&TypeTests[P.first], P.second);
11190 }
11191 }
11192
11193 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
11194 return true;
11195
11196 return false;
11197}
11198
11199/// VFuncIdList
11200/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
11201bool LLParser::parseVFuncIdList(
11202 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
11203 assert(Lex.getKind() == Kind);
11204 Lex.Lex();
11205
11206 if (parseToken(lltok::colon, "expected ':' here") ||
11207 parseToken(lltok::lparen, "expected '(' here"))
11208 return true;
11209
11210 IdToIndexMapType IdToIndexMap;
11211 do {
11212 FunctionSummary::VFuncId VFuncId;
11213 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
11214 return true;
11215 VFuncIdList.push_back(VFuncId);
11216 } while (EatIfPresent(lltok::comma));
11217
11218 if (parseToken(lltok::rparen, "expected ')' here"))
11219 return true;
11220
11221 // Now that the VFuncIdList vector is finalized, it is safe to save the
11222 // locations of any forward GV references that need updating later.
11223 for (auto I : IdToIndexMap) {
11224 auto &Ids = ForwardRefTypeIds[I.first];
11225 for (auto P : I.second) {
11226 assert(VFuncIdList[P.first].GUID == 0 &&
11227 "Forward referenced type id GUID expected to be 0");
11228 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
11229 }
11230 }
11231
11232 return false;
11233}
11234
11235/// ConstVCallList
11236/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
11237bool LLParser::parseConstVCallList(
11238 lltok::Kind Kind,
11239 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
11240 assert(Lex.getKind() == Kind);
11241 Lex.Lex();
11242
11243 if (parseToken(lltok::colon, "expected ':' here") ||
11244 parseToken(lltok::lparen, "expected '(' here"))
11245 return true;
11246
11247 IdToIndexMapType IdToIndexMap;
11248 do {
11249 FunctionSummary::ConstVCall ConstVCall;
11250 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
11251 return true;
11252 ConstVCallList.push_back(ConstVCall);
11253 } while (EatIfPresent(lltok::comma));
11254
11255 if (parseToken(lltok::rparen, "expected ')' here"))
11256 return true;
11257
11258 // Now that the ConstVCallList vector is finalized, it is safe to save the
11259 // locations of any forward GV references that need updating later.
11260 for (auto I : IdToIndexMap) {
11261 auto &Ids = ForwardRefTypeIds[I.first];
11262 for (auto P : I.second) {
11263 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
11264 "Forward referenced type id GUID expected to be 0");
11265 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
11266 }
11267 }
11268
11269 return false;
11270}
11271
11272/// ConstVCall
11273/// ::= '(' VFuncId ',' Args ')'
11274bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
11275 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11276 if (parseToken(lltok::lparen, "expected '(' here") ||
11277 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
11278 return true;
11279
11280 if (EatIfPresent(lltok::comma))
11281 if (parseArgs(ConstVCall.Args))
11282 return true;
11283
11284 if (parseToken(lltok::rparen, "expected ')' here"))
11285 return true;
11286
11287 return false;
11288}
11289
11290/// VFuncId
11291/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
11292/// 'offset' ':' UInt64 ')'
11293bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11294 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11295 assert(Lex.getKind() == lltok::kw_vFuncId);
11296 Lex.Lex();
11297
11298 if (parseToken(lltok::colon, "expected ':' here") ||
11299 parseToken(lltok::lparen, "expected '(' here"))
11300 return true;
11301
11302 if (Lex.getKind() == lltok::SummaryID) {
11303 VFuncId.GUID = 0;
11304 unsigned ID = Lex.getUIntVal();
11305 LocTy Loc = Lex.getLoc();
11306 // Keep track of the array index needing a forward reference.
11307 // We will save the location of the GUID needing an update, but
11308 // can only do so once the caller's std::vector is finalized.
11309 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
11310 Lex.Lex();
11311 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
11312 parseToken(lltok::colon, "expected ':' here") ||
11313 parseUInt64(VFuncId.GUID))
11314 return true;
11315
11316 if (parseToken(lltok::comma, "expected ',' here") ||
11317 parseToken(lltok::kw_offset, "expected 'offset' here") ||
11318 parseToken(lltok::colon, "expected ':' here") ||
11319 parseUInt64(VFuncId.Offset) ||
11320 parseToken(lltok::rparen, "expected ')' here"))
11321 return true;
11322
11323 return false;
11324}
11325
11326/// GVFlags
11327/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
11328/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
11329/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
11330/// 'canAutoHide' ':' Flag ',' ')'
11331bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11332 assert(Lex.getKind() == lltok::kw_flags);
11333 Lex.Lex();
11334
11335 if (parseToken(lltok::colon, "expected ':' here") ||
11336 parseToken(lltok::lparen, "expected '(' here"))
11337 return true;
11338
11339 do {
11340 unsigned Flag = 0;
11341 switch (Lex.getKind()) {
11342 case lltok::kw_linkage:
11343 Lex.Lex();
11344 if (parseToken(lltok::colon, "expected ':'"))
11345 return true;
11346 bool HasLinkage;
11347 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
11348 assert(HasLinkage && "Linkage not optional in summary entry");
11349 Lex.Lex();
11350 break;
11352 Lex.Lex();
11353 if (parseToken(lltok::colon, "expected ':'"))
11354 return true;
11355 parseOptionalVisibility(Flag);
11356 GVFlags.Visibility = Flag;
11357 break;
11359 Lex.Lex();
11360 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11361 return true;
11362 GVFlags.NotEligibleToImport = Flag;
11363 break;
11364 case lltok::kw_live:
11365 Lex.Lex();
11366 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11367 return true;
11368 GVFlags.Live = Flag;
11369 break;
11370 case lltok::kw_dsoLocal:
11371 Lex.Lex();
11372 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11373 return true;
11374 GVFlags.DSOLocal = Flag;
11375 break;
11377 Lex.Lex();
11378 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11379 return true;
11380 GVFlags.CanAutoHide = Flag;
11381 break;
11383 Lex.Lex();
11384 if (parseToken(lltok::colon, "expected ':'"))
11385 return true;
11387 if (parseOptionalImportType(Lex.getKind(), IK))
11388 return true;
11389 GVFlags.ImportType = static_cast<unsigned>(IK);
11390 Lex.Lex();
11391 break;
11393 Lex.Lex();
11394 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11395 return true;
11396 GVFlags.NoRenameOnPromotion = Flag;
11397 break;
11398 default:
11399 return error(Lex.getLoc(), "expected gv flag type");
11400 }
11401 } while (EatIfPresent(lltok::comma));
11402
11403 if (parseToken(lltok::rparen, "expected ')' here"))
11404 return true;
11405
11406 return false;
11407}
11408
11409/// GVarFlags
11410/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
11411/// ',' 'writeonly' ':' Flag
11412/// ',' 'constant' ':' Flag ')'
11413bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11414 assert(Lex.getKind() == lltok::kw_varFlags);
11415 Lex.Lex();
11416
11417 if (parseToken(lltok::colon, "expected ':' here") ||
11418 parseToken(lltok::lparen, "expected '(' here"))
11419 return true;
11420
11421 auto ParseRest = [this](unsigned int &Val) {
11422 Lex.Lex();
11423 if (parseToken(lltok::colon, "expected ':'"))
11424 return true;
11425 return parseFlag(Val);
11426 };
11427
11428 do {
11429 unsigned Flag = 0;
11430 switch (Lex.getKind()) {
11431 case lltok::kw_readonly:
11432 if (ParseRest(Flag))
11433 return true;
11434 GVarFlags.MaybeReadOnly = Flag;
11435 break;
11436 case lltok::kw_writeonly:
11437 if (ParseRest(Flag))
11438 return true;
11439 GVarFlags.MaybeWriteOnly = Flag;
11440 break;
11441 case lltok::kw_constant:
11442 if (ParseRest(Flag))
11443 return true;
11444 GVarFlags.Constant = Flag;
11445 break;
11447 if (ParseRest(Flag))
11448 return true;
11449 GVarFlags.VCallVisibility = Flag;
11450 break;
11451 default:
11452 return error(Lex.getLoc(), "expected gvar flag type");
11453 }
11454 } while (EatIfPresent(lltok::comma));
11455 return parseToken(lltok::rparen, "expected ')' here");
11456}
11457
11458/// ModuleReference
11459/// ::= 'module' ':' UInt
11460bool LLParser::parseModuleReference(StringRef &ModulePath) {
11461 // parse module id.
11462 if (parseToken(lltok::kw_module, "expected 'module' here") ||
11463 parseToken(lltok::colon, "expected ':' here") ||
11464 parseToken(lltok::SummaryID, "expected module ID"))
11465 return true;
11466
11467 unsigned ModuleID = Lex.getUIntVal();
11468 auto I = ModuleIdMap.find(ModuleID);
11469 // We should have already parsed all module IDs
11470 assert(I != ModuleIdMap.end());
11471 ModulePath = I->second;
11472 return false;
11473}
11474
11475/// GVReference
11476/// ::= SummaryID
11477bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11478 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
11479 if (!ReadOnly)
11480 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11481 if (parseToken(lltok::SummaryID, "expected GV ID"))
11482 return true;
11483
11484 GVId = Lex.getUIntVal();
11485 // Check if we already have a VI for this GV
11486 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11487 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11488 VI = NumberedValueInfos[GVId];
11489 } else
11490 // We will create a forward reference to the stored location.
11491 VI = ValueInfo(false, FwdVIRef);
11492
11493 if (ReadOnly)
11494 VI.setReadOnly();
11495 if (WriteOnly)
11496 VI.setWriteOnly();
11497 return false;
11498}
11499
11500/// OptionalAllocs
11501/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11502/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11503/// ',' MemProfs ')'
11504/// Version ::= UInt32
11505bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11506 assert(Lex.getKind() == lltok::kw_allocs);
11507 Lex.Lex();
11508
11509 if (parseToken(lltok::colon, "expected ':' in allocs") ||
11510 parseToken(lltok::lparen, "expected '(' in allocs"))
11511 return true;
11512
11513 // parse each alloc
11514 do {
11515 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
11516 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
11517 parseToken(lltok::colon, "expected ':'") ||
11518 parseToken(lltok::lparen, "expected '(' in versions"))
11519 return true;
11520
11521 SmallVector<uint8_t> Versions;
11522 do {
11523 uint8_t V = 0;
11524 if (parseAllocType(V))
11525 return true;
11526 Versions.push_back(V);
11527 } while (EatIfPresent(lltok::comma));
11528
11529 if (parseToken(lltok::rparen, "expected ')' in versions") ||
11530 parseToken(lltok::comma, "expected ',' in alloc"))
11531 return true;
11532
11533 std::vector<MIBInfo> MIBs;
11534 if (parseMemProfs(MIBs))
11535 return true;
11536
11537 Allocs.push_back({Versions, MIBs});
11538
11539 if (parseToken(lltok::rparen, "expected ')' in alloc"))
11540 return true;
11541 } while (EatIfPresent(lltok::comma));
11542
11543 if (parseToken(lltok::rparen, "expected ')' in allocs"))
11544 return true;
11545
11546 return false;
11547}
11548
11549/// MemProfs
11550/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11551/// MemProf ::= '(' 'type' ':' AllocType
11552/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11553/// StackId ::= UInt64
11554bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11555 assert(Lex.getKind() == lltok::kw_memProf);
11556 Lex.Lex();
11557
11558 if (parseToken(lltok::colon, "expected ':' in memprof") ||
11559 parseToken(lltok::lparen, "expected '(' in memprof"))
11560 return true;
11561
11562 // parse each MIB
11563 do {
11564 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
11565 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
11566 parseToken(lltok::colon, "expected ':'"))
11567 return true;
11568
11569 uint8_t AllocType;
11570 if (parseAllocType(AllocType))
11571 return true;
11572
11573 if (parseToken(lltok::comma, "expected ',' in memprof") ||
11574 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
11575 parseToken(lltok::colon, "expected ':'") ||
11576 parseToken(lltok::lparen, "expected '(' in stackIds"))
11577 return true;
11578
11579 SmallVector<unsigned> StackIdIndices;
11580 // Combined index alloc records may not have a stack id list.
11581 if (Lex.getKind() != lltok::rparen) {
11582 do {
11583 uint64_t StackId = 0;
11584 if (parseUInt64(StackId))
11585 return true;
11586 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11587 } while (EatIfPresent(lltok::comma));
11588 }
11589
11590 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11591 return true;
11592
11593 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11594
11595 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11596 return true;
11597 } while (EatIfPresent(lltok::comma));
11598
11599 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11600 return true;
11601
11602 return false;
11603}
11604
11605/// AllocType
11606/// := ('none'|'notcold'|'cold'|'hot'|'ambiguous')
11607bool LLParser::parseAllocType(uint8_t &AllocType) {
11608 switch (Lex.getKind()) {
11609 case lltok::kw_none:
11611 break;
11612 case lltok::kw_notcold:
11614 break;
11616 // Both not cold and cold: the contexts reaching the allocation could not
11617 // be disambiguated.
11618 AllocType =
11620 break;
11621 case lltok::kw_cold:
11623 break;
11624 case lltok::kw_hot:
11625 AllocType = (uint8_t)AllocationType::Hot;
11626 break;
11627 default:
11628 return error(Lex.getLoc(), "invalid alloc type");
11629 }
11630 Lex.Lex();
11631 return false;
11632}
11633
11634/// OptionalCallsites
11635/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11636/// Callsite ::= '(' 'callee' ':' GVReference
11637/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11638/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11639/// Version ::= UInt32
11640/// StackId ::= UInt64
11641bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11642 assert(Lex.getKind() == lltok::kw_callsites);
11643 Lex.Lex();
11644
11645 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11646 parseToken(lltok::lparen, "expected '(' in callsites"))
11647 return true;
11648
11649 IdToIndexMapType IdToIndexMap;
11650 // parse each callsite
11651 do {
11652 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11653 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11654 parseToken(lltok::colon, "expected ':'"))
11655 return true;
11656
11657 ValueInfo VI;
11658 unsigned GVId = 0;
11659 LocTy Loc = Lex.getLoc();
11660 if (!EatIfPresent(lltok::kw_null)) {
11661 if (parseGVReference(VI, GVId))
11662 return true;
11663 }
11664
11665 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11666 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11667 parseToken(lltok::colon, "expected ':'") ||
11668 parseToken(lltok::lparen, "expected '(' in clones"))
11669 return true;
11670
11671 SmallVector<unsigned> Clones;
11672 do {
11673 unsigned V = 0;
11674 if (parseUInt32(V))
11675 return true;
11676 Clones.push_back(V);
11677 } while (EatIfPresent(lltok::comma));
11678
11679 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11680 parseToken(lltok::comma, "expected ',' in callsite") ||
11681 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11682 parseToken(lltok::colon, "expected ':'") ||
11683 parseToken(lltok::lparen, "expected '(' in stackIds"))
11684 return true;
11685
11686 SmallVector<unsigned> StackIdIndices;
11687 // Synthesized callsite records will not have a stack id list.
11688 if (Lex.getKind() != lltok::rparen) {
11689 do {
11690 uint64_t StackId = 0;
11691 if (parseUInt64(StackId))
11692 return true;
11693 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11694 } while (EatIfPresent(lltok::comma));
11695 }
11696
11697 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11698 return true;
11699
11700 // Keep track of the Callsites array index needing a forward reference.
11701 // We will save the location of the ValueInfo needing an update, but
11702 // can only do so once the SmallVector is finalized.
11703 if (VI.getRef() == FwdVIRef)
11704 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11705 Callsites.push_back({VI, Clones, StackIdIndices});
11706
11707 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11708 return true;
11709 } while (EatIfPresent(lltok::comma));
11710
11711 // Now that the Callsites vector is finalized, it is safe to save the
11712 // locations of any forward GV references that need updating later.
11713 for (auto I : IdToIndexMap) {
11714 auto &Infos = ForwardRefValueInfos[I.first];
11715 for (auto P : I.second) {
11716 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11717 "Forward referenced ValueInfo expected to be empty");
11718 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11719 }
11720 }
11721
11722 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11723 return true;
11724
11725 return false;
11726}
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:77
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:235
#define PARSE_MD_FIELDS()
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
static ValueInfo EmptyVI
#define GET_OR_DISTINCT(CLASS, ARGS)
bool isOldDbgFormatIntrinsic(StringRef Name)
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
static std::string getTypeString(Type *T)
Definition LLParser.cpp:68
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
static const auto FwdVIRef
static bool isAtomic(MachineBasicBlock::iterator I)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
Type::TypeID TypeID
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
if(PassOpts->AAPipeline)
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
SmallVector< MachineOperand, 4 > Cond
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:674
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:306
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:396
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:146
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:126
@ None
No attributes have been set.
Definition Attributes.h:128
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI 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:692
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:749
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:660
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
LocTy getLoc() const
Definition LLLexer.h:71
LLVM_ABI bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:170
LLLexer::LocTy LocTy
Definition LLParser.h:110
LLVMContext & getContext()
Definition LLParser.h:235
LLVM_ABI bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:154
LLVM_ABI bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:141
LLVM_ABI bool parseMetadataDefinitions(SlotMapping &Slots, ArrayRef< SMLoc > DefinitionEnds)
Definition LLParser.cpp:185
LLVM_ABI bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:122
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
Metadata node.
Definition Metadata.h: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.
@ 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)
@ 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:192
@ kw_cxx_fast_tlscc
Definition LLToken.h:174
@ kw_extractvalue
Definition LLToken.h:378
@ kw_dso_preemptable
Definition LLToken.h:51
@ DwarfVirtuality
Definition LLToken.h:520
@ DwarfLangDialect
Definition LLToken.h:523
@ 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:226
@ kw_mustBeUnreachable
Definition LLToken.h:428
@ kw_internal
Definition LLToken.h:54
@ kw_wasm_emscripten_invokecc
Definition LLToken.h:189
@ kw_target_mem
Definition LLToken.h:212
@ kw_no_sanitize_hwaddress
Definition LLToken.h:499
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:468
@ kw_canAutoHide
Definition LLToken.h:411
@ kw_alwaysInline
Definition LLToken.h:424
@ kw_insertelement
Definition LLToken.h:375
@ kw_linkonce
Definition LLToken.h:55
@ kw_cheriot_librarycallcc
Definition LLToken.h:195
@ kw_fmaximumnum
Definition LLToken.h:297
@ kw_inaccessiblememonly
Definition LLToken.h:219
@ kw_amdgpu_gfx
Definition LLToken.h:185
@ kw_getelementptr
Definition LLToken.h:372
@ FloatHexLiteral
Definition LLToken.h:540
@ kw_m68k_rtdcc
Definition LLToken.h:188
@ kw_preserve_nonecc
Definition LLToken.h:169
@ kw_x86_fastcallcc
Definition LLToken.h:143
@ kw_visibility
Definition LLToken.h:407
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:194
@ kw_positivezero
Definition LLToken.h:232
@ kw_unordered
Definition LLToken.h:96
@ kw_singleImpl
Definition LLToken.h:471
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:141
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:448
@ kw_aarch64_sve_vector_pcs
Definition LLToken.h:151
@ kw_amdgpu_kernel
Definition LLToken.h:184
@ kw_uselistorder
Definition LLToken.h:393
@ kw_blockcount
Definition LLToken.h:403
@ kw_notEligibleToImport
Definition LLToken.h:408
@ kw_linkonce_odr
Definition LLToken.h:56
@ kw_protected
Definition LLToken.h:66
@ kw_cfiFunctionDecls
Definition LLToken.h:405
@ kw_dllexport
Definition LLToken.h:61
@ kw_x86_vectorcallcc
Definition LLToken.h:145
@ kw_ptx_device
Definition LLToken.h:159
@ kw_personality
Definition LLToken.h:347
@ DwarfEnumKind
Definition LLToken.h:534
@ kw_declaration
Definition LLToken.h:414
@ kw_elementwise
Definition LLToken.h:94
@ DwarfAttEncoding
Definition LLToken.h:519
@ kw_external
Definition LLToken.h:71
@ kw_spir_kernel
Definition LLToken.h:160
@ kw_local_unnamed_addr
Definition LLToken.h:68
@ kw_hasUnknownCall
Definition LLToken.h:427
@ kw_x86_intrcc
Definition LLToken.h:171
@ kw_addrspacecast
Definition LLToken.h:342
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:517
@ kw_x86_thiscallcc
Definition LLToken.h:144
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:193
@ kw_unnamed_addr
Definition LLToken.h:67
@ NameTableKind
Definition LLToken.h:526
@ kw_inlineBits
Definition LLToken.h:466
@ kw_weak_odr
Definition LLToken.h:58
@ kw_dllimport
Definition LLToken.h:60
@ kw_argmemonly
Definition LLToken.h:218
@ kw_blockaddress
Definition LLToken.h:380
@ kw_amdgpu_gfx_whole_wave
Definition LLToken.h:186
@ kw_landingpad
Definition LLToken.h:346
@ kw_aarch64_vector_pcs
Definition LLToken.h:150
@ kw_source_filename
Definition LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition LLToken.h:447
@ FixedPointKind
Definition LLToken.h:527
@ kw_target_mem1
Definition LLToken.h:214
@ kw_ptx_kernel
Definition LLToken.h:158
@ kw_extractelement
Definition LLToken.h:374
@ kw_branchFunnel
Definition LLToken.h:472
@ kw_typeidCompatibleVTable
Definition LLToken.h:453
@ kw_vTableFuncs
Definition LLToken.h:439
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:446
@ kw_no_sanitize_address
Definition LLToken.h:496
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:220
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:502
@ DwarfSourceLangName
Definition LLToken.h:522
@ kw_noRenameOnPromotion
Definition LLToken.h:415
@ kw_amdgpu_cs_chain_preserve
Definition LLToken.h:183
@ kw_thread_local
Definition LLToken.h:72
@ kw_catchswitch
Definition LLToken.h:360
@ kw_cfiFunctionDefs
Definition LLToken.h:404
@ kw_extern_weak
Definition LLToken.h:70
@ kw_arm_aapcscc
Definition LLToken.h:148
@ kw_read_provenance
Definition LLToken.h:227
@ kw_cleanuppad
Definition LLToken.h:363
@ kw_available_externally
Definition LLToken.h:63
@ kw_singleImplName
Definition LLToken.h:474
@ kw_target_mem0
Definition LLToken.h:213
@ kw_swifttailcc
Definition LLToken.h:166
@ kw_monotonic
Definition LLToken.h:97
@ kw_typeTestAssumeVCalls
Definition LLToken.h:445
@ kw_preservesign
Definition LLToken.h:231
@ kw_attributes
Definition LLToken.h:198
@ kw_code_model
Definition LLToken.h:123
@ kw_localdynamic
Definition LLToken.h:73
@ kw_uniformRetVal
Definition LLToken.h:477
@ kw_sideeffect
Definition LLToken.h:128
@ kw_sizeM1BitWidth
Definition LLToken.h:462
@ kw_nodeduplicate
Definition LLToken.h:262
@ kw_avr_signalcc
Definition LLToken.h:157
@ kw_bitextract
Definition LLToken.h:385
@ kw_exactmatch
Definition LLToken.h:260
@ kw_fminimumnum
Definition LLToken.h:298
@ kw_unreachable
Definition LLToken.h:358
@ kw_intel_ocl_bicc
Definition LLToken.h:140
@ kw_dso_local
Definition LLToken.h:50
@ kw_returnDoesNotAlias
Definition LLToken.h:422
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:152
@ kw_preserve_allcc
Definition LLToken.h:168
@ kw_importType
Definition LLToken.h:412
@ kw_cleanupret
Definition LLToken.h:359
@ kw_shufflevector
Definition LLToken.h:376
@ kw_riscv_vector_cc
Definition LLToken.h:191
@ kw_avr_intrcc
Definition LLToken.h:156
@ kw_definition
Definition LLToken.h:413
@ kw_virtualConstProp
Definition LLToken.h:479
@ kw_vcall_visibility
Definition LLToken.h:467
@ kw_appending
Definition LLToken.h:59
@ kw_inaccessiblemem
Definition LLToken.h:211
@ kw_preserve_mostcc
Definition LLToken.h:167
@ kw_arm_aapcs_vfpcc
Definition LLToken.h:149
@ kw_typeTestRes
Definition LLToken.h:455
@ kw_x86_regcallcc
Definition LLToken.h:146
@ kw_typeIdInfo
Definition LLToken.h:443
@ kw_amdgpu_cs_chain
Definition LLToken.h:182
@ kw_dso_local_equivalent
Definition LLToken.h:381
@ kw_x86_64_sysvcc
Definition LLToken.h:162
@ DbgRecordType
Definition LLToken.h:533
@ kw_address_is_null
Definition LLToken.h:225
@ kw_musttail
Definition LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition LLToken.h:154
@ kw_uniqueRetVal
Definition LLToken.h:478
@ kw_insertvalue
Definition LLToken.h:379
@ kw_speculative
Definition LLToken.h:473
@ kw_indirectbr
Definition LLToken.h:355
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:55
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:369
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()
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:54
@ t_PackedConstantStruct
Definition LLParser.h:72
@ t_ConstantStruct
Definition LLParser.h:71
@ t_ConstantSplat
Definition LLParser.h:69
enum llvm::ValID::@273232264270353276247031231016211363171152164072 Kind
unsigned UIntVal
Definition LLParser.h:76
FunctionType * FTy
Definition LLParser.h:77
LLLexer::LocTy Loc
Definition LLParser.h:75
std::string StrVal
Definition LLParser.h:78
Struct that holds a reference to a particular GUID in a global value summary.
const GlobalValueSummaryMapTy::value_type * getRef() const
bool isWriteOnly() const
bool isReadOnly() const
@ UniformRetVal
Uniform return value optimization.
@ VirtualConstProp
Virtual constant propagation.
@ UniqueRetVal
Unique return value optimization.
@ Indir
Just do a regular virtual call.
uint64_t Info
Additional information for the resolution:
enum llvm::WholeProgramDevirtResolution::ByArg::Kind TheKind
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
@ SingleImpl
Single implementation devirtualization.
@ Indir
Just do a regular virtual call.
@ Speculative
Speculative devirtualization.
@ BranchFunnel
When retpoline mitigation is enabled, use a branch funnel that is defined in the merged module.