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