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