LLVM 23.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/// Run: module ::= toplevelentity*
76bool LLParser::Run(bool UpgradeDebugInfo,
77 DataLayoutCallbackTy DataLayoutCallback) {
78 // Prime the lexer.
79 Lex.Lex();
80
81 if (Context.shouldDiscardValueNames())
82 return error(
83 Lex.getLoc(),
84 "Can't read textual IR with a Context that discards named Values");
85
86 if (M) {
87 if (parseTargetDefinitions(DataLayoutCallback))
88 return true;
89 }
90
91 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
92 validateEndOfIndex();
93}
94
96 const SlotMapping *Slots) {
97 restoreParsingState(Slots);
98 Lex.Lex();
99
100 Type *Ty = nullptr;
101 if (parseType(Ty) || parseConstantValue(Ty, C))
102 return true;
103 if (Lex.getKind() != lltok::Eof)
104 return error(Lex.getLoc(), "expected end of string");
105 return false;
106}
107
109 const SlotMapping *Slots) {
110 restoreParsingState(Slots);
111 Lex.Lex();
112
113 Read = 0;
114 SMLoc Start = Lex.getLoc();
115 Ty = nullptr;
116 if (parseType(Ty))
117 return true;
118 SMLoc End = Lex.getLoc();
119 Read = End.getPointer() - Start.getPointer();
120
121 return false;
122}
123
125 const SlotMapping *Slots) {
126 restoreParsingState(Slots);
127 Lex.Lex();
128
129 Read = 0;
130 SMLoc Start = Lex.getLoc();
131 Result = nullptr;
132 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
133 SMLoc End = Lex.getLoc();
134 Read = End.getPointer() - Start.getPointer();
135
136 return Status;
137}
138
139void LLParser::restoreParsingState(const SlotMapping *Slots) {
140 if (!Slots)
141 return;
142 NumberedVals = Slots->GlobalValues;
143 NumberedMetadata = Slots->MetadataNodes;
144 for (const auto &I : Slots->NamedTypes)
145 NamedTypes.insert(
146 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
147 for (const auto &I : Slots->Types)
148 NumberedTypes.insert(
149 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
150}
151
153 // White-list intrinsics that are safe to drop.
155 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
156 return;
157
159 for (Value *V : II->args())
160 if (auto *MV = dyn_cast<MetadataAsValue>(V))
161 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
162 if (MD->isTemporary())
163 MVs.push_back(MV);
164
165 if (!MVs.empty()) {
166 assert(II->use_empty() && "Cannot have uses");
167 II->eraseFromParent();
168
169 // Also remove no longer used MetadataAsValue wrappers.
170 for (MetadataAsValue *MV : MVs)
171 if (MV->use_empty())
172 delete MV;
173 }
174}
175
176void LLParser::dropUnknownMetadataReferences() {
177 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
178 for (Function &F : *M) {
179 F.eraseMetadataIf(Pred);
180 for (Instruction &I : make_early_inc_range(instructions(F))) {
181 I.eraseMetadataIf(Pred);
182
183 if (auto *II = dyn_cast<IntrinsicInst>(&I))
185 }
186 }
187
188 for (GlobalVariable &GV : M->globals())
189 GV.eraseMetadataIf(Pred);
190
191 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
192 // Check whether there is only a single use left, which would be in our
193 // own NumberedMetadata.
194 if (Info.first->getNumTemporaryUses() == 1) {
195 NumberedMetadata.erase(ID);
196 ForwardRefMDNodes.erase(ID);
197 }
198 }
199}
200
201/// validateEndOfModule - Do final validity and basic correctness checks at the
202/// end of the module.
203bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
204 if (!M)
205 return false;
206
207 // We should have already returned an error if we observed both intrinsics and
208 // records in this IR.
209 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
210 "Mixed debug intrinsics/records seen without a parsing error?");
211
212 // Handle any function attribute group forward references.
213 for (const auto &RAG : ForwardRefAttrGroups) {
214 Value *V = RAG.first;
215 const std::vector<unsigned> &Attrs = RAG.second;
216 AttrBuilder B(Context);
217
218 for (const auto &Attr : Attrs) {
219 auto R = NumberedAttrBuilders.find(Attr);
220 if (R != NumberedAttrBuilders.end())
221 B.merge(R->second);
222 }
223
224 if (Function *Fn = dyn_cast<Function>(V)) {
225 AttributeList AS = Fn->getAttributes();
226 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
227 AS = AS.removeFnAttributes(Context);
228
229 FnAttrs.merge(B);
230
231 // If the alignment was parsed as an attribute, move to the alignment
232 // field.
233 if (MaybeAlign A = FnAttrs.getAlignment()) {
234 Fn->setAlignment(*A);
235 FnAttrs.removeAttribute(Attribute::Alignment);
236 }
237
238 AS = AS.addFnAttributes(Context, FnAttrs);
239 Fn->setAttributes(AS);
240 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
241 AttributeList AS = CI->getAttributes();
242 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
243 AS = AS.removeFnAttributes(Context);
244 FnAttrs.merge(B);
245 AS = AS.addFnAttributes(Context, FnAttrs);
246 CI->setAttributes(AS);
247 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
248 AttributeList AS = II->getAttributes();
249 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
250 AS = AS.removeFnAttributes(Context);
251 FnAttrs.merge(B);
252 AS = AS.addFnAttributes(Context, FnAttrs);
253 II->setAttributes(AS);
254 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
255 AttributeList AS = CBI->getAttributes();
256 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
257 AS = AS.removeFnAttributes(Context);
258 FnAttrs.merge(B);
259 AS = AS.addFnAttributes(Context, FnAttrs);
260 CBI->setAttributes(AS);
261 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
262 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
263 Attrs.merge(B);
264 GV->setAttributes(AttributeSet::get(Context,Attrs));
265 } else {
266 llvm_unreachable("invalid object with forward attribute group reference");
267 }
268 }
269
270 // If there are entries in ForwardRefBlockAddresses at this point, the
271 // function was never defined.
272 if (!ForwardRefBlockAddresses.empty())
273 return error(ForwardRefBlockAddresses.begin()->first.Loc,
274 "expected function name in blockaddress");
275
276 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
277 GlobalValue *FwdRef) {
278 GlobalValue *GV = nullptr;
279 if (GVRef.Kind == ValID::t_GlobalName) {
280 GV = M->getNamedValue(GVRef.StrVal);
281 } else {
282 GV = NumberedVals.get(GVRef.UIntVal);
283 }
284
285 if (!GV)
286 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
287 "' referenced by dso_local_equivalent");
288
289 if (!GV->getValueType()->isFunctionTy())
290 return error(GVRef.Loc,
291 "expected a function, alias to function, or ifunc "
292 "in dso_local_equivalent");
293
294 auto *Equiv = DSOLocalEquivalent::get(GV);
295 FwdRef->replaceAllUsesWith(Equiv);
296 FwdRef->eraseFromParent();
297 return false;
298 };
299
300 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
301 // point, they are references after the function was defined. Resolve those
302 // now.
303 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
304 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
305 return true;
306 }
307 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
308 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
309 return true;
310 }
311 ForwardRefDSOLocalEquivalentIDs.clear();
312 ForwardRefDSOLocalEquivalentNames.clear();
313
314 for (const auto &NT : NumberedTypes)
315 if (NT.second.second.isValid())
316 return error(NT.second.second,
317 "use of undefined type '%" + Twine(NT.first) + "'");
318
319 for (const auto &[Name, TypeInfo] : NamedTypes)
320 if (TypeInfo.second.isValid())
321 return error(TypeInfo.second,
322 "use of undefined type named '" + Name + "'");
323
324 if (!ForwardRefComdats.empty())
325 return error(ForwardRefComdats.begin()->second,
326 "use of undefined comdat '$" +
327 ForwardRefComdats.begin()->first + "'");
328
329 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
330 if (StringRef(Name).starts_with("llvm.")) {
332 // Automatically create declarations for intrinsics. Intrinsics can only
333 // be called directly, so the call function type directly determines the
334 // declaration function type.
335 //
336 // Additionally, automatically add the required mangling suffix to the
337 // intrinsic name. This means that we may replace a single forward
338 // declaration with multiple functions here.
339 for (Use &U : make_early_inc_range(Info.first->uses())) {
340 auto *CB = dyn_cast<CallBase>(U.getUser());
341 if (!CB || !CB->isCallee(&U))
342 return error(Info.second, "intrinsic can only be used as callee");
343
344 std::string ErrorMsg;
345 raw_string_ostream ErrorOS(ErrorMsg);
346
347 SmallVector<Type *> OverloadTys;
348 if (IID != Intrinsic::not_intrinsic &&
349 Intrinsic::isSignatureValid(IID, CB->getFunctionType(), OverloadTys,
350 ErrorOS)) {
351 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
352 } else {
353 // Try to upgrade the intrinsic.
354 Function *TmpF = Function::Create(CB->getFunctionType(),
356 Function *NewF = nullptr;
357 if (!UpgradeIntrinsicFunction(TmpF, NewF)) {
358 if (IID == Intrinsic::not_intrinsic)
359 return error(Info.second, "unknown intrinsic '" + Name + "'");
360 return error(Info.second, ErrorMsg);
361 }
362
363 U.set(TmpF);
364 UpgradeIntrinsicCall(CB, NewF);
365 if (TmpF->use_empty())
366 TmpF->eraseFromParent();
367 }
368 }
369
370 Info.first->eraseFromParent();
371 ForwardRefVals.erase(Name);
372 continue;
373 }
374
375 // If incomplete IR is allowed, also add declarations for
376 // non-intrinsics.
378 continue;
379
380 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
381 FunctionType *FTy = nullptr;
382 for (Use &U : V->uses()) {
383 auto *CB = dyn_cast<CallBase>(U.getUser());
384 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
385 return nullptr;
386 FTy = CB->getFunctionType();
387 }
388 return FTy;
389 };
390
391 // First check whether this global is only used in calls with the same
392 // type, in which case we'll insert a function. Otherwise, fall back to
393 // using a dummy i8 type.
394 Type *Ty = GetCommonFunctionType(Info.first);
395 if (!Ty)
396 Ty = Type::getInt8Ty(Context);
397
398 GlobalValue *GV;
399 if (auto *FTy = dyn_cast<FunctionType>(Ty))
401 else
402 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
404 /*Initializer*/ nullptr, Name);
405 Info.first->replaceAllUsesWith(GV);
406 Info.first->eraseFromParent();
407 ForwardRefVals.erase(Name);
408 }
409
410 if (!ForwardRefVals.empty())
411 return error(ForwardRefVals.begin()->second.second,
412 "use of undefined value '@" + ForwardRefVals.begin()->first +
413 "'");
414
415 if (!ForwardRefValIDs.empty())
416 return error(ForwardRefValIDs.begin()->second.second,
417 "use of undefined value '@" +
418 Twine(ForwardRefValIDs.begin()->first) + "'");
419
420 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
421 dropUnknownMetadataReferences();
422
423 if (!ForwardRefMDNodes.empty())
424 return error(ForwardRefMDNodes.begin()->second.second,
425 "use of undefined metadata '!" +
426 Twine(ForwardRefMDNodes.begin()->first) + "'");
427
428 // Resolve metadata cycles.
429 for (auto &N : NumberedMetadata) {
430 if (N.second && !N.second->isResolved())
431 N.second->resolveCycles();
432 }
433
435 NewDistinctSPs.clear();
436
437 for (auto *Inst : InstsWithTBAATag) {
438 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
439 // With incomplete IR, the tbaa metadata may have been dropped.
441 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
442 if (MD) {
443 auto *UpgradedMD = UpgradeTBAANode(*MD);
444 if (MD != UpgradedMD)
445 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
446 }
447 }
448
449 // Look for intrinsic functions and CallInst that need to be upgraded. We use
450 // make_early_inc_range here because we may remove some functions.
451 for (Function &F : llvm::make_early_inc_range(*M))
453
454 if (UpgradeDebugInfo)
456
461
462 if (!Slots)
463 return false;
464 // Initialize the slot mapping.
465 // Because by this point we've parsed and validated everything, we can "steal"
466 // the mapping from LLParser as it doesn't need it anymore.
467 Slots->GlobalValues = std::move(NumberedVals);
468 Slots->MetadataNodes = std::move(NumberedMetadata);
469 for (const auto &I : NamedTypes)
470 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
471 for (const auto &I : NumberedTypes)
472 Slots->Types.insert(std::make_pair(I.first, I.second.first));
473
474 return false;
475}
476
477/// Do final validity and basic correctness checks at the end of the index.
478bool LLParser::validateEndOfIndex() {
479 if (!Index)
480 return false;
481
482 if (!ForwardRefValueInfos.empty())
483 return error(ForwardRefValueInfos.begin()->second.front().second,
484 "use of undefined summary '^" +
485 Twine(ForwardRefValueInfos.begin()->first) + "'");
486
487 if (!ForwardRefAliasees.empty())
488 return error(ForwardRefAliasees.begin()->second.front().second,
489 "use of undefined summary '^" +
490 Twine(ForwardRefAliasees.begin()->first) + "'");
491
492 if (!ForwardRefTypeIds.empty())
493 return error(ForwardRefTypeIds.begin()->second.front().second,
494 "use of undefined type id summary '^" +
495 Twine(ForwardRefTypeIds.begin()->first) + "'");
496
497 return false;
498}
499
500//===----------------------------------------------------------------------===//
501// Top-Level Entities
502//===----------------------------------------------------------------------===//
503
504bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
505 // Delay parsing of the data layout string until the target triple is known.
506 // Then, pass both the the target triple and the tentative data layout string
507 // to DataLayoutCallback, allowing to override the DL string.
508 // This enables importing modules with invalid DL strings.
509 std::string TentativeDLStr = M->getDataLayoutStr();
510 LocTy DLStrLoc;
511
512 bool Done = false;
513 while (!Done) {
514 switch (Lex.getKind()) {
515 case lltok::kw_target:
516 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
517 return true;
518 break;
520 if (parseSourceFileName())
521 return true;
522 break;
523 default:
524 Done = true;
525 }
526 }
527 // Run the override callback to potentially change the data layout string, and
528 // parse the data layout string.
529 if (auto LayoutOverride =
530 DataLayoutCallback(M->getTargetTriple().str(), TentativeDLStr)) {
531 TentativeDLStr = *LayoutOverride;
532 DLStrLoc = {};
533 }
534 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
535 if (!MaybeDL)
536 return error(DLStrLoc, toString(MaybeDL.takeError()));
537 M->setDataLayout(MaybeDL.get());
538 return false;
539}
540
541bool LLParser::parseTopLevelEntities() {
542 // If there is no Module, then parse just the summary index entries.
543 if (!M) {
544 while (true) {
545 switch (Lex.getKind()) {
546 case lltok::Eof:
547 return false;
548 case lltok::SummaryID:
549 if (parseSummaryEntry())
550 return true;
551 break;
553 if (parseSourceFileName())
554 return true;
555 break;
556 default:
557 // Skip everything else
558 Lex.Lex();
559 }
560 }
561 }
562 while (true) {
563 switch (Lex.getKind()) {
564 default:
565 return tokError("expected top-level entity");
566 case lltok::Eof: return false;
568 if (parseDeclare())
569 return true;
570 break;
571 case lltok::kw_define:
572 if (parseDefine())
573 return true;
574 break;
575 case lltok::kw_module:
576 if (parseModuleAsm())
577 return true;
578 break;
580 if (parseUnnamedType())
581 return true;
582 break;
583 case lltok::LocalVar:
584 if (parseNamedType())
585 return true;
586 break;
587 case lltok::GlobalID:
588 if (parseUnnamedGlobal())
589 return true;
590 break;
591 case lltok::GlobalVar:
592 if (parseNamedGlobal())
593 return true;
594 break;
595 case lltok::ComdatVar: if (parseComdat()) return true; break;
596 case lltok::exclaim:
597 if (parseStandaloneMetadata())
598 return true;
599 break;
600 case lltok::SummaryID:
601 if (parseSummaryEntry())
602 return true;
603 break;
605 if (parseNamedMetadata())
606 return true;
607 break;
609 if (parseUnnamedAttrGrp())
610 return true;
611 break;
613 if (parseUseListOrder())
614 return true;
615 break;
617 if (parseUseListOrderBB())
618 return true;
619 break;
620 }
621 }
622}
623
624/// toplevelentity
625/// ::= 'module' 'asm' STRINGCONSTANT
626bool LLParser::parseModuleAsm() {
627 assert(Lex.getKind() == lltok::kw_module);
628 Lex.Lex();
629
630 std::string AsmStr;
631 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
632 parseStringConstant(AsmStr))
633 return true;
634
635 M->appendModuleInlineAsm(AsmStr);
636 return false;
637}
638
639/// toplevelentity
640/// ::= 'target' 'triple' '=' STRINGCONSTANT
641/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
642bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
643 LocTy &DLStrLoc) {
644 assert(Lex.getKind() == lltok::kw_target);
645 std::string Str;
646 switch (Lex.Lex()) {
647 default:
648 return tokError("unknown target property");
649 case lltok::kw_triple:
650 Lex.Lex();
651 if (parseToken(lltok::equal, "expected '=' after target triple") ||
652 parseStringConstant(Str))
653 return true;
654 M->setTargetTriple(Triple(std::move(Str)));
655 return false;
657 Lex.Lex();
658 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
659 return true;
660 DLStrLoc = Lex.getLoc();
661 if (parseStringConstant(TentativeDLStr))
662 return true;
663 return false;
664 }
665}
666
667/// toplevelentity
668/// ::= 'source_filename' '=' STRINGCONSTANT
669bool LLParser::parseSourceFileName() {
670 assert(Lex.getKind() == lltok::kw_source_filename);
671 Lex.Lex();
672 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
673 parseStringConstant(SourceFileName))
674 return true;
675 if (M)
676 M->setSourceFileName(SourceFileName);
677 return false;
678}
679
680/// parseUnnamedType:
681/// ::= LocalVarID '=' 'type' type
682bool LLParser::parseUnnamedType() {
683 LocTy TypeLoc = Lex.getLoc();
684 unsigned TypeID = Lex.getUIntVal();
685 Lex.Lex(); // eat LocalVarID;
686
687 if (parseToken(lltok::equal, "expected '=' after name") ||
688 parseToken(lltok::kw_type, "expected 'type' after '='"))
689 return true;
690
691 Type *Result = nullptr;
692 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
693 return true;
694
695 if (!isa<StructType>(Result)) {
696 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
697 if (Entry.first)
698 return error(TypeLoc, "non-struct types may not be recursive");
699 Entry.first = Result;
700 Entry.second = SMLoc();
701 }
702
703 return false;
704}
705
706/// toplevelentity
707/// ::= LocalVar '=' 'type' type
708bool LLParser::parseNamedType() {
709 std::string Name = Lex.getStrVal();
710 LocTy NameLoc = Lex.getLoc();
711 Lex.Lex(); // eat LocalVar.
712
713 if (parseToken(lltok::equal, "expected '=' after name") ||
714 parseToken(lltok::kw_type, "expected 'type' after name"))
715 return true;
716
717 Type *Result = nullptr;
718 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
719 return true;
720
721 if (!isa<StructType>(Result)) {
722 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
723 if (Entry.first)
724 return error(NameLoc, "non-struct types may not be recursive");
725 Entry.first = Result;
726 Entry.second = SMLoc();
727 }
728
729 return false;
730}
731
732/// toplevelentity
733/// ::= 'declare' FunctionHeader
734bool LLParser::parseDeclare() {
735 assert(Lex.getKind() == lltok::kw_declare);
736 Lex.Lex();
737
738 std::vector<std::pair<unsigned, MDNode *>> MDs;
739 while (Lex.getKind() == lltok::MetadataVar) {
740 unsigned MDK;
741 MDNode *N;
742 if (parseMetadataAttachment(MDK, N))
743 return true;
744 MDs.push_back({MDK, N});
745 }
746
747 Function *F;
748 unsigned FunctionNumber = -1;
749 SmallVector<unsigned> UnnamedArgNums;
750 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
751 return true;
752 for (auto &MD : MDs)
753 F->addMetadata(MD.first, *MD.second);
754 return false;
755}
756
757/// toplevelentity
758/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
759bool LLParser::parseDefine() {
760 assert(Lex.getKind() == lltok::kw_define);
761
762 FileLoc FunctionStart = getTokLineColumnPos();
763 Lex.Lex();
764
765 Function *F;
766 unsigned FunctionNumber = -1;
767 SmallVector<unsigned> UnnamedArgNums;
768 bool RetValue =
769 parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
770 parseOptionalFunctionMetadata(*F) ||
771 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
772 if (ParserContext)
773 ParserContext->addFunctionLocation(
774 F, FileLocRange(FunctionStart, getPrevTokEndLineColumnPos()));
775
776 return RetValue;
777}
778
779/// parseGlobalType
780/// ::= 'constant'
781/// ::= 'global'
782bool LLParser::parseGlobalType(bool &IsConstant) {
783 if (Lex.getKind() == lltok::kw_constant)
784 IsConstant = true;
785 else if (Lex.getKind() == lltok::kw_global)
786 IsConstant = false;
787 else {
788 IsConstant = false;
789 return tokError("expected 'global' or 'constant'");
790 }
791 Lex.Lex();
792 return false;
793}
794
795bool LLParser::parseOptionalUnnamedAddr(
796 GlobalVariable::UnnamedAddr &UnnamedAddr) {
797 if (EatIfPresent(lltok::kw_unnamed_addr))
799 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
801 else
802 UnnamedAddr = GlobalValue::UnnamedAddr::None;
803 return false;
804}
805
806/// parseUnnamedGlobal:
807/// OptionalVisibility (ALIAS | IFUNC) ...
808/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
809/// OptionalDLLStorageClass
810/// ... -> global variable
811/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
812/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
813/// OptionalVisibility
814/// OptionalDLLStorageClass
815/// ... -> global variable
816bool LLParser::parseUnnamedGlobal() {
817 unsigned VarID;
818 std::string Name;
819 LocTy NameLoc = Lex.getLoc();
820
821 // Handle the GlobalID form.
822 if (Lex.getKind() == lltok::GlobalID) {
823 VarID = Lex.getUIntVal();
824 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
825 return true;
826
827 Lex.Lex(); // eat GlobalID;
828 if (parseToken(lltok::equal, "expected '=' after name"))
829 return true;
830 } else {
831 VarID = NumberedVals.getNext();
832 }
833
834 bool HasLinkage;
835 unsigned Linkage, Visibility, DLLStorageClass;
836 bool DSOLocal;
838 GlobalVariable::UnnamedAddr UnnamedAddr;
839 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
840 DSOLocal) ||
841 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
842 return true;
843
844 switch (Lex.getKind()) {
845 default:
846 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
847 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
848 case lltok::kw_alias:
849 case lltok::kw_ifunc:
850 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
851 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
852 }
853}
854
855/// parseNamedGlobal:
856/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
857/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
858/// OptionalVisibility OptionalDLLStorageClass
859/// ... -> global variable
860bool LLParser::parseNamedGlobal() {
861 assert(Lex.getKind() == lltok::GlobalVar);
862 LocTy NameLoc = Lex.getLoc();
863 std::string Name = Lex.getStrVal();
864 Lex.Lex();
865
866 bool HasLinkage;
867 unsigned Linkage, Visibility, DLLStorageClass;
868 bool DSOLocal;
870 GlobalVariable::UnnamedAddr UnnamedAddr;
871 if (parseToken(lltok::equal, "expected '=' in global variable") ||
872 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
873 DSOLocal) ||
874 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
875 return true;
876
877 switch (Lex.getKind()) {
878 default:
879 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
880 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
881 case lltok::kw_alias:
882 case lltok::kw_ifunc:
883 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
884 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
885 }
886}
887
888bool LLParser::parseComdat() {
889 assert(Lex.getKind() == lltok::ComdatVar);
890 std::string Name = Lex.getStrVal();
891 LocTy NameLoc = Lex.getLoc();
892 Lex.Lex();
893
894 if (parseToken(lltok::equal, "expected '=' here"))
895 return true;
896
897 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
898 return tokError("expected comdat type");
899
901 switch (Lex.getKind()) {
902 default:
903 return tokError("unknown selection kind");
904 case lltok::kw_any:
905 SK = Comdat::Any;
906 break;
909 break;
911 SK = Comdat::Largest;
912 break;
915 break;
917 SK = Comdat::SameSize;
918 break;
919 }
920 Lex.Lex();
921
922 // See if the comdat was forward referenced, if so, use the comdat.
923 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
924 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
925 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
926 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
927
928 Comdat *C;
929 if (I != ComdatSymTab.end())
930 C = &I->second;
931 else
932 C = M->getOrInsertComdat(Name);
933 C->setSelectionKind(SK);
934
935 return false;
936}
937
938// MDString:
939// ::= '!' STRINGCONSTANT
940bool LLParser::parseMDString(MDString *&Result) {
941 std::string Str;
942 if (parseStringConstant(Str))
943 return true;
944 Result = MDString::get(Context, Str);
945 return false;
946}
947
948// MDNode:
949// ::= '!' MDNodeNumber
950bool LLParser::parseMDNodeID(MDNode *&Result) {
951 // !{ ..., !42, ... }
952 LocTy IDLoc = Lex.getLoc();
953 unsigned MID = 0;
954 if (parseUInt32(MID))
955 return true;
956
957 // If not a forward reference, just return it now.
958 auto [It, Inserted] = NumberedMetadata.try_emplace(MID);
959 if (!Inserted) {
960 Result = It->second;
961 return false;
962 }
963
964 // Otherwise, create MDNode forward reference.
965 auto &FwdRef = ForwardRefMDNodes[MID];
966 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
967
968 Result = FwdRef.first.get();
969 It->second.reset(Result);
970 return false;
971}
972
973/// parseNamedMetadata:
974/// !foo = !{ !1, !2 }
975bool LLParser::parseNamedMetadata() {
976 assert(Lex.getKind() == lltok::MetadataVar);
977 std::string Name = Lex.getStrVal();
978 Lex.Lex();
979
980 if (parseToken(lltok::equal, "expected '=' here") ||
981 parseToken(lltok::exclaim, "Expected '!' here") ||
982 parseToken(lltok::lbrace, "Expected '{' here"))
983 return true;
984
985 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
986 if (Lex.getKind() != lltok::rbrace)
987 do {
988 MDNode *N = nullptr;
989 // parse DIExpressions inline as a special case. They are still MDNodes,
990 // so they can still appear in named metadata. Remove this logic if they
991 // become plain Metadata.
992 if (Lex.getKind() == lltok::MetadataVar &&
993 Lex.getStrVal() == "DIExpression") {
994 if (parseDIExpression(N, /*IsDistinct=*/false))
995 return true;
996 // DIArgLists should only appear inline in a function, as they may
997 // contain LocalAsMetadata arguments which require a function context.
998 } else if (Lex.getKind() == lltok::MetadataVar &&
999 Lex.getStrVal() == "DIArgList") {
1000 return tokError("found DIArgList outside of function");
1001 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1002 parseMDNodeID(N)) {
1003 return true;
1004 }
1005 NMD->addOperand(N);
1006 } while (EatIfPresent(lltok::comma));
1007
1008 return parseToken(lltok::rbrace, "expected end of metadata node");
1009}
1010
1011/// parseStandaloneMetadata:
1012/// !42 = !{...}
1013bool LLParser::parseStandaloneMetadata() {
1014 assert(Lex.getKind() == lltok::exclaim);
1015 Lex.Lex();
1016 unsigned MetadataID = 0;
1017
1018 MDNode *Init;
1019 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1020 return true;
1021
1022 // Detect common error, from old metadata syntax.
1023 if (Lex.getKind() == lltok::Type)
1024 return tokError("unexpected type in metadata definition");
1025
1026 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1027 if (Lex.getKind() == lltok::MetadataVar) {
1028 if (parseSpecializedMDNode(Init, IsDistinct))
1029 return true;
1030 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1031 parseMDTuple(Init, IsDistinct))
1032 return true;
1033
1034 // See if this was forward referenced, if so, handle it.
1035 auto FI = ForwardRefMDNodes.find(MetadataID);
1036 if (FI != ForwardRefMDNodes.end()) {
1037 auto *ToReplace = FI->second.first.get();
1038 // DIAssignID has its own special forward-reference "replacement" for
1039 // attachments (the temporary attachments are never actually attached).
1040 if (isa<DIAssignID>(Init)) {
1041 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1042 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1043 "Inst unexpectedly already has DIAssignID attachment");
1044 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1045 }
1046 }
1047
1048 ToReplace->replaceAllUsesWith(Init);
1049 ForwardRefMDNodes.erase(FI);
1050
1051 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1052 } else {
1053 auto [It, Inserted] = NumberedMetadata.try_emplace(MetadataID);
1054 if (!Inserted)
1055 return tokError("Metadata id is already used");
1056 It->second.reset(Init);
1057 }
1058
1059 return false;
1060}
1061
1062// Skips a single module summary entry.
1063bool LLParser::skipModuleSummaryEntry() {
1064 // Each module summary entry consists of a tag for the entry
1065 // type, followed by a colon, then the fields which may be surrounded by
1066 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1067 // support is in place we will look for the tokens corresponding to the
1068 // expected tags.
1069 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1070 Lex.getKind() != lltok::kw_typeid &&
1071 Lex.getKind() != lltok::kw_typeidCompatibleVTable &&
1072 Lex.getKind() != lltok::kw_flags && Lex.getKind() != lltok::kw_blockcount)
1073 return tokError("Expected 'gv', 'module', 'typeid', "
1074 "'typeidCompatibleVTable', 'flags' or 'blockcount' at the "
1075 "start of summary entry");
1076 if (Lex.getKind() == lltok::kw_flags)
1077 return parseSummaryIndexFlags();
1078 if (Lex.getKind() == lltok::kw_blockcount)
1079 return parseBlockCount();
1080 Lex.Lex();
1081 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1082 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1083 return true;
1084 // Now walk through the parenthesized entry, until the number of open
1085 // parentheses goes back down to 0 (the first '(' was parsed above).
1086 unsigned NumOpenParen = 1;
1087 do {
1088 switch (Lex.getKind()) {
1089 case lltok::lparen:
1090 NumOpenParen++;
1091 break;
1092 case lltok::rparen:
1093 NumOpenParen--;
1094 break;
1095 case lltok::Eof:
1096 return tokError("found end of file while parsing summary entry");
1097 default:
1098 // Skip everything in between parentheses.
1099 break;
1100 }
1101 Lex.Lex();
1102 } while (NumOpenParen > 0);
1103 return false;
1104}
1105
1106/// SummaryEntry
1107/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1108bool LLParser::parseSummaryEntry() {
1109 assert(Lex.getKind() == lltok::SummaryID);
1110 unsigned SummaryID = Lex.getUIntVal();
1111
1112 // For summary entries, colons should be treated as distinct tokens,
1113 // not an indication of the end of a label token.
1114 Lex.setIgnoreColonInIdentifiers(true);
1115
1116 Lex.Lex();
1117 if (parseToken(lltok::equal, "expected '=' here"))
1118 return true;
1119
1120 // If we don't have an index object, skip the summary entry.
1121 if (!Index)
1122 return skipModuleSummaryEntry();
1123
1124 bool result = false;
1125 switch (Lex.getKind()) {
1126 case lltok::kw_gv:
1127 result = parseGVEntry(SummaryID);
1128 break;
1129 case lltok::kw_module:
1130 result = parseModuleEntry(SummaryID);
1131 break;
1132 case lltok::kw_typeid:
1133 result = parseTypeIdEntry(SummaryID);
1134 break;
1136 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1137 break;
1138 case lltok::kw_flags:
1139 result = parseSummaryIndexFlags();
1140 break;
1142 result = parseBlockCount();
1143 break;
1144 default:
1145 result = error(Lex.getLoc(), "unexpected summary kind");
1146 break;
1147 }
1148 Lex.setIgnoreColonInIdentifiers(false);
1149 return result;
1150}
1151
1160
1161// If there was an explicit dso_local, update GV. In the absence of an explicit
1162// dso_local we keep the default value.
1163static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1164 if (DSOLocal)
1165 GV.setDSOLocal(true);
1166}
1167
1168/// parseAliasOrIFunc:
1169/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1170/// OptionalVisibility OptionalDLLStorageClass
1171/// OptionalThreadLocal OptionalUnnamedAddr
1172/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1173///
1174/// AliaseeOrResolver
1175/// ::= TypeAndValue
1176///
1177/// SymbolAttrs
1178/// ::= ',' 'partition' StringConstant
1179///
1180/// Everything through OptionalUnnamedAddr has already been parsed.
1181///
1182bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1183 LocTy NameLoc, unsigned L, unsigned Visibility,
1184 unsigned DLLStorageClass, bool DSOLocal,
1186 GlobalVariable::UnnamedAddr UnnamedAddr) {
1187 bool IsAlias;
1188 if (Lex.getKind() == lltok::kw_alias)
1189 IsAlias = true;
1190 else if (Lex.getKind() == lltok::kw_ifunc)
1191 IsAlias = false;
1192 else
1193 llvm_unreachable("Not an alias or ifunc!");
1194 Lex.Lex();
1195
1197
1198 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1199 return error(NameLoc, "invalid linkage type for alias");
1200
1201 if (!isValidVisibilityForLinkage(Visibility, L))
1202 return error(NameLoc,
1203 "symbol with local linkage must have default visibility");
1204
1205 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1206 return error(NameLoc,
1207 "symbol with local linkage cannot have a DLL storage class");
1208
1209 Type *Ty;
1210 LocTy ExplicitTypeLoc = Lex.getLoc();
1211 if (parseType(Ty) ||
1212 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1213 return true;
1214
1215 Constant *Aliasee;
1216 LocTy AliaseeLoc = Lex.getLoc();
1217 if (Lex.getKind() != lltok::kw_bitcast &&
1218 Lex.getKind() != lltok::kw_getelementptr &&
1219 Lex.getKind() != lltok::kw_addrspacecast &&
1220 Lex.getKind() != lltok::kw_inttoptr) {
1221 if (parseGlobalTypeAndValue(Aliasee))
1222 return true;
1223 } else {
1224 // The bitcast dest type is not present, it is implied by the dest type.
1225 ValID ID;
1226 if (parseValID(ID, /*PFS=*/nullptr))
1227 return true;
1228 if (ID.Kind != ValID::t_Constant)
1229 return error(AliaseeLoc, "invalid aliasee");
1230 Aliasee = ID.ConstantVal;
1231 }
1232
1233 Type *AliaseeType = Aliasee->getType();
1234 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1235 if (!PTy)
1236 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1237 unsigned AddrSpace = PTy->getAddressSpace();
1238
1239 GlobalValue *GVal = nullptr;
1240
1241 // See if the alias was forward referenced, if so, prepare to replace the
1242 // forward reference.
1243 if (!Name.empty()) {
1244 auto I = ForwardRefVals.find(Name);
1245 if (I != ForwardRefVals.end()) {
1246 GVal = I->second.first;
1247 ForwardRefVals.erase(Name);
1248 } else if (M->getNamedValue(Name)) {
1249 return error(NameLoc, "redefinition of global '@" + Name + "'");
1250 }
1251 } else {
1252 auto I = ForwardRefValIDs.find(NameID);
1253 if (I != ForwardRefValIDs.end()) {
1254 GVal = I->second.first;
1255 ForwardRefValIDs.erase(I);
1256 }
1257 }
1258
1259 // Okay, create the alias/ifunc but do not insert it into the module yet.
1260 std::unique_ptr<GlobalAlias> GA;
1261 std::unique_ptr<GlobalIFunc> GI;
1262 GlobalValue *GV;
1263 if (IsAlias) {
1264 GA.reset(GlobalAlias::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1265 /*Parent=*/nullptr));
1266 GV = GA.get();
1267 } else {
1268 GI.reset(GlobalIFunc::create(Ty, AddrSpace, Linkage, Name, Aliasee,
1269 /*Parent=*/nullptr));
1270 GV = GI.get();
1271 }
1272 GV->setThreadLocalMode(TLM);
1275 GV->setUnnamedAddr(UnnamedAddr);
1276 maybeSetDSOLocal(DSOLocal, *GV);
1277
1278 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1279 // Now parse them if there are any.
1280 while (Lex.getKind() == lltok::comma) {
1281 Lex.Lex();
1282
1283 if (Lex.getKind() == lltok::kw_partition) {
1284 Lex.Lex();
1285 GV->setPartition(Lex.getStrVal());
1286 if (parseToken(lltok::StringConstant, "expected partition string"))
1287 return true;
1288 } else if (!IsAlias && Lex.getKind() == lltok::MetadataVar) {
1289 if (parseGlobalObjectMetadataAttachment(*GI))
1290 return true;
1291 } else {
1292 return tokError("unknown alias or ifunc property!");
1293 }
1294 }
1295
1296 if (Name.empty())
1297 NumberedVals.add(NameID, GV);
1298
1299 if (GVal) {
1300 // Verify that types agree.
1301 if (GVal->getType() != GV->getType())
1302 return error(
1303 ExplicitTypeLoc,
1304 "forward reference and definition of alias have different types");
1305
1306 // If they agree, just RAUW the old value with the alias and remove the
1307 // forward ref info.
1308 GVal->replaceAllUsesWith(GV);
1309 GVal->eraseFromParent();
1310 }
1311
1312 // Insert into the module, we know its name won't collide now.
1313 if (IsAlias)
1314 M->insertAlias(GA.release());
1315 else
1316 M->insertIFunc(GI.release());
1317 assert(GV->getName() == Name && "Should not be a name conflict!");
1318
1319 return false;
1320}
1321
1322static bool isSanitizer(lltok::Kind Kind) {
1323 switch (Kind) {
1326 case lltok::kw_sanitize_memtag:
1328 return true;
1329 default:
1330 return false;
1331 }
1332}
1333
1334bool LLParser::parseSanitizer(GlobalVariable *GV) {
1335 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1337 if (GV->hasSanitizerMetadata())
1338 Meta = GV->getSanitizerMetadata();
1339
1340 switch (Lex.getKind()) {
1342 Meta.NoAddress = true;
1343 break;
1345 Meta.NoHWAddress = true;
1346 break;
1347 case lltok::kw_sanitize_memtag:
1348 Meta.Memtag = true;
1349 break;
1351 Meta.IsDynInit = true;
1352 break;
1353 default:
1354 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1355 }
1356 GV->setSanitizerMetadata(Meta);
1357 Lex.Lex();
1358 return false;
1359}
1360
1361/// parseGlobal
1362/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1363/// OptionalVisibility OptionalDLLStorageClass
1364/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1365/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1366/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1367/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1368/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1369/// Const OptionalAttrs
1370///
1371/// Everything up to and including OptionalUnnamedAddr has been parsed
1372/// already.
1373///
1374bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1375 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1376 unsigned Visibility, unsigned DLLStorageClass,
1377 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1378 GlobalVariable::UnnamedAddr UnnamedAddr) {
1379 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1380 return error(NameLoc,
1381 "symbol with local linkage must have default visibility");
1382
1383 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1384 return error(NameLoc,
1385 "symbol with local linkage cannot have a DLL storage class");
1386
1387 unsigned AddrSpace;
1388 bool IsConstant, IsExternallyInitialized;
1389 LocTy IsExternallyInitializedLoc;
1390 LocTy TyLoc;
1391
1392 Type *Ty = nullptr;
1393 if (parseOptionalAddrSpace(AddrSpace) ||
1394 parseOptionalToken(lltok::kw_externally_initialized,
1395 IsExternallyInitialized,
1396 &IsExternallyInitializedLoc) ||
1397 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1398 return true;
1399
1400 // If the linkage is specified and is external, then no initializer is
1401 // present.
1402 Constant *Init = nullptr;
1403 if (!HasLinkage ||
1406 if (parseGlobalValue(Ty, Init))
1407 return true;
1408 }
1409
1411 return error(TyLoc, "invalid type for global variable");
1412
1413 GlobalValue *GVal = nullptr;
1414
1415 // See if the global was forward referenced, if so, use the global.
1416 if (!Name.empty()) {
1417 auto I = ForwardRefVals.find(Name);
1418 if (I != ForwardRefVals.end()) {
1419 GVal = I->second.first;
1420 ForwardRefVals.erase(I);
1421 } else if (M->getNamedValue(Name)) {
1422 return error(NameLoc, "redefinition of global '@" + Name + "'");
1423 }
1424 } else {
1425 // Handle @"", where a name is syntactically specified, but semantically
1426 // missing.
1427 if (NameID == (unsigned)-1)
1428 NameID = NumberedVals.getNext();
1429
1430 auto I = ForwardRefValIDs.find(NameID);
1431 if (I != ForwardRefValIDs.end()) {
1432 GVal = I->second.first;
1433 ForwardRefValIDs.erase(I);
1434 }
1435 }
1436
1437 GlobalVariable *GV = new GlobalVariable(
1438 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1440
1441 if (Name.empty())
1442 NumberedVals.add(NameID, GV);
1443
1444 // Set the parsed properties on the global.
1445 if (Init)
1446 GV->setInitializer(Init);
1447 GV->setConstant(IsConstant);
1449 maybeSetDSOLocal(DSOLocal, *GV);
1452 GV->setExternallyInitialized(IsExternallyInitialized);
1453 GV->setThreadLocalMode(TLM);
1454 GV->setUnnamedAddr(UnnamedAddr);
1455
1456 if (GVal) {
1457 if (GVal->getAddressSpace() != AddrSpace)
1458 return error(
1459 TyLoc,
1460 "forward reference and definition of global have different types");
1461
1462 GVal->replaceAllUsesWith(GV);
1463 GVal->eraseFromParent();
1464 }
1465
1466 // parse attributes on the global.
1467 while (Lex.getKind() == lltok::comma) {
1468 Lex.Lex();
1469
1470 if (Lex.getKind() == lltok::kw_section) {
1471 Lex.Lex();
1472 GV->setSection(Lex.getStrVal());
1473 if (parseToken(lltok::StringConstant, "expected global section string"))
1474 return true;
1475 } else if (Lex.getKind() == lltok::kw_partition) {
1476 Lex.Lex();
1477 GV->setPartition(Lex.getStrVal());
1478 if (parseToken(lltok::StringConstant, "expected partition string"))
1479 return true;
1480 } else if (Lex.getKind() == lltok::kw_align) {
1481 MaybeAlign Alignment;
1482 if (parseOptionalAlignment(Alignment))
1483 return true;
1484 if (Alignment)
1485 GV->setAlignment(*Alignment);
1486 } else if (Lex.getKind() == lltok::kw_code_model) {
1488 if (parseOptionalCodeModel(CodeModel))
1489 return true;
1490 GV->setCodeModel(CodeModel);
1491 } else if (Lex.getKind() == lltok::MetadataVar) {
1492 if (parseGlobalObjectMetadataAttachment(*GV))
1493 return true;
1494 } else if (isSanitizer(Lex.getKind())) {
1495 if (parseSanitizer(GV))
1496 return true;
1497 } else {
1498 Comdat *C;
1499 if (parseOptionalComdat(Name, C))
1500 return true;
1501 if (C)
1502 GV->setComdat(C);
1503 else
1504 return tokError("unknown global variable property!");
1505 }
1506 }
1507
1508 AttrBuilder Attrs(M->getContext());
1509 LocTy BuiltinLoc;
1510 std::vector<unsigned> FwdRefAttrGrps;
1511 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1512 return true;
1513 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1514 GV->setAttributes(AttributeSet::get(Context, Attrs));
1515 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1516 }
1517
1518 return false;
1519}
1520
1521/// parseUnnamedAttrGrp
1522/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1523bool LLParser::parseUnnamedAttrGrp() {
1524 assert(Lex.getKind() == lltok::kw_attributes);
1525 LocTy AttrGrpLoc = Lex.getLoc();
1526 Lex.Lex();
1527
1528 if (Lex.getKind() != lltok::AttrGrpID)
1529 return tokError("expected attribute group id");
1530
1531 unsigned VarID = Lex.getUIntVal();
1532 std::vector<unsigned> unused;
1533 LocTy BuiltinLoc;
1534 Lex.Lex();
1535
1536 if (parseToken(lltok::equal, "expected '=' here") ||
1537 parseToken(lltok::lbrace, "expected '{' here"))
1538 return true;
1539
1540 auto R = NumberedAttrBuilders.find(VarID);
1541 if (R == NumberedAttrBuilders.end())
1542 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1543
1544 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1545 parseToken(lltok::rbrace, "expected end of attribute group"))
1546 return true;
1547
1548 if (!R->second.hasAttributes())
1549 return error(AttrGrpLoc, "attribute group has no attributes");
1550
1551 return false;
1552}
1553
1555 switch (Kind) {
1556#define GET_ATTR_NAMES
1557#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1558 case lltok::kw_##DISPLAY_NAME: \
1559 return Attribute::ENUM_NAME;
1560#include "llvm/IR/Attributes.inc"
1561 default:
1562 return Attribute::None;
1563 }
1564}
1565
1566bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1567 bool InAttrGroup) {
1568 if (Attribute::isTypeAttrKind(Attr))
1569 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1570
1571 switch (Attr) {
1572 case Attribute::Alignment: {
1573 MaybeAlign Alignment;
1574 if (InAttrGroup) {
1575 uint32_t Value = 0;
1576 Lex.Lex();
1577 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1578 return true;
1579 Alignment = Align(Value);
1580 } else {
1581 if (parseOptionalAlignment(Alignment, true))
1582 return true;
1583 }
1584 B.addAlignmentAttr(Alignment);
1585 return false;
1586 }
1587 case Attribute::StackAlignment: {
1588 unsigned Alignment;
1589 if (InAttrGroup) {
1590 Lex.Lex();
1591 if (parseToken(lltok::equal, "expected '=' here") ||
1592 parseUInt32(Alignment))
1593 return true;
1594 } else {
1595 if (parseOptionalStackAlignment(Alignment))
1596 return true;
1597 }
1598 B.addStackAlignmentAttr(Alignment);
1599 return false;
1600 }
1601 case Attribute::AllocSize: {
1602 unsigned ElemSizeArg;
1603 std::optional<unsigned> NumElemsArg;
1604 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1605 return true;
1606 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1607 return false;
1608 }
1609 case Attribute::VScaleRange: {
1610 unsigned MinValue, MaxValue;
1611 if (parseVScaleRangeArguments(MinValue, MaxValue))
1612 return true;
1613 B.addVScaleRangeAttr(MinValue,
1614 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1615 return false;
1616 }
1617 case Attribute::Dereferenceable: {
1618 std::optional<uint64_t> Bytes;
1619 if (parseOptionalAttrBytes(lltok::kw_dereferenceable, Bytes))
1620 return true;
1621 assert(Bytes.has_value());
1622 B.addDereferenceableAttr(Bytes.value());
1623 return false;
1624 }
1625 case Attribute::DeadOnReturn: {
1626 std::optional<uint64_t> Bytes;
1627 if (parseOptionalAttrBytes(lltok::kw_dead_on_return, Bytes,
1628 /*ErrorNoBytes=*/false))
1629 return true;
1630 if (Bytes.has_value()) {
1631 B.addDeadOnReturnAttr(DeadOnReturnInfo(Bytes.value()));
1632 } else {
1633 B.addDeadOnReturnAttr(DeadOnReturnInfo());
1634 }
1635 return false;
1636 }
1637 case Attribute::DereferenceableOrNull: {
1638 std::optional<uint64_t> Bytes;
1639 if (parseOptionalAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1640 return true;
1641 assert(Bytes.has_value());
1642 B.addDereferenceableOrNullAttr(Bytes.value());
1643 return false;
1644 }
1645 case Attribute::UWTable: {
1647 if (parseOptionalUWTableKind(Kind))
1648 return true;
1649 B.addUWTableAttr(Kind);
1650 return false;
1651 }
1652 case Attribute::AllocKind: {
1654 if (parseAllocKind(Kind))
1655 return true;
1656 B.addAllocKindAttr(Kind);
1657 return false;
1658 }
1659 case Attribute::Memory: {
1660 std::optional<MemoryEffects> ME = parseMemoryAttr();
1661 if (!ME)
1662 return true;
1663 B.addMemoryAttr(*ME);
1664 return false;
1665 }
1666 case Attribute::DenormalFPEnv: {
1667 std::optional<DenormalFPEnv> Mode = parseDenormalFPEnvAttr();
1668 if (!Mode)
1669 return true;
1670
1671 B.addDenormalFPEnvAttr(*Mode);
1672 return false;
1673 }
1674 case Attribute::NoFPClass: {
1675 if (FPClassTest NoFPClass =
1676 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1677 B.addNoFPClassAttr(NoFPClass);
1678 return false;
1679 }
1680
1681 return true;
1682 }
1683 case Attribute::Range:
1684 return parseRangeAttr(B);
1685 case Attribute::Initializes:
1686 return parseInitializesAttr(B);
1687 case Attribute::Captures:
1688 return parseCapturesAttr(B);
1689 default:
1690 B.addAttribute(Attr);
1691 Lex.Lex();
1692 return false;
1693 }
1694}
1695
1697 switch (Kind) {
1698 case lltok::kw_readnone:
1699 ME &= MemoryEffects::none();
1700 return true;
1701 case lltok::kw_readonly:
1703 return true;
1704 case lltok::kw_writeonly:
1706 return true;
1709 return true;
1712 return true;
1715 return true;
1716 default:
1717 return false;
1718 }
1719}
1720
1721/// parseFnAttributeValuePairs
1722/// ::= <attr> | <attr> '=' <value>
1723bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1724 std::vector<unsigned> &FwdRefAttrGrps,
1725 bool InAttrGrp, LocTy &BuiltinLoc) {
1726 bool HaveError = false;
1727
1728 B.clear();
1729
1731 while (true) {
1732 lltok::Kind Token = Lex.getKind();
1733 if (Token == lltok::rbrace)
1734 break; // Finished.
1735
1736 if (Token == lltok::StringConstant) {
1737 if (parseStringAttribute(B))
1738 return true;
1739 continue;
1740 }
1741
1742 if (Token == lltok::AttrGrpID) {
1743 // Allow a function to reference an attribute group:
1744 //
1745 // define void @foo() #1 { ... }
1746 if (InAttrGrp) {
1747 HaveError |= error(
1748 Lex.getLoc(),
1749 "cannot have an attribute group reference in an attribute group");
1750 } else {
1751 // Save the reference to the attribute group. We'll fill it in later.
1752 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1753 }
1754 Lex.Lex();
1755 continue;
1756 }
1757
1758 SMLoc Loc = Lex.getLoc();
1759 if (Token == lltok::kw_builtin)
1760 BuiltinLoc = Loc;
1761
1762 if (upgradeMemoryAttr(ME, Token)) {
1763 Lex.Lex();
1764 continue;
1765 }
1766
1768 if (Attr == Attribute::None) {
1769 if (!InAttrGrp)
1770 break;
1771 return error(Lex.getLoc(), "unterminated attribute group");
1772 }
1773
1774 if (parseEnumAttribute(Attr, B, InAttrGrp))
1775 return true;
1776
1777 // As a hack, we allow function alignment to be initially parsed as an
1778 // attribute on a function declaration/definition or added to an attribute
1779 // group and later moved to the alignment field.
1780 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1781 HaveError |= error(Loc, "this attribute does not apply to functions");
1782 }
1783
1784 if (ME != MemoryEffects::unknown())
1785 B.addMemoryAttr(ME);
1786 return HaveError;
1787}
1788
1789//===----------------------------------------------------------------------===//
1790// GlobalValue Reference/Resolution Routines.
1791//===----------------------------------------------------------------------===//
1792
1794 // The used global type does not matter. We will later RAUW it with a
1795 // global/function of the correct type.
1796 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1799 PTy->getAddressSpace());
1800}
1801
1802Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1803 Value *Val) {
1804 Type *ValTy = Val->getType();
1805 if (ValTy == Ty)
1806 return Val;
1807 if (Ty->isLabelTy())
1808 error(Loc, "'" + Name + "' is not a basic block");
1809 else
1810 error(Loc, "'" + Name + "' defined with type '" +
1811 getTypeString(Val->getType()) + "' but expected '" +
1812 getTypeString(Ty) + "'");
1813 return nullptr;
1814}
1815
1816/// getGlobalVal - Get a value with the specified name or ID, creating a
1817/// forward reference record if needed. This can return null if the value
1818/// exists but does not have the right type.
1819GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1820 LocTy Loc) {
1822 if (!PTy) {
1823 error(Loc, "global variable reference must have pointer type");
1824 return nullptr;
1825 }
1826
1827 // Look this name up in the normal function symbol table.
1828 GlobalValue *Val =
1829 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1830
1831 // If this is a forward reference for the value, see if we already created a
1832 // forward ref record.
1833 if (!Val) {
1834 auto I = ForwardRefVals.find(Name);
1835 if (I != ForwardRefVals.end())
1836 Val = I->second.first;
1837 }
1838
1839 // If we have the value in the symbol table or fwd-ref table, return it.
1840 if (Val)
1842 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1843
1844 // Otherwise, create a new forward reference for this value and remember it.
1845 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1846 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1847 return FwdVal;
1848}
1849
1850GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1852 if (!PTy) {
1853 error(Loc, "global variable reference must have pointer type");
1854 return nullptr;
1855 }
1856
1857 GlobalValue *Val = NumberedVals.get(ID);
1858
1859 // If this is a forward reference for the value, see if we already created a
1860 // forward ref record.
1861 if (!Val) {
1862 auto I = ForwardRefValIDs.find(ID);
1863 if (I != ForwardRefValIDs.end())
1864 Val = I->second.first;
1865 }
1866
1867 // If we have the value in the symbol table or fwd-ref table, return it.
1868 if (Val)
1870 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1871
1872 // Otherwise, create a new forward reference for this value and remember it.
1873 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1874 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1875 return FwdVal;
1876}
1877
1878//===----------------------------------------------------------------------===//
1879// Comdat Reference/Resolution Routines.
1880//===----------------------------------------------------------------------===//
1881
1882Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1883 // Look this name up in the comdat symbol table.
1884 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1885 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1886 if (I != ComdatSymTab.end())
1887 return &I->second;
1888
1889 // Otherwise, create a new forward reference for this value and remember it.
1890 Comdat *C = M->getOrInsertComdat(Name);
1891 ForwardRefComdats[Name] = Loc;
1892 return C;
1893}
1894
1895//===----------------------------------------------------------------------===//
1896// Helper Routines.
1897//===----------------------------------------------------------------------===//
1898
1899/// parseToken - If the current token has the specified kind, eat it and return
1900/// success. Otherwise, emit the specified error and return failure.
1901bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1902 if (Lex.getKind() != T)
1903 return tokError(ErrMsg);
1904 Lex.Lex();
1905 return false;
1906}
1907
1908/// parseStringConstant
1909/// ::= StringConstant
1910bool LLParser::parseStringConstant(std::string &Result) {
1911 if (Lex.getKind() != lltok::StringConstant)
1912 return tokError("expected string constant");
1913 Result = Lex.getStrVal();
1914 Lex.Lex();
1915 return false;
1916}
1917
1918/// parseUInt32
1919/// ::= uint32
1920bool LLParser::parseUInt32(uint32_t &Val) {
1921 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1922 return tokError("expected integer");
1923 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1924 if (Val64 != unsigned(Val64))
1925 return tokError("expected 32-bit integer (too large)");
1926 Val = Val64;
1927 Lex.Lex();
1928 return false;
1929}
1930
1931/// parseUInt64
1932/// ::= uint64
1933bool LLParser::parseUInt64(uint64_t &Val) {
1934 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1935 return tokError("expected integer");
1936 Val = Lex.getAPSIntVal().getLimitedValue();
1937 Lex.Lex();
1938 return false;
1939}
1940
1941/// parseTLSModel
1942/// := 'localdynamic'
1943/// := 'initialexec'
1944/// := 'localexec'
1945bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1946 switch (Lex.getKind()) {
1947 default:
1948 return tokError("expected localdynamic, initialexec or localexec");
1951 break;
1954 break;
1957 break;
1958 }
1959
1960 Lex.Lex();
1961 return false;
1962}
1963
1964/// parseOptionalThreadLocal
1965/// := /*empty*/
1966/// := 'thread_local'
1967/// := 'thread_local' '(' tlsmodel ')'
1968bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1970 if (!EatIfPresent(lltok::kw_thread_local))
1971 return false;
1972
1974 if (Lex.getKind() == lltok::lparen) {
1975 Lex.Lex();
1976 return parseTLSModel(TLM) ||
1977 parseToken(lltok::rparen, "expected ')' after thread local model");
1978 }
1979 return false;
1980}
1981
1982/// parseOptionalAddrSpace
1983/// := /*empty*/
1984/// := 'addrspace' '(' uint32 ')'
1985bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1986 AddrSpace = DefaultAS;
1987 if (!EatIfPresent(lltok::kw_addrspace))
1988 return false;
1989
1990 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1991 if (Lex.getKind() == lltok::StringConstant) {
1992 const std::string &AddrSpaceStr = Lex.getStrVal();
1993 if (AddrSpaceStr == "A") {
1994 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1995 } else if (AddrSpaceStr == "G") {
1996 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1997 } else if (AddrSpaceStr == "P") {
1998 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1999 } else if (std::optional<unsigned> AS =
2000 M->getDataLayout().getNamedAddressSpace(AddrSpaceStr)) {
2001 AddrSpace = *AS;
2002 } else {
2003 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
2004 }
2005 Lex.Lex();
2006 return false;
2007 }
2008 if (Lex.getKind() != lltok::APSInt)
2009 return tokError("expected integer or string constant");
2010 SMLoc Loc = Lex.getLoc();
2011 if (parseUInt32(AddrSpace))
2012 return true;
2013 if (!isUInt<24>(AddrSpace))
2014 return error(Loc, "invalid address space, must be a 24-bit integer");
2015 return false;
2016 };
2017
2018 return parseToken(lltok::lparen, "expected '(' in address space") ||
2019 ParseAddrspaceValue(AddrSpace) ||
2020 parseToken(lltok::rparen, "expected ')' in address space");
2021}
2022
2023/// parseStringAttribute
2024/// := StringConstant
2025/// := StringConstant '=' StringConstant
2026bool LLParser::parseStringAttribute(AttrBuilder &B) {
2027 std::string Attr = Lex.getStrVal();
2028 Lex.Lex();
2029 std::string Val;
2030 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
2031 return true;
2032 B.addAttribute(Attr, Val);
2033 return false;
2034}
2035
2036/// Parse a potentially empty list of parameter or return attributes.
2037bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
2038 bool HaveError = false;
2039
2040 B.clear();
2041
2042 while (true) {
2043 lltok::Kind Token = Lex.getKind();
2044 if (Token == lltok::StringConstant) {
2045 if (parseStringAttribute(B))
2046 return true;
2047 continue;
2048 }
2049
2050 if (Token == lltok::kw_nocapture) {
2051 Lex.Lex();
2052 B.addCapturesAttr(CaptureInfo::none());
2053 continue;
2054 }
2055
2056 SMLoc Loc = Lex.getLoc();
2058 if (Attr == Attribute::None)
2059 return HaveError;
2060
2061 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2062 return true;
2063
2064 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2065 HaveError |= error(Loc, "this attribute does not apply to parameters");
2066 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2067 HaveError |= error(Loc, "this attribute does not apply to return values");
2068 }
2069}
2070
2071static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2072 HasLinkage = true;
2073 switch (Kind) {
2074 default:
2075 HasLinkage = false;
2077 case lltok::kw_private:
2079 case lltok::kw_internal:
2081 case lltok::kw_weak:
2083 case lltok::kw_weak_odr:
2085 case lltok::kw_linkonce:
2093 case lltok::kw_common:
2097 case lltok::kw_external:
2099 }
2100}
2101
2102/// parseOptionalLinkage
2103/// ::= /*empty*/
2104/// ::= 'private'
2105/// ::= 'internal'
2106/// ::= 'weak'
2107/// ::= 'weak_odr'
2108/// ::= 'linkonce'
2109/// ::= 'linkonce_odr'
2110/// ::= 'available_externally'
2111/// ::= 'appending'
2112/// ::= 'common'
2113/// ::= 'extern_weak'
2114/// ::= 'external'
2115bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2116 unsigned &Visibility,
2117 unsigned &DLLStorageClass, bool &DSOLocal) {
2118 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2119 if (HasLinkage)
2120 Lex.Lex();
2121 parseOptionalDSOLocal(DSOLocal);
2122 parseOptionalVisibility(Visibility);
2123 parseOptionalDLLStorageClass(DLLStorageClass);
2124
2125 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2126 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2127 }
2128
2129 return false;
2130}
2131
2132void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2133 switch (Lex.getKind()) {
2134 default:
2135 DSOLocal = false;
2136 break;
2138 DSOLocal = true;
2139 Lex.Lex();
2140 break;
2142 DSOLocal = false;
2143 Lex.Lex();
2144 break;
2145 }
2146}
2147
2148/// parseOptionalVisibility
2149/// ::= /*empty*/
2150/// ::= 'default'
2151/// ::= 'hidden'
2152/// ::= 'protected'
2153///
2154void LLParser::parseOptionalVisibility(unsigned &Res) {
2155 switch (Lex.getKind()) {
2156 default:
2158 return;
2159 case lltok::kw_default:
2161 break;
2162 case lltok::kw_hidden:
2164 break;
2167 break;
2168 }
2169 Lex.Lex();
2170}
2171
2172bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2174 switch (Kind) {
2175 default:
2176 return tokError("unknown import kind. Expect definition or declaration.");
2179 return false;
2182 return false;
2183 }
2184}
2185
2186/// parseOptionalDLLStorageClass
2187/// ::= /*empty*/
2188/// ::= 'dllimport'
2189/// ::= 'dllexport'
2190///
2191void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2192 switch (Lex.getKind()) {
2193 default:
2195 return;
2198 break;
2201 break;
2202 }
2203 Lex.Lex();
2204}
2205
2206/// parseOptionalCallingConv
2207/// ::= /*empty*/
2208/// ::= 'ccc'
2209/// ::= 'fastcc'
2210/// ::= 'intel_ocl_bicc'
2211/// ::= 'coldcc'
2212/// ::= 'cfguard_checkcc'
2213/// ::= 'x86_stdcallcc'
2214/// ::= 'x86_fastcallcc'
2215/// ::= 'x86_thiscallcc'
2216/// ::= 'x86_vectorcallcc'
2217/// ::= 'arm_apcscc'
2218/// ::= 'arm_aapcscc'
2219/// ::= 'arm_aapcs_vfpcc'
2220/// ::= 'aarch64_vector_pcs'
2221/// ::= 'aarch64_sve_vector_pcs'
2222/// ::= 'aarch64_sme_preservemost_from_x0'
2223/// ::= 'aarch64_sme_preservemost_from_x1'
2224/// ::= 'aarch64_sme_preservemost_from_x2'
2225/// ::= 'msp430_intrcc'
2226/// ::= 'avr_intrcc'
2227/// ::= 'avr_signalcc'
2228/// ::= 'ptx_kernel'
2229/// ::= 'ptx_device'
2230/// ::= 'spir_func'
2231/// ::= 'spir_kernel'
2232/// ::= 'x86_64_sysvcc'
2233/// ::= 'win64cc'
2234/// ::= 'anyregcc'
2235/// ::= 'preserve_mostcc'
2236/// ::= 'preserve_allcc'
2237/// ::= 'preserve_nonecc'
2238/// ::= 'ghccc'
2239/// ::= 'swiftcc'
2240/// ::= 'swifttailcc'
2241/// ::= 'x86_intrcc'
2242/// ::= 'hhvmcc'
2243/// ::= 'hhvm_ccc'
2244/// ::= 'cxx_fast_tlscc'
2245/// ::= 'amdgpu_vs'
2246/// ::= 'amdgpu_ls'
2247/// ::= 'amdgpu_hs'
2248/// ::= 'amdgpu_es'
2249/// ::= 'amdgpu_gs'
2250/// ::= 'amdgpu_ps'
2251/// ::= 'amdgpu_cs'
2252/// ::= 'amdgpu_cs_chain'
2253/// ::= 'amdgpu_cs_chain_preserve'
2254/// ::= 'amdgpu_kernel'
2255/// ::= 'tailcc'
2256/// ::= 'm68k_rtdcc'
2257/// ::= 'graalcc'
2258/// ::= 'riscv_vector_cc'
2259/// ::= 'riscv_vls_cc'
2260/// ::= 'cc' UINT
2261///
2262bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2263 switch (Lex.getKind()) {
2264 default: CC = CallingConv::C; return false;
2265 case lltok::kw_ccc: CC = CallingConv::C; break;
2266 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2267 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2280 break;
2283 break;
2286 break;
2289 break;
2299 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2300 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2304 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2305 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2308 case lltok::kw_hhvmcc:
2310 break;
2311 case lltok::kw_hhvm_ccc:
2313 break;
2325 break;
2328 break;
2332 break;
2333 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2335 case lltok::kw_graalcc: CC = CallingConv::GRAAL; break;
2338 break;
2340 // Default ABI_VLEN
2342 Lex.Lex();
2343 if (!EatIfPresent(lltok::lparen))
2344 break;
2345 uint32_t ABIVlen;
2346 if (parseUInt32(ABIVlen) || !EatIfPresent(lltok::rparen))
2347 return true;
2348 switch (ABIVlen) {
2349 default:
2350 return tokError("unknown RISC-V ABI VLEN");
2351#define CC_VLS_CASE(ABIVlen) \
2352 case ABIVlen: \
2353 CC = CallingConv::RISCV_VLSCall_##ABIVlen; \
2354 break;
2355 CC_VLS_CASE(32)
2356 CC_VLS_CASE(64)
2357 CC_VLS_CASE(128)
2358 CC_VLS_CASE(256)
2359 CC_VLS_CASE(512)
2360 CC_VLS_CASE(1024)
2361 CC_VLS_CASE(2048)
2362 CC_VLS_CASE(4096)
2363 CC_VLS_CASE(8192)
2364 CC_VLS_CASE(16384)
2365 CC_VLS_CASE(32768)
2366 CC_VLS_CASE(65536)
2367#undef CC_VLS_CASE
2368 }
2369 return false;
2372 break;
2375 break;
2378 break;
2379 case lltok::kw_cc: {
2380 Lex.Lex();
2381 return parseUInt32(CC);
2382 }
2383 }
2384
2385 Lex.Lex();
2386 return false;
2387}
2388
2389/// parseMetadataAttachment
2390/// ::= !dbg !42
2391bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2392 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2393
2394 std::string Name = Lex.getStrVal();
2395 Kind = M->getMDKindID(Name);
2396 Lex.Lex();
2397
2398 return parseMDNode(MD);
2399}
2400
2401/// parseInstructionMetadata
2402/// ::= !dbg !42 (',' !dbg !57)*
2403bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2404 do {
2405 if (Lex.getKind() != lltok::MetadataVar)
2406 return tokError("expected metadata after comma");
2407
2408 unsigned MDK;
2409 MDNode *N;
2410 if (parseMetadataAttachment(MDK, N))
2411 return true;
2412
2413 if (MDK == LLVMContext::MD_DIAssignID)
2414 TempDIAssignIDAttachments[N].push_back(&Inst);
2415 else
2416 Inst.setMetadata(MDK, N);
2417
2418 if (MDK == LLVMContext::MD_tbaa)
2419 InstsWithTBAATag.push_back(&Inst);
2420
2421 // If this is the end of the list, we're done.
2422 } while (EatIfPresent(lltok::comma));
2423 return false;
2424}
2425
2426/// parseGlobalObjectMetadataAttachment
2427/// ::= !dbg !57
2428bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2429 unsigned MDK;
2430 MDNode *N;
2431 if (parseMetadataAttachment(MDK, N))
2432 return true;
2433
2434 GO.addMetadata(MDK, *N);
2435 return false;
2436}
2437
2438/// parseOptionalFunctionMetadata
2439/// ::= (!dbg !57)*
2440bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2441 while (Lex.getKind() == lltok::MetadataVar)
2442 if (parseGlobalObjectMetadataAttachment(F))
2443 return true;
2444 return false;
2445}
2446
2447/// parseOptionalAlignment
2448/// ::= /* empty */
2449/// ::= 'align' 4
2450bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2451 Alignment = std::nullopt;
2452 if (!EatIfPresent(lltok::kw_align))
2453 return false;
2454 LocTy AlignLoc = Lex.getLoc();
2455 uint64_t Value = 0;
2456
2457 LocTy ParenLoc = Lex.getLoc();
2458 bool HaveParens = false;
2459 if (AllowParens) {
2460 if (EatIfPresent(lltok::lparen))
2461 HaveParens = true;
2462 }
2463
2464 if (parseUInt64(Value))
2465 return true;
2466
2467 if (HaveParens && !EatIfPresent(lltok::rparen))
2468 return error(ParenLoc, "expected ')'");
2469
2470 if (!isPowerOf2_64(Value))
2471 return error(AlignLoc, "alignment is not a power of two");
2473 return error(AlignLoc, "huge alignments are not supported yet");
2474 Alignment = Align(Value);
2475 return false;
2476}
2477
2478/// parseOptionalPrefAlignment
2479/// ::= /* empty */
2480/// ::= 'prefalign' '(' 4 ')'
2481bool LLParser::parseOptionalPrefAlignment(MaybeAlign &Alignment) {
2482 Alignment = std::nullopt;
2483 if (!EatIfPresent(lltok::kw_prefalign))
2484 return false;
2485 LocTy AlignLoc = Lex.getLoc();
2486 uint64_t Value = 0;
2487
2488 LocTy ParenLoc = Lex.getLoc();
2489 if (!EatIfPresent(lltok::lparen))
2490 return error(ParenLoc, "expected '('");
2491
2492 if (parseUInt64(Value))
2493 return true;
2494
2495 ParenLoc = Lex.getLoc();
2496 if (!EatIfPresent(lltok::rparen))
2497 return error(ParenLoc, "expected ')'");
2498
2499 if (!isPowerOf2_64(Value))
2500 return error(AlignLoc, "alignment is not a power of two");
2502 return error(AlignLoc, "huge alignments are not supported yet");
2503 Alignment = Align(Value);
2504 return false;
2505}
2506
2507/// parseOptionalCodeModel
2508/// ::= /* empty */
2509/// ::= 'code_model' "large"
2510bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2511 Lex.Lex();
2512 auto StrVal = Lex.getStrVal();
2513 auto ErrMsg = "expected global code model string";
2514 if (StrVal == "tiny")
2515 model = CodeModel::Tiny;
2516 else if (StrVal == "small")
2517 model = CodeModel::Small;
2518 else if (StrVal == "kernel")
2519 model = CodeModel::Kernel;
2520 else if (StrVal == "medium")
2521 model = CodeModel::Medium;
2522 else if (StrVal == "large")
2523 model = CodeModel::Large;
2524 else
2525 return tokError(ErrMsg);
2526 if (parseToken(lltok::StringConstant, ErrMsg))
2527 return true;
2528 return false;
2529}
2530
2531/// parseOptionalAttrBytes
2532/// ::= /* empty */
2533/// ::= AttrKind '(' 4 ')'
2534///
2535/// where AttrKind is either 'dereferenceable', 'dereferenceable_or_null', or
2536/// 'dead_on_return'
2537bool LLParser::parseOptionalAttrBytes(lltok::Kind AttrKind,
2538 std::optional<uint64_t> &Bytes,
2539 bool ErrorNoBytes) {
2540 assert((AttrKind == lltok::kw_dereferenceable ||
2541 AttrKind == lltok::kw_dereferenceable_or_null ||
2542 AttrKind == lltok::kw_dead_on_return) &&
2543 "contract!");
2544
2545 Bytes = 0;
2546 if (!EatIfPresent(AttrKind))
2547 return false;
2548 LocTy ParenLoc = Lex.getLoc();
2549 if (!EatIfPresent(lltok::lparen)) {
2550 if (ErrorNoBytes)
2551 return error(ParenLoc, "expected '('");
2552 Bytes = std::nullopt;
2553 return false;
2554 }
2555 LocTy DerefLoc = Lex.getLoc();
2556 if (parseUInt64(Bytes.value()))
2557 return true;
2558 ParenLoc = Lex.getLoc();
2559 if (!EatIfPresent(lltok::rparen))
2560 return error(ParenLoc, "expected ')'");
2561 if (!Bytes.value())
2562 return error(DerefLoc, "byte count specified must be non-zero");
2563 return false;
2564}
2565
2566bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2567 Lex.Lex();
2569 if (!EatIfPresent(lltok::lparen))
2570 return false;
2571 LocTy KindLoc = Lex.getLoc();
2572 if (Lex.getKind() == lltok::kw_sync)
2574 else if (Lex.getKind() == lltok::kw_async)
2576 else
2577 return error(KindLoc, "expected unwind table kind");
2578 Lex.Lex();
2579 return parseToken(lltok::rparen, "expected ')'");
2580}
2581
2582bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2583 Lex.Lex();
2584 LocTy ParenLoc = Lex.getLoc();
2585 if (!EatIfPresent(lltok::lparen))
2586 return error(ParenLoc, "expected '('");
2587 LocTy KindLoc = Lex.getLoc();
2588 std::string Arg;
2589 if (parseStringConstant(Arg))
2590 return error(KindLoc, "expected allockind value");
2591 for (StringRef A : llvm::split(Arg, ",")) {
2592 if (A == "alloc") {
2594 } else if (A == "realloc") {
2596 } else if (A == "free") {
2598 } else if (A == "uninitialized") {
2600 } else if (A == "zeroed") {
2602 } else if (A == "aligned") {
2604 } else {
2605 return error(KindLoc, Twine("unknown allockind ") + A);
2606 }
2607 }
2608 ParenLoc = Lex.getLoc();
2609 if (!EatIfPresent(lltok::rparen))
2610 return error(ParenLoc, "expected ')'");
2611 if (Kind == AllocFnKind::Unknown)
2612 return error(KindLoc, "expected allockind value");
2613 return false;
2614}
2615
2617 using Loc = IRMemLocation;
2618
2619 switch (Tok) {
2620 case lltok::kw_argmem:
2621 return {Loc::ArgMem};
2623 return {Loc::InaccessibleMem};
2624 case lltok::kw_errnomem:
2625 return {Loc::ErrnoMem};
2627 return {Loc::TargetMem0};
2629 return {Loc::TargetMem1};
2630 case lltok::kw_target_mem: {
2633 Targets.push_back(Loc);
2634 return Targets;
2635 }
2636 default:
2637 return {};
2638 }
2639}
2640
2641static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2642 switch (Tok) {
2643 case lltok::kw_none:
2644 return ModRefInfo::NoModRef;
2645 case lltok::kw_read:
2646 return ModRefInfo::Ref;
2647 case lltok::kw_write:
2648 return ModRefInfo::Mod;
2650 return ModRefInfo::ModRef;
2651 default:
2652 return std::nullopt;
2653 }
2654}
2655
2656static std::optional<DenormalMode::DenormalModeKind>
2658 switch (Tok) {
2659 case lltok::kw_ieee:
2660 return DenormalMode::IEEE;
2665 case lltok::kw_dynamic:
2666 return DenormalMode::Dynamic;
2667 default:
2668 return std::nullopt;
2669 }
2670}
2671
2672std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2674
2675 // We use syntax like memory(argmem: read), so the colon should not be
2676 // interpreted as a label terminator.
2677 Lex.setIgnoreColonInIdentifiers(true);
2678 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2679
2680 Lex.Lex();
2681 if (!EatIfPresent(lltok::lparen)) {
2682 tokError("expected '('");
2683 return std::nullopt;
2684 }
2685
2686 bool SeenLoc = false;
2687 bool SeenTargetLoc = false;
2688 do {
2689 SmallVector<IRMemLocation, 2> Locs = keywordToLoc(Lex.getKind());
2690 if (!Locs.empty()) {
2691 Lex.Lex();
2692 if (!EatIfPresent(lltok::colon)) {
2693 tokError("expected ':' after location");
2694 return std::nullopt;
2695 }
2696 }
2697
2698 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2699 if (!MR) {
2700 if (Locs.empty())
2701 tokError("expected memory location (argmem, inaccessiblemem, errnomem) "
2702 "or access kind (none, read, write, readwrite)");
2703 else
2704 tokError("expected access kind (none, read, write, readwrite)");
2705 return std::nullopt;
2706 }
2707
2708 Lex.Lex();
2709 if (!Locs.empty()) {
2710 SeenLoc = true;
2711 for (IRMemLocation Loc : Locs) {
2712 ME = ME.getWithModRef(Loc, *MR);
2713 if (ME.isTargetMemLoc(Loc) && Locs.size() == 1)
2714 SeenTargetLoc = true;
2715 }
2716 if (Locs.size() > 1 && SeenTargetLoc) {
2717 tokError("target memory default access kind must be specified first");
2718 return std::nullopt;
2719 }
2720
2721 } else {
2722 if (SeenLoc) {
2723 tokError("default access kind must be specified first");
2724 return std::nullopt;
2725 }
2726 ME = MemoryEffects(*MR);
2727 }
2728
2729 if (EatIfPresent(lltok::rparen))
2730 return ME;
2731 } while (EatIfPresent(lltok::comma));
2732
2733 tokError("unterminated memory attribute");
2734 return std::nullopt;
2735}
2736
2737std::optional<DenormalMode> LLParser::parseDenormalFPEnvEntry() {
2738 std::optional<DenormalMode::DenormalModeKind> OutputMode =
2739 keywordToDenormalModeKind(Lex.getKind());
2740 if (!OutputMode) {
2741 tokError("expected denormal behavior kind (ieee, preservesign, "
2742 "positivezero, dynamic)");
2743 return {};
2744 }
2745
2746 Lex.Lex();
2747
2748 std::optional<DenormalMode::DenormalModeKind> InputMode;
2749 if (EatIfPresent(lltok::bar)) {
2750 InputMode = keywordToDenormalModeKind(Lex.getKind());
2751 if (!InputMode) {
2752 tokError("expected denormal behavior kind (ieee, preservesign, "
2753 "positivezero, dynamic)");
2754 return {};
2755 }
2756
2757 Lex.Lex();
2758 } else {
2759 // Single item, input == output mode
2760 InputMode = OutputMode;
2761 }
2762
2763 return DenormalMode(*OutputMode, *InputMode);
2764}
2765
2766std::optional<DenormalFPEnv> LLParser::parseDenormalFPEnvAttr() {
2767 // We use syntax like denormal_fpenv(float: preservesign), so the colon should
2768 // not be interpreted as a label terminator.
2769 Lex.setIgnoreColonInIdentifiers(true);
2770 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
2771
2772 Lex.Lex();
2773
2774 if (parseToken(lltok::lparen, "expected '('"))
2775 return {};
2776
2777 DenormalMode DefaultMode = DenormalMode::getIEEE();
2778 DenormalMode F32Mode = DenormalMode::getInvalid();
2779
2780 bool HasDefaultSection = false;
2781 if (Lex.getKind() != lltok::Type) {
2782 std::optional<DenormalMode> ParsedDefaultMode = parseDenormalFPEnvEntry();
2783 if (!ParsedDefaultMode)
2784 return {};
2785 DefaultMode = *ParsedDefaultMode;
2786 HasDefaultSection = true;
2787 }
2788
2789 bool HasComma = EatIfPresent(lltok::comma);
2790 if (Lex.getKind() == lltok::Type) {
2791 if (HasDefaultSection && !HasComma) {
2792 tokError("expected ',' before float:");
2793 return {};
2794 }
2795
2796 Type *Ty = nullptr;
2797 if (parseType(Ty) || !Ty->isFloatTy()) {
2798 tokError("expected float:");
2799 return {};
2800 }
2801
2802 if (parseToken(lltok::colon, "expected ':' before float denormal_fpenv"))
2803 return {};
2804
2805 std::optional<DenormalMode> ParsedF32Mode = parseDenormalFPEnvEntry();
2806 if (!ParsedF32Mode)
2807 return {};
2808
2809 F32Mode = *ParsedF32Mode;
2810 }
2811
2812 if (parseToken(lltok::rparen, "unterminated denormal_fpenv"))
2813 return {};
2814
2815 return DenormalFPEnv(DefaultMode, F32Mode);
2816}
2817
2818static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2819 switch (Tok) {
2820 case lltok::kw_all:
2821 return fcAllFlags;
2822 case lltok::kw_nan:
2823 return fcNan;
2824 case lltok::kw_snan:
2825 return fcSNan;
2826 case lltok::kw_qnan:
2827 return fcQNan;
2828 case lltok::kw_inf:
2829 return fcInf;
2830 case lltok::kw_ninf:
2831 return fcNegInf;
2832 case lltok::kw_pinf:
2833 return fcPosInf;
2834 case lltok::kw_norm:
2835 return fcNormal;
2836 case lltok::kw_nnorm:
2837 return fcNegNormal;
2838 case lltok::kw_pnorm:
2839 return fcPosNormal;
2840 case lltok::kw_sub:
2841 return fcSubnormal;
2842 case lltok::kw_nsub:
2843 return fcNegSubnormal;
2844 case lltok::kw_psub:
2845 return fcPosSubnormal;
2846 case lltok::kw_zero:
2847 return fcZero;
2848 case lltok::kw_nzero:
2849 return fcNegZero;
2850 case lltok::kw_pzero:
2851 return fcPosZero;
2852 default:
2853 return 0;
2854 }
2855}
2856
2857unsigned LLParser::parseNoFPClassAttr() {
2858 unsigned Mask = fcNone;
2859
2860 Lex.Lex();
2861 if (!EatIfPresent(lltok::lparen)) {
2862 tokError("expected '('");
2863 return 0;
2864 }
2865
2866 do {
2867 uint64_t Value = 0;
2868 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2869 if (TestMask != 0) {
2870 Mask |= TestMask;
2871 // TODO: Disallow overlapping masks to avoid copy paste errors
2872 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2873 !parseUInt64(Value)) {
2874 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2875 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2876 return 0;
2877 }
2878
2879 if (!EatIfPresent(lltok::rparen)) {
2880 error(Lex.getLoc(), "expected ')'");
2881 return 0;
2882 }
2883
2884 return Value;
2885 } else {
2886 error(Lex.getLoc(), "expected nofpclass test mask");
2887 return 0;
2888 }
2889
2890 Lex.Lex();
2891 if (EatIfPresent(lltok::rparen))
2892 return Mask;
2893 } while (1);
2894
2895 llvm_unreachable("unterminated nofpclass attribute");
2896}
2897
2898/// parseOptionalCommaAlign
2899/// ::=
2900/// ::= ',' align 4
2901///
2902/// This returns with AteExtraComma set to true if it ate an excess comma at the
2903/// end.
2904bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2905 bool &AteExtraComma) {
2906 AteExtraComma = false;
2907 while (EatIfPresent(lltok::comma)) {
2908 // Metadata at the end is an early exit.
2909 if (Lex.getKind() == lltok::MetadataVar) {
2910 AteExtraComma = true;
2911 return false;
2912 }
2913
2914 if (Lex.getKind() != lltok::kw_align)
2915 return error(Lex.getLoc(), "expected metadata or 'align'");
2916
2917 if (parseOptionalAlignment(Alignment))
2918 return true;
2919 }
2920
2921 return false;
2922}
2923
2924/// parseOptionalCommaAddrSpace
2925/// ::=
2926/// ::= ',' addrspace(1)
2927///
2928/// This returns with AteExtraComma set to true if it ate an excess comma at the
2929/// end.
2930bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2931 bool &AteExtraComma) {
2932 AteExtraComma = false;
2933 while (EatIfPresent(lltok::comma)) {
2934 // Metadata at the end is an early exit.
2935 if (Lex.getKind() == lltok::MetadataVar) {
2936 AteExtraComma = true;
2937 return false;
2938 }
2939
2940 Loc = Lex.getLoc();
2941 if (Lex.getKind() != lltok::kw_addrspace)
2942 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2943
2944 if (parseOptionalAddrSpace(AddrSpace))
2945 return true;
2946 }
2947
2948 return false;
2949}
2950
2951bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2952 std::optional<unsigned> &HowManyArg) {
2953 Lex.Lex();
2954
2955 auto StartParen = Lex.getLoc();
2956 if (!EatIfPresent(lltok::lparen))
2957 return error(StartParen, "expected '('");
2958
2959 if (parseUInt32(BaseSizeArg))
2960 return true;
2961
2962 if (EatIfPresent(lltok::comma)) {
2963 auto HowManyAt = Lex.getLoc();
2964 unsigned HowMany;
2965 if (parseUInt32(HowMany))
2966 return true;
2967 if (HowMany == BaseSizeArg)
2968 return error(HowManyAt,
2969 "'allocsize' indices can't refer to the same parameter");
2970 HowManyArg = HowMany;
2971 } else
2972 HowManyArg = std::nullopt;
2973
2974 auto EndParen = Lex.getLoc();
2975 if (!EatIfPresent(lltok::rparen))
2976 return error(EndParen, "expected ')'");
2977 return false;
2978}
2979
2980bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2981 unsigned &MaxValue) {
2982 Lex.Lex();
2983
2984 auto StartParen = Lex.getLoc();
2985 if (!EatIfPresent(lltok::lparen))
2986 return error(StartParen, "expected '('");
2987
2988 if (parseUInt32(MinValue))
2989 return true;
2990
2991 if (EatIfPresent(lltok::comma)) {
2992 if (parseUInt32(MaxValue))
2993 return true;
2994 } else
2995 MaxValue = MinValue;
2996
2997 auto EndParen = Lex.getLoc();
2998 if (!EatIfPresent(lltok::rparen))
2999 return error(EndParen, "expected ')'");
3000 return false;
3001}
3002
3003/// parseScopeAndOrdering
3004/// if isAtomic: ::= SyncScope? AtomicOrdering
3005/// else: ::=
3006///
3007/// This sets Scope and Ordering to the parsed values.
3008bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
3009 AtomicOrdering &Ordering) {
3010 if (!IsAtomic)
3011 return false;
3012
3013 return parseScope(SSID) || parseOrdering(Ordering);
3014}
3015
3016/// parseScope
3017/// ::= syncscope("singlethread" | "<target scope>")?
3018///
3019/// This sets synchronization scope ID to the ID of the parsed value.
3020bool LLParser::parseScope(SyncScope::ID &SSID) {
3021 SSID = SyncScope::System;
3022 if (EatIfPresent(lltok::kw_syncscope)) {
3023 auto StartParenAt = Lex.getLoc();
3024 if (!EatIfPresent(lltok::lparen))
3025 return error(StartParenAt, "Expected '(' in syncscope");
3026
3027 std::string SSN;
3028 auto SSNAt = Lex.getLoc();
3029 if (parseStringConstant(SSN))
3030 return error(SSNAt, "Expected synchronization scope name");
3031
3032 auto EndParenAt = Lex.getLoc();
3033 if (!EatIfPresent(lltok::rparen))
3034 return error(EndParenAt, "Expected ')' in syncscope");
3035
3036 SSID = Context.getOrInsertSyncScopeID(SSN);
3037 }
3038
3039 return false;
3040}
3041
3042/// parseOrdering
3043/// ::= AtomicOrdering
3044///
3045/// This sets Ordering to the parsed value.
3046bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
3047 switch (Lex.getKind()) {
3048 default:
3049 return tokError("Expected ordering on atomic instruction");
3052 // Not specified yet:
3053 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
3057 case lltok::kw_seq_cst:
3059 break;
3060 }
3061 Lex.Lex();
3062 return false;
3063}
3064
3065/// parseOptionalStackAlignment
3066/// ::= /* empty */
3067/// ::= 'alignstack' '(' 4 ')'
3068bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
3069 Alignment = 0;
3070 if (!EatIfPresent(lltok::kw_alignstack))
3071 return false;
3072 LocTy ParenLoc = Lex.getLoc();
3073 if (!EatIfPresent(lltok::lparen))
3074 return error(ParenLoc, "expected '('");
3075 LocTy AlignLoc = Lex.getLoc();
3076 if (parseUInt32(Alignment))
3077 return true;
3078 ParenLoc = Lex.getLoc();
3079 if (!EatIfPresent(lltok::rparen))
3080 return error(ParenLoc, "expected ')'");
3081 if (!isPowerOf2_32(Alignment))
3082 return error(AlignLoc, "stack alignment is not a power of two");
3083 return false;
3084}
3085
3086/// parseIndexList - This parses the index list for an insert/extractvalue
3087/// instruction. This sets AteExtraComma in the case where we eat an extra
3088/// comma at the end of the line and find that it is followed by metadata.
3089/// Clients that don't allow metadata can call the version of this function that
3090/// only takes one argument.
3091///
3092/// parseIndexList
3093/// ::= (',' uint32)+
3094///
3095bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
3096 bool &AteExtraComma) {
3097 AteExtraComma = false;
3098
3099 if (Lex.getKind() != lltok::comma)
3100 return tokError("expected ',' as start of index list");
3101
3102 while (EatIfPresent(lltok::comma)) {
3103 if (Lex.getKind() == lltok::MetadataVar) {
3104 if (Indices.empty())
3105 return tokError("expected index");
3106 AteExtraComma = true;
3107 return false;
3108 }
3109 unsigned Idx = 0;
3110 if (parseUInt32(Idx))
3111 return true;
3112 Indices.push_back(Idx);
3113 }
3114
3115 return false;
3116}
3117
3118//===----------------------------------------------------------------------===//
3119// Type Parsing.
3120//===----------------------------------------------------------------------===//
3121
3122/// parseType - parse a type.
3123bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
3124 SMLoc TypeLoc = Lex.getLoc();
3125 switch (Lex.getKind()) {
3126 default:
3127 return tokError(Msg);
3128 case lltok::Type:
3129 // Type ::= 'float' | 'void' (etc)
3130 Result = Lex.getTyVal();
3131 Lex.Lex();
3132
3133 // Handle "ptr" opaque pointer type.
3134 //
3135 // Type ::= ptr ('addrspace' '(' uint32 ')')?
3136 if (Result->isPointerTy()) {
3137 unsigned AddrSpace;
3138 if (parseOptionalAddrSpace(AddrSpace))
3139 return true;
3140 Result = PointerType::get(getContext(), AddrSpace);
3141
3142 // Give a nice error for 'ptr*'.
3143 if (Lex.getKind() == lltok::star)
3144 return tokError("ptr* is invalid - use ptr instead");
3145
3146 // Fall through to parsing the type suffixes only if this 'ptr' is a
3147 // function return. Otherwise, return success, implicitly rejecting other
3148 // suffixes.
3149 if (Lex.getKind() != lltok::lparen)
3150 return false;
3151 }
3152 break;
3153 case lltok::kw_target: {
3154 // Type ::= TargetExtType
3155 if (parseTargetExtType(Result))
3156 return true;
3157 break;
3158 }
3159 case lltok::lbrace:
3160 // Type ::= StructType
3161 if (parseAnonStructType(Result, false))
3162 return true;
3163 break;
3164 case lltok::lsquare:
3165 // Type ::= '[' ... ']'
3166 Lex.Lex(); // eat the lsquare.
3167 if (parseArrayVectorType(Result, false))
3168 return true;
3169 break;
3170 case lltok::less: // Either vector or packed struct.
3171 // Type ::= '<' ... '>'
3172 Lex.Lex();
3173 if (Lex.getKind() == lltok::lbrace) {
3174 if (parseAnonStructType(Result, true) ||
3175 parseToken(lltok::greater, "expected '>' at end of packed struct"))
3176 return true;
3177 } else if (parseArrayVectorType(Result, true))
3178 return true;
3179 break;
3180 case lltok::LocalVar: {
3181 // Type ::= %foo
3182 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
3183
3184 // If the type hasn't been defined yet, create a forward definition and
3185 // remember where that forward def'n was seen (in case it never is defined).
3186 if (!Entry.first) {
3187 Entry.first = StructType::create(Context, Lex.getStrVal());
3188 Entry.second = Lex.getLoc();
3189 }
3190 Result = Entry.first;
3191 Lex.Lex();
3192 break;
3193 }
3194
3195 case lltok::LocalVarID: {
3196 // Type ::= %4
3197 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
3198
3199 // If the type hasn't been defined yet, create a forward definition and
3200 // remember where that forward def'n was seen (in case it never is defined).
3201 if (!Entry.first) {
3202 Entry.first = StructType::create(Context);
3203 Entry.second = Lex.getLoc();
3204 }
3205 Result = Entry.first;
3206 Lex.Lex();
3207 break;
3208 }
3209 }
3210
3211 // parse the type suffixes.
3212 while (true) {
3213 switch (Lex.getKind()) {
3214 // End of type.
3215 default:
3216 if (!AllowVoid && Result->isVoidTy())
3217 return error(TypeLoc, "void type only allowed for function results");
3218 return false;
3219
3220 // Type ::= Type '*'
3221 case lltok::star:
3222 if (Result->isLabelTy())
3223 return tokError("basic block pointers are invalid");
3224 if (Result->isVoidTy())
3225 return tokError("pointers to void are invalid - use i8* instead");
3227 return tokError("pointer to this type is invalid");
3228 Result = PointerType::getUnqual(Context);
3229 Lex.Lex();
3230 break;
3231
3232 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
3233 case lltok::kw_addrspace: {
3234 if (Result->isLabelTy())
3235 return tokError("basic block pointers are invalid");
3236 if (Result->isVoidTy())
3237 return tokError("pointers to void are invalid; use i8* instead");
3239 return tokError("pointer to this type is invalid");
3240 unsigned AddrSpace;
3241 if (parseOptionalAddrSpace(AddrSpace) ||
3242 parseToken(lltok::star, "expected '*' in address space"))
3243 return true;
3244
3245 Result = PointerType::get(Context, AddrSpace);
3246 break;
3247 }
3248
3249 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3250 case lltok::lparen:
3251 if (parseFunctionType(Result))
3252 return true;
3253 break;
3254 }
3255 }
3256}
3257
3258/// parseParameterList
3259/// ::= '(' ')'
3260/// ::= '(' Arg (',' Arg)* ')'
3261/// Arg
3262/// ::= Type OptionalAttributes Value OptionalAttributes
3263bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3264 PerFunctionState &PFS, bool IsMustTailCall,
3265 bool InVarArgsFunc) {
3266 if (parseToken(lltok::lparen, "expected '(' in call"))
3267 return true;
3268
3269 while (Lex.getKind() != lltok::rparen) {
3270 // If this isn't the first argument, we need a comma.
3271 if (!ArgList.empty() &&
3272 parseToken(lltok::comma, "expected ',' in argument list"))
3273 return true;
3274
3275 // parse an ellipsis if this is a musttail call in a variadic function.
3276 if (Lex.getKind() == lltok::dotdotdot) {
3277 const char *Msg = "unexpected ellipsis in argument list for ";
3278 if (!IsMustTailCall)
3279 return tokError(Twine(Msg) + "non-musttail call");
3280 if (!InVarArgsFunc)
3281 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3282 Lex.Lex(); // Lex the '...', it is purely for readability.
3283 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3284 }
3285
3286 // parse the argument.
3287 LocTy ArgLoc;
3288 Type *ArgTy = nullptr;
3289 Value *V;
3290 if (parseType(ArgTy, ArgLoc))
3291 return true;
3293 return error(ArgLoc, "invalid type for function argument");
3294
3295 AttrBuilder ArgAttrs(M->getContext());
3296
3297 if (ArgTy->isMetadataTy()) {
3298 if (parseMetadataAsValue(V, PFS))
3299 return true;
3300 } else {
3301 // Otherwise, handle normal operands.
3302 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3303 return true;
3304 }
3305 ArgList.push_back(ParamInfo(
3306 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3307 }
3308
3309 if (IsMustTailCall && InVarArgsFunc)
3310 return tokError("expected '...' at end of argument list for musttail call "
3311 "in varargs function");
3312
3313 Lex.Lex(); // Lex the ')'.
3314 return false;
3315}
3316
3317/// parseRequiredTypeAttr
3318/// ::= attrname(<ty>)
3319bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3320 Attribute::AttrKind AttrKind) {
3321 Type *Ty = nullptr;
3322 if (!EatIfPresent(AttrToken))
3323 return true;
3324 if (!EatIfPresent(lltok::lparen))
3325 return error(Lex.getLoc(), "expected '('");
3326 if (parseType(Ty))
3327 return true;
3328 if (!EatIfPresent(lltok::rparen))
3329 return error(Lex.getLoc(), "expected ')'");
3330
3331 B.addTypeAttr(AttrKind, Ty);
3332 return false;
3333}
3334
3335/// parseRangeAttr
3336/// ::= range(<ty> <n>,<n>)
3337bool LLParser::parseRangeAttr(AttrBuilder &B) {
3338 Lex.Lex();
3339
3340 APInt Lower;
3341 APInt Upper;
3342 Type *Ty = nullptr;
3343 LocTy TyLoc;
3344
3345 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3346 if (Lex.getKind() != lltok::APSInt)
3347 return tokError("expected integer");
3348 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3349 return tokError(
3350 "integer is too large for the bit width of specified type");
3351 Val = Lex.getAPSIntVal().extend(BitWidth);
3352 Lex.Lex();
3353 return false;
3354 };
3355
3356 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3357 return true;
3358 if (!Ty->isIntegerTy())
3359 return error(TyLoc, "the range must have integer type!");
3360
3361 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3362
3363 if (ParseAPSInt(BitWidth, Lower) ||
3364 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3365 return true;
3366 if (Lower == Upper && !Lower.isZero())
3367 return tokError("the range represent the empty set but limits aren't 0!");
3368
3369 if (parseToken(lltok::rparen, "expected ')'"))
3370 return true;
3371
3372 B.addRangeAttr(ConstantRange(Lower, Upper));
3373 return false;
3374}
3375
3376/// parseInitializesAttr
3377/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3378bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3379 Lex.Lex();
3380
3381 auto ParseAPSInt = [&](APInt &Val) {
3382 if (Lex.getKind() != lltok::APSInt)
3383 return tokError("expected integer");
3384 Val = Lex.getAPSIntVal().extend(64);
3385 Lex.Lex();
3386 return false;
3387 };
3388
3389 if (parseToken(lltok::lparen, "expected '('"))
3390 return true;
3391
3393 // Parse each constant range.
3394 do {
3395 APInt Lower, Upper;
3396 if (parseToken(lltok::lparen, "expected '('"))
3397 return true;
3398
3399 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3400 ParseAPSInt(Upper))
3401 return true;
3402
3403 if (Lower == Upper)
3404 return tokError("the range should not represent the full or empty set!");
3405
3406 if (parseToken(lltok::rparen, "expected ')'"))
3407 return true;
3408
3409 RangeList.push_back(ConstantRange(Lower, Upper));
3410 } while (EatIfPresent(lltok::comma));
3411
3412 if (parseToken(lltok::rparen, "expected ')'"))
3413 return true;
3414
3415 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3416 if (!CRLOrNull.has_value())
3417 return tokError("Invalid (unordered or overlapping) range list");
3418 B.addInitializesAttr(*CRLOrNull);
3419 return false;
3420}
3421
3422bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3424 std::optional<CaptureComponents> Ret;
3425
3426 // We use syntax like captures(ret: address, provenance), so the colon
3427 // should not be interpreted as a label terminator.
3428 Lex.setIgnoreColonInIdentifiers(true);
3429 llvm::scope_exit _([&] { Lex.setIgnoreColonInIdentifiers(false); });
3430
3431 Lex.Lex();
3432 if (parseToken(lltok::lparen, "expected '('"))
3433 return true;
3434
3435 CaptureComponents *Current = &Other;
3436 bool SeenComponent = false;
3437 while (true) {
3438 if (EatIfPresent(lltok::kw_ret)) {
3439 if (parseToken(lltok::colon, "expected ':'"))
3440 return true;
3441 if (Ret)
3442 return tokError("duplicate 'ret' location");
3444 Current = &*Ret;
3445 SeenComponent = false;
3446 }
3447
3448 if (EatIfPresent(lltok::kw_none)) {
3449 if (SeenComponent)
3450 return tokError("cannot use 'none' with other component");
3451 *Current = CaptureComponents::None;
3452 } else {
3453 if (SeenComponent && capturesNothing(*Current))
3454 return tokError("cannot use 'none' with other component");
3455
3456 if (EatIfPresent(lltok::kw_address_is_null))
3458 else if (EatIfPresent(lltok::kw_address))
3459 *Current |= CaptureComponents::Address;
3460 else if (EatIfPresent(lltok::kw_provenance))
3462 else if (EatIfPresent(lltok::kw_read_provenance))
3464 else
3465 return tokError("expected one of 'none', 'address', 'address_is_null', "
3466 "'provenance' or 'read_provenance'");
3467 }
3468
3469 SeenComponent = true;
3470 if (EatIfPresent(lltok::rparen))
3471 break;
3472
3473 if (parseToken(lltok::comma, "expected ',' or ')'"))
3474 return true;
3475 }
3476
3477 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3478 return false;
3479}
3480
3481/// parseOptionalOperandBundles
3482/// ::= /*empty*/
3483/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3484///
3485/// OperandBundle
3486/// ::= bundle-tag '(' ')'
3487/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3488///
3489/// bundle-tag ::= String Constant
3490bool LLParser::parseOptionalOperandBundles(
3491 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3492 LocTy BeginLoc = Lex.getLoc();
3493 if (!EatIfPresent(lltok::lsquare))
3494 return false;
3495
3496 while (Lex.getKind() != lltok::rsquare) {
3497 // If this isn't the first operand bundle, we need a comma.
3498 if (!BundleList.empty() &&
3499 parseToken(lltok::comma, "expected ',' in input list"))
3500 return true;
3501
3502 std::string Tag;
3503 if (parseStringConstant(Tag))
3504 return true;
3505
3506 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3507 return true;
3508
3509 std::vector<Value *> Inputs;
3510 while (Lex.getKind() != lltok::rparen) {
3511 // If this isn't the first input, we need a comma.
3512 if (!Inputs.empty() &&
3513 parseToken(lltok::comma, "expected ',' in input list"))
3514 return true;
3515
3516 Type *Ty = nullptr;
3517 Value *Input = nullptr;
3518 if (parseType(Ty))
3519 return true;
3520 if (Ty->isMetadataTy()) {
3521 if (parseMetadataAsValue(Input, PFS))
3522 return true;
3523 } else if (parseValue(Ty, Input, PFS)) {
3524 return true;
3525 }
3526 Inputs.push_back(Input);
3527 }
3528
3529 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3530
3531 Lex.Lex(); // Lex the ')'.
3532 }
3533
3534 if (BundleList.empty())
3535 return error(BeginLoc, "operand bundle set must not be empty");
3536
3537 Lex.Lex(); // Lex the ']'.
3538 return false;
3539}
3540
3541bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3542 unsigned NextID, unsigned ID) {
3543 if (ID < NextID)
3544 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3545 Twine(NextID) + "' or greater");
3546
3547 return false;
3548}
3549
3550/// parseArgumentList - parse the argument list for a function type or function
3551/// prototype.
3552/// ::= '(' ArgTypeListI ')'
3553/// ArgTypeListI
3554/// ::= /*empty*/
3555/// ::= '...'
3556/// ::= ArgTypeList ',' '...'
3557/// ::= ArgType (',' ArgType)*
3558///
3559bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3560 SmallVectorImpl<unsigned> &UnnamedArgNums,
3561 bool &IsVarArg) {
3562 unsigned CurValID = 0;
3563 IsVarArg = false;
3564 assert(Lex.getKind() == lltok::lparen);
3565 Lex.Lex(); // eat the (.
3566
3567 if (Lex.getKind() != lltok::rparen) {
3568 do {
3569 // Handle ... at end of arg list.
3570 if (EatIfPresent(lltok::dotdotdot)) {
3571 IsVarArg = true;
3572 break;
3573 }
3574
3575 // Otherwise must be an argument type.
3576 LocTy TypeLoc = Lex.getLoc();
3577 Type *ArgTy = nullptr;
3578 AttrBuilder Attrs(M->getContext());
3579 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3580 return true;
3581
3582 if (ArgTy->isVoidTy())
3583 return error(TypeLoc, "argument can not have void type");
3584
3585 std::string Name;
3586 FileLoc IdentStart;
3587 FileLoc IdentEnd;
3588 bool Unnamed = false;
3589 if (Lex.getKind() == lltok::LocalVar) {
3590 Name = Lex.getStrVal();
3591 IdentStart = getTokLineColumnPos();
3592 Lex.Lex();
3593 IdentEnd = getPrevTokEndLineColumnPos();
3594 } else {
3595 unsigned ArgID;
3596 if (Lex.getKind() == lltok::LocalVarID) {
3597 ArgID = Lex.getUIntVal();
3598 IdentStart = getTokLineColumnPos();
3599 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3600 return true;
3601 Lex.Lex();
3602 IdentEnd = getPrevTokEndLineColumnPos();
3603 } else {
3604 ArgID = CurValID;
3605 Unnamed = true;
3606 }
3607 UnnamedArgNums.push_back(ArgID);
3608 CurValID = ArgID + 1;
3609 }
3610
3612 return error(TypeLoc, "invalid type for function argument");
3613
3614 ArgList.emplace_back(
3615 TypeLoc, ArgTy,
3616 Unnamed ? std::nullopt
3617 : std::make_optional(FileLocRange(IdentStart, IdentEnd)),
3618 AttributeSet::get(ArgTy->getContext(), Attrs), std::move(Name));
3619 } while (EatIfPresent(lltok::comma));
3620 }
3621
3622 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3623}
3624
3625/// parseFunctionType
3626/// ::= Type ArgumentList OptionalAttrs
3627bool LLParser::parseFunctionType(Type *&Result) {
3628 assert(Lex.getKind() == lltok::lparen);
3629
3631 return tokError("invalid function return type");
3632
3634 bool IsVarArg;
3635 SmallVector<unsigned> UnnamedArgNums;
3636 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3637 return true;
3638
3639 // Reject names on the arguments lists.
3640 for (const ArgInfo &Arg : ArgList) {
3641 if (!Arg.Name.empty())
3642 return error(Arg.Loc, "argument name invalid in function type");
3643 if (Arg.Attrs.hasAttributes())
3644 return error(Arg.Loc, "argument attributes invalid in function type");
3645 }
3646
3647 SmallVector<Type*, 16> ArgListTy;
3648 for (const ArgInfo &Arg : ArgList)
3649 ArgListTy.push_back(Arg.Ty);
3650
3651 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3652 return false;
3653}
3654
3655/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3656/// other structs.
3657bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3659 if (parseStructBody(Elts))
3660 return true;
3661
3662 Result = StructType::get(Context, Elts, Packed);
3663 return false;
3664}
3665
3666/// parseStructDefinition - parse a struct in a 'type' definition.
3667bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3668 std::pair<Type *, LocTy> &Entry,
3669 Type *&ResultTy) {
3670 // If the type was already defined, diagnose the redefinition.
3671 if (Entry.first && !Entry.second.isValid())
3672 return error(TypeLoc, "redefinition of type");
3673
3674 // If we have opaque, just return without filling in the definition for the
3675 // struct. This counts as a definition as far as the .ll file goes.
3676 if (EatIfPresent(lltok::kw_opaque)) {
3677 // This type is being defined, so clear the location to indicate this.
3678 Entry.second = SMLoc();
3679
3680 // If this type number has never been uttered, create it.
3681 if (!Entry.first)
3682 Entry.first = StructType::create(Context, Name);
3683 ResultTy = Entry.first;
3684 return false;
3685 }
3686
3687 // If the type starts with '<', then it is either a packed struct or a vector.
3688 bool isPacked = EatIfPresent(lltok::less);
3689
3690 // If we don't have a struct, then we have a random type alias, which we
3691 // accept for compatibility with old files. These types are not allowed to be
3692 // forward referenced and not allowed to be recursive.
3693 if (Lex.getKind() != lltok::lbrace) {
3694 if (Entry.first)
3695 return error(TypeLoc, "forward references to non-struct type");
3696
3697 ResultTy = nullptr;
3698 if (isPacked)
3699 return parseArrayVectorType(ResultTy, true);
3700 return parseType(ResultTy);
3701 }
3702
3703 // This type is being defined, so clear the location to indicate this.
3704 Entry.second = SMLoc();
3705
3706 // If this type number has never been uttered, create it.
3707 if (!Entry.first)
3708 Entry.first = StructType::create(Context, Name);
3709
3710 StructType *STy = cast<StructType>(Entry.first);
3711
3713 if (parseStructBody(Body) ||
3714 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3715 return true;
3716
3717 if (auto E = STy->setBodyOrError(Body, isPacked))
3718 return tokError(toString(std::move(E)));
3719
3720 ResultTy = STy;
3721 return false;
3722}
3723
3724/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3725/// StructType
3726/// ::= '{' '}'
3727/// ::= '{' Type (',' Type)* '}'
3728/// ::= '<' '{' '}' '>'
3729/// ::= '<' '{' Type (',' Type)* '}' '>'
3730bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3731 assert(Lex.getKind() == lltok::lbrace);
3732 Lex.Lex(); // Consume the '{'
3733
3734 // Handle the empty struct.
3735 if (EatIfPresent(lltok::rbrace))
3736 return false;
3737
3738 LocTy EltTyLoc = Lex.getLoc();
3739 Type *Ty = nullptr;
3740 if (parseType(Ty))
3741 return true;
3742 Body.push_back(Ty);
3743
3745 return error(EltTyLoc, "invalid element type for struct");
3746
3747 while (EatIfPresent(lltok::comma)) {
3748 EltTyLoc = Lex.getLoc();
3749 if (parseType(Ty))
3750 return true;
3751
3753 return error(EltTyLoc, "invalid element type for struct");
3754
3755 Body.push_back(Ty);
3756 }
3757
3758 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3759}
3760
3761/// parseArrayVectorType - parse an array or vector type, assuming the first
3762/// token has already been consumed.
3763/// Type
3764/// ::= '[' APSINTVAL 'x' Types ']'
3765/// ::= '<' APSINTVAL 'x' Types '>'
3766/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3767bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3768 bool Scalable = false;
3769
3770 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3771 Lex.Lex(); // consume the 'vscale'
3772 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3773 return true;
3774
3775 Scalable = true;
3776 }
3777
3778 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3779 Lex.getAPSIntVal().getBitWidth() > 64)
3780 return tokError("expected number in address space");
3781
3782 LocTy SizeLoc = Lex.getLoc();
3783 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3784 Lex.Lex();
3785
3786 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3787 return true;
3788
3789 LocTy TypeLoc = Lex.getLoc();
3790 Type *EltTy = nullptr;
3791 if (parseType(EltTy))
3792 return true;
3793
3794 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3795 "expected end of sequential type"))
3796 return true;
3797
3798 if (IsVector) {
3799 if (Size == 0)
3800 return error(SizeLoc, "zero element vector is illegal");
3801 if ((unsigned)Size != Size)
3802 return error(SizeLoc, "size too large for vector");
3804 return error(TypeLoc, "invalid vector element type");
3805 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3806 } else {
3808 return error(TypeLoc, "invalid array element type");
3809 Result = ArrayType::get(EltTy, Size);
3810 }
3811 return false;
3812}
3813
3814/// parseTargetExtType - handle target extension type syntax
3815/// TargetExtType
3816/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3817///
3818/// TargetExtTypeParams
3819/// ::= /*empty*/
3820/// ::= ',' Type TargetExtTypeParams
3821///
3822/// TargetExtIntParams
3823/// ::= /*empty*/
3824/// ::= ',' uint32 TargetExtIntParams
3825bool LLParser::parseTargetExtType(Type *&Result) {
3826 Lex.Lex(); // Eat the 'target' keyword.
3827
3828 // Get the mandatory type name.
3829 std::string TypeName;
3830 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3831 parseStringConstant(TypeName))
3832 return true;
3833
3834 // Parse all of the integer and type parameters at the same time; the use of
3835 // SeenInt will allow us to catch cases where type parameters follow integer
3836 // parameters.
3837 SmallVector<Type *> TypeParams;
3838 SmallVector<unsigned> IntParams;
3839 bool SeenInt = false;
3840 while (Lex.getKind() == lltok::comma) {
3841 Lex.Lex(); // Eat the comma.
3842
3843 if (Lex.getKind() == lltok::APSInt) {
3844 SeenInt = true;
3845 unsigned IntVal;
3846 if (parseUInt32(IntVal))
3847 return true;
3848 IntParams.push_back(IntVal);
3849 } else if (SeenInt) {
3850 // The only other kind of parameter we support is type parameters, which
3851 // must precede the integer parameters. This is therefore an error.
3852 return tokError("expected uint32 param");
3853 } else {
3854 Type *TypeParam;
3855 if (parseType(TypeParam, /*AllowVoid=*/true))
3856 return true;
3857 TypeParams.push_back(TypeParam);
3858 }
3859 }
3860
3861 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3862 return true;
3863
3864 auto TTy =
3865 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3866 if (auto E = TTy.takeError())
3867 return tokError(toString(std::move(E)));
3868
3869 Result = *TTy;
3870 return false;
3871}
3872
3873//===----------------------------------------------------------------------===//
3874// Function Semantic Analysis.
3875//===----------------------------------------------------------------------===//
3876
3877LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3878 int functionNumber,
3879 ArrayRef<unsigned> UnnamedArgNums)
3880 : P(p), F(f), FunctionNumber(functionNumber) {
3881
3882 // Insert unnamed arguments into the NumberedVals list.
3883 auto It = UnnamedArgNums.begin();
3884 for (Argument &A : F.args()) {
3885 if (!A.hasName()) {
3886 unsigned ArgNum = *It++;
3887 NumberedVals.add(ArgNum, &A);
3888 }
3889 }
3890}
3891
3892LLParser::PerFunctionState::~PerFunctionState() {
3893 // If there were any forward referenced non-basicblock values, delete them.
3894
3895 for (const auto &P : ForwardRefVals) {
3896 if (isa<BasicBlock>(P.second.first))
3897 continue;
3898 P.second.first->replaceAllUsesWith(
3899 PoisonValue::get(P.second.first->getType()));
3900 P.second.first->deleteValue();
3901 }
3902
3903 for (const auto &P : ForwardRefValIDs) {
3904 if (isa<BasicBlock>(P.second.first))
3905 continue;
3906 P.second.first->replaceAllUsesWith(
3907 PoisonValue::get(P.second.first->getType()));
3908 P.second.first->deleteValue();
3909 }
3910}
3911
3912bool LLParser::PerFunctionState::finishFunction() {
3913 if (!ForwardRefVals.empty())
3914 return P.error(ForwardRefVals.begin()->second.second,
3915 "use of undefined value '%" + ForwardRefVals.begin()->first +
3916 "'");
3917 if (!ForwardRefValIDs.empty())
3918 return P.error(ForwardRefValIDs.begin()->second.second,
3919 "use of undefined value '%" +
3920 Twine(ForwardRefValIDs.begin()->first) + "'");
3921 return false;
3922}
3923
3924/// getVal - Get a value with the specified name or ID, creating a
3925/// forward reference record if needed. This can return null if the value
3926/// exists but does not have the right type.
3927Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3928 LocTy Loc) {
3929 // Look this name up in the normal function symbol table.
3930 Value *Val = F.getValueSymbolTable()->lookup(Name);
3931
3932 // If this is a forward reference for the value, see if we already created a
3933 // forward ref record.
3934 if (!Val) {
3935 auto I = ForwardRefVals.find(Name);
3936 if (I != ForwardRefVals.end())
3937 Val = I->second.first;
3938 }
3939
3940 // If we have the value in the symbol table or fwd-ref table, return it.
3941 if (Val)
3942 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3943
3944 // Don't make placeholders with invalid type.
3945 if (!Ty->isFirstClassType()) {
3946 P.error(Loc, "invalid use of a non-first-class type");
3947 return nullptr;
3948 }
3949
3950 // Otherwise, create a new forward reference for this value and remember it.
3951 Value *FwdVal;
3952 if (Ty->isLabelTy()) {
3953 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3954 } else {
3955 FwdVal = new Argument(Ty, Name);
3956 }
3957 if (FwdVal->getName() != Name) {
3958 P.error(Loc, "name is too long which can result in name collisions, "
3959 "consider making the name shorter or "
3960 "increasing -non-global-value-max-name-size");
3961 return nullptr;
3962 }
3963
3964 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3965 return FwdVal;
3966}
3967
3968Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3969 // Look this name up in the normal function symbol table.
3970 Value *Val = NumberedVals.get(ID);
3971
3972 // If this is a forward reference for the value, see if we already created a
3973 // forward ref record.
3974 if (!Val) {
3975 auto I = ForwardRefValIDs.find(ID);
3976 if (I != ForwardRefValIDs.end())
3977 Val = I->second.first;
3978 }
3979
3980 // If we have the value in the symbol table or fwd-ref table, return it.
3981 if (Val)
3982 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3983
3984 if (!Ty->isFirstClassType()) {
3985 P.error(Loc, "invalid use of a non-first-class type");
3986 return nullptr;
3987 }
3988
3989 // Otherwise, create a new forward reference for this value and remember it.
3990 Value *FwdVal;
3991 if (Ty->isLabelTy()) {
3992 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3993 } else {
3994 FwdVal = new Argument(Ty);
3995 }
3996
3997 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3998 return FwdVal;
3999}
4000
4001/// setInstName - After an instruction is parsed and inserted into its
4002/// basic block, this installs its name.
4003bool LLParser::PerFunctionState::setInstName(int NameID,
4004 const std::string &NameStr,
4005 LocTy NameLoc, Instruction *Inst) {
4006 // If this instruction has void type, it cannot have a name or ID specified.
4007 if (Inst->getType()->isVoidTy()) {
4008 if (NameID != -1 || !NameStr.empty())
4009 return P.error(NameLoc, "instructions returning void cannot have a name");
4010 return false;
4011 }
4012
4013 // If this was a numbered instruction, verify that the instruction is the
4014 // expected value and resolve any forward references.
4015 if (NameStr.empty()) {
4016 // If neither a name nor an ID was specified, just use the next ID.
4017 if (NameID == -1)
4018 NameID = NumberedVals.getNext();
4019
4020 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
4021 NameID))
4022 return true;
4023
4024 auto FI = ForwardRefValIDs.find(NameID);
4025 if (FI != ForwardRefValIDs.end()) {
4026 Value *Sentinel = FI->second.first;
4027 if (Sentinel->getType() != Inst->getType())
4028 return P.error(NameLoc, "instruction forward referenced with type '" +
4029 getTypeString(FI->second.first->getType()) +
4030 "'");
4031
4032 Sentinel->replaceAllUsesWith(Inst);
4033 Sentinel->deleteValue();
4034 ForwardRefValIDs.erase(FI);
4035 }
4036
4037 NumberedVals.add(NameID, Inst);
4038 return false;
4039 }
4040
4041 // Otherwise, the instruction had a name. Resolve forward refs and set it.
4042 auto FI = ForwardRefVals.find(NameStr);
4043 if (FI != ForwardRefVals.end()) {
4044 Value *Sentinel = FI->second.first;
4045 if (Sentinel->getType() != Inst->getType())
4046 return P.error(NameLoc, "instruction forward referenced with type '" +
4047 getTypeString(FI->second.first->getType()) +
4048 "'");
4049
4050 Sentinel->replaceAllUsesWith(Inst);
4051 Sentinel->deleteValue();
4052 ForwardRefVals.erase(FI);
4053 }
4054
4055 // Set the name on the instruction.
4056 Inst->setName(NameStr);
4057
4058 if (Inst->getName() != NameStr)
4059 return P.error(NameLoc, "multiple definition of local value named '" +
4060 NameStr + "'");
4061 return false;
4062}
4063
4064/// getBB - Get a basic block with the specified name or ID, creating a
4065/// forward reference record if needed.
4066BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
4067 LocTy Loc) {
4069 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
4070}
4071
4072BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
4074 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
4075}
4076
4077/// defineBB - Define the specified basic block, which is either named or
4078/// unnamed. If there is an error, this returns null otherwise it returns
4079/// the block being defined.
4080BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
4081 int NameID, LocTy Loc) {
4082 BasicBlock *BB;
4083 if (Name.empty()) {
4084 if (NameID != -1) {
4085 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
4086 return nullptr;
4087 } else {
4088 NameID = NumberedVals.getNext();
4089 }
4090 BB = getBB(NameID, Loc);
4091 if (!BB) {
4092 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
4093 return nullptr;
4094 }
4095 } else {
4096 BB = getBB(Name, Loc);
4097 if (!BB) {
4098 P.error(Loc, "unable to create block named '" + Name + "'");
4099 return nullptr;
4100 }
4101 }
4102
4103 // Move the block to the end of the function. Forward ref'd blocks are
4104 // inserted wherever they happen to be referenced.
4105 F.splice(F.end(), &F, BB->getIterator());
4106
4107 // Remove the block from forward ref sets.
4108 if (Name.empty()) {
4109 ForwardRefValIDs.erase(NameID);
4110 NumberedVals.add(NameID, BB);
4111 } else {
4112 // BB forward references are already in the function symbol table.
4113 ForwardRefVals.erase(Name);
4114 }
4115
4116 return BB;
4117}
4118
4119//===----------------------------------------------------------------------===//
4120// Constants.
4121//===----------------------------------------------------------------------===//
4122
4123/// parseValID - parse an abstract value that doesn't necessarily have a
4124/// type implied. For example, if we parse "4" we don't know what integer type
4125/// it has. The value will later be combined with its type and checked for
4126/// basic correctness. PFS is used to convert function-local operands of
4127/// metadata (since metadata operands are not just parsed here but also
4128/// converted to values). PFS can be null when we are not parsing metadata
4129/// values inside a function.
4130bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
4131 ID.Loc = Lex.getLoc();
4132 switch (Lex.getKind()) {
4133 default:
4134 return tokError("expected value token");
4135 case lltok::GlobalID: // @42
4136 ID.UIntVal = Lex.getUIntVal();
4137 ID.Kind = ValID::t_GlobalID;
4138 break;
4139 case lltok::GlobalVar: // @foo
4140 ID.StrVal = Lex.getStrVal();
4141 ID.Kind = ValID::t_GlobalName;
4142 break;
4143 case lltok::LocalVarID: // %42
4144 ID.UIntVal = Lex.getUIntVal();
4145 ID.Kind = ValID::t_LocalID;
4146 break;
4147 case lltok::LocalVar: // %foo
4148 ID.StrVal = Lex.getStrVal();
4149 ID.Kind = ValID::t_LocalName;
4150 break;
4151 case lltok::APSInt:
4152 ID.APSIntVal = Lex.getAPSIntVal();
4153 ID.Kind = ValID::t_APSInt;
4154 break;
4155 case lltok::APFloat: {
4156 ID.APFloatVal = Lex.getAPFloatVal();
4157 ID.Kind = ValID::t_APFloat;
4158 break;
4159 }
4160 case lltok::FloatLiteral: {
4161 if (!ExpectedTy)
4162 return error(ID.Loc, "unexpected floating-point literal");
4163 if (!ExpectedTy->isFloatingPointTy())
4164 return error(ID.Loc, "floating-point constant invalid for type");
4165 ID.APFloatVal = APFloat(ExpectedTy->getFltSemantics());
4166 APFloat::opStatus Except =
4167 cantFail(ID.APFloatVal.convertFromString(
4168 Lex.getStrVal(), RoundingMode::NearestTiesToEven),
4169 "Invalid float strings should be caught by the lexer");
4170 // Forbid overflowing and underflowing literals, but permit inexact
4171 // literals. Underflow is thrown when the result is denormal, so to allow
4172 // denormals, only reject underflowing literals that resulted in a zero.
4173 if (Except & APFloat::opOverflow)
4174 return error(ID.Loc, "floating-point constant overflowed type");
4175 if ((Except & APFloat::opUnderflow) && ID.APFloatVal.isZero())
4176 return error(ID.Loc, "floating-point constant underflowed type");
4177 ID.Kind = ValID::t_APFloat;
4178 break;
4179 }
4181 if (!ExpectedTy)
4182 return error(ID.Loc, "unexpected floating-point literal");
4183 const auto &Semantics = ExpectedTy->getFltSemantics();
4184 const APInt &Bits = Lex.getAPSIntVal();
4185 if (APFloat::getSizeInBits(Semantics) != Bits.getBitWidth())
4186 return error(ID.Loc, "float hex literal has incorrect number of bits");
4187 ID.APFloatVal = APFloat(Semantics, Bits);
4188 ID.Kind = ValID::t_APFloat;
4189 break;
4190 }
4191 case lltok::kw_true:
4192 ID.ConstantVal = ConstantInt::getTrue(Context);
4193 ID.Kind = ValID::t_Constant;
4194 break;
4195 case lltok::kw_false:
4196 ID.ConstantVal = ConstantInt::getFalse(Context);
4197 ID.Kind = ValID::t_Constant;
4198 break;
4199 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
4200 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
4201 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
4202 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
4203 case lltok::kw_none: ID.Kind = ValID::t_None; break;
4204
4205 case lltok::lbrace: {
4206 // ValID ::= '{' ConstVector '}'
4207 Lex.Lex();
4209 if (parseGlobalValueVector(Elts) ||
4210 parseToken(lltok::rbrace, "expected end of struct constant"))
4211 return true;
4212
4213 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4214 ID.UIntVal = Elts.size();
4215 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4216 Elts.size() * sizeof(Elts[0]));
4218 return false;
4219 }
4220 case lltok::less: {
4221 // ValID ::= '<' ConstVector '>' --> Vector.
4222 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
4223 Lex.Lex();
4224 bool isPackedStruct = EatIfPresent(lltok::lbrace);
4225
4227 LocTy FirstEltLoc = Lex.getLoc();
4228 if (parseGlobalValueVector(Elts) ||
4229 (isPackedStruct &&
4230 parseToken(lltok::rbrace, "expected end of packed struct")) ||
4231 parseToken(lltok::greater, "expected end of constant"))
4232 return true;
4233
4234 if (isPackedStruct) {
4235 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
4236 memcpy(ID.ConstantStructElts.get(), Elts.data(),
4237 Elts.size() * sizeof(Elts[0]));
4238 ID.UIntVal = Elts.size();
4240 return false;
4241 }
4242
4243 if (Elts.empty())
4244 return error(ID.Loc, "constant vector must not be empty");
4245
4246 if (!Elts[0]->getType()->isIntegerTy() && !Elts[0]->getType()->isByteTy() &&
4247 !Elts[0]->getType()->isFloatingPointTy() &&
4248 !Elts[0]->getType()->isPointerTy())
4249 return error(
4250 FirstEltLoc,
4251 "vector elements must have integer, byte, pointer or floating point "
4252 "type");
4253
4254 // Verify that all the vector elements have the same type.
4255 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
4256 if (Elts[i]->getType() != Elts[0]->getType())
4257 return error(FirstEltLoc, "vector element #" + Twine(i) +
4258 " is not of type '" +
4259 getTypeString(Elts[0]->getType()));
4260
4261 ID.ConstantVal = ConstantVector::get(Elts);
4262 ID.Kind = ValID::t_Constant;
4263 return false;
4264 }
4265 case lltok::lsquare: { // Array Constant
4266 Lex.Lex();
4268 LocTy FirstEltLoc = Lex.getLoc();
4269 if (parseGlobalValueVector(Elts) ||
4270 parseToken(lltok::rsquare, "expected end of array constant"))
4271 return true;
4272
4273 // Handle empty element.
4274 if (Elts.empty()) {
4275 // Use undef instead of an array because it's inconvenient to determine
4276 // the element type at this point, there being no elements to examine.
4277 ID.Kind = ValID::t_EmptyArray;
4278 return false;
4279 }
4280
4281 if (!Elts[0]->getType()->isFirstClassType())
4282 return error(FirstEltLoc, "invalid array element type: " +
4283 getTypeString(Elts[0]->getType()));
4284
4285 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
4286
4287 // Verify all elements are correct type!
4288 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
4289 if (Elts[i]->getType() != Elts[0]->getType())
4290 return error(FirstEltLoc, "array element #" + Twine(i) +
4291 " is not of type '" +
4292 getTypeString(Elts[0]->getType()));
4293 }
4294
4295 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4296 ID.Kind = ValID::t_Constant;
4297 return false;
4298 }
4299 case lltok::kw_c: { // c "foo"
4300 Lex.Lex();
4301 ArrayType *ATy = cast<ArrayType>(ExpectedTy);
4302 ID.ConstantVal = ConstantDataArray::getString(
4303 Context, Lex.getStrVal(), false, ATy->getElementType()->isByteTy());
4304 if (parseToken(lltok::StringConstant, "expected string"))
4305 return true;
4306 ID.Kind = ValID::t_Constant;
4307 return false;
4308 }
4309 case lltok::kw_asm: {
4310 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4311 // STRINGCONSTANT
4312 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4313 Lex.Lex();
4314 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4315 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4316 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4317 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4318 parseStringConstant(ID.StrVal) ||
4319 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4320 parseToken(lltok::StringConstant, "expected constraint string"))
4321 return true;
4322 ID.StrVal2 = Lex.getStrVal();
4323 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4324 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4325 ID.Kind = ValID::t_InlineAsm;
4326 return false;
4327 }
4328
4330 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4331 Lex.Lex();
4332
4333 ValID Fn, Label;
4334
4335 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4336 parseValID(Fn, PFS) ||
4337 parseToken(lltok::comma,
4338 "expected comma in block address expression") ||
4339 parseValID(Label, PFS) ||
4340 parseToken(lltok::rparen, "expected ')' in block address expression"))
4341 return true;
4342
4344 return error(Fn.Loc, "expected function name in blockaddress");
4345 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4346 return error(Label.Loc, "expected basic block name in blockaddress");
4347
4348 // Try to find the function (but skip it if it's forward-referenced).
4349 GlobalValue *GV = nullptr;
4350 if (Fn.Kind == ValID::t_GlobalID) {
4351 GV = NumberedVals.get(Fn.UIntVal);
4352 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4353 GV = M->getNamedValue(Fn.StrVal);
4354 }
4355 Function *F = nullptr;
4356 if (GV) {
4357 // Confirm that it's actually a function with a definition.
4358 if (!isa<Function>(GV))
4359 return error(Fn.Loc, "expected function name in blockaddress");
4360 F = cast<Function>(GV);
4361 if (F->isDeclaration())
4362 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4363 }
4364
4365 if (!F) {
4366 // Make a global variable as a placeholder for this reference.
4367 GlobalValue *&FwdRef =
4368 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4369 if (!FwdRef) {
4370 unsigned FwdDeclAS;
4371 if (ExpectedTy) {
4372 // If we know the type that the blockaddress is being assigned to,
4373 // we can use the address space of that type.
4374 if (!ExpectedTy->isPointerTy())
4375 return error(ID.Loc,
4376 "type of blockaddress must be a pointer and not '" +
4377 getTypeString(ExpectedTy) + "'");
4378 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4379 } else if (PFS) {
4380 // Otherwise, we default the address space of the current function.
4381 FwdDeclAS = PFS->getFunction().getAddressSpace();
4382 } else {
4383 llvm_unreachable("Unknown address space for blockaddress");
4384 }
4385 FwdRef = new GlobalVariable(
4386 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4387 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4388 }
4389
4390 ID.ConstantVal = FwdRef;
4391 ID.Kind = ValID::t_Constant;
4392 return false;
4393 }
4394
4395 // We found the function; now find the basic block. Don't use PFS, since we
4396 // might be inside a constant expression.
4397 BasicBlock *BB;
4398 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4399 if (Label.Kind == ValID::t_LocalID)
4400 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4401 else
4402 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4403 if (!BB)
4404 return error(Label.Loc, "referenced value is not a basic block");
4405 } else {
4406 if (Label.Kind == ValID::t_LocalID)
4407 return error(Label.Loc, "cannot take address of numeric label after "
4408 "the function is defined");
4410 F->getValueSymbolTable()->lookup(Label.StrVal));
4411 if (!BB)
4412 return error(Label.Loc, "referenced value is not a basic block");
4413 }
4414
4415 ID.ConstantVal = BlockAddress::get(F, BB);
4416 ID.Kind = ValID::t_Constant;
4417 return false;
4418 }
4419
4421 // ValID ::= 'dso_local_equivalent' @foo
4422 Lex.Lex();
4423
4424 ValID Fn;
4425
4426 if (parseValID(Fn, PFS))
4427 return true;
4428
4430 return error(Fn.Loc,
4431 "expected global value name in dso_local_equivalent");
4432
4433 // Try to find the function (but skip it if it's forward-referenced).
4434 GlobalValue *GV = nullptr;
4435 if (Fn.Kind == ValID::t_GlobalID) {
4436 GV = NumberedVals.get(Fn.UIntVal);
4437 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4438 GV = M->getNamedValue(Fn.StrVal);
4439 }
4440
4441 if (!GV) {
4442 // Make a placeholder global variable as a placeholder for this reference.
4443 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4444 ? ForwardRefDSOLocalEquivalentIDs
4445 : ForwardRefDSOLocalEquivalentNames;
4446 GlobalValue *&FwdRef = FwdRefMap[Fn];
4447 if (!FwdRef) {
4448 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4449 GlobalValue::InternalLinkage, nullptr, "",
4451 }
4452
4453 ID.ConstantVal = FwdRef;
4454 ID.Kind = ValID::t_Constant;
4455 return false;
4456 }
4457
4458 if (!GV->getValueType()->isFunctionTy())
4459 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4460 "in dso_local_equivalent");
4461
4462 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4463 ID.Kind = ValID::t_Constant;
4464 return false;
4465 }
4466
4467 case lltok::kw_no_cfi: {
4468 // ValID ::= 'no_cfi' @foo
4469 Lex.Lex();
4470
4471 if (parseValID(ID, PFS))
4472 return true;
4473
4474 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4475 return error(ID.Loc, "expected global value name in no_cfi");
4476
4477 ID.NoCFI = true;
4478 return false;
4479 }
4480 case lltok::kw_ptrauth: {
4481 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4482 // (',' i64 <disc> (',' ptr addrdisc (',' ptr ds)?
4483 // )? )? ')'
4484 Lex.Lex();
4485
4486 Constant *Ptr, *Key;
4487 Constant *Disc = nullptr, *AddrDisc = nullptr,
4488 *DeactivationSymbol = nullptr;
4489
4490 if (parseToken(lltok::lparen,
4491 "expected '(' in constant ptrauth expression") ||
4492 parseGlobalTypeAndValue(Ptr) ||
4493 parseToken(lltok::comma,
4494 "expected comma in constant ptrauth expression") ||
4495 parseGlobalTypeAndValue(Key))
4496 return true;
4497 // If present, parse the optional disc/addrdisc/ds.
4498 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(Disc))
4499 return true;
4500 if (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc))
4501 return true;
4502 if (EatIfPresent(lltok::comma) &&
4503 parseGlobalTypeAndValue(DeactivationSymbol))
4504 return true;
4505 if (parseToken(lltok::rparen,
4506 "expected ')' in constant ptrauth expression"))
4507 return true;
4508
4509 if (!Ptr->getType()->isPointerTy())
4510 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4511
4512 auto *KeyC = dyn_cast<ConstantInt>(Key);
4513 if (!KeyC || KeyC->getBitWidth() != 32)
4514 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4515
4516 ConstantInt *DiscC = nullptr;
4517 if (Disc) {
4518 DiscC = dyn_cast<ConstantInt>(Disc);
4519 if (!DiscC || DiscC->getBitWidth() != 64)
4520 return error(
4521 ID.Loc,
4522 "constant ptrauth integer discriminator must be i64 constant");
4523 } else {
4524 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4525 }
4526
4527 if (AddrDisc) {
4528 if (!AddrDisc->getType()->isPointerTy())
4529 return error(
4530 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4531 } else {
4532 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4533 }
4534
4535 if (!DeactivationSymbol)
4536 DeactivationSymbol =
4538 if (!DeactivationSymbol->getType()->isPointerTy())
4539 return error(ID.Loc,
4540 "constant ptrauth deactivation symbol must be a pointer");
4541
4542 ID.ConstantVal =
4543 ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc, DeactivationSymbol);
4544 ID.Kind = ValID::t_Constant;
4545 return false;
4546 }
4547
4548 case lltok::kw_trunc:
4549 case lltok::kw_bitcast:
4551 case lltok::kw_inttoptr:
4553 case lltok::kw_ptrtoint: {
4554 unsigned Opc = Lex.getUIntVal();
4555 Type *DestTy = nullptr;
4556 Constant *SrcVal;
4557 Lex.Lex();
4558 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4559 parseGlobalTypeAndValue(SrcVal) ||
4560 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4561 parseType(DestTy) ||
4562 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4563 return true;
4564 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4565 return error(ID.Loc, "invalid cast opcode for cast from '" +
4566 getTypeString(SrcVal->getType()) + "' to '" +
4567 getTypeString(DestTy) + "'");
4569 SrcVal, DestTy);
4570 ID.Kind = ValID::t_Constant;
4571 return false;
4572 }
4574 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4576 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4577 case lltok::kw_udiv:
4578 return error(ID.Loc, "udiv constexprs are no longer supported");
4579 case lltok::kw_sdiv:
4580 return error(ID.Loc, "sdiv constexprs are no longer supported");
4581 case lltok::kw_urem:
4582 return error(ID.Loc, "urem constexprs are no longer supported");
4583 case lltok::kw_srem:
4584 return error(ID.Loc, "srem constexprs are no longer supported");
4585 case lltok::kw_fadd:
4586 return error(ID.Loc, "fadd constexprs are no longer supported");
4587 case lltok::kw_fsub:
4588 return error(ID.Loc, "fsub constexprs are no longer supported");
4589 case lltok::kw_fmul:
4590 return error(ID.Loc, "fmul constexprs are no longer supported");
4591 case lltok::kw_fdiv:
4592 return error(ID.Loc, "fdiv constexprs are no longer supported");
4593 case lltok::kw_frem:
4594 return error(ID.Loc, "frem constexprs are no longer supported");
4595 case lltok::kw_and:
4596 return error(ID.Loc, "and constexprs are no longer supported");
4597 case lltok::kw_or:
4598 return error(ID.Loc, "or constexprs are no longer supported");
4599 case lltok::kw_lshr:
4600 return error(ID.Loc, "lshr constexprs are no longer supported");
4601 case lltok::kw_ashr:
4602 return error(ID.Loc, "ashr constexprs are no longer supported");
4603 case lltok::kw_shl:
4604 return error(ID.Loc, "shl constexprs are no longer supported");
4605 case lltok::kw_mul:
4606 return error(ID.Loc, "mul constexprs are no longer supported");
4607 case lltok::kw_fneg:
4608 return error(ID.Loc, "fneg constexprs are no longer supported");
4609 case lltok::kw_select:
4610 return error(ID.Loc, "select constexprs are no longer supported");
4611 case lltok::kw_zext:
4612 return error(ID.Loc, "zext constexprs are no longer supported");
4613 case lltok::kw_sext:
4614 return error(ID.Loc, "sext constexprs are no longer supported");
4615 case lltok::kw_fptrunc:
4616 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4617 case lltok::kw_fpext:
4618 return error(ID.Loc, "fpext constexprs are no longer supported");
4619 case lltok::kw_uitofp:
4620 return error(ID.Loc, "uitofp constexprs are no longer supported");
4621 case lltok::kw_sitofp:
4622 return error(ID.Loc, "sitofp constexprs are no longer supported");
4623 case lltok::kw_fptoui:
4624 return error(ID.Loc, "fptoui constexprs are no longer supported");
4625 case lltok::kw_fptosi:
4626 return error(ID.Loc, "fptosi constexprs are no longer supported");
4627 case lltok::kw_icmp:
4628 return error(ID.Loc, "icmp constexprs are no longer supported");
4629 case lltok::kw_fcmp:
4630 return error(ID.Loc, "fcmp constexprs are no longer supported");
4631
4632 // Binary Operators.
4633 case lltok::kw_add:
4634 case lltok::kw_sub:
4635 case lltok::kw_xor: {
4636 bool NUW = false;
4637 bool NSW = false;
4638 unsigned Opc = Lex.getUIntVal();
4639 Constant *Val0, *Val1;
4640 Lex.Lex();
4641 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4642 Opc == Instruction::Mul) {
4643 if (EatIfPresent(lltok::kw_nuw))
4644 NUW = true;
4645 if (EatIfPresent(lltok::kw_nsw)) {
4646 NSW = true;
4647 if (EatIfPresent(lltok::kw_nuw))
4648 NUW = true;
4649 }
4650 }
4651 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4652 parseGlobalTypeAndValue(Val0) ||
4653 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4654 parseGlobalTypeAndValue(Val1) ||
4655 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4656 return true;
4657 if (Val0->getType() != Val1->getType())
4658 return error(ID.Loc, "operands of constexpr must have same type");
4659 // Check that the type is valid for the operator.
4660 if (!Val0->getType()->isIntOrIntVectorTy())
4661 return error(ID.Loc,
4662 "constexpr requires integer or integer vector operands");
4663 unsigned Flags = 0;
4666 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4667 ID.Kind = ValID::t_Constant;
4668 return false;
4669 }
4670
4671 case lltok::kw_splat: {
4672 Lex.Lex();
4673 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4674 return true;
4675 Constant *C;
4676 if (parseGlobalTypeAndValue(C))
4677 return true;
4678 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4679 return true;
4680
4681 ID.ConstantVal = C;
4683 return false;
4684 }
4685
4690 unsigned Opc = Lex.getUIntVal();
4692 GEPNoWrapFlags NW;
4693 bool HasInRange = false;
4694 APSInt InRangeStart;
4695 APSInt InRangeEnd;
4696 Type *Ty;
4697 Lex.Lex();
4698
4699 if (Opc == Instruction::GetElementPtr) {
4700 while (true) {
4701 if (EatIfPresent(lltok::kw_inbounds))
4703 else if (EatIfPresent(lltok::kw_nusw))
4705 else if (EatIfPresent(lltok::kw_nuw))
4707 else
4708 break;
4709 }
4710
4711 if (EatIfPresent(lltok::kw_inrange)) {
4712 if (parseToken(lltok::lparen, "expected '('"))
4713 return true;
4714 if (Lex.getKind() != lltok::APSInt)
4715 return tokError("expected integer");
4716 InRangeStart = Lex.getAPSIntVal();
4717 Lex.Lex();
4718 if (parseToken(lltok::comma, "expected ','"))
4719 return true;
4720 if (Lex.getKind() != lltok::APSInt)
4721 return tokError("expected integer");
4722 InRangeEnd = Lex.getAPSIntVal();
4723 Lex.Lex();
4724 if (parseToken(lltok::rparen, "expected ')'"))
4725 return true;
4726 HasInRange = true;
4727 }
4728 }
4729
4730 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4731 return true;
4732
4733 if (Opc == Instruction::GetElementPtr) {
4734 if (parseType(Ty) ||
4735 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4736 return true;
4737 }
4738
4739 if (parseGlobalValueVector(Elts) ||
4740 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4741 return true;
4742
4743 if (Opc == Instruction::GetElementPtr) {
4744 if (Elts.size() == 0 ||
4745 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4746 return error(ID.Loc, "base of getelementptr must be a pointer");
4747
4748 Type *BaseType = Elts[0]->getType();
4749 std::optional<ConstantRange> InRange;
4750 if (HasInRange) {
4751 unsigned IndexWidth =
4752 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4753 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4754 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4755 if (InRangeStart.sge(InRangeEnd))
4756 return error(ID.Loc, "expected end to be larger than start");
4757 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4758 }
4759
4760 unsigned GEPWidth =
4761 BaseType->isVectorTy()
4762 ? cast<FixedVectorType>(BaseType)->getNumElements()
4763 : 0;
4764
4765 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4766 for (Constant *Val : Indices) {
4767 Type *ValTy = Val->getType();
4768 if (!ValTy->isIntOrIntVectorTy())
4769 return error(ID.Loc, "getelementptr index must be an integer");
4770 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4771 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4772 if (GEPWidth && (ValNumEl != GEPWidth))
4773 return error(
4774 ID.Loc,
4775 "getelementptr vector index has a wrong number of elements");
4776 // GEPWidth may have been unknown because the base is a scalar,
4777 // but it is known now.
4778 GEPWidth = ValNumEl;
4779 }
4780 }
4781
4782 SmallPtrSet<Type*, 4> Visited;
4783 if (!Indices.empty() && !Ty->isSized(&Visited))
4784 return error(ID.Loc, "base element of getelementptr must be sized");
4785
4787 return error(ID.Loc, "invalid base element for constant getelementptr");
4788
4789 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4790 return error(ID.Loc, "invalid getelementptr indices");
4791
4792 ID.ConstantVal =
4793 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4794 } else if (Opc == Instruction::ShuffleVector) {
4795 if (Elts.size() != 3)
4796 return error(ID.Loc, "expected three operands to shufflevector");
4797 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4798 return error(ID.Loc, "invalid operands to shufflevector");
4799 SmallVector<int, 16> Mask;
4801 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4802 } else if (Opc == Instruction::ExtractElement) {
4803 if (Elts.size() != 2)
4804 return error(ID.Loc, "expected two operands to extractelement");
4805 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4806 return error(ID.Loc, "invalid extractelement operands");
4807 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4808 } else {
4809 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4810 if (Elts.size() != 3)
4811 return error(ID.Loc, "expected three operands to insertelement");
4812 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4813 return error(ID.Loc, "invalid insertelement operands");
4814 ID.ConstantVal =
4815 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4816 }
4817
4818 ID.Kind = ValID::t_Constant;
4819 return false;
4820 }
4821 }
4822
4823 Lex.Lex();
4824 return false;
4825}
4826
4827/// parseGlobalValue - parse a global value with the specified type.
4828bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4829 C = nullptr;
4830 ValID ID;
4831 Value *V = nullptr;
4832 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4833 convertValIDToValue(Ty, ID, V, nullptr);
4834 if (V && !(C = dyn_cast<Constant>(V)))
4835 return error(ID.Loc, "global values must be constants");
4836 return Parsed;
4837}
4838
4839bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4840 Type *Ty = nullptr;
4841 return parseType(Ty) || parseGlobalValue(Ty, V);
4842}
4843
4844bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4845 C = nullptr;
4846
4847 LocTy KwLoc = Lex.getLoc();
4848 if (!EatIfPresent(lltok::kw_comdat))
4849 return false;
4850
4851 if (EatIfPresent(lltok::lparen)) {
4852 if (Lex.getKind() != lltok::ComdatVar)
4853 return tokError("expected comdat variable");
4854 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4855 Lex.Lex();
4856 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4857 return true;
4858 } else {
4859 if (GlobalName.empty())
4860 return tokError("comdat cannot be unnamed");
4861 C = getComdat(std::string(GlobalName), KwLoc);
4862 }
4863
4864 return false;
4865}
4866
4867/// parseGlobalValueVector
4868/// ::= /*empty*/
4869/// ::= TypeAndValue (',' TypeAndValue)*
4870bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4871 // Empty list.
4872 if (Lex.getKind() == lltok::rbrace ||
4873 Lex.getKind() == lltok::rsquare ||
4874 Lex.getKind() == lltok::greater ||
4875 Lex.getKind() == lltok::rparen)
4876 return false;
4877
4878 do {
4879 // Let the caller deal with inrange.
4880 if (Lex.getKind() == lltok::kw_inrange)
4881 return false;
4882
4883 Constant *C;
4884 if (parseGlobalTypeAndValue(C))
4885 return true;
4886 Elts.push_back(C);
4887 } while (EatIfPresent(lltok::comma));
4888
4889 return false;
4890}
4891
4892bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4894 if (parseMDNodeVector(Elts))
4895 return true;
4896
4897 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4898 return false;
4899}
4900
4901/// MDNode:
4902/// ::= !{ ... }
4903/// ::= !7
4904/// ::= !DILocation(...)
4905bool LLParser::parseMDNode(MDNode *&N) {
4906 if (Lex.getKind() == lltok::MetadataVar)
4907 return parseSpecializedMDNode(N);
4908
4909 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4910}
4911
4912bool LLParser::parseMDNodeTail(MDNode *&N) {
4913 // !{ ... }
4914 if (Lex.getKind() == lltok::lbrace)
4915 return parseMDTuple(N);
4916
4917 // !42
4918 return parseMDNodeID(N);
4919}
4920
4921namespace {
4922
4923/// Structure to represent an optional metadata field.
4924template <class FieldTy> struct MDFieldImpl {
4925 typedef MDFieldImpl ImplTy;
4926 FieldTy Val;
4927 bool Seen;
4928
4929 void assign(FieldTy Val) {
4930 Seen = true;
4931 this->Val = std::move(Val);
4932 }
4933
4934 explicit MDFieldImpl(FieldTy Default)
4935 : Val(std::move(Default)), Seen(false) {}
4936};
4937
4938/// Structure to represent an optional metadata field that
4939/// can be of either type (A or B) and encapsulates the
4940/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4941/// to reimplement the specifics for representing each Field.
4942template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4943 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4944 FieldTypeA A;
4945 FieldTypeB B;
4946 bool Seen;
4947
4948 enum {
4949 IsInvalid = 0,
4950 IsTypeA = 1,
4951 IsTypeB = 2
4952 } WhatIs;
4953
4954 void assign(FieldTypeA A) {
4955 Seen = true;
4956 this->A = std::move(A);
4957 WhatIs = IsTypeA;
4958 }
4959
4960 void assign(FieldTypeB B) {
4961 Seen = true;
4962 this->B = std::move(B);
4963 WhatIs = IsTypeB;
4964 }
4965
4966 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4967 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4968 WhatIs(IsInvalid) {}
4969};
4970
4971struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4972 uint64_t Max;
4973
4974 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4975 : ImplTy(Default), Max(Max) {}
4976};
4977
4978struct LineField : public MDUnsignedField {
4979 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4980};
4981
4982struct ColumnField : public MDUnsignedField {
4983 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4984};
4985
4986struct DwarfTagField : public MDUnsignedField {
4987 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4988 DwarfTagField(dwarf::Tag DefaultTag)
4989 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4990};
4991
4992struct DwarfMacinfoTypeField : public MDUnsignedField {
4993 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4994 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4995 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4996};
4997
4998struct DwarfAttEncodingField : public MDUnsignedField {
4999 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
5000};
5001
5002struct DwarfVirtualityField : public MDUnsignedField {
5003 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
5004};
5005
5006struct DwarfLangField : public MDUnsignedField {
5007 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
5008};
5009
5010struct DwarfSourceLangNameField : public MDUnsignedField {
5011 DwarfSourceLangNameField() : MDUnsignedField(0, UINT32_MAX) {}
5012};
5013
5014struct DwarfLangDialectField : public MDUnsignedField {
5015 DwarfLangDialectField()
5016 : MDUnsignedField(0, dwarf::DW_LLVM_LANG_DIALECT_max) {}
5017};
5018
5019struct DwarfCCField : public MDUnsignedField {
5020 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
5021};
5022
5023struct DwarfEnumKindField : public MDUnsignedField {
5024 DwarfEnumKindField()
5025 : MDUnsignedField(dwarf::DW_APPLE_ENUM_KIND_invalid,
5026 dwarf::DW_APPLE_ENUM_KIND_max) {}
5027};
5028
5029struct EmissionKindField : public MDUnsignedField {
5030 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
5031};
5032
5033struct FixedPointKindField : public MDUnsignedField {
5034 FixedPointKindField()
5035 : MDUnsignedField(0, DIFixedPointType::LastFixedPointKind) {}
5036};
5037
5038struct NameTableKindField : public MDUnsignedField {
5039 NameTableKindField()
5040 : MDUnsignedField(
5041 0, (unsigned)
5042 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
5043};
5044
5045struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
5046 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
5047};
5048
5049struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
5050 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
5051};
5052
5053struct MDAPSIntField : public MDFieldImpl<APSInt> {
5054 MDAPSIntField() : ImplTy(APSInt()) {}
5055};
5056
5057struct MDSignedField : public MDFieldImpl<int64_t> {
5058 int64_t Min = INT64_MIN;
5059 int64_t Max = INT64_MAX;
5060
5061 MDSignedField(int64_t Default = 0)
5062 : ImplTy(Default) {}
5063 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
5064 : ImplTy(Default), Min(Min), Max(Max) {}
5065};
5066
5067struct MDBoolField : public MDFieldImpl<bool> {
5068 MDBoolField(bool Default = false) : ImplTy(Default) {}
5069};
5070
5071struct MDField : public MDFieldImpl<Metadata *> {
5072 bool AllowNull;
5073
5074 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
5075};
5076
5077struct MDStringField : public MDFieldImpl<MDString *> {
5078 enum class EmptyIs {
5079 Null, //< Allow empty input string, map to nullptr
5080 Empty, //< Allow empty input string, map to an empty MDString
5081 Error, //< Disallow empty string, map to an error
5082 } EmptyIs;
5083 MDStringField(enum EmptyIs EmptyIs = EmptyIs::Null)
5084 : ImplTy(nullptr), EmptyIs(EmptyIs) {}
5085};
5086
5087struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
5088 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
5089};
5090
5091struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
5092 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
5093};
5094
5095struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
5096 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
5097 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
5098
5099 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
5100 bool AllowNull = true)
5101 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
5102
5103 bool isMDSignedField() const { return WhatIs == IsTypeA; }
5104 bool isMDField() const { return WhatIs == IsTypeB; }
5105 int64_t getMDSignedValue() const {
5106 assert(isMDSignedField() && "Wrong field type");
5107 return A.Val;
5108 }
5109 Metadata *getMDFieldValue() const {
5110 assert(isMDField() && "Wrong field type");
5111 return B.Val;
5112 }
5113};
5114
5115struct MDUnsignedOrMDField : MDEitherFieldImpl<MDUnsignedField, MDField> {
5116 MDUnsignedOrMDField(uint64_t Default = 0, bool AllowNull = true)
5117 : ImplTy(MDUnsignedField(Default), MDField(AllowNull)) {}
5118
5119 MDUnsignedOrMDField(uint64_t Default, uint64_t Max, bool AllowNull = true)
5120 : ImplTy(MDUnsignedField(Default, Max), MDField(AllowNull)) {}
5121
5122 bool isMDUnsignedField() const { return WhatIs == IsTypeA; }
5123 bool isMDField() const { return WhatIs == IsTypeB; }
5124 uint64_t getMDUnsignedValue() const {
5125 assert(isMDUnsignedField() && "Wrong field type");
5126 return A.Val;
5127 }
5128 Metadata *getMDFieldValue() const {
5129 assert(isMDField() && "Wrong field type");
5130 return B.Val;
5131 }
5132
5133 Metadata *getValueAsMetadata(LLVMContext &Context) const {
5134 if (isMDUnsignedField())
5136 ConstantInt::get(Type::getInt64Ty(Context), getMDUnsignedValue()));
5137 if (isMDField())
5138 return getMDFieldValue();
5139 return nullptr;
5140 }
5141};
5142
5143} // end anonymous namespace
5144
5145namespace llvm {
5146
5147template <>
5148bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
5149 if (Lex.getKind() != lltok::APSInt)
5150 return tokError("expected integer");
5151
5152 Result.assign(Lex.getAPSIntVal());
5153 Lex.Lex();
5154 return false;
5155}
5156
5157template <>
5158bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5159 MDUnsignedField &Result) {
5160 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5161 return tokError("expected unsigned integer");
5162
5163 auto &U = Lex.getAPSIntVal();
5164 if (U.ugt(Result.Max))
5165 return tokError("value for '" + Name + "' too large, limit is " +
5166 Twine(Result.Max));
5167 Result.assign(U.getZExtValue());
5168 assert(Result.Val <= Result.Max && "Expected value in range");
5169 Lex.Lex();
5170 return false;
5171}
5172
5173template <>
5174bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
5175 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5176}
5177template <>
5178bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
5179 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5180}
5181
5182template <>
5183bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
5184 if (Lex.getKind() == lltok::APSInt)
5185 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5186
5187 if (Lex.getKind() != lltok::DwarfTag)
5188 return tokError("expected DWARF tag");
5189
5190 unsigned Tag = dwarf::getTag(Lex.getStrVal());
5192 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
5193 assert(Tag <= Result.Max && "Expected valid DWARF tag");
5194
5195 Result.assign(Tag);
5196 Lex.Lex();
5197 return false;
5198}
5199
5200template <>
5201bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5202 DwarfMacinfoTypeField &Result) {
5203 if (Lex.getKind() == lltok::APSInt)
5204 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5205
5206 if (Lex.getKind() != lltok::DwarfMacinfo)
5207 return tokError("expected DWARF macinfo type");
5208
5209 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
5210 if (Macinfo == dwarf::DW_MACINFO_invalid)
5211 return tokError("invalid DWARF macinfo type" + Twine(" '") +
5212 Lex.getStrVal() + "'");
5213 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
5214
5215 Result.assign(Macinfo);
5216 Lex.Lex();
5217 return false;
5218}
5219
5220template <>
5221bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5222 DwarfVirtualityField &Result) {
5223 if (Lex.getKind() == lltok::APSInt)
5224 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5225
5226 if (Lex.getKind() != lltok::DwarfVirtuality)
5227 return tokError("expected DWARF virtuality code");
5228
5229 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
5230 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
5231 return tokError("invalid DWARF virtuality code" + Twine(" '") +
5232 Lex.getStrVal() + "'");
5233 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
5234 Result.assign(Virtuality);
5235 Lex.Lex();
5236 return false;
5237}
5238
5239template <>
5240bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5241 DwarfEnumKindField &Result) {
5242 if (Lex.getKind() == lltok::APSInt)
5243 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5244
5245 if (Lex.getKind() != lltok::DwarfEnumKind)
5246 return tokError("expected DWARF enum kind code");
5247
5248 unsigned EnumKind = dwarf::getEnumKind(Lex.getStrVal());
5249 if (EnumKind == dwarf::DW_APPLE_ENUM_KIND_invalid)
5250 return tokError("invalid DWARF enum kind code" + Twine(" '") +
5251 Lex.getStrVal() + "'");
5252 assert(EnumKind <= Result.Max && "Expected valid DWARF enum kind code");
5253 Result.assign(EnumKind);
5254 Lex.Lex();
5255 return false;
5256}
5257
5258template <>
5259bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
5260 if (Lex.getKind() == lltok::APSInt)
5261 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5262
5263 if (Lex.getKind() != lltok::DwarfLang)
5264 return tokError("expected DWARF language");
5265
5266 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
5267 if (!Lang)
5268 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
5269 "'");
5270 assert(Lang <= Result.Max && "Expected valid DWARF language");
5271 Result.assign(Lang);
5272 Lex.Lex();
5273 return false;
5274}
5275
5276template <>
5277bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5278 DwarfSourceLangNameField &Result) {
5279 if (Lex.getKind() == lltok::APSInt)
5280 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5281
5282 if (Lex.getKind() != lltok::DwarfSourceLangName)
5283 return tokError("expected DWARF source language name");
5284
5285 unsigned Lang = dwarf::getSourceLanguageName(Lex.getStrVal());
5286 if (!Lang)
5287 return tokError("invalid DWARF source language name" + Twine(" '") +
5288 Lex.getStrVal() + "'");
5289 assert(Lang <= Result.Max && "Expected valid DWARF source language name");
5290 Result.assign(Lang);
5291 Lex.Lex();
5292 return false;
5293}
5294
5295template <>
5296bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5297 DwarfLangDialectField &Result) {
5298 // Specifying the dialect field requires a recognized dialect: simt or
5299 // tile (numerically 1 or 2). Omitting the field is the only way to
5300 // express "no dialect specified".
5301 if (Lex.getKind() == lltok::APSInt) {
5302 if (Lex.getAPSIntVal() == 0)
5303 return tokError("value for 'dialect' must be a known DWARF language "
5304 "dialect (DW_LLVM_LANG_DIALECT_simt or "
5305 "DW_LLVM_LANG_DIALECT_tile)");
5306 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5307 }
5308
5309 if (Lex.getKind() != lltok::DwarfLangDialect)
5310 return tokError("expected DWARF language dialect");
5311
5312 StringRef DialectString = Lex.getStrVal();
5313 // getLanguageDialect returns a sentinel above Result.Max for unknown
5314 // spellings; only simt and tile are registered, so any unrecognized
5315 // DW_LLVM_LANG_DIALECT_* token is rejected here.
5316 unsigned Dialect = dwarf::getLanguageDialect(DialectString);
5317 if (Dialect > Result.Max)
5318 return tokError("invalid DWARF language dialect" + Twine(" '") +
5319 DialectString + "'");
5320 Result.assign(Dialect);
5321 Lex.Lex();
5322 return false;
5323}
5324
5325template <>
5326bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
5327 if (Lex.getKind() == lltok::APSInt)
5328 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5329
5330 if (Lex.getKind() != lltok::DwarfCC)
5331 return tokError("expected DWARF calling convention");
5332
5333 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
5334 if (!CC)
5335 return tokError("invalid DWARF calling convention" + Twine(" '") +
5336 Lex.getStrVal() + "'");
5337 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
5338 Result.assign(CC);
5339 Lex.Lex();
5340 return false;
5341}
5342
5343template <>
5344bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5345 EmissionKindField &Result) {
5346 if (Lex.getKind() == lltok::APSInt)
5347 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5348
5349 if (Lex.getKind() != lltok::EmissionKind)
5350 return tokError("expected emission kind");
5351
5352 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
5353 if (!Kind)
5354 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
5355 "'");
5356 assert(*Kind <= Result.Max && "Expected valid emission kind");
5357 Result.assign(*Kind);
5358 Lex.Lex();
5359 return false;
5360}
5361
5362template <>
5363bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5364 FixedPointKindField &Result) {
5365 if (Lex.getKind() == lltok::APSInt)
5366 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5367
5368 if (Lex.getKind() != lltok::FixedPointKind)
5369 return tokError("expected fixed-point kind");
5370
5371 auto Kind = DIFixedPointType::getFixedPointKind(Lex.getStrVal());
5372 if (!Kind)
5373 return tokError("invalid fixed-point kind" + Twine(" '") + Lex.getStrVal() +
5374 "'");
5375 assert(*Kind <= Result.Max && "Expected valid fixed-point kind");
5376 Result.assign(*Kind);
5377 Lex.Lex();
5378 return false;
5379}
5380
5381template <>
5382bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5383 NameTableKindField &Result) {
5384 if (Lex.getKind() == lltok::APSInt)
5385 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5386
5387 if (Lex.getKind() != lltok::NameTableKind)
5388 return tokError("expected nameTable kind");
5389
5390 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
5391 if (!Kind)
5392 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
5393 "'");
5394 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
5395 Result.assign((unsigned)*Kind);
5396 Lex.Lex();
5397 return false;
5398}
5399
5400template <>
5401bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5402 DwarfAttEncodingField &Result) {
5403 if (Lex.getKind() == lltok::APSInt)
5404 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
5405
5406 if (Lex.getKind() != lltok::DwarfAttEncoding)
5407 return tokError("expected DWARF type attribute encoding");
5408
5409 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
5410 if (!Encoding)
5411 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
5412 Lex.getStrVal() + "'");
5413 assert(Encoding <= Result.Max && "Expected valid DWARF language");
5414 Result.assign(Encoding);
5415 Lex.Lex();
5416 return false;
5417}
5418
5419/// DIFlagField
5420/// ::= uint32
5421/// ::= DIFlagVector
5422/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
5423template <>
5424bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
5425
5426 // parser for a single flag.
5427 auto parseFlag = [&](DINode::DIFlags &Val) {
5428 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5429 uint32_t TempVal = static_cast<uint32_t>(Val);
5430 bool Res = parseUInt32(TempVal);
5431 Val = static_cast<DINode::DIFlags>(TempVal);
5432 return Res;
5433 }
5434
5435 if (Lex.getKind() != lltok::DIFlag)
5436 return tokError("expected debug info flag");
5437
5438 Val = DINode::getFlag(Lex.getStrVal());
5439 if (!Val)
5440 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
5441 "'");
5442 Lex.Lex();
5443 return false;
5444 };
5445
5446 // parse the flags and combine them together.
5447 DINode::DIFlags Combined = DINode::FlagZero;
5448 do {
5449 DINode::DIFlags Val;
5450 if (parseFlag(Val))
5451 return true;
5452 Combined |= Val;
5453 } while (EatIfPresent(lltok::bar));
5454
5455 Result.assign(Combined);
5456 return false;
5457}
5458
5459/// DISPFlagField
5460/// ::= uint32
5461/// ::= DISPFlagVector
5462/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5463template <>
5464bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5465
5466 // parser for a single flag.
5467 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5468 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5469 uint32_t TempVal = static_cast<uint32_t>(Val);
5470 bool Res = parseUInt32(TempVal);
5471 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5472 return Res;
5473 }
5474
5475 if (Lex.getKind() != lltok::DISPFlag)
5476 return tokError("expected debug info flag");
5477
5478 Val = DISubprogram::getFlag(Lex.getStrVal());
5479 if (!Val)
5480 return tokError(Twine("invalid subprogram debug info flag '") +
5481 Lex.getStrVal() + "'");
5482 Lex.Lex();
5483 return false;
5484 };
5485
5486 // parse the flags and combine them together.
5487 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5488 do {
5490 if (parseFlag(Val))
5491 return true;
5492 Combined |= Val;
5493 } while (EatIfPresent(lltok::bar));
5494
5495 Result.assign(Combined);
5496 return false;
5497}
5498
5499template <>
5500bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5501 if (Lex.getKind() != lltok::APSInt)
5502 return tokError("expected signed integer");
5503
5504 auto &S = Lex.getAPSIntVal();
5505 if (S < Result.Min)
5506 return tokError("value for '" + Name + "' too small, limit is " +
5507 Twine(Result.Min));
5508 if (S > Result.Max)
5509 return tokError("value for '" + Name + "' too large, limit is " +
5510 Twine(Result.Max));
5511 Result.assign(S.getExtValue());
5512 assert(Result.Val >= Result.Min && "Expected value in range");
5513 assert(Result.Val <= Result.Max && "Expected value in range");
5514 Lex.Lex();
5515 return false;
5516}
5517
5518template <>
5519bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5520 switch (Lex.getKind()) {
5521 default:
5522 return tokError("expected 'true' or 'false'");
5523 case lltok::kw_true:
5524 Result.assign(true);
5525 break;
5526 case lltok::kw_false:
5527 Result.assign(false);
5528 break;
5529 }
5530 Lex.Lex();
5531 return false;
5532}
5533
5534template <>
5535bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5536 if (Lex.getKind() == lltok::kw_null) {
5537 if (!Result.AllowNull)
5538 return tokError("'" + Name + "' cannot be null");
5539 Lex.Lex();
5540 Result.assign(nullptr);
5541 return false;
5542 }
5543
5544 Metadata *MD;
5545 if (parseMetadata(MD, nullptr))
5546 return true;
5547
5548 Result.assign(MD);
5549 return false;
5550}
5551
5552template <>
5553bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5554 MDSignedOrMDField &Result) {
5555 // Try to parse a signed int.
5556 if (Lex.getKind() == lltok::APSInt) {
5557 MDSignedField Res = Result.A;
5558 if (!parseMDField(Loc, Name, Res)) {
5559 Result.assign(Res);
5560 return false;
5561 }
5562 return true;
5563 }
5564
5565 // Otherwise, try to parse as an MDField.
5566 MDField Res = Result.B;
5567 if (!parseMDField(Loc, Name, Res)) {
5568 Result.assign(Res);
5569 return false;
5570 }
5571
5572 return true;
5573}
5574
5575template <>
5576bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5577 MDUnsignedOrMDField &Result) {
5578 // Try to parse an unsigned int.
5579 if (Lex.getKind() == lltok::APSInt) {
5580 MDUnsignedField Res = Result.A;
5581 if (!parseMDField(Loc, Name, Res)) {
5582 Result.assign(Res);
5583 return false;
5584 }
5585 return true;
5586 }
5587
5588 // Otherwise, try to parse as an MDField.
5589 MDField Res = Result.B;
5590 if (!parseMDField(Loc, Name, Res)) {
5591 Result.assign(Res);
5592 return false;
5593 }
5594
5595 return true;
5596}
5597
5598template <>
5599bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5600 LocTy ValueLoc = Lex.getLoc();
5601 std::string S;
5602 if (parseStringConstant(S))
5603 return true;
5604
5605 if (S.empty()) {
5606 switch (Result.EmptyIs) {
5607 case MDStringField::EmptyIs::Null:
5608 Result.assign(nullptr);
5609 return false;
5610 case MDStringField::EmptyIs::Empty:
5611 break;
5612 case MDStringField::EmptyIs::Error:
5613 return error(ValueLoc, "'" + Name + "' cannot be empty");
5614 }
5615 }
5616
5617 Result.assign(MDString::get(Context, S));
5618 return false;
5619}
5620
5621template <>
5622bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5624 if (parseMDNodeVector(MDs))
5625 return true;
5626
5627 Result.assign(std::move(MDs));
5628 return false;
5629}
5630
5631template <>
5632bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5633 ChecksumKindField &Result) {
5634 std::optional<DIFile::ChecksumKind> CSKind =
5635 DIFile::getChecksumKind(Lex.getStrVal());
5636
5637 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5638 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5639 "'");
5640
5641 Result.assign(*CSKind);
5642 Lex.Lex();
5643 return false;
5644}
5645
5646} // end namespace llvm
5647
5648template <class ParserTy>
5649bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5650 do {
5651 if (Lex.getKind() != lltok::LabelStr)
5652 return tokError("expected field label here");
5653
5654 if (ParseField())
5655 return true;
5656 } while (EatIfPresent(lltok::comma));
5657
5658 return false;
5659}
5660
5661template <class ParserTy>
5662bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5663 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5664 Lex.Lex();
5665
5666 if (parseToken(lltok::lparen, "expected '(' here"))
5667 return true;
5668 if (Lex.getKind() != lltok::rparen)
5669 if (parseMDFieldsImplBody(ParseField))
5670 return true;
5671
5672 ClosingLoc = Lex.getLoc();
5673 return parseToken(lltok::rparen, "expected ')' here");
5674}
5675
5676template <class FieldTy>
5677bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5678 if (Result.Seen)
5679 return tokError("field '" + Name + "' cannot be specified more than once");
5680
5681 LocTy Loc = Lex.getLoc();
5682 Lex.Lex();
5683 return parseMDField(Loc, Name, Result);
5684}
5685
5686bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5687 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5688
5689#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5690 if (Lex.getStrVal() == #CLASS) \
5691 return parse##CLASS(N, IsDistinct);
5692#include "llvm/IR/Metadata.def"
5693
5694 return tokError("expected metadata type");
5695}
5696
5697#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5698#define NOP_FIELD(NAME, TYPE, INIT)
5699#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5700 if (!NAME.Seen) \
5701 return error(ClosingLoc, "missing required field '" #NAME "'");
5702#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5703 if (Lex.getStrVal() == #NAME) \
5704 return parseMDField(#NAME, NAME);
5705#define PARSE_MD_FIELDS() \
5706 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5707 do { \
5708 LocTy ClosingLoc; \
5709 if (parseMDFieldsImpl( \
5710 [&]() -> bool { \
5711 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5712 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5713 "'"); \
5714 }, \
5715 ClosingLoc)) \
5716 return true; \
5717 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5718 } while (false)
5719#define GET_OR_DISTINCT(CLASS, ARGS) \
5720 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5721
5722/// parseDILocationFields:
5723/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5724/// isImplicitCode: true, atomGroup: 1, atomRank: 1)
5725bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5726#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5727 OPTIONAL(line, LineField, ); \
5728 OPTIONAL(column, ColumnField, ); \
5729 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5730 OPTIONAL(inlinedAt, MDField, ); \
5731 OPTIONAL(isImplicitCode, MDBoolField, (false)); \
5732 OPTIONAL(atomGroup, MDUnsignedField, (0, UINT64_MAX)); \
5733 OPTIONAL(atomRank, MDUnsignedField, (0, UINT8_MAX));
5735#undef VISIT_MD_FIELDS
5736
5737 Result = GET_OR_DISTINCT(
5738 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val,
5739 isImplicitCode.Val, atomGroup.Val, atomRank.Val));
5740 return false;
5741}
5742
5743/// parseDIAssignID:
5744/// ::= distinct !DIAssignID()
5745bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5746 if (!IsDistinct)
5747 return tokError("missing 'distinct', required for !DIAssignID()");
5748
5749 Lex.Lex();
5750
5751 // Now eat the parens.
5752 if (parseToken(lltok::lparen, "expected '(' here"))
5753 return true;
5754 if (parseToken(lltok::rparen, "expected ')' here"))
5755 return true;
5756
5758 return false;
5759}
5760
5761/// parseGenericDINode:
5762/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5763bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5764#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5765 REQUIRED(tag, DwarfTagField, ); \
5766 OPTIONAL(header, MDStringField, ); \
5767 OPTIONAL(operands, MDFieldList, );
5769#undef VISIT_MD_FIELDS
5770
5771 Result = GET_OR_DISTINCT(GenericDINode,
5772 (Context, tag.Val, header.Val, operands.Val));
5773 return false;
5774}
5775
5776/// parseDISubrangeType:
5777/// ::= !DISubrangeType(name: "whatever", file: !0,
5778/// line: 7, scope: !1, baseType: !2, size: 32,
5779/// align: 32, flags: 0, lowerBound: !3
5780/// upperBound: !4, stride: !5, bias: !6)
5781bool LLParser::parseDISubrangeType(MDNode *&Result, bool IsDistinct) {
5782#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5783 OPTIONAL(name, MDStringField, ); \
5784 OPTIONAL(file, MDField, ); \
5785 OPTIONAL(line, LineField, ); \
5786 OPTIONAL(scope, MDField, ); \
5787 OPTIONAL(baseType, MDField, ); \
5788 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5789 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5790 OPTIONAL(flags, DIFlagField, ); \
5791 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5792 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5793 OPTIONAL(stride, MDSignedOrMDField, ); \
5794 OPTIONAL(bias, MDSignedOrMDField, );
5796#undef VISIT_MD_FIELDS
5797
5798 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
5799 if (Bound.isMDSignedField())
5801 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5802 if (Bound.isMDField())
5803 return Bound.getMDFieldValue();
5804 return nullptr;
5805 };
5806
5807 Metadata *LowerBound = convToMetadata(lowerBound);
5808 Metadata *UpperBound = convToMetadata(upperBound);
5809 Metadata *Stride = convToMetadata(stride);
5810 Metadata *Bias = convToMetadata(bias);
5811
5813 DISubrangeType, (Context, name.Val, file.Val, line.Val, scope.Val,
5814 size.getValueAsMetadata(Context), align.Val, flags.Val,
5815 baseType.Val, LowerBound, UpperBound, Stride, Bias));
5816
5817 return false;
5818}
5819
5820/// parseDISubrange:
5821/// ::= !DISubrange(count: 30, lowerBound: 2)
5822/// ::= !DISubrange(count: !node, lowerBound: 2)
5823/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5824bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5825#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5826 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5827 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5828 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5829 OPTIONAL(stride, MDSignedOrMDField, );
5831#undef VISIT_MD_FIELDS
5832
5833 Metadata *Count = nullptr;
5834 Metadata *LowerBound = nullptr;
5835 Metadata *UpperBound = nullptr;
5836 Metadata *Stride = nullptr;
5837
5838 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5839 if (Bound.isMDSignedField())
5841 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5842 if (Bound.isMDField())
5843 return Bound.getMDFieldValue();
5844 return nullptr;
5845 };
5846
5847 Count = convToMetadata(count);
5848 LowerBound = convToMetadata(lowerBound);
5849 UpperBound = convToMetadata(upperBound);
5850 Stride = convToMetadata(stride);
5851
5852 Result = GET_OR_DISTINCT(DISubrange,
5853 (Context, Count, LowerBound, UpperBound, Stride));
5854
5855 return false;
5856}
5857
5858/// parseDIGenericSubrange:
5859/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5860/// !node3)
5861bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5862#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5863 OPTIONAL(count, MDSignedOrMDField, ); \
5864 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5865 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5866 OPTIONAL(stride, MDSignedOrMDField, );
5868#undef VISIT_MD_FIELDS
5869
5870 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5871 if (Bound.isMDSignedField())
5872 return DIExpression::get(
5873 Context, {dwarf::DW_OP_consts,
5874 static_cast<uint64_t>(Bound.getMDSignedValue())});
5875 if (Bound.isMDField())
5876 return Bound.getMDFieldValue();
5877 return nullptr;
5878 };
5879
5880 Metadata *Count = ConvToMetadata(count);
5881 Metadata *LowerBound = ConvToMetadata(lowerBound);
5882 Metadata *UpperBound = ConvToMetadata(upperBound);
5883 Metadata *Stride = ConvToMetadata(stride);
5884
5885 Result = GET_OR_DISTINCT(DIGenericSubrange,
5886 (Context, Count, LowerBound, UpperBound, Stride));
5887
5888 return false;
5889}
5890
5891/// parseDIEnumerator:
5892/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5893bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5894#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5895 REQUIRED(name, MDStringField, ); \
5896 REQUIRED(value, MDAPSIntField, ); \
5897 OPTIONAL(isUnsigned, MDBoolField, (false));
5899#undef VISIT_MD_FIELDS
5900
5901 if (isUnsigned.Val && value.Val.isNegative())
5902 return tokError("unsigned enumerator with negative value");
5903
5904 APSInt Value(value.Val);
5905 // Add a leading zero so that unsigned values with the msb set are not
5906 // mistaken for negative values when used for signed enumerators.
5907 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5908 Value = Value.zext(Value.getBitWidth() + 1);
5909
5910 Result =
5911 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5912
5913 return false;
5914}
5915
5916/// parseDIBasicType:
5917/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5918/// encoding: DW_ATE_encoding, flags: 0)
5919bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5920#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5921 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5922 OPTIONAL(name, MDStringField, ); \
5923 OPTIONAL(file, MDField, ); \
5924 OPTIONAL(line, LineField, ); \
5925 OPTIONAL(scope, MDField, ); \
5926 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5927 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5928 OPTIONAL(dataSize, MDUnsignedField, (0, UINT32_MAX)); \
5929 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5930 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5931 OPTIONAL(flags, DIFlagField, );
5933#undef VISIT_MD_FIELDS
5934
5936 DIBasicType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
5937 size.getValueAsMetadata(Context), align.Val, encoding.Val,
5938 num_extra_inhabitants.Val, dataSize.Val, flags.Val));
5939 return false;
5940}
5941
5942/// parseDIFixedPointType:
5943/// ::= !DIFixedPointType(tag: DW_TAG_base_type, name: "xyz", size: 32,
5944/// align: 32, encoding: DW_ATE_signed_fixed,
5945/// flags: 0, kind: Rational, factor: 3, numerator: 1,
5946/// denominator: 8)
5947bool LLParser::parseDIFixedPointType(MDNode *&Result, bool IsDistinct) {
5948#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5949 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5950 OPTIONAL(name, MDStringField, ); \
5951 OPTIONAL(file, MDField, ); \
5952 OPTIONAL(line, LineField, ); \
5953 OPTIONAL(scope, MDField, ); \
5954 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5955 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5956 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5957 OPTIONAL(flags, DIFlagField, ); \
5958 OPTIONAL(kind, FixedPointKindField, ); \
5959 OPTIONAL(factor, MDSignedField, ); \
5960 OPTIONAL(numerator, MDAPSIntField, ); \
5961 OPTIONAL(denominator, MDAPSIntField, );
5963#undef VISIT_MD_FIELDS
5964
5965 Result = GET_OR_DISTINCT(DIFixedPointType,
5966 (Context, tag.Val, name.Val, file.Val, line.Val,
5967 scope.Val, size.getValueAsMetadata(Context),
5968 align.Val, encoding.Val, flags.Val, kind.Val,
5969 factor.Val, numerator.Val, denominator.Val));
5970 return false;
5971}
5972
5973/// parseDIStringType:
5974/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5975bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5976#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5977 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5978 OPTIONAL(name, MDStringField, ); \
5979 OPTIONAL(stringLength, MDField, ); \
5980 OPTIONAL(stringLengthExpression, MDField, ); \
5981 OPTIONAL(stringLocationExpression, MDField, ); \
5982 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
5983 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5984 OPTIONAL(encoding, DwarfAttEncodingField, );
5986#undef VISIT_MD_FIELDS
5987
5989 DIStringType,
5990 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5991 stringLocationExpression.Val, size.getValueAsMetadata(Context),
5992 align.Val, encoding.Val));
5993 return false;
5994}
5995
5996/// parseDIDerivedType:
5997/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5998/// line: 7, scope: !1, baseType: !2, size: 32,
5999/// align: 32, offset: 0, flags: 0, extraData: !3,
6000/// dwarfAddressSpace: 3, ptrAuthKey: 1,
6001/// ptrAuthIsAddressDiscriminated: true,
6002/// ptrAuthExtraDiscriminator: 0x1234,
6003/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
6004/// )
6005bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
6006#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6007 REQUIRED(tag, DwarfTagField, ); \
6008 OPTIONAL(name, MDStringField, ); \
6009 OPTIONAL(file, MDField, ); \
6010 OPTIONAL(line, LineField, ); \
6011 OPTIONAL(scope, MDField, ); \
6012 REQUIRED(baseType, MDField, ); \
6013 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6014 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6015 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6016 OPTIONAL(flags, DIFlagField, ); \
6017 OPTIONAL(extraData, MDField, ); \
6018 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
6019 OPTIONAL(annotations, MDField, ); \
6020 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
6021 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
6022 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
6023 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
6024 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
6026#undef VISIT_MD_FIELDS
6027
6028 std::optional<unsigned> DWARFAddressSpace;
6029 if (dwarfAddressSpace.Val != UINT32_MAX)
6030 DWARFAddressSpace = dwarfAddressSpace.Val;
6031 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
6032 if (ptrAuthKey.Val)
6033 PtrAuthData.emplace(
6034 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
6035 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
6036 ptrAuthAuthenticatesNullValues.Val);
6037
6039 DIDerivedType, (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val,
6040 baseType.Val, size.getValueAsMetadata(Context), align.Val,
6041 offset.getValueAsMetadata(Context), DWARFAddressSpace,
6042 PtrAuthData, flags.Val, extraData.Val, annotations.Val));
6043 return false;
6044}
6045
6046bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
6047#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6048 REQUIRED(tag, DwarfTagField, ); \
6049 OPTIONAL(name, MDStringField, ); \
6050 OPTIONAL(file, MDField, ); \
6051 OPTIONAL(line, LineField, ); \
6052 OPTIONAL(scope, MDField, ); \
6053 OPTIONAL(baseType, MDField, ); \
6054 OPTIONAL(size, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6055 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6056 OPTIONAL(offset, MDUnsignedOrMDField, (0, UINT64_MAX)); \
6057 OPTIONAL(flags, DIFlagField, ); \
6058 OPTIONAL(elements, MDField, ); \
6059 OPTIONAL(runtimeLang, DwarfLangField, ); \
6060 OPTIONAL(enumKind, DwarfEnumKindField, ); \
6061 OPTIONAL(vtableHolder, MDField, ); \
6062 OPTIONAL(templateParams, MDField, ); \
6063 OPTIONAL(identifier, MDStringField, ); \
6064 OPTIONAL(discriminator, MDField, ); \
6065 OPTIONAL(dataLocation, MDField, ); \
6066 OPTIONAL(associated, MDField, ); \
6067 OPTIONAL(allocated, MDField, ); \
6068 OPTIONAL(rank, MDSignedOrMDField, ); \
6069 OPTIONAL(annotations, MDField, ); \
6070 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
6071 OPTIONAL(specification, MDField, ); \
6072 OPTIONAL(bitStride, MDField, );
6074#undef VISIT_MD_FIELDS
6075
6076 Metadata *Rank = nullptr;
6077 if (rank.isMDSignedField())
6079 Type::getInt64Ty(Context), rank.getMDSignedValue()));
6080 else if (rank.isMDField())
6081 Rank = rank.getMDFieldValue();
6082
6083 std::optional<unsigned> EnumKind;
6084 if (enumKind.Val != dwarf::DW_APPLE_ENUM_KIND_invalid)
6085 EnumKind = enumKind.Val;
6086
6087 // If this has an identifier try to build an ODR type.
6088 if (identifier.Val)
6089 if (auto *CT = DICompositeType::buildODRType(
6090 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
6091 scope.Val, baseType.Val, size.getValueAsMetadata(Context),
6092 align.Val, offset.getValueAsMetadata(Context), specification.Val,
6093 num_extra_inhabitants.Val, flags.Val, elements.Val, runtimeLang.Val,
6094 EnumKind, vtableHolder.Val, templateParams.Val, discriminator.Val,
6095 dataLocation.Val, associated.Val, allocated.Val, Rank,
6096 annotations.Val, bitStride.Val)) {
6097 Result = CT;
6098 return false;
6099 }
6100
6101 // Create a new node, and save it in the context if it belongs in the type
6102 // map.
6104 DICompositeType,
6105 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
6106 size.getValueAsMetadata(Context), align.Val,
6107 offset.getValueAsMetadata(Context), flags.Val, elements.Val,
6108 runtimeLang.Val, EnumKind, vtableHolder.Val, templateParams.Val,
6109 identifier.Val, discriminator.Val, dataLocation.Val, associated.Val,
6110 allocated.Val, Rank, annotations.Val, specification.Val,
6111 num_extra_inhabitants.Val, bitStride.Val));
6112 return false;
6113}
6114
6115bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
6116#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6117 OPTIONAL(flags, DIFlagField, ); \
6118 OPTIONAL(cc, DwarfCCField, ); \
6119 REQUIRED(types, MDField, );
6121#undef VISIT_MD_FIELDS
6122
6123 Result = GET_OR_DISTINCT(DISubroutineType,
6124 (Context, flags.Val, cc.Val, types.Val));
6125 return false;
6126}
6127
6128/// parseDIFileType:
6129/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
6130/// checksumkind: CSK_MD5,
6131/// checksum: "000102030405060708090a0b0c0d0e0f",
6132/// source: "source file contents")
6133bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
6134 // The default constructed value for checksumkind is required, but will never
6135 // be used, as the parser checks if the field was actually Seen before using
6136 // the Val.
6137#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6138 REQUIRED(filename, MDStringField, ); \
6139 REQUIRED(directory, MDStringField, ); \
6140 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
6141 OPTIONAL(checksum, MDStringField, ); \
6142 OPTIONAL(source, MDStringField, (MDStringField::EmptyIs::Empty));
6144#undef VISIT_MD_FIELDS
6145
6146 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
6147 if (checksumkind.Seen && checksum.Seen)
6148 OptChecksum.emplace(checksumkind.Val, checksum.Val);
6149 else if (checksumkind.Seen || checksum.Seen)
6150 return tokError("'checksumkind' and 'checksum' must be provided together");
6151
6152 MDString *Source = nullptr;
6153 if (source.Seen)
6154 Source = source.Val;
6156 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
6157 return false;
6158}
6159
6160/// parseDICompileUnit:
6161/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
6162/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
6163/// splitDebugFilename: "abc.debug",
6164/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
6165/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
6166/// sysroot: "/", sdk: "MacOSX.sdk",
6167/// dialect: DW_LLVM_LANG_DIALECT_simt)
6168bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
6169 if (!IsDistinct)
6170 return tokError("missing 'distinct', required for !DICompileUnit");
6171
6172 LocTy Loc = Lex.getLoc();
6173
6174#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6175 REQUIRED(file, MDField, (/* AllowNull */ false)); \
6176 OPTIONAL(language, DwarfLangField, ); \
6177 OPTIONAL(sourceLanguageName, DwarfSourceLangNameField, ); \
6178 OPTIONAL(sourceLanguageVersion, MDUnsignedField, (0, UINT32_MAX)); \
6179 OPTIONAL(producer, MDStringField, ); \
6180 OPTIONAL(isOptimized, MDBoolField, ); \
6181 OPTIONAL(flags, MDStringField, ); \
6182 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
6183 OPTIONAL(splitDebugFilename, MDStringField, ); \
6184 OPTIONAL(emissionKind, EmissionKindField, ); \
6185 OPTIONAL(enums, MDField, ); \
6186 OPTIONAL(retainedTypes, MDField, ); \
6187 OPTIONAL(globals, MDField, ); \
6188 OPTIONAL(imports, MDField, ); \
6189 OPTIONAL(macros, MDField, ); \
6190 OPTIONAL(dwoId, MDUnsignedField, ); \
6191 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
6192 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
6193 OPTIONAL(nameTableKind, NameTableKindField, ); \
6194 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
6195 OPTIONAL(sysroot, MDStringField, ); \
6196 OPTIONAL(sdk, MDStringField, ); \
6197 OPTIONAL(dialect, DwarfLangDialectField, );
6199#undef VISIT_MD_FIELDS
6200
6201 if (!language.Seen && !sourceLanguageName.Seen)
6202 return error(Loc, "missing one of 'language' or 'sourceLanguageName', "
6203 "required for !DICompileUnit");
6204
6205 if (language.Seen && sourceLanguageName.Seen)
6206 return error(Loc, "can only specify one of 'language' and "
6207 "'sourceLanguageName' on !DICompileUnit");
6208
6209 if (sourceLanguageVersion.Seen && !sourceLanguageName.Seen)
6210 return error(Loc, "'sourceLanguageVersion' requires an associated "
6211 "'sourceLanguageName' on !DICompileUnit");
6212
6213 uint16_t Dialect = static_cast<uint16_t>(dialect.Val);
6214 DISourceLanguageName SourceLanguage =
6215 language.Seen
6216 ? DISourceLanguageName(static_cast<uint16_t>(language.Val), Dialect)
6217 : DISourceLanguageName(
6218 static_cast<uint16_t>(sourceLanguageName.Val),
6219 static_cast<uint32_t>(sourceLanguageVersion.Val), Dialect);
6220
6222 Context, SourceLanguage, file.Val, producer.Val, isOptimized.Val,
6223 flags.Val, runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val,
6224 enums.Val, retainedTypes.Val, globals.Val, imports.Val, macros.Val,
6225 dwoId.Val, splitDebugInlining.Val, debugInfoForProfiling.Val,
6226 nameTableKind.Val, rangesBaseAddress.Val, sysroot.Val, sdk.Val);
6227 return false;
6228}
6229
6230/// parseDISubprogram:
6231/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
6232/// file: !1, line: 7, type: !2, isLocal: false,
6233/// isDefinition: true, scopeLine: 8, containingType: !3,
6234/// virtuality: DW_VIRTUALTIY_pure_virtual,
6235/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
6236/// spFlags: 10, isOptimized: false, templateParams: !4,
6237/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
6238/// annotations: !8)
6239bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
6240 auto Loc = Lex.getLoc();
6241#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6242 OPTIONAL(scope, MDField, ); \
6243 OPTIONAL(name, MDStringField, ); \
6244 OPTIONAL(linkageName, MDStringField, ); \
6245 OPTIONAL(file, MDField, ); \
6246 OPTIONAL(line, LineField, ); \
6247 REQUIRED(type, MDField, (/* AllowNull */ false)); \
6248 OPTIONAL(isLocal, MDBoolField, ); \
6249 OPTIONAL(isDefinition, MDBoolField, (true)); \
6250 OPTIONAL(scopeLine, LineField, ); \
6251 OPTIONAL(containingType, MDField, ); \
6252 OPTIONAL(virtuality, DwarfVirtualityField, ); \
6253 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
6254 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
6255 OPTIONAL(flags, DIFlagField, ); \
6256 OPTIONAL(spFlags, DISPFlagField, ); \
6257 OPTIONAL(isOptimized, MDBoolField, ); \
6258 OPTIONAL(unit, MDField, ); \
6259 OPTIONAL(templateParams, MDField, ); \
6260 OPTIONAL(declaration, MDField, ); \
6261 OPTIONAL(retainedNodes, MDField, ); \
6262 OPTIONAL(thrownTypes, MDField, ); \
6263 OPTIONAL(annotations, MDField, ); \
6264 OPTIONAL(targetFuncName, MDStringField, ); \
6265 OPTIONAL(keyInstructions, MDBoolField, );
6267#undef VISIT_MD_FIELDS
6268
6269 // An explicit spFlags field takes precedence over individual fields in
6270 // older IR versions.
6271 DISubprogram::DISPFlags SPFlags =
6272 spFlags.Seen ? spFlags.Val
6273 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
6274 isOptimized.Val, virtuality.Val);
6275 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
6276 return error(
6277 Loc,
6278 "missing 'distinct', required for !DISubprogram that is a Definition");
6280 DISubprogram,
6281 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
6282 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
6283 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
6284 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
6285 targetFuncName.Val, keyInstructions.Val));
6286
6287 if (IsDistinct)
6288 NewDistinctSPs.push_back(cast<DISubprogram>(Result));
6289
6290 return false;
6291}
6292
6293/// parseDILexicalBlock:
6294/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
6295bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
6296#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6297 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6298 OPTIONAL(file, MDField, ); \
6299 OPTIONAL(line, LineField, ); \
6300 OPTIONAL(column, ColumnField, );
6302#undef VISIT_MD_FIELDS
6303
6305 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
6306 return false;
6307}
6308
6309/// parseDILexicalBlockFile:
6310/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
6311bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
6312#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6313 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6314 OPTIONAL(file, MDField, ); \
6315 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
6317#undef VISIT_MD_FIELDS
6318
6319 Result = GET_OR_DISTINCT(DILexicalBlockFile,
6320 (Context, scope.Val, file.Val, discriminator.Val));
6321 return false;
6322}
6323
6324/// parseDICommonBlock:
6325/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
6326bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
6327#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6328 REQUIRED(scope, MDField, ); \
6329 OPTIONAL(declaration, MDField, ); \
6330 OPTIONAL(name, MDStringField, ); \
6331 OPTIONAL(file, MDField, ); \
6332 OPTIONAL(line, LineField, );
6334#undef VISIT_MD_FIELDS
6335
6336 Result = GET_OR_DISTINCT(DICommonBlock,
6337 (Context, scope.Val, declaration.Val, name.Val,
6338 file.Val, line.Val));
6339 return false;
6340}
6341
6342/// parseDINamespace:
6343/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
6344bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
6345#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6346 REQUIRED(scope, MDField, ); \
6347 OPTIONAL(name, MDStringField, ); \
6348 OPTIONAL(exportSymbols, MDBoolField, );
6350#undef VISIT_MD_FIELDS
6351
6352 Result = GET_OR_DISTINCT(DINamespace,
6353 (Context, scope.Val, name.Val, exportSymbols.Val));
6354 return false;
6355}
6356
6357/// parseDIMacro:
6358/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
6359/// "SomeValue")
6360bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
6361#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6362 REQUIRED(type, DwarfMacinfoTypeField, ); \
6363 OPTIONAL(line, LineField, ); \
6364 REQUIRED(name, MDStringField, ); \
6365 OPTIONAL(value, MDStringField, );
6367#undef VISIT_MD_FIELDS
6368
6369 Result = GET_OR_DISTINCT(DIMacro,
6370 (Context, type.Val, line.Val, name.Val, value.Val));
6371 return false;
6372}
6373
6374/// parseDIMacroFile:
6375/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
6376bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
6377#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6378 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
6379 OPTIONAL(line, LineField, ); \
6380 REQUIRED(file, MDField, ); \
6381 OPTIONAL(nodes, MDField, );
6383#undef VISIT_MD_FIELDS
6384
6385 Result = GET_OR_DISTINCT(DIMacroFile,
6386 (Context, type.Val, line.Val, file.Val, nodes.Val));
6387 return false;
6388}
6389
6390/// parseDIModule:
6391/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
6392/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
6393/// file: !1, line: 4, isDecl: false)
6394bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
6395#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6396 REQUIRED(scope, MDField, ); \
6397 REQUIRED(name, MDStringField, ); \
6398 OPTIONAL(configMacros, MDStringField, ); \
6399 OPTIONAL(includePath, MDStringField, ); \
6400 OPTIONAL(apinotes, MDStringField, ); \
6401 OPTIONAL(file, MDField, ); \
6402 OPTIONAL(line, LineField, ); \
6403 OPTIONAL(isDecl, MDBoolField, );
6405#undef VISIT_MD_FIELDS
6406
6407 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
6408 configMacros.Val, includePath.Val,
6409 apinotes.Val, line.Val, isDecl.Val));
6410 return false;
6411}
6412
6413/// parseDITemplateTypeParameter:
6414/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
6415bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
6416#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6417 OPTIONAL(name, MDStringField, ); \
6418 REQUIRED(type, MDField, ); \
6419 OPTIONAL(defaulted, MDBoolField, );
6421#undef VISIT_MD_FIELDS
6422
6423 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
6424 (Context, name.Val, type.Val, defaulted.Val));
6425 return false;
6426}
6427
6428/// parseDITemplateValueParameter:
6429/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
6430/// name: "V", type: !1, defaulted: false,
6431/// value: i32 7)
6432bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
6433#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6434 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
6435 OPTIONAL(name, MDStringField, ); \
6436 OPTIONAL(type, MDField, ); \
6437 OPTIONAL(defaulted, MDBoolField, ); \
6438 REQUIRED(value, MDField, );
6439
6441#undef VISIT_MD_FIELDS
6442
6444 DITemplateValueParameter,
6445 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
6446 return false;
6447}
6448
6449/// parseDIGlobalVariable:
6450/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
6451/// file: !1, line: 7, type: !2, isLocal: false,
6452/// isDefinition: true, templateParams: !3,
6453/// declaration: !4, align: 8)
6454bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
6455#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6456 OPTIONAL(name, MDStringField, (MDStringField::EmptyIs::Error)); \
6457 OPTIONAL(scope, MDField, ); \
6458 OPTIONAL(linkageName, MDStringField, ); \
6459 OPTIONAL(file, MDField, ); \
6460 OPTIONAL(line, LineField, ); \
6461 OPTIONAL(type, MDField, ); \
6462 OPTIONAL(isLocal, MDBoolField, ); \
6463 OPTIONAL(isDefinition, MDBoolField, (true)); \
6464 OPTIONAL(templateParams, MDField, ); \
6465 OPTIONAL(declaration, MDField, ); \
6466 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6467 OPTIONAL(annotations, MDField, );
6469#undef VISIT_MD_FIELDS
6470
6471 Result =
6472 GET_OR_DISTINCT(DIGlobalVariable,
6473 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
6474 line.Val, type.Val, isLocal.Val, isDefinition.Val,
6475 declaration.Val, templateParams.Val, align.Val,
6476 annotations.Val));
6477 return false;
6478}
6479
6480/// parseDILocalVariable:
6481/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
6482/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6483/// align: 8)
6484/// ::= !DILocalVariable(scope: !0, name: "foo",
6485/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
6486/// align: 8)
6487bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
6488#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6489 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6490 OPTIONAL(name, MDStringField, ); \
6491 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
6492 OPTIONAL(file, MDField, ); \
6493 OPTIONAL(line, LineField, ); \
6494 OPTIONAL(type, MDField, ); \
6495 OPTIONAL(flags, DIFlagField, ); \
6496 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
6497 OPTIONAL(annotations, MDField, );
6499#undef VISIT_MD_FIELDS
6500
6501 Result = GET_OR_DISTINCT(DILocalVariable,
6502 (Context, scope.Val, name.Val, file.Val, line.Val,
6503 type.Val, arg.Val, flags.Val, align.Val,
6504 annotations.Val));
6505 return false;
6506}
6507
6508/// parseDILabel:
6509/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7, column: 4)
6510bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
6511#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6512 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
6513 REQUIRED(name, MDStringField, ); \
6514 REQUIRED(file, MDField, ); \
6515 REQUIRED(line, LineField, ); \
6516 OPTIONAL(column, ColumnField, ); \
6517 OPTIONAL(isArtificial, MDBoolField, ); \
6518 OPTIONAL(coroSuspendIdx, MDUnsignedField, );
6520#undef VISIT_MD_FIELDS
6521
6522 std::optional<unsigned> CoroSuspendIdx =
6523 coroSuspendIdx.Seen ? std::optional<unsigned>(coroSuspendIdx.Val)
6524 : std::nullopt;
6525
6526 Result = GET_OR_DISTINCT(DILabel,
6527 (Context, scope.Val, name.Val, file.Val, line.Val,
6528 column.Val, isArtificial.Val, CoroSuspendIdx));
6529 return false;
6530}
6531
6532/// parseDIExpressionBody:
6533/// ::= (0, 7, -1)
6534bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
6535 if (parseToken(lltok::lparen, "expected '(' here"))
6536 return true;
6537
6538 SmallVector<uint64_t, 8> Elements;
6539 if (Lex.getKind() != lltok::rparen)
6540 do {
6541 if (Lex.getKind() == lltok::DwarfOp) {
6542 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
6543 Lex.Lex();
6544 Elements.push_back(Op);
6545 continue;
6546 }
6547 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
6548 }
6549
6550 if (Lex.getKind() == lltok::DwarfAttEncoding) {
6551 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
6552 Lex.Lex();
6553 Elements.push_back(Op);
6554 continue;
6555 }
6556 return tokError(Twine("invalid DWARF attribute encoding '") +
6557 Lex.getStrVal() + "'");
6558 }
6559
6560 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
6561 return tokError("expected unsigned integer");
6562
6563 auto &U = Lex.getAPSIntVal();
6564 if (U.ugt(UINT64_MAX))
6565 return tokError("element too large, limit is " + Twine(UINT64_MAX));
6566 Elements.push_back(U.getZExtValue());
6567 Lex.Lex();
6568 } while (EatIfPresent(lltok::comma));
6569
6570 if (parseToken(lltok::rparen, "expected ')' here"))
6571 return true;
6572
6573 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
6574 return false;
6575}
6576
6577/// parseDIExpression:
6578/// ::= !DIExpression(0, 7, -1)
6579bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
6580 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6581 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
6582 Lex.Lex();
6583
6584 return parseDIExpressionBody(Result, IsDistinct);
6585}
6586
6587/// ParseDIArgList:
6588/// ::= !DIArgList(i32 7, i64 %0)
6589bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
6590 assert(PFS && "Expected valid function state");
6591 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
6592 Lex.Lex();
6593
6594 if (parseToken(lltok::lparen, "expected '(' here"))
6595 return true;
6596
6598 if (Lex.getKind() != lltok::rparen)
6599 do {
6600 Metadata *MD;
6601 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
6602 return true;
6603 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
6604 } while (EatIfPresent(lltok::comma));
6605
6606 if (parseToken(lltok::rparen, "expected ')' here"))
6607 return true;
6608
6609 MD = DIArgList::get(Context, Args);
6610 return false;
6611}
6612
6613/// parseDIGlobalVariableExpression:
6614/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
6615bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6616 bool IsDistinct) {
6617#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6618 REQUIRED(var, MDField, ); \
6619 REQUIRED(expr, MDField, );
6621#undef VISIT_MD_FIELDS
6622
6623 Result =
6624 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6625 return false;
6626}
6627
6628/// parseDIObjCProperty:
6629/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6630/// getter: "getFoo", attributes: 7, type: !2)
6631bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6632#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6633 OPTIONAL(name, MDStringField, ); \
6634 OPTIONAL(file, MDField, ); \
6635 OPTIONAL(line, LineField, ); \
6636 OPTIONAL(setter, MDStringField, ); \
6637 OPTIONAL(getter, MDStringField, ); \
6638 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6639 OPTIONAL(type, MDField, );
6641#undef VISIT_MD_FIELDS
6642
6643 Result = GET_OR_DISTINCT(DIObjCProperty,
6644 (Context, name.Val, file.Val, line.Val, getter.Val,
6645 setter.Val, attributes.Val, type.Val));
6646 return false;
6647}
6648
6649/// parseDIImportedEntity:
6650/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6651/// line: 7, name: "foo", elements: !2)
6652bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6653#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6654 REQUIRED(tag, DwarfTagField, ); \
6655 REQUIRED(scope, MDField, ); \
6656 OPTIONAL(entity, MDField, ); \
6657 OPTIONAL(file, MDField, ); \
6658 OPTIONAL(line, LineField, ); \
6659 OPTIONAL(name, MDStringField, ); \
6660 OPTIONAL(elements, MDField, );
6662#undef VISIT_MD_FIELDS
6663
6664 Result = GET_OR_DISTINCT(DIImportedEntity,
6665 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6666 line.Val, name.Val, elements.Val));
6667 return false;
6668}
6669
6670#undef PARSE_MD_FIELD
6671#undef NOP_FIELD
6672#undef REQUIRE_FIELD
6673#undef DECLARE_FIELD
6674
6675/// parseMetadataAsValue
6676/// ::= metadata i32 %local
6677/// ::= metadata i32 @global
6678/// ::= metadata i32 7
6679/// ::= metadata !0
6680/// ::= metadata !{...}
6681/// ::= metadata !"string"
6682bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6683 // Note: the type 'metadata' has already been parsed.
6684 Metadata *MD;
6685 if (parseMetadata(MD, &PFS))
6686 return true;
6687
6688 V = MetadataAsValue::get(Context, MD);
6689 return false;
6690}
6691
6692/// parseValueAsMetadata
6693/// ::= i32 %local
6694/// ::= i32 @global
6695/// ::= i32 7
6696bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6697 PerFunctionState *PFS) {
6698 Type *Ty;
6699 LocTy Loc;
6700 if (parseType(Ty, TypeMsg, Loc))
6701 return true;
6702 if (Ty->isMetadataTy())
6703 return error(Loc, "invalid metadata-value-metadata roundtrip");
6704
6705 Value *V;
6706 if (parseValue(Ty, V, PFS))
6707 return true;
6708
6709 MD = ValueAsMetadata::get(V);
6710 return false;
6711}
6712
6713/// parseMetadata
6714/// ::= i32 %local
6715/// ::= i32 @global
6716/// ::= i32 7
6717/// ::= !42
6718/// ::= !{...}
6719/// ::= !"string"
6720/// ::= !DILocation(...)
6721bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6722 if (Lex.getKind() == lltok::MetadataVar) {
6723 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6724 // so parsing this requires a Function State.
6725 if (Lex.getStrVal() == "DIArgList") {
6726 Metadata *AL;
6727 if (parseDIArgList(AL, PFS))
6728 return true;
6729 MD = AL;
6730 return false;
6731 }
6732 MDNode *N;
6733 if (parseSpecializedMDNode(N)) {
6734 return true;
6735 }
6736 MD = N;
6737 return false;
6738 }
6739
6740 // ValueAsMetadata:
6741 // <type> <value>
6742 if (Lex.getKind() != lltok::exclaim)
6743 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6744
6745 // '!'.
6746 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6747 Lex.Lex();
6748
6749 // MDString:
6750 // ::= '!' STRINGCONSTANT
6751 if (Lex.getKind() == lltok::StringConstant) {
6752 MDString *S;
6753 if (parseMDString(S))
6754 return true;
6755 MD = S;
6756 return false;
6757 }
6758
6759 // MDNode:
6760 // !{ ... }
6761 // !7
6762 MDNode *N;
6763 if (parseMDNodeTail(N))
6764 return true;
6765 MD = N;
6766 return false;
6767}
6768
6769//===----------------------------------------------------------------------===//
6770// Function Parsing.
6771//===----------------------------------------------------------------------===//
6772
6773bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6774 PerFunctionState *PFS) {
6775 if (Ty->isFunctionTy())
6776 return error(ID.Loc, "functions are not values, refer to them as pointers");
6777
6778 switch (ID.Kind) {
6779 case ValID::t_LocalID:
6780 if (!PFS)
6781 return error(ID.Loc, "invalid use of function-local name");
6782 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6783 return V == nullptr;
6784 case ValID::t_LocalName:
6785 if (!PFS)
6786 return error(ID.Loc, "invalid use of function-local name");
6787 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6788 return V == nullptr;
6789 case ValID::t_InlineAsm: {
6790 if (!ID.FTy)
6791 return error(ID.Loc, "invalid type for inline asm constraint string");
6792 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6793 return error(ID.Loc, toString(std::move(Err)));
6794 V = InlineAsm::get(
6795 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6796 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6797 return false;
6798 }
6800 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6801 if (V && ID.NoCFI)
6803 return V == nullptr;
6804 case ValID::t_GlobalID:
6805 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6806 if (V && ID.NoCFI)
6808 return V == nullptr;
6809 case ValID::t_APSInt:
6810 if (!Ty->isIntegerTy() && !Ty->isByteTy())
6811 return error(ID.Loc, "integer/byte constant must have integer/byte type");
6812 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6813 Ty->isIntegerTy() ? V = ConstantInt::get(Context, ID.APSIntVal)
6814 : V = ConstantByte::get(Context, ID.APSIntVal);
6815 return false;
6816 case ValID::t_APFloat:
6817 if (!Ty->isFloatingPointTy() ||
6818 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6819 return error(ID.Loc, "floating point constant invalid for type");
6820
6821 // The lexer has no type info, so builds all half, bfloat, float, and double
6822 // FP constants as double. Fix this here. Long double does not need this.
6823 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6824 // Check for signaling before potentially converting and losing that info.
6825 bool IsSNAN = ID.APFloatVal.isSignaling();
6826 bool Ignored;
6827 if (Ty->isHalfTy())
6828 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
6829 &Ignored);
6830 else if (Ty->isBFloatTy())
6831 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6832 &Ignored);
6833 else if (Ty->isFloatTy())
6834 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
6835 &Ignored);
6836 if (IsSNAN) {
6837 // The convert call above may quiet an SNaN, so manufacture another
6838 // SNaN. The bitcast works because the payload (significand) parameter
6839 // is truncated to fit.
6840 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6841 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6842 ID.APFloatVal.isNegative(), &Payload);
6843 }
6844 }
6845 V = ConstantFP::get(Context, ID.APFloatVal);
6846
6847 if (V->getType() != Ty)
6848 return error(ID.Loc, "floating point constant does not have type '" +
6849 getTypeString(Ty) + "'");
6850
6851 return false;
6852 case ValID::t_Null:
6853 if (!Ty->isPointerTy())
6854 return error(ID.Loc, "null must be a pointer type");
6856 return false;
6857 case ValID::t_Undef:
6858 // FIXME: LabelTy should not be a first-class type.
6859 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6860 return error(ID.Loc, "invalid type for undef constant");
6861 V = UndefValue::get(Ty);
6862 return false;
6864 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6865 return error(ID.Loc, "invalid empty array initializer");
6866 V = PoisonValue::get(Ty);
6867 return false;
6868 case ValID::t_Zero:
6869 // FIXME: LabelTy should not be a first-class type.
6870 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6871 return error(ID.Loc, "invalid type for null constant");
6872 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6873 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6874 return error(ID.Loc, "invalid type for null constant");
6876 return false;
6877 case ValID::t_None:
6878 if (!Ty->isTokenTy())
6879 return error(ID.Loc, "invalid type for none constant");
6881 return false;
6882 case ValID::t_Poison:
6883 // FIXME: LabelTy should not be a first-class type.
6884 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6885 return error(ID.Loc, "invalid type for poison constant");
6886 V = PoisonValue::get(Ty);
6887 return false;
6888 case ValID::t_Constant:
6889 if (ID.ConstantVal->getType() != Ty)
6890 return error(ID.Loc, "constant expression type mismatch: got type '" +
6891 getTypeString(ID.ConstantVal->getType()) +
6892 "' but expected '" + getTypeString(Ty) + "'");
6893 V = ID.ConstantVal;
6894 return false;
6896 if (!Ty->isVectorTy())
6897 return error(ID.Loc, "vector constant must have vector type");
6898 if (ID.ConstantVal->getType() != Ty->getScalarType())
6899 return error(ID.Loc, "constant expression type mismatch: got type '" +
6900 getTypeString(ID.ConstantVal->getType()) +
6901 "' but expected '" +
6902 getTypeString(Ty->getScalarType()) + "'");
6903 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6904 ID.ConstantVal);
6905 return false;
6908 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6909 if (ST->getNumElements() != ID.UIntVal)
6910 return error(ID.Loc,
6911 "initializer with struct type has wrong # elements");
6912 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6913 return error(ID.Loc, "packed'ness of initializer and type don't match");
6914
6915 // Verify that the elements are compatible with the structtype.
6916 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6917 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6918 return error(
6919 ID.Loc,
6920 "element " + Twine(i) +
6921 " of struct initializer doesn't match struct element type");
6922
6924 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6925 } else
6926 return error(ID.Loc, "constant expression type mismatch");
6927 return false;
6928 }
6929 llvm_unreachable("Invalid ValID");
6930}
6931
6932bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6933 C = nullptr;
6934 ValID ID;
6935 auto Loc = Lex.getLoc();
6936 if (parseValID(ID, /*PFS=*/nullptr, /*ExpectedTy=*/Ty))
6937 return true;
6938 switch (ID.Kind) {
6939 case ValID::t_APSInt:
6940 case ValID::t_APFloat:
6941 case ValID::t_Undef:
6942 case ValID::t_Poison:
6943 case ValID::t_Zero:
6944 case ValID::t_Constant:
6948 Value *V;
6949 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6950 return true;
6951 assert(isa<Constant>(V) && "Expected a constant value");
6952 C = cast<Constant>(V);
6953 return false;
6954 }
6955 case ValID::t_Null:
6957 return false;
6958 default:
6959 return error(Loc, "expected a constant value");
6960 }
6961}
6962
6963bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6964 V = nullptr;
6965 ValID ID;
6966
6967 FileLoc Start = getTokLineColumnPos();
6968 bool Ret = parseValID(ID, PFS, Ty) || convertValIDToValue(Ty, ID, V, PFS);
6969 if (!Ret && ParserContext) {
6970 FileLoc End = getPrevTokEndLineColumnPos();
6971 ParserContext->addValueReferenceAtLocation(V, FileLocRange(Start, End));
6972 }
6973 return Ret;
6974}
6975
6976bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6977 Type *Ty = nullptr;
6978 return parseType(Ty) || parseValue(Ty, V, PFS);
6979}
6980
6981bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6982 PerFunctionState &PFS) {
6983 Value *V;
6984 Loc = Lex.getLoc();
6985 if (parseTypeAndValue(V, PFS))
6986 return true;
6987 if (!isa<BasicBlock>(V))
6988 return error(Loc, "expected a basic block");
6989 BB = cast<BasicBlock>(V);
6990 return false;
6991}
6992
6994 // Exit early for the common (non-debug-intrinsic) case.
6995 // We can make this the only check when we begin supporting all "llvm.dbg"
6996 // intrinsics in the new debug info format.
6997 if (!Name.starts_with("llvm.dbg."))
6998 return false;
7000 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
7001 FnID == Intrinsic::dbg_assign;
7002}
7003
7004/// FunctionHeader
7005/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
7006/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
7007/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
7008/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
7009bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
7010 unsigned &FunctionNumber,
7011 SmallVectorImpl<unsigned> &UnnamedArgNums) {
7012 // parse the linkage.
7013 LocTy LinkageLoc = Lex.getLoc();
7014 unsigned Linkage;
7015 unsigned Visibility;
7016 unsigned DLLStorageClass;
7017 bool DSOLocal;
7018 AttrBuilder RetAttrs(M->getContext());
7019 unsigned CC;
7020 bool HasLinkage;
7021 Type *RetType = nullptr;
7022 LocTy RetTypeLoc = Lex.getLoc();
7023 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
7024 DSOLocal) ||
7025 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7026 parseType(RetType, RetTypeLoc, true /*void allowed*/))
7027 return true;
7028
7029 // Verify that the linkage is ok.
7032 break; // always ok.
7034 if (IsDefine)
7035 return error(LinkageLoc, "invalid linkage for function definition");
7036 break;
7044 if (!IsDefine)
7045 return error(LinkageLoc, "invalid linkage for function declaration");
7046 break;
7049 return error(LinkageLoc, "invalid function linkage type");
7050 }
7051
7052 if (!isValidVisibilityForLinkage(Visibility, Linkage))
7053 return error(LinkageLoc,
7054 "symbol with local linkage must have default visibility");
7055
7056 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
7057 return error(LinkageLoc,
7058 "symbol with local linkage cannot have a DLL storage class");
7059
7060 if (!FunctionType::isValidReturnType(RetType))
7061 return error(RetTypeLoc, "invalid function return type");
7062
7063 LocTy NameLoc = Lex.getLoc();
7064
7065 std::string FunctionName;
7066 if (Lex.getKind() == lltok::GlobalVar) {
7067 FunctionName = Lex.getStrVal();
7068 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
7069 FunctionNumber = Lex.getUIntVal();
7070 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
7071 FunctionNumber))
7072 return true;
7073 } else {
7074 return tokError("expected function name");
7075 }
7076
7077 Lex.Lex();
7078
7079 if (Lex.getKind() != lltok::lparen)
7080 return tokError("expected '(' in function argument list");
7081
7083 bool IsVarArg;
7084 AttrBuilder FuncAttrs(M->getContext());
7085 std::vector<unsigned> FwdRefAttrGrps;
7086 LocTy BuiltinLoc;
7087 std::string Section;
7088 std::string Partition;
7089 MaybeAlign Alignment, PrefAlignment;
7090 std::string GC;
7092 unsigned AddrSpace = 0;
7093 Constant *Prefix = nullptr;
7094 Constant *Prologue = nullptr;
7095 Constant *PersonalityFn = nullptr;
7096 Comdat *C;
7097
7098 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
7099 parseOptionalUnnamedAddr(UnnamedAddr) ||
7100 parseOptionalProgramAddrSpace(AddrSpace) ||
7101 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
7102 BuiltinLoc) ||
7103 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
7104 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
7105 parseOptionalComdat(FunctionName, C) ||
7106 parseOptionalAlignment(Alignment) ||
7107 parseOptionalPrefAlignment(PrefAlignment) ||
7108 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
7109 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
7110 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
7111 (EatIfPresent(lltok::kw_personality) &&
7112 parseGlobalTypeAndValue(PersonalityFn)))
7113 return true;
7114
7115 if (FuncAttrs.contains(Attribute::Builtin))
7116 return error(BuiltinLoc, "'builtin' attribute not valid on function");
7117
7118 // If the alignment was parsed as an attribute, move to the alignment field.
7119 if (MaybeAlign A = FuncAttrs.getAlignment()) {
7120 Alignment = A;
7121 FuncAttrs.removeAttribute(Attribute::Alignment);
7122 }
7123
7124 // Okay, if we got here, the function is syntactically valid. Convert types
7125 // and do semantic checks.
7126 std::vector<Type*> ParamTypeList;
7128
7129 for (const ArgInfo &Arg : ArgList) {
7130 ParamTypeList.push_back(Arg.Ty);
7131 Attrs.push_back(Arg.Attrs);
7132 }
7133
7134 AttributeList PAL =
7135 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
7136 AttributeSet::get(Context, RetAttrs), Attrs);
7137
7138 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
7139 return error(RetTypeLoc, "functions with 'sret' argument must return void");
7140
7141 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
7142 PointerType *PFT = PointerType::get(Context, AddrSpace);
7143
7144 Fn = nullptr;
7145 GlobalValue *FwdFn = nullptr;
7146 if (!FunctionName.empty()) {
7147 // If this was a definition of a forward reference, remove the definition
7148 // from the forward reference table and fill in the forward ref.
7149 auto FRVI = ForwardRefVals.find(FunctionName);
7150 if (FRVI != ForwardRefVals.end()) {
7151 FwdFn = FRVI->second.first;
7152 if (FwdFn->getType() != PFT)
7153 return error(FRVI->second.second,
7154 "invalid forward reference to "
7155 "function '" +
7156 FunctionName +
7157 "' with wrong type: "
7158 "expected '" +
7159 getTypeString(PFT) + "' but was '" +
7160 getTypeString(FwdFn->getType()) + "'");
7161 ForwardRefVals.erase(FRVI);
7162 } else if ((Fn = M->getFunction(FunctionName))) {
7163 // Reject redefinitions.
7164 return error(NameLoc,
7165 "invalid redefinition of function '" + FunctionName + "'");
7166 } else if (M->getNamedValue(FunctionName)) {
7167 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
7168 }
7169
7170 } else {
7171 // Handle @"", where a name is syntactically specified, but semantically
7172 // missing.
7173 if (FunctionNumber == (unsigned)-1)
7174 FunctionNumber = NumberedVals.getNext();
7175
7176 // If this is a definition of a forward referenced function, make sure the
7177 // types agree.
7178 auto I = ForwardRefValIDs.find(FunctionNumber);
7179 if (I != ForwardRefValIDs.end()) {
7180 FwdFn = I->second.first;
7181 if (FwdFn->getType() != PFT)
7182 return error(NameLoc, "type of definition and forward reference of '@" +
7183 Twine(FunctionNumber) +
7184 "' disagree: "
7185 "expected '" +
7186 getTypeString(PFT) + "' but was '" +
7187 getTypeString(FwdFn->getType()) + "'");
7188 ForwardRefValIDs.erase(I);
7189 }
7190 }
7191
7193 FunctionName, M);
7194
7195 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
7196
7197 if (FunctionName.empty())
7198 NumberedVals.add(FunctionNumber, Fn);
7199
7201 maybeSetDSOLocal(DSOLocal, *Fn);
7204 Fn->setCallingConv(CC);
7205 Fn->setAttributes(PAL);
7206 Fn->setUnnamedAddr(UnnamedAddr);
7207 if (Alignment)
7208 Fn->setAlignment(*Alignment);
7209 Fn->setPreferredAlignment(PrefAlignment);
7210 Fn->setSection(Section);
7211 Fn->setPartition(Partition);
7212 Fn->setComdat(C);
7213 Fn->setPersonalityFn(PersonalityFn);
7214 if (!GC.empty()) Fn->setGC(GC);
7215 Fn->setPrefixData(Prefix);
7216 Fn->setPrologueData(Prologue);
7217 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
7218
7219 // Add all of the arguments we parsed to the function.
7220 Function::arg_iterator ArgIt = Fn->arg_begin();
7221 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
7222 if (ParserContext && ArgList[i].IdentLoc)
7223 ParserContext->addInstructionOrArgumentLocation(
7224 &*ArgIt, ArgList[i].IdentLoc.value());
7225 // If the argument has a name, insert it into the argument symbol table.
7226 if (ArgList[i].Name.empty()) continue;
7227
7228 // Set the name, if it conflicted, it will be auto-renamed.
7229 ArgIt->setName(ArgList[i].Name);
7230
7231 if (ArgIt->getName() != ArgList[i].Name)
7232 return error(ArgList[i].Loc,
7233 "redefinition of argument '%" + ArgList[i].Name + "'");
7234 }
7235
7236 if (FwdFn) {
7237 FwdFn->replaceAllUsesWith(Fn);
7238 FwdFn->eraseFromParent();
7239 }
7240
7241 if (IsDefine)
7242 return false;
7243
7244 // Check the declaration has no block address forward references.
7245 ValID ID;
7246 if (FunctionName.empty()) {
7247 ID.Kind = ValID::t_GlobalID;
7248 ID.UIntVal = FunctionNumber;
7249 } else {
7250 ID.Kind = ValID::t_GlobalName;
7251 ID.StrVal = FunctionName;
7252 }
7253 auto Blocks = ForwardRefBlockAddresses.find(ID);
7254 if (Blocks != ForwardRefBlockAddresses.end())
7255 return error(Blocks->first.Loc,
7256 "cannot take blockaddress inside a declaration");
7257 return false;
7258}
7259
7260bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
7261 ValID ID;
7262 if (FunctionNumber == -1) {
7263 ID.Kind = ValID::t_GlobalName;
7264 ID.StrVal = std::string(F.getName());
7265 } else {
7266 ID.Kind = ValID::t_GlobalID;
7267 ID.UIntVal = FunctionNumber;
7268 }
7269
7270 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
7271 if (Blocks == P.ForwardRefBlockAddresses.end())
7272 return false;
7273
7274 for (const auto &I : Blocks->second) {
7275 const ValID &BBID = I.first;
7276 GlobalValue *GV = I.second;
7277
7278 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
7279 "Expected local id or name");
7280 BasicBlock *BB;
7281 if (BBID.Kind == ValID::t_LocalName)
7282 BB = getBB(BBID.StrVal, BBID.Loc);
7283 else
7284 BB = getBB(BBID.UIntVal, BBID.Loc);
7285 if (!BB)
7286 return P.error(BBID.Loc, "referenced value is not a basic block");
7287
7288 Value *ResolvedVal = BlockAddress::get(&F, BB);
7289 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
7290 ResolvedVal);
7291 if (!ResolvedVal)
7292 return true;
7293 GV->replaceAllUsesWith(ResolvedVal);
7294 GV->eraseFromParent();
7295 }
7296
7297 P.ForwardRefBlockAddresses.erase(Blocks);
7298 return false;
7299}
7300
7301/// parseFunctionBody
7302/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
7303bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
7304 ArrayRef<unsigned> UnnamedArgNums) {
7305 if (Lex.getKind() != lltok::lbrace)
7306 return tokError("expected '{' in function body");
7307 Lex.Lex(); // eat the {.
7308
7309 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
7310
7311 // Resolve block addresses and allow basic blocks to be forward-declared
7312 // within this function.
7313 if (PFS.resolveForwardRefBlockAddresses())
7314 return true;
7315 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
7316
7317 // We need at least one basic block.
7318 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
7319 return tokError("function body requires at least one basic block");
7320
7321 while (Lex.getKind() != lltok::rbrace &&
7322 Lex.getKind() != lltok::kw_uselistorder)
7323 if (parseBasicBlock(PFS))
7324 return true;
7325
7326 while (Lex.getKind() != lltok::rbrace)
7327 if (parseUseListOrder(&PFS))
7328 return true;
7329
7330 // Eat the }.
7331 Lex.Lex();
7332
7333 // Verify function is ok.
7334 return PFS.finishFunction();
7335}
7336
7337/// parseBasicBlock
7338/// ::= (LabelStr|LabelID)? Instruction*
7339bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
7340 FileLoc BBStart = getTokLineColumnPos();
7341
7342 // If this basic block starts out with a name, remember it.
7343 std::string Name;
7344 int NameID = -1;
7345 LocTy NameLoc = Lex.getLoc();
7346 if (Lex.getKind() == lltok::LabelStr) {
7347 Name = Lex.getStrVal();
7348 Lex.Lex();
7349 } else if (Lex.getKind() == lltok::LabelID) {
7350 NameID = Lex.getUIntVal();
7351 Lex.Lex();
7352 }
7353
7354 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
7355 if (!BB)
7356 return true;
7357
7358 std::string NameStr;
7359
7360 // Parse the instructions and debug values in this block until we get a
7361 // terminator.
7362 Instruction *Inst;
7363 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
7364 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
7365 SmallVector<DbgRecordPtr> TrailingDbgRecord;
7366 do {
7367 // Handle debug records first - there should always be an instruction
7368 // following the debug records, i.e. they cannot appear after the block
7369 // terminator.
7370 while (Lex.getKind() == lltok::hash) {
7371 if (SeenOldDbgInfoFormat)
7372 return error(Lex.getLoc(), "debug record should not appear in a module "
7373 "containing debug info intrinsics");
7374 SeenNewDbgInfoFormat = true;
7375 Lex.Lex();
7376
7377 DbgRecord *DR;
7378 if (parseDebugRecord(DR, PFS))
7379 return true;
7380 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
7381 }
7382
7383 FileLoc InstStart = getTokLineColumnPos();
7384 // This instruction may have three possibilities for a name: a) none
7385 // specified, b) name specified "%foo =", c) number specified: "%4 =".
7386 LocTy NameLoc = Lex.getLoc();
7387 int NameID = -1;
7388 NameStr = "";
7389
7390 if (Lex.getKind() == lltok::LocalVarID) {
7391 NameID = Lex.getUIntVal();
7392 Lex.Lex();
7393 if (parseToken(lltok::equal, "expected '=' after instruction id"))
7394 return true;
7395 } else if (Lex.getKind() == lltok::LocalVar) {
7396 NameStr = Lex.getStrVal();
7397 Lex.Lex();
7398 if (parseToken(lltok::equal, "expected '=' after instruction name"))
7399 return true;
7400 }
7401
7402 switch (parseInstruction(Inst, BB, PFS)) {
7403 default:
7404 llvm_unreachable("Unknown parseInstruction result!");
7405 case InstError: return true;
7406 case InstNormal:
7407 Inst->insertInto(BB, BB->end());
7408
7409 // With a normal result, we check to see if the instruction is followed by
7410 // a comma and metadata.
7411 if (EatIfPresent(lltok::comma))
7412 if (parseInstructionMetadata(*Inst))
7413 return true;
7414 break;
7415 case InstExtraComma:
7416 Inst->insertInto(BB, BB->end());
7417
7418 // If the instruction parser ate an extra comma at the end of it, it
7419 // *must* be followed by metadata.
7420 if (parseInstructionMetadata(*Inst))
7421 return true;
7422 break;
7423 }
7424
7425 // Set the name on the instruction.
7426 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
7427 return true;
7428
7429 // Attach any preceding debug values to this instruction.
7430 for (DbgRecordPtr &DR : TrailingDbgRecord)
7431 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
7432 TrailingDbgRecord.clear();
7433 if (ParserContext) {
7434 ParserContext->addInstructionOrArgumentLocation(
7435 Inst, FileLocRange(InstStart, getPrevTokEndLineColumnPos()));
7436 }
7437 } while (!Inst->isTerminator());
7438
7439 if (ParserContext)
7440 ParserContext->addBlockLocation(
7441 BB, FileLocRange(BBStart, getPrevTokEndLineColumnPos()));
7442
7443 assert(TrailingDbgRecord.empty() &&
7444 "All debug values should have been attached to an instruction.");
7445
7446 return false;
7447}
7448
7449/// parseDebugRecord
7450/// ::= #dbg_label '(' MDNode ')'
7451/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
7452/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
7453bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
7454 using RecordKind = DbgRecord::Kind;
7455 using LocType = DbgVariableRecord::LocationType;
7456 LocTy DVRLoc = Lex.getLoc();
7457 if (Lex.getKind() != lltok::DbgRecordType)
7458 return error(DVRLoc, "expected debug record type here");
7459 RecordKind RecordType = StringSwitch<RecordKind>(Lex.getStrVal())
7460 .Case("declare", RecordKind::ValueKind)
7461 .Case("value", RecordKind::ValueKind)
7462 .Case("assign", RecordKind::ValueKind)
7463 .Case("label", RecordKind::LabelKind)
7464 .Case("declare_value", RecordKind::ValueKind);
7465
7466 // Parsing labels is trivial; parse here and early exit, otherwise go into the
7467 // full DbgVariableRecord processing stage.
7468 if (RecordType == RecordKind::LabelKind) {
7469 Lex.Lex();
7470 if (parseToken(lltok::lparen, "Expected '(' here"))
7471 return true;
7472 MDNode *Label;
7473 if (parseMDNode(Label))
7474 return true;
7475 if (parseToken(lltok::comma, "Expected ',' here"))
7476 return true;
7477 MDNode *DbgLoc;
7478 if (parseMDNode(DbgLoc))
7479 return true;
7480 if (parseToken(lltok::rparen, "Expected ')' here"))
7481 return true;
7483 return false;
7484 }
7485
7486 LocType ValueType = StringSwitch<LocType>(Lex.getStrVal())
7487 .Case("declare", LocType::Declare)
7488 .Case("value", LocType::Value)
7489 .Case("assign", LocType::Assign)
7490 .Case("declare_value", LocType::DeclareValue);
7491
7492 Lex.Lex();
7493 if (parseToken(lltok::lparen, "Expected '(' here"))
7494 return true;
7495
7496 // Parse Value field.
7497 Metadata *ValLocMD;
7498 if (parseMetadata(ValLocMD, &PFS))
7499 return true;
7500 if (parseToken(lltok::comma, "Expected ',' here"))
7501 return true;
7502
7503 // Parse Variable field.
7504 MDNode *Variable;
7505 if (parseMDNode(Variable))
7506 return true;
7507 if (parseToken(lltok::comma, "Expected ',' here"))
7508 return true;
7509
7510 // Parse Expression field.
7511 MDNode *Expression;
7512 if (parseMDNode(Expression))
7513 return true;
7514 if (parseToken(lltok::comma, "Expected ',' here"))
7515 return true;
7516
7517 // Parse additional fields for #dbg_assign.
7518 MDNode *AssignID = nullptr;
7519 Metadata *AddressLocation = nullptr;
7520 MDNode *AddressExpression = nullptr;
7521 if (ValueType == LocType::Assign) {
7522 // Parse DIAssignID.
7523 if (parseMDNode(AssignID))
7524 return true;
7525 if (parseToken(lltok::comma, "Expected ',' here"))
7526 return true;
7527
7528 // Parse address ValueAsMetadata.
7529 if (parseMetadata(AddressLocation, &PFS))
7530 return true;
7531 if (parseToken(lltok::comma, "Expected ',' here"))
7532 return true;
7533
7534 // Parse address DIExpression.
7535 if (parseMDNode(AddressExpression))
7536 return true;
7537 if (parseToken(lltok::comma, "Expected ',' here"))
7538 return true;
7539 }
7540
7541 /// Parse DILocation.
7542 MDNode *DebugLoc;
7543 if (parseMDNode(DebugLoc))
7544 return true;
7545
7546 if (parseToken(lltok::rparen, "Expected ')' here"))
7547 return true;
7549 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
7550 AddressExpression, DebugLoc);
7551 return false;
7552}
7553//===----------------------------------------------------------------------===//
7554// Instruction Parsing.
7555//===----------------------------------------------------------------------===//
7556
7557/// parseInstruction - parse one of the many different instructions.
7558///
7559int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
7560 PerFunctionState &PFS) {
7561 lltok::Kind Token = Lex.getKind();
7562 if (Token == lltok::Eof)
7563 return tokError("found end of file when expecting more instructions");
7564 LocTy Loc = Lex.getLoc();
7565 unsigned KeywordVal = Lex.getUIntVal();
7566 Lex.Lex(); // Eat the keyword.
7567
7568 switch (Token) {
7569 default:
7570 return error(Loc, "expected instruction opcode");
7571 // Terminator Instructions.
7572 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
7573 case lltok::kw_ret:
7574 return parseRet(Inst, BB, PFS);
7575 case lltok::kw_br:
7576 return parseBr(Inst, PFS);
7577 case lltok::kw_switch:
7578 return parseSwitch(Inst, PFS);
7580 return parseIndirectBr(Inst, PFS);
7581 case lltok::kw_invoke:
7582 return parseInvoke(Inst, PFS);
7583 case lltok::kw_resume:
7584 return parseResume(Inst, PFS);
7586 return parseCleanupRet(Inst, PFS);
7587 case lltok::kw_catchret:
7588 return parseCatchRet(Inst, PFS);
7590 return parseCatchSwitch(Inst, PFS);
7591 case lltok::kw_catchpad:
7592 return parseCatchPad(Inst, PFS);
7594 return parseCleanupPad(Inst, PFS);
7595 case lltok::kw_callbr:
7596 return parseCallBr(Inst, PFS);
7597 // Unary Operators.
7598 case lltok::kw_fneg: {
7599 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7600 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
7601 if (Res != 0)
7602 return Res;
7603 if (FMF.any())
7604 Inst->setFastMathFlags(FMF);
7605 return false;
7606 }
7607 // Binary Operators.
7608 case lltok::kw_add:
7609 case lltok::kw_sub:
7610 case lltok::kw_mul:
7611 case lltok::kw_shl: {
7612 bool NUW = EatIfPresent(lltok::kw_nuw);
7613 bool NSW = EatIfPresent(lltok::kw_nsw);
7614 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
7615
7616 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7617 return true;
7618
7619 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
7620 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
7621 return false;
7622 }
7623 case lltok::kw_fadd:
7624 case lltok::kw_fsub:
7625 case lltok::kw_fmul:
7626 case lltok::kw_fdiv:
7627 case lltok::kw_frem: {
7628 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7629 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
7630 if (Res != 0)
7631 return Res;
7632 if (FMF.any())
7633 Inst->setFastMathFlags(FMF);
7634 return 0;
7635 }
7636
7637 case lltok::kw_sdiv:
7638 case lltok::kw_udiv:
7639 case lltok::kw_lshr:
7640 case lltok::kw_ashr: {
7641 bool Exact = EatIfPresent(lltok::kw_exact);
7642
7643 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7644 return true;
7645 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7646 return false;
7647 }
7648
7649 case lltok::kw_urem:
7650 case lltok::kw_srem:
7651 return parseArithmetic(Inst, PFS, KeywordVal,
7652 /*IsFP*/ false);
7653 case lltok::kw_or: {
7654 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7655 if (parseLogical(Inst, PFS, KeywordVal))
7656 return true;
7657 if (Disjoint)
7658 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7659 return false;
7660 }
7661 case lltok::kw_and:
7662 case lltok::kw_xor:
7663 return parseLogical(Inst, PFS, KeywordVal);
7664 case lltok::kw_icmp: {
7665 bool SameSign = EatIfPresent(lltok::kw_samesign);
7666 if (parseCompare(Inst, PFS, KeywordVal))
7667 return true;
7668 if (SameSign)
7669 cast<ICmpInst>(Inst)->setSameSign();
7670 return false;
7671 }
7672 case lltok::kw_fcmp: {
7673 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7674 int Res = parseCompare(Inst, PFS, KeywordVal);
7675 if (Res != 0)
7676 return Res;
7677 if (FMF.any())
7678 Inst->setFastMathFlags(FMF);
7679 return 0;
7680 }
7681
7682 // Casts.
7683 case lltok::kw_uitofp:
7684 case lltok::kw_zext: {
7685 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7686 bool Res = parseCast(Inst, PFS, KeywordVal);
7687 if (Res != 0)
7688 return Res;
7689 if (NonNeg)
7690 Inst->setNonNeg();
7691 return 0;
7692 }
7693 case lltok::kw_trunc: {
7694 bool NUW = EatIfPresent(lltok::kw_nuw);
7695 bool NSW = EatIfPresent(lltok::kw_nsw);
7696 if (!NUW)
7697 NUW = EatIfPresent(lltok::kw_nuw);
7698 if (parseCast(Inst, PFS, KeywordVal))
7699 return true;
7700 if (NUW)
7701 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7702 if (NSW)
7703 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7704 return false;
7705 }
7706 case lltok::kw_sext:
7707 case lltok::kw_bitcast:
7709 case lltok::kw_sitofp:
7710 case lltok::kw_fptoui:
7711 case lltok::kw_fptosi:
7712 case lltok::kw_inttoptr:
7714 case lltok::kw_ptrtoint:
7715 return parseCast(Inst, PFS, KeywordVal);
7716 case lltok::kw_fptrunc:
7717 case lltok::kw_fpext: {
7718 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7719 if (parseCast(Inst, PFS, KeywordVal))
7720 return true;
7721 if (FMF.any())
7722 Inst->setFastMathFlags(FMF);
7723 return false;
7724 }
7725
7726 // Other.
7727 case lltok::kw_select: {
7728 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7729 int Res = parseSelect(Inst, PFS);
7730 if (Res != 0)
7731 return Res;
7732 if (FMF.any()) {
7733 if (!isa<FPMathOperator>(Inst))
7734 return error(Loc, "fast-math-flags specified for select without "
7735 "floating-point scalar or vector return type");
7736 Inst->setFastMathFlags(FMF);
7737 }
7738 return 0;
7739 }
7740 case lltok::kw_va_arg:
7741 return parseVAArg(Inst, PFS);
7743 return parseExtractElement(Inst, PFS);
7745 return parseInsertElement(Inst, PFS);
7747 return parseShuffleVector(Inst, PFS);
7748 case lltok::kw_phi: {
7749 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7750 int Res = parsePHI(Inst, PFS);
7751 if (Res != 0)
7752 return Res;
7753 if (FMF.any()) {
7754 if (!isa<FPMathOperator>(Inst))
7755 return error(Loc, "fast-math-flags specified for phi without "
7756 "floating-point scalar or vector return type");
7757 Inst->setFastMathFlags(FMF);
7758 }
7759 return 0;
7760 }
7762 return parseLandingPad(Inst, PFS);
7763 case lltok::kw_freeze:
7764 return parseFreeze(Inst, PFS);
7765 // Call.
7766 case lltok::kw_call:
7767 return parseCall(Inst, PFS, CallInst::TCK_None);
7768 case lltok::kw_tail:
7769 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7770 case lltok::kw_musttail:
7771 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7772 case lltok::kw_notail:
7773 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7774 // Memory.
7775 case lltok::kw_alloca:
7776 return parseAlloc(Inst, PFS);
7777 case lltok::kw_load:
7778 return parseLoad(Inst, PFS);
7779 case lltok::kw_store:
7780 return parseStore(Inst, PFS);
7781 case lltok::kw_cmpxchg:
7782 return parseCmpXchg(Inst, PFS);
7784 return parseAtomicRMW(Inst, PFS);
7785 case lltok::kw_fence:
7786 return parseFence(Inst, PFS);
7788 return parseGetElementPtr(Inst, PFS);
7790 return parseExtractValue(Inst, PFS);
7792 return parseInsertValue(Inst, PFS);
7793 }
7794}
7795
7796/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7797bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7798 if (Opc == Instruction::FCmp) {
7799 switch (Lex.getKind()) {
7800 default:
7801 return tokError("expected fcmp predicate (e.g. 'oeq')");
7802 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7803 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7804 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7805 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7806 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7807 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7808 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7809 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7810 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7811 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7812 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7813 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7814 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7815 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7816 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7817 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7818 }
7819 } else {
7820 switch (Lex.getKind()) {
7821 default:
7822 return tokError("expected icmp predicate (e.g. 'eq')");
7823 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7824 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7825 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7826 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7827 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7828 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7829 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7830 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7831 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7832 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7833 }
7834 }
7835 Lex.Lex();
7836 return false;
7837}
7838
7839//===----------------------------------------------------------------------===//
7840// Terminator Instructions.
7841//===----------------------------------------------------------------------===//
7842
7843/// parseRet - parse a return instruction.
7844/// ::= 'ret' void (',' !dbg, !1)*
7845/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7846bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7847 PerFunctionState &PFS) {
7848 SMLoc TypeLoc = Lex.getLoc();
7849 Type *Ty = nullptr;
7850 if (parseType(Ty, true /*void allowed*/))
7851 return true;
7852
7853 Type *ResType = PFS.getFunction().getReturnType();
7854
7855 if (Ty->isVoidTy()) {
7856 if (!ResType->isVoidTy())
7857 return error(TypeLoc, "value doesn't match function result type '" +
7858 getTypeString(ResType) + "'");
7859
7860 Inst = ReturnInst::Create(Context);
7861 return false;
7862 }
7863
7864 Value *RV;
7865 if (parseValue(Ty, RV, PFS))
7866 return true;
7867
7868 if (ResType != RV->getType())
7869 return error(TypeLoc, "value doesn't match function result type '" +
7870 getTypeString(ResType) + "'");
7871
7872 Inst = ReturnInst::Create(Context, RV);
7873 return false;
7874}
7875
7876/// parseBr
7877/// ::= 'br' TypeAndValue
7878/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7879bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7880 LocTy Loc, Loc2;
7881 Value *Op0;
7882 BasicBlock *Op1, *Op2;
7883 if (parseTypeAndValue(Op0, Loc, PFS))
7884 return true;
7885
7886 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7887 Inst = UncondBrInst::Create(BB);
7888 return false;
7889 }
7890
7891 if (Op0->getType() != Type::getInt1Ty(Context))
7892 return error(Loc, "branch condition must have 'i1' type");
7893
7894 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7895 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7896 parseToken(lltok::comma, "expected ',' after true destination") ||
7897 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7898 return true;
7899
7900 Inst = CondBrInst::Create(Op0, Op1, Op2);
7901 return false;
7902}
7903
7904/// parseSwitch
7905/// Instruction
7906/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7907/// JumpTable
7908/// ::= (TypeAndValue ',' TypeAndValue)*
7909bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7910 LocTy CondLoc, BBLoc;
7911 Value *Cond;
7912 BasicBlock *DefaultBB;
7913 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7914 parseToken(lltok::comma, "expected ',' after switch condition") ||
7915 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7916 parseToken(lltok::lsquare, "expected '[' with switch table"))
7917 return true;
7918
7919 if (!Cond->getType()->isIntegerTy())
7920 return error(CondLoc, "switch condition must have integer type");
7921
7922 // parse the jump table pairs.
7923 SmallPtrSet<Value*, 32> SeenCases;
7925 while (Lex.getKind() != lltok::rsquare) {
7926 Value *Constant;
7927 BasicBlock *DestBB;
7928
7929 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7930 parseToken(lltok::comma, "expected ',' after case value") ||
7931 parseTypeAndBasicBlock(DestBB, PFS))
7932 return true;
7933
7934 if (!SeenCases.insert(Constant).second)
7935 return error(CondLoc, "duplicate case value in switch");
7936 if (!isa<ConstantInt>(Constant))
7937 return error(CondLoc, "case value is not a constant integer");
7938
7939 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7940 }
7941
7942 Lex.Lex(); // Eat the ']'.
7943
7944 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7945 for (const auto &[OnVal, Dest] : Table)
7946 SI->addCase(OnVal, Dest);
7947 Inst = SI;
7948 return false;
7949}
7950
7951/// parseIndirectBr
7952/// Instruction
7953/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7954bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7955 LocTy AddrLoc;
7956 Value *Address;
7957 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7958 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7959 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7960 return true;
7961
7962 if (!Address->getType()->isPointerTy())
7963 return error(AddrLoc, "indirectbr address must have pointer type");
7964
7965 // parse the destination list.
7966 SmallVector<BasicBlock*, 16> DestList;
7967
7968 if (Lex.getKind() != lltok::rsquare) {
7969 BasicBlock *DestBB;
7970 if (parseTypeAndBasicBlock(DestBB, PFS))
7971 return true;
7972 DestList.push_back(DestBB);
7973
7974 while (EatIfPresent(lltok::comma)) {
7975 if (parseTypeAndBasicBlock(DestBB, PFS))
7976 return true;
7977 DestList.push_back(DestBB);
7978 }
7979 }
7980
7981 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7982 return true;
7983
7984 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
7985 for (BasicBlock *Dest : DestList)
7986 IBI->addDestination(Dest);
7987 Inst = IBI;
7988 return false;
7989}
7990
7991// If RetType is a non-function pointer type, then this is the short syntax
7992// for the call, which means that RetType is just the return type. Infer the
7993// rest of the function argument types from the arguments that are present.
7994bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7995 FunctionType *&FuncTy) {
7996 FuncTy = dyn_cast<FunctionType>(RetType);
7997 if (!FuncTy) {
7998 // Pull out the types of all of the arguments...
7999 SmallVector<Type *, 8> ParamTypes;
8000 ParamTypes.reserve(ArgList.size());
8001 for (const ParamInfo &Arg : ArgList)
8002 ParamTypes.push_back(Arg.V->getType());
8003
8004 if (!FunctionType::isValidReturnType(RetType))
8005 return true;
8006
8007 FuncTy = FunctionType::get(RetType, ParamTypes, false);
8008 }
8009 return false;
8010}
8011
8012/// parseInvoke
8013/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
8014/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
8015bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
8016 LocTy CallLoc = Lex.getLoc();
8017 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8018 std::vector<unsigned> FwdRefAttrGrps;
8019 LocTy NoBuiltinLoc;
8020 unsigned CC;
8021 unsigned InvokeAddrSpace;
8022 Type *RetType = nullptr;
8023 LocTy RetTypeLoc;
8024 ValID CalleeID;
8027
8028 BasicBlock *NormalBB, *UnwindBB;
8029 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8030 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
8031 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8032 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8033 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8034 NoBuiltinLoc) ||
8035 parseOptionalOperandBundles(BundleList, PFS) ||
8036 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
8037 parseTypeAndBasicBlock(NormalBB, PFS) ||
8038 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
8039 parseTypeAndBasicBlock(UnwindBB, PFS))
8040 return true;
8041
8042 // If RetType is a non-function pointer type, then this is the short syntax
8043 // for the call, which means that RetType is just the return type. Infer the
8044 // rest of the function argument types from the arguments that are present.
8045 FunctionType *Ty;
8046 if (resolveFunctionType(RetType, ArgList, Ty))
8047 return error(RetTypeLoc, "Invalid result type for LLVM function");
8048
8049 CalleeID.FTy = Ty;
8050
8051 // Look up the callee.
8052 Value *Callee;
8053 if (convertValIDToValue(PointerType::get(Context, InvokeAddrSpace), CalleeID,
8054 Callee, &PFS))
8055 return true;
8056
8057 // Set up the Attribute for the function.
8058 SmallVector<Value *, 8> Args;
8060
8061 // Loop through FunctionType's arguments and ensure they are specified
8062 // correctly. Also, gather any parameter attributes.
8063 FunctionType::param_iterator I = Ty->param_begin();
8064 FunctionType::param_iterator E = Ty->param_end();
8065 for (const ParamInfo &Arg : ArgList) {
8066 Type *ExpectedTy = nullptr;
8067 if (I != E) {
8068 ExpectedTy = *I++;
8069 } else if (!Ty->isVarArg()) {
8070 return error(Arg.Loc, "too many arguments specified");
8071 }
8072
8073 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8074 return error(Arg.Loc, "argument is not of expected type '" +
8075 getTypeString(ExpectedTy) + "'");
8076 Args.push_back(Arg.V);
8077 ArgAttrs.push_back(Arg.Attrs);
8078 }
8079
8080 if (I != E)
8081 return error(CallLoc, "not enough parameters specified for call");
8082
8083 // Finish off the Attribute and check them
8084 AttributeList PAL =
8085 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8086 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8087
8088 InvokeInst *II =
8089 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
8090 II->setCallingConv(CC);
8091 II->setAttributes(PAL);
8092 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
8093 Inst = II;
8094 return false;
8095}
8096
8097/// parseResume
8098/// ::= 'resume' TypeAndValue
8099bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
8100 Value *Exn; LocTy ExnLoc;
8101 if (parseTypeAndValue(Exn, ExnLoc, PFS))
8102 return true;
8103
8104 ResumeInst *RI = ResumeInst::Create(Exn);
8105 Inst = RI;
8106 return false;
8107}
8108
8109bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
8110 PerFunctionState &PFS) {
8111 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
8112 return true;
8113
8114 while (Lex.getKind() != lltok::rsquare) {
8115 // If this isn't the first argument, we need a comma.
8116 if (!Args.empty() &&
8117 parseToken(lltok::comma, "expected ',' in argument list"))
8118 return true;
8119
8120 // parse the argument.
8121 LocTy ArgLoc;
8122 Type *ArgTy = nullptr;
8123 if (parseType(ArgTy, ArgLoc))
8124 return true;
8125
8126 Value *V;
8127 if (ArgTy->isMetadataTy()) {
8128 if (parseMetadataAsValue(V, PFS))
8129 return true;
8130 } else {
8131 if (parseValue(ArgTy, V, PFS))
8132 return true;
8133 }
8134 Args.push_back(V);
8135 }
8136
8137 Lex.Lex(); // Lex the ']'.
8138 return false;
8139}
8140
8141/// parseCleanupRet
8142/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
8143bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
8144 Value *CleanupPad = nullptr;
8145
8146 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
8147 return true;
8148
8149 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
8150 return true;
8151
8152 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
8153 return true;
8154
8155 BasicBlock *UnwindBB = nullptr;
8156 if (Lex.getKind() == lltok::kw_to) {
8157 Lex.Lex();
8158 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
8159 return true;
8160 } else {
8161 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
8162 return true;
8163 }
8164 }
8165
8166 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
8167 return false;
8168}
8169
8170/// parseCatchRet
8171/// ::= 'catchret' from Parent Value 'to' TypeAndValue
8172bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
8173 Value *CatchPad = nullptr;
8174
8175 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
8176 return true;
8177
8178 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
8179 return true;
8180
8181 BasicBlock *BB;
8182 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
8183 parseTypeAndBasicBlock(BB, PFS))
8184 return true;
8185
8186 Inst = CatchReturnInst::Create(CatchPad, BB);
8187 return false;
8188}
8189
8190/// parseCatchSwitch
8191/// ::= 'catchswitch' within Parent
8192bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
8193 Value *ParentPad;
8194
8195 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
8196 return true;
8197
8198 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8199 Lex.getKind() != lltok::LocalVarID)
8200 return tokError("expected scope value for catchswitch");
8201
8202 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8203 return true;
8204
8205 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
8206 return true;
8207
8209 do {
8210 BasicBlock *DestBB;
8211 if (parseTypeAndBasicBlock(DestBB, PFS))
8212 return true;
8213 Table.push_back(DestBB);
8214 } while (EatIfPresent(lltok::comma));
8215
8216 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
8217 return true;
8218
8219 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
8220 return true;
8221
8222 BasicBlock *UnwindBB = nullptr;
8223 if (EatIfPresent(lltok::kw_to)) {
8224 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
8225 return true;
8226 } else {
8227 if (parseTypeAndBasicBlock(UnwindBB, PFS))
8228 return true;
8229 }
8230
8231 auto *CatchSwitch =
8232 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
8233 for (BasicBlock *DestBB : Table)
8234 CatchSwitch->addHandler(DestBB);
8235 Inst = CatchSwitch;
8236 return false;
8237}
8238
8239/// parseCatchPad
8240/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
8241bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
8242 Value *CatchSwitch = nullptr;
8243
8244 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
8245 return true;
8246
8247 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
8248 return tokError("expected scope value for catchpad");
8249
8250 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
8251 return true;
8252
8253 SmallVector<Value *, 8> Args;
8254 if (parseExceptionArgs(Args, PFS))
8255 return true;
8256
8257 Inst = CatchPadInst::Create(CatchSwitch, Args);
8258 return false;
8259}
8260
8261/// parseCleanupPad
8262/// ::= 'cleanuppad' within Parent ParamList
8263bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
8264 Value *ParentPad = nullptr;
8265
8266 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
8267 return true;
8268
8269 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
8270 Lex.getKind() != lltok::LocalVarID)
8271 return tokError("expected scope value for cleanuppad");
8272
8273 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
8274 return true;
8275
8276 SmallVector<Value *, 8> Args;
8277 if (parseExceptionArgs(Args, PFS))
8278 return true;
8279
8280 Inst = CleanupPadInst::Create(ParentPad, Args);
8281 return false;
8282}
8283
8284//===----------------------------------------------------------------------===//
8285// Unary Operators.
8286//===----------------------------------------------------------------------===//
8287
8288/// parseUnaryOp
8289/// ::= UnaryOp TypeAndValue ',' Value
8290///
8291/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8292/// operand is allowed.
8293bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
8294 unsigned Opc, bool IsFP) {
8295 LocTy Loc; Value *LHS;
8296 if (parseTypeAndValue(LHS, Loc, PFS))
8297 return true;
8298
8299 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8301
8302 if (!Valid)
8303 return error(Loc, "invalid operand type for instruction");
8304
8306 return false;
8307}
8308
8309/// parseCallBr
8310/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
8311/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
8312/// '[' LabelList ']'
8313bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
8314 LocTy CallLoc = Lex.getLoc();
8315 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8316 std::vector<unsigned> FwdRefAttrGrps;
8317 LocTy NoBuiltinLoc;
8318 unsigned CC;
8319 Type *RetType = nullptr;
8320 LocTy RetTypeLoc;
8321 ValID CalleeID;
8324
8325 BasicBlock *DefaultDest;
8326 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8327 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8328 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
8329 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
8330 NoBuiltinLoc) ||
8331 parseOptionalOperandBundles(BundleList, PFS) ||
8332 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
8333 parseTypeAndBasicBlock(DefaultDest, PFS) ||
8334 parseToken(lltok::lsquare, "expected '[' in callbr"))
8335 return true;
8336
8337 // parse the destination list.
8338 SmallVector<BasicBlock *, 16> IndirectDests;
8339
8340 if (Lex.getKind() != lltok::rsquare) {
8341 BasicBlock *DestBB;
8342 if (parseTypeAndBasicBlock(DestBB, PFS))
8343 return true;
8344 IndirectDests.push_back(DestBB);
8345
8346 while (EatIfPresent(lltok::comma)) {
8347 if (parseTypeAndBasicBlock(DestBB, PFS))
8348 return true;
8349 IndirectDests.push_back(DestBB);
8350 }
8351 }
8352
8353 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
8354 return true;
8355
8356 // If RetType is a non-function pointer type, then this is the short syntax
8357 // for the call, which means that RetType is just the return type. Infer the
8358 // rest of the function argument types from the arguments that are present.
8359 FunctionType *Ty;
8360 if (resolveFunctionType(RetType, ArgList, Ty))
8361 return error(RetTypeLoc, "Invalid result type for LLVM function");
8362
8363 CalleeID.FTy = Ty;
8364
8365 // Look up the callee.
8366 Value *Callee;
8367 if (convertValIDToValue(PointerType::getUnqual(Context), CalleeID, Callee,
8368 &PFS))
8369 return true;
8370
8371 // Set up the Attribute for the function.
8372 SmallVector<Value *, 8> Args;
8374
8375 // Loop through FunctionType's arguments and ensure they are specified
8376 // correctly. Also, gather any parameter attributes.
8377 FunctionType::param_iterator I = Ty->param_begin();
8378 FunctionType::param_iterator E = Ty->param_end();
8379 for (const ParamInfo &Arg : ArgList) {
8380 Type *ExpectedTy = nullptr;
8381 if (I != E) {
8382 ExpectedTy = *I++;
8383 } else if (!Ty->isVarArg()) {
8384 return error(Arg.Loc, "too many arguments specified");
8385 }
8386
8387 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8388 return error(Arg.Loc, "argument is not of expected type '" +
8389 getTypeString(ExpectedTy) + "'");
8390 Args.push_back(Arg.V);
8391 ArgAttrs.push_back(Arg.Attrs);
8392 }
8393
8394 if (I != E)
8395 return error(CallLoc, "not enough parameters specified for call");
8396
8397 // Finish off the Attribute and check them
8398 AttributeList PAL =
8399 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8400 AttributeSet::get(Context, RetAttrs), ArgAttrs);
8401
8402 CallBrInst *CBI =
8403 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
8404 BundleList);
8405 CBI->setCallingConv(CC);
8406 CBI->setAttributes(PAL);
8407 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
8408 Inst = CBI;
8409 return false;
8410}
8411
8412//===----------------------------------------------------------------------===//
8413// Binary Operators.
8414//===----------------------------------------------------------------------===//
8415
8416/// parseArithmetic
8417/// ::= ArithmeticOps TypeAndValue ',' Value
8418///
8419/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
8420/// operand is allowed.
8421bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
8422 unsigned Opc, bool IsFP) {
8423 LocTy Loc; Value *LHS, *RHS;
8424 if (parseTypeAndValue(LHS, Loc, PFS) ||
8425 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
8426 parseValue(LHS->getType(), RHS, PFS))
8427 return true;
8428
8429 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
8431
8432 if (!Valid)
8433 return error(Loc, "invalid operand type for instruction");
8434
8436 return false;
8437}
8438
8439/// parseLogical
8440/// ::= ArithmeticOps TypeAndValue ',' Value {
8441bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
8442 unsigned Opc) {
8443 LocTy Loc; Value *LHS, *RHS;
8444 if (parseTypeAndValue(LHS, Loc, PFS) ||
8445 parseToken(lltok::comma, "expected ',' in logical operation") ||
8446 parseValue(LHS->getType(), RHS, PFS))
8447 return true;
8448
8449 if (!LHS->getType()->isIntOrIntVectorTy())
8450 return error(Loc,
8451 "instruction requires integer or integer vector operands");
8452
8454 return false;
8455}
8456
8457/// parseCompare
8458/// ::= 'icmp' IPredicates TypeAndValue ',' Value
8459/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
8460bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
8461 unsigned Opc) {
8462 // parse the integer/fp comparison predicate.
8463 LocTy Loc;
8464 unsigned Pred;
8465 Value *LHS, *RHS;
8466 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
8467 parseToken(lltok::comma, "expected ',' after compare value") ||
8468 parseValue(LHS->getType(), RHS, PFS))
8469 return true;
8470
8471 if (Opc == Instruction::FCmp) {
8472 if (!LHS->getType()->isFPOrFPVectorTy())
8473 return error(Loc, "fcmp requires floating point operands");
8474 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8475 } else {
8476 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
8477 if (!LHS->getType()->isIntOrIntVectorTy() &&
8479 return error(Loc, "icmp requires integer operands");
8480 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
8481 }
8482 return false;
8483}
8484
8485//===----------------------------------------------------------------------===//
8486// Other Instructions.
8487//===----------------------------------------------------------------------===//
8488
8489/// parseCast
8490/// ::= CastOpc TypeAndValue 'to' Type
8491bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
8492 unsigned Opc) {
8493 LocTy Loc;
8494 Value *Op;
8495 Type *DestTy = nullptr;
8496 if (parseTypeAndValue(Op, Loc, PFS) ||
8497 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
8498 parseType(DestTy))
8499 return true;
8500
8502 return error(Loc, "invalid cast opcode for cast from '" +
8503 getTypeString(Op->getType()) + "' to '" +
8504 getTypeString(DestTy) + "'");
8505 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
8506 return false;
8507}
8508
8509/// parseSelect
8510/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8511bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
8512 LocTy Loc;
8513 Value *Op0, *Op1, *Op2;
8514 if (parseTypeAndValue(Op0, Loc, PFS) ||
8515 parseToken(lltok::comma, "expected ',' after select condition") ||
8516 parseTypeAndValue(Op1, PFS) ||
8517 parseToken(lltok::comma, "expected ',' after select value") ||
8518 parseTypeAndValue(Op2, PFS))
8519 return true;
8520
8521 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
8522 return error(Loc, Reason);
8523
8524 Inst = SelectInst::Create(Op0, Op1, Op2);
8525 return false;
8526}
8527
8528/// parseVAArg
8529/// ::= 'va_arg' TypeAndValue ',' Type
8530bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
8531 Value *Op;
8532 Type *EltTy = nullptr;
8533 LocTy TypeLoc;
8534 if (parseTypeAndValue(Op, PFS) ||
8535 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
8536 parseType(EltTy, TypeLoc))
8537 return true;
8538
8539 if (!EltTy->isFirstClassType())
8540 return error(TypeLoc, "va_arg requires operand with first class type");
8541
8542 Inst = new VAArgInst(Op, EltTy);
8543 return false;
8544}
8545
8546/// parseExtractElement
8547/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
8548bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
8549 LocTy Loc;
8550 Value *Op0, *Op1;
8551 if (parseTypeAndValue(Op0, Loc, PFS) ||
8552 parseToken(lltok::comma, "expected ',' after extract value") ||
8553 parseTypeAndValue(Op1, PFS))
8554 return true;
8555
8557 return error(Loc, "invalid extractelement operands");
8558
8559 Inst = ExtractElementInst::Create(Op0, Op1);
8560 return false;
8561}
8562
8563/// parseInsertElement
8564/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8565bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
8566 LocTy Loc;
8567 Value *Op0, *Op1, *Op2;
8568 if (parseTypeAndValue(Op0, Loc, PFS) ||
8569 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8570 parseTypeAndValue(Op1, PFS) ||
8571 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8572 parseTypeAndValue(Op2, PFS))
8573 return true;
8574
8575 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
8576 return error(Loc, "invalid insertelement operands");
8577
8578 Inst = InsertElementInst::Create(Op0, Op1, Op2);
8579 return false;
8580}
8581
8582/// parseShuffleVector
8583/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
8584bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
8585 LocTy Loc;
8586 Value *Op0, *Op1, *Op2;
8587 if (parseTypeAndValue(Op0, Loc, PFS) ||
8588 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
8589 parseTypeAndValue(Op1, PFS) ||
8590 parseToken(lltok::comma, "expected ',' after shuffle value") ||
8591 parseTypeAndValue(Op2, PFS))
8592 return true;
8593
8594 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
8595 return error(Loc, "invalid shufflevector operands");
8596
8597 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
8598 return false;
8599}
8600
8601/// parsePHI
8602/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
8603int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
8604 Type *Ty = nullptr; LocTy TypeLoc;
8605 Value *Op0, *Op1;
8606
8607 if (parseType(Ty, TypeLoc))
8608 return true;
8609
8610 if (!Ty->isFirstClassType())
8611 return error(TypeLoc, "phi node must have first class type");
8612
8613 bool First = true;
8614 bool AteExtraComma = false;
8616
8617 while (true) {
8618 if (First) {
8619 if (Lex.getKind() != lltok::lsquare)
8620 break;
8621 First = false;
8622 } else if (!EatIfPresent(lltok::comma))
8623 break;
8624
8625 if (Lex.getKind() == lltok::MetadataVar) {
8626 AteExtraComma = true;
8627 break;
8628 }
8629
8630 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
8631 parseValue(Ty, Op0, PFS) ||
8632 parseToken(lltok::comma, "expected ',' after insertelement value") ||
8633 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
8634 parseToken(lltok::rsquare, "expected ']' in phi value list"))
8635 return true;
8636
8637 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
8638 }
8639
8640 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8641 for (const auto &[Val, BB] : PHIVals)
8642 PN->addIncoming(Val, BB);
8643 Inst = PN;
8644 return AteExtraComma ? InstExtraComma : InstNormal;
8645}
8646
8647/// parseLandingPad
8648/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8649/// Clause
8650/// ::= 'catch' TypeAndValue
8651/// ::= 'filter'
8652/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8653bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8654 Type *Ty = nullptr; LocTy TyLoc;
8655
8656 if (parseType(Ty, TyLoc))
8657 return true;
8658
8659 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8660 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8661
8662 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8664 if (EatIfPresent(lltok::kw_catch))
8666 else if (EatIfPresent(lltok::kw_filter))
8668 else
8669 return tokError("expected 'catch' or 'filter' clause type");
8670
8671 Value *V;
8672 LocTy VLoc;
8673 if (parseTypeAndValue(V, VLoc, PFS))
8674 return true;
8675
8676 // A 'catch' type expects a non-array constant. A filter clause expects an
8677 // array constant.
8678 if (CT == LandingPadInst::Catch) {
8679 if (isa<ArrayType>(V->getType()))
8680 return error(VLoc, "'catch' clause has an invalid type");
8681 } else {
8682 if (!isa<ArrayType>(V->getType()))
8683 return error(VLoc, "'filter' clause has an invalid type");
8684 }
8685
8687 if (!CV)
8688 return error(VLoc, "clause argument must be a constant");
8689 LP->addClause(CV);
8690 }
8691
8692 Inst = LP.release();
8693 return false;
8694}
8695
8696/// parseFreeze
8697/// ::= 'freeze' Type Value
8698bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8699 LocTy Loc;
8700 Value *Op;
8701 if (parseTypeAndValue(Op, Loc, PFS))
8702 return true;
8703
8704 Inst = new FreezeInst(Op);
8705 return false;
8706}
8707
8708/// parseCall
8709/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8710/// OptionalAttrs Type Value ParameterList OptionalAttrs
8711/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8712/// OptionalAttrs Type Value ParameterList OptionalAttrs
8713/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8714/// OptionalAttrs Type Value ParameterList OptionalAttrs
8715/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8716/// OptionalAttrs Type Value ParameterList OptionalAttrs
8717bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8719 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8720 std::vector<unsigned> FwdRefAttrGrps;
8721 LocTy BuiltinLoc;
8722 unsigned CallAddrSpace;
8723 unsigned CC;
8724 Type *RetType = nullptr;
8725 LocTy RetTypeLoc;
8726 ValID CalleeID;
8729 LocTy CallLoc = Lex.getLoc();
8730
8731 if (TCK != CallInst::TCK_None &&
8732 parseToken(lltok::kw_call,
8733 "expected 'tail call', 'musttail call', or 'notail call'"))
8734 return true;
8735
8736 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8737
8738 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8739 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8740 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8741 parseValID(CalleeID, &PFS) ||
8742 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8743 PFS.getFunction().isVarArg()) ||
8744 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8745 parseOptionalOperandBundles(BundleList, PFS))
8746 return true;
8747
8748 // If RetType is a non-function pointer type, then this is the short syntax
8749 // for the call, which means that RetType is just the return type. Infer the
8750 // rest of the function argument types from the arguments that are present.
8751 FunctionType *Ty;
8752 if (resolveFunctionType(RetType, ArgList, Ty))
8753 return error(RetTypeLoc, "Invalid result type for LLVM function");
8754
8755 CalleeID.FTy = Ty;
8756
8757 // Look up the callee.
8758 Value *Callee;
8759 if (convertValIDToValue(PointerType::get(Context, CallAddrSpace), CalleeID,
8760 Callee, &PFS))
8761 return true;
8762
8763 // Set up the Attribute for the function.
8765
8766 SmallVector<Value*, 8> Args;
8767
8768 // Loop through FunctionType's arguments and ensure they are specified
8769 // correctly. Also, gather any parameter attributes.
8770 FunctionType::param_iterator I = Ty->param_begin();
8771 FunctionType::param_iterator E = Ty->param_end();
8772 for (const ParamInfo &Arg : ArgList) {
8773 Type *ExpectedTy = nullptr;
8774 if (I != E) {
8775 ExpectedTy = *I++;
8776 } else if (!Ty->isVarArg()) {
8777 return error(Arg.Loc, "too many arguments specified");
8778 }
8779
8780 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8781 return error(Arg.Loc, "argument is not of expected type '" +
8782 getTypeString(ExpectedTy) + "'");
8783 Args.push_back(Arg.V);
8784 Attrs.push_back(Arg.Attrs);
8785 }
8786
8787 if (I != E)
8788 return error(CallLoc, "not enough parameters specified for call");
8789
8790 // Finish off the Attribute and check them
8791 AttributeList PAL =
8792 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8793 AttributeSet::get(Context, RetAttrs), Attrs);
8794
8795 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8796 CI->setTailCallKind(TCK);
8797 CI->setCallingConv(CC);
8798 if (FMF.any()) {
8799 if (!isa<FPMathOperator>(CI)) {
8800 CI->deleteValue();
8801 return error(CallLoc, "fast-math-flags specified for call without "
8802 "floating-point scalar or vector return type");
8803 }
8804 CI->setFastMathFlags(FMF);
8805 }
8806
8807 if (CalleeID.Kind == ValID::t_GlobalName &&
8808 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8809 if (SeenNewDbgInfoFormat) {
8810 CI->deleteValue();
8811 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8812 "using non-intrinsic debug info");
8813 }
8814 SeenOldDbgInfoFormat = true;
8815 }
8816 CI->setAttributes(PAL);
8817 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8818 Inst = CI;
8819 return false;
8820}
8821
8822//===----------------------------------------------------------------------===//
8823// Memory Instructions.
8824//===----------------------------------------------------------------------===//
8825
8826/// parseAlloc
8827/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8828/// (',' 'align' i32)? (',', 'addrspace(n))?
8829int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8830 Value *Size = nullptr;
8831 LocTy SizeLoc, TyLoc, ASLoc;
8832 MaybeAlign Alignment;
8833 unsigned AddrSpace = 0;
8834 Type *Ty = nullptr;
8835
8836 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8837 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8838
8839 if (parseType(Ty, TyLoc))
8840 return true;
8841
8843 return error(TyLoc, "invalid type for alloca");
8844
8845 bool AteExtraComma = false;
8846 if (EatIfPresent(lltok::comma)) {
8847 if (Lex.getKind() == lltok::kw_align) {
8848 if (parseOptionalAlignment(Alignment))
8849 return true;
8850 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8851 return true;
8852 } else if (Lex.getKind() == lltok::kw_addrspace) {
8853 ASLoc = Lex.getLoc();
8854 if (parseOptionalAddrSpace(AddrSpace))
8855 return true;
8856 } else if (Lex.getKind() == lltok::MetadataVar) {
8857 AteExtraComma = true;
8858 } else {
8859 if (parseTypeAndValue(Size, SizeLoc, PFS))
8860 return true;
8861 if (EatIfPresent(lltok::comma)) {
8862 if (Lex.getKind() == lltok::kw_align) {
8863 if (parseOptionalAlignment(Alignment))
8864 return true;
8865 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8866 return true;
8867 } else if (Lex.getKind() == lltok::kw_addrspace) {
8868 ASLoc = Lex.getLoc();
8869 if (parseOptionalAddrSpace(AddrSpace))
8870 return true;
8871 } else if (Lex.getKind() == lltok::MetadataVar) {
8872 AteExtraComma = true;
8873 }
8874 }
8875 }
8876 }
8877
8878 if (Size && !Size->getType()->isIntegerTy())
8879 return error(SizeLoc, "element count must have integer type");
8880
8881 SmallPtrSet<Type *, 4> Visited;
8882 if (!Alignment && !Ty->isSized(&Visited))
8883 return error(TyLoc, "Cannot allocate unsized type");
8884 if (!Alignment)
8885 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8886 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8887 AI->setUsedWithInAlloca(IsInAlloca);
8888 AI->setSwiftError(IsSwiftError);
8889 Inst = AI;
8890 return AteExtraComma ? InstExtraComma : InstNormal;
8891}
8892
8893/// parseLoad
8894/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8895/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8896/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8897int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8898 Value *Val; LocTy Loc;
8899 MaybeAlign Alignment;
8900 bool AteExtraComma = false;
8901 bool isAtomic = false;
8904
8905 if (Lex.getKind() == lltok::kw_atomic) {
8906 isAtomic = true;
8907 Lex.Lex();
8908 }
8909
8910 bool isVolatile = false;
8911 if (Lex.getKind() == lltok::kw_volatile) {
8912 isVolatile = true;
8913 Lex.Lex();
8914 }
8915
8916 Type *Ty;
8917 LocTy ExplicitTypeLoc = Lex.getLoc();
8918 if (parseType(Ty) ||
8919 parseToken(lltok::comma, "expected comma after load's type") ||
8920 parseTypeAndValue(Val, Loc, PFS) ||
8921 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8922 parseOptionalCommaAlign(Alignment, AteExtraComma))
8923 return true;
8924
8925 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8926 return error(Loc, "load operand must be a pointer to a first class type");
8927 if (isAtomic && !Alignment)
8928 return error(Loc, "atomic load must have explicit non-zero alignment");
8929 if (Ordering == AtomicOrdering::Release ||
8931 return error(Loc, "atomic load cannot use Release ordering");
8932
8933 SmallPtrSet<Type *, 4> Visited;
8934 if (!Alignment && !Ty->isSized(&Visited))
8935 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8936 if (!Alignment)
8937 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8938 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8939 return AteExtraComma ? InstExtraComma : InstNormal;
8940}
8941
8942/// parseStore
8943
8944/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8945/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8946/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8947int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8948 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8949 MaybeAlign Alignment;
8950 bool AteExtraComma = false;
8951 bool isAtomic = false;
8954
8955 if (Lex.getKind() == lltok::kw_atomic) {
8956 isAtomic = true;
8957 Lex.Lex();
8958 }
8959
8960 bool isVolatile = false;
8961 if (Lex.getKind() == lltok::kw_volatile) {
8962 isVolatile = true;
8963 Lex.Lex();
8964 }
8965
8966 if (parseTypeAndValue(Val, Loc, PFS) ||
8967 parseToken(lltok::comma, "expected ',' after store operand") ||
8968 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8969 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8970 parseOptionalCommaAlign(Alignment, AteExtraComma))
8971 return true;
8972
8973 if (!Ptr->getType()->isPointerTy())
8974 return error(PtrLoc, "store operand must be a pointer");
8975 if (!Val->getType()->isFirstClassType())
8976 return error(Loc, "store operand must be a first class value");
8977 if (isAtomic && !Alignment)
8978 return error(Loc, "atomic store must have explicit non-zero alignment");
8979 if (Ordering == AtomicOrdering::Acquire ||
8981 return error(Loc, "atomic store cannot use Acquire ordering");
8982 SmallPtrSet<Type *, 4> Visited;
8983 if (!Alignment && !Val->getType()->isSized(&Visited))
8984 return error(Loc, "storing unsized types is not allowed");
8985 if (!Alignment)
8986 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8987
8988 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8989 return AteExtraComma ? InstExtraComma : InstNormal;
8990}
8991
8992/// parseCmpXchg
8993/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8994/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8995/// 'Align'?
8996int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8997 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8998 bool AteExtraComma = false;
8999 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
9000 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
9002 bool isVolatile = false;
9003 bool isWeak = false;
9004 MaybeAlign Alignment;
9005
9006 if (EatIfPresent(lltok::kw_weak))
9007 isWeak = true;
9008
9009 if (EatIfPresent(lltok::kw_volatile))
9010 isVolatile = true;
9011
9012 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9013 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
9014 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
9015 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
9016 parseTypeAndValue(New, NewLoc, PFS) ||
9017 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
9018 parseOrdering(FailureOrdering) ||
9019 parseOptionalCommaAlign(Alignment, AteExtraComma))
9020 return true;
9021
9022 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
9023 return tokError("invalid cmpxchg success ordering");
9024 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
9025 return tokError("invalid cmpxchg failure ordering");
9026 if (!Ptr->getType()->isPointerTy())
9027 return error(PtrLoc, "cmpxchg operand must be a pointer");
9028 if (Cmp->getType() != New->getType())
9029 return error(NewLoc, "compare value and new value type do not match");
9030 if (!New->getType()->isFirstClassType())
9031 return error(NewLoc, "cmpxchg operand must be a first class value");
9032
9033 const Align DefaultAlignment(
9034 PFS.getFunction().getDataLayout().getTypeStoreSize(
9035 Cmp->getType()));
9036
9037 AtomicCmpXchgInst *CXI =
9038 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
9039 SuccessOrdering, FailureOrdering, SSID);
9040 CXI->setVolatile(isVolatile);
9041 CXI->setWeak(isWeak);
9042
9043 Inst = CXI;
9044 return AteExtraComma ? InstExtraComma : InstNormal;
9045}
9046
9047/// parseAtomicRMW
9048/// ::= 'atomicrmw' 'volatile'? 'elementwise'? BinOp TypeAndValue ','
9049/// TypeAndValue
9050/// 'singlethread'? AtomicOrdering
9051int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
9052 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
9053 bool AteExtraComma = false;
9056 bool IsVolatile = false;
9057 bool IsElementwise = false;
9058 bool IsFP = false;
9060 MaybeAlign Alignment;
9061
9062 if (EatIfPresent(lltok::kw_volatile))
9063 IsVolatile = true;
9064 if (EatIfPresent(lltok::kw_elementwise))
9065 IsElementwise = true;
9066
9067 switch (Lex.getKind()) {
9068 default:
9069 return tokError("expected binary operation in atomicrmw");
9083 break;
9086 break;
9089 break;
9090 case lltok::kw_usub_sat:
9092 break;
9093 case lltok::kw_fadd:
9095 IsFP = true;
9096 break;
9097 case lltok::kw_fsub:
9099 IsFP = true;
9100 break;
9101 case lltok::kw_fmax:
9103 IsFP = true;
9104 break;
9105 case lltok::kw_fmin:
9107 IsFP = true;
9108 break;
9109 case lltok::kw_fmaximum:
9111 IsFP = true;
9112 break;
9113 case lltok::kw_fminimum:
9115 IsFP = true;
9116 break;
9119 IsFP = true;
9120 break;
9123 IsFP = true;
9124 break;
9125 }
9126 Lex.Lex(); // Eat the operation.
9127
9128 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
9129 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
9130 parseTypeAndValue(Val, ValLoc, PFS) ||
9131 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
9132 parseOptionalCommaAlign(Alignment, AteExtraComma))
9133 return true;
9134
9135 if (Ordering == AtomicOrdering::Unordered)
9136 return tokError("atomicrmw cannot be unordered");
9137 if (!Ptr->getType()->isPointerTy())
9138 return error(PtrLoc, "atomicrmw operand must be a pointer");
9139 if (Val->getType()->isScalableTy())
9140 return error(ValLoc, "atomicrmw operand may not be scalable");
9141
9142 // For elementwise ops, the value must be a fixed vector type whose element
9143 // type is legal for the corresponding scalar atomicrmw operation. So assign
9144 // ScalarTy the element type for elementwise ops so we can check this.
9145 Type *ScalarTy = Val->getType();
9146 if (IsElementwise) {
9147 auto *VecTy = dyn_cast<FixedVectorType>(Val->getType());
9148 if (!VecTy)
9149 return error(ValLoc,
9150 "atomicrmw elementwise operand must be a fixed vector type");
9151 ScalarTy = VecTy->getElementType();
9152 }
9153
9155 if (!ScalarTy->isIntegerTy() && !ScalarTy->isFloatingPointTy() &&
9156 !ScalarTy->isPointerTy()) {
9157 return error(
9158 ValLoc,
9160 " operand must be an integer, floating point, or pointer type");
9161 }
9162 } else if (IsFP) {
9163 if (!ScalarTy->isFPOrFPVectorTy()) {
9164 return error(ValLoc, "atomicrmw " +
9166 " operand must be a floating point type");
9167 }
9168 } else {
9169 if (!ScalarTy->isIntegerTy()) {
9170 return error(ValLoc, "atomicrmw " +
9172 " operand must be an integer");
9173 }
9174 }
9175
9176 unsigned Size =
9177 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(Val->getType());
9178 if (Size < 8 || (Size & (Size - 1)))
9179 return error(ValLoc,
9180 "atomicrmw operand must have a power-of-two byte size");
9181 const Align DefaultAlignment(
9182 PFS.getFunction().getDataLayout().getTypeStoreSize(Val->getType()));
9183 AtomicRMWInst *RMWI = new AtomicRMWInst(Operation, Ptr, Val,
9184 Alignment.value_or(DefaultAlignment),
9185 Ordering, SSID, IsElementwise);
9186 RMWI->setVolatile(IsVolatile);
9187 Inst = RMWI;
9188 return AteExtraComma ? InstExtraComma : InstNormal;
9189}
9190
9191/// parseFence
9192/// ::= 'fence' 'singlethread'? AtomicOrdering
9193int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
9196 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
9197 return true;
9198
9199 if (Ordering == AtomicOrdering::Unordered)
9200 return tokError("fence cannot be unordered");
9201 if (Ordering == AtomicOrdering::Monotonic)
9202 return tokError("fence cannot be monotonic");
9203
9204 Inst = new FenceInst(Context, Ordering, SSID);
9205 return InstNormal;
9206}
9207
9208/// parseGetElementPtr
9209/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
9210int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
9211 Value *Ptr = nullptr;
9212 Value *Val = nullptr;
9213 LocTy Loc, EltLoc;
9214 GEPNoWrapFlags NW;
9215
9216 while (true) {
9217 if (EatIfPresent(lltok::kw_inbounds))
9219 else if (EatIfPresent(lltok::kw_nusw))
9221 else if (EatIfPresent(lltok::kw_nuw))
9223 else
9224 break;
9225 }
9226
9227 Type *Ty = nullptr;
9228 if (parseType(Ty) ||
9229 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
9230 parseTypeAndValue(Ptr, Loc, PFS))
9231 return true;
9232
9233 Type *BaseType = Ptr->getType();
9234 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
9235 if (!BasePointerType)
9236 return error(Loc, "base of getelementptr must be a pointer");
9237
9238 SmallVector<Value*, 16> Indices;
9239 bool AteExtraComma = false;
9240 // GEP returns a vector of pointers if at least one of parameters is a vector.
9241 // All vector parameters should have the same vector width.
9242 ElementCount GEPWidth = BaseType->isVectorTy()
9243 ? cast<VectorType>(BaseType)->getElementCount()
9245
9246 while (EatIfPresent(lltok::comma)) {
9247 if (Lex.getKind() == lltok::MetadataVar) {
9248 AteExtraComma = true;
9249 break;
9250 }
9251 if (parseTypeAndValue(Val, EltLoc, PFS))
9252 return true;
9253 if (!Val->getType()->isIntOrIntVectorTy())
9254 return error(EltLoc, "getelementptr index must be an integer");
9255
9256 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
9257 ElementCount ValNumEl = ValVTy->getElementCount();
9258 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
9259 return error(
9260 EltLoc,
9261 "getelementptr vector index has a wrong number of elements");
9262 GEPWidth = ValNumEl;
9263 }
9264 Indices.push_back(Val);
9265 }
9266
9267 SmallPtrSet<Type*, 4> Visited;
9268 if (!Indices.empty() && !Ty->isSized(&Visited))
9269 return error(Loc, "base element of getelementptr must be sized");
9270
9271 auto *STy = dyn_cast<StructType>(Ty);
9272 if (STy && STy->isScalableTy())
9273 return error(Loc, "getelementptr cannot target structure that contains "
9274 "scalable vector type");
9275
9276 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
9277 return error(Loc, "invalid getelementptr indices");
9278 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ty, Ptr, Indices);
9279 Inst = GEP;
9280 GEP->setNoWrapFlags(NW);
9281 return AteExtraComma ? InstExtraComma : InstNormal;
9282}
9283
9284/// parseExtractValue
9285/// ::= 'extractvalue' TypeAndValue (',' uint32)+
9286int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
9287 Value *Val; LocTy Loc;
9288 SmallVector<unsigned, 4> Indices;
9289 bool AteExtraComma;
9290 if (parseTypeAndValue(Val, Loc, PFS) ||
9291 parseIndexList(Indices, AteExtraComma))
9292 return true;
9293
9294 if (!Val->getType()->isAggregateType())
9295 return error(Loc, "extractvalue operand must be aggregate type");
9296
9297 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
9298 return error(Loc, "invalid indices for extractvalue");
9299 Inst = ExtractValueInst::Create(Val, Indices);
9300 return AteExtraComma ? InstExtraComma : InstNormal;
9301}
9302
9303/// parseInsertValue
9304/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
9305int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
9306 Value *Val0, *Val1; LocTy Loc0, Loc1;
9307 SmallVector<unsigned, 4> Indices;
9308 bool AteExtraComma;
9309 if (parseTypeAndValue(Val0, Loc0, PFS) ||
9310 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
9311 parseTypeAndValue(Val1, Loc1, PFS) ||
9312 parseIndexList(Indices, AteExtraComma))
9313 return true;
9314
9315 if (!Val0->getType()->isAggregateType())
9316 return error(Loc0, "insertvalue operand must be aggregate type");
9317
9318 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
9319 if (!IndexedType)
9320 return error(Loc0, "invalid indices for insertvalue");
9321 if (IndexedType != Val1->getType())
9322 return error(Loc1, "insertvalue operand and field disagree in type: '" +
9323 getTypeString(Val1->getType()) + "' instead of '" +
9324 getTypeString(IndexedType) + "'");
9325 Inst = InsertValueInst::Create(Val0, Val1, Indices);
9326 return AteExtraComma ? InstExtraComma : InstNormal;
9327}
9328
9329//===----------------------------------------------------------------------===//
9330// Embedded metadata.
9331//===----------------------------------------------------------------------===//
9332
9333/// parseMDNodeVector
9334/// ::= { Element (',' Element)* }
9335/// Element
9336/// ::= 'null' | Metadata
9337bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
9338 if (parseToken(lltok::lbrace, "expected '{' here"))
9339 return true;
9340
9341 // Check for an empty list.
9342 if (EatIfPresent(lltok::rbrace))
9343 return false;
9344
9345 do {
9346 if (EatIfPresent(lltok::kw_null)) {
9347 Elts.push_back(nullptr);
9348 continue;
9349 }
9350
9351 Metadata *MD;
9352 if (parseMetadata(MD, nullptr))
9353 return true;
9354 Elts.push_back(MD);
9355 } while (EatIfPresent(lltok::comma));
9356
9357 return parseToken(lltok::rbrace, "expected end of metadata node");
9358}
9359
9360//===----------------------------------------------------------------------===//
9361// Use-list order directives.
9362//===----------------------------------------------------------------------===//
9363bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
9364 SMLoc Loc) {
9365 if (!V->hasUseList())
9366 return false;
9367 if (V->use_empty())
9368 return error(Loc, "value has no uses");
9369
9370 unsigned NumUses = 0;
9371 SmallDenseMap<const Use *, unsigned, 16> Order;
9372 for (const Use &U : V->uses()) {
9373 if (++NumUses > Indexes.size())
9374 break;
9375 Order[&U] = Indexes[NumUses - 1];
9376 }
9377 if (NumUses < 2)
9378 return error(Loc, "value only has one use");
9379 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
9380 return error(Loc,
9381 "wrong number of indexes, expected " + Twine(V->getNumUses()));
9382
9383 V->sortUseList([&](const Use &L, const Use &R) {
9384 return Order.lookup(&L) < Order.lookup(&R);
9385 });
9386 return false;
9387}
9388
9389/// parseUseListOrderIndexes
9390/// ::= '{' uint32 (',' uint32)+ '}'
9391bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
9392 SMLoc Loc = Lex.getLoc();
9393 if (parseToken(lltok::lbrace, "expected '{' here"))
9394 return true;
9395 if (Lex.getKind() == lltok::rbrace)
9396 return tokError("expected non-empty list of uselistorder indexes");
9397
9398 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
9399 // indexes should be distinct numbers in the range [0, size-1], and should
9400 // not be in order.
9401 unsigned Offset = 0;
9402 unsigned Max = 0;
9403 bool IsOrdered = true;
9404 assert(Indexes.empty() && "Expected empty order vector");
9405 do {
9406 unsigned Index;
9407 if (parseUInt32(Index))
9408 return true;
9409
9410 // Update consistency checks.
9411 Offset += Index - Indexes.size();
9412 Max = std::max(Max, Index);
9413 IsOrdered &= Index == Indexes.size();
9414
9415 Indexes.push_back(Index);
9416 } while (EatIfPresent(lltok::comma));
9417
9418 if (parseToken(lltok::rbrace, "expected '}' here"))
9419 return true;
9420
9421 if (Indexes.size() < 2)
9422 return error(Loc, "expected >= 2 uselistorder indexes");
9423 if (Offset != 0 || Max >= Indexes.size())
9424 return error(Loc,
9425 "expected distinct uselistorder indexes in range [0, size)");
9426 if (IsOrdered)
9427 return error(Loc, "expected uselistorder indexes to change the order");
9428
9429 return false;
9430}
9431
9432/// parseUseListOrder
9433/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
9434bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
9435 SMLoc Loc = Lex.getLoc();
9436 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
9437 return true;
9438
9439 Value *V;
9440 SmallVector<unsigned, 16> Indexes;
9441 if (parseTypeAndValue(V, PFS) ||
9442 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
9443 parseUseListOrderIndexes(Indexes))
9444 return true;
9445
9446 return sortUseListOrder(V, Indexes, Loc);
9447}
9448
9449/// parseUseListOrderBB
9450/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
9451bool LLParser::parseUseListOrderBB() {
9452 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
9453 SMLoc Loc = Lex.getLoc();
9454 Lex.Lex();
9455
9456 ValID Fn, Label;
9457 SmallVector<unsigned, 16> Indexes;
9458 if (parseValID(Fn, /*PFS=*/nullptr) ||
9459 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9460 parseValID(Label, /*PFS=*/nullptr) ||
9461 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
9462 parseUseListOrderIndexes(Indexes))
9463 return true;
9464
9465 // Check the function.
9466 GlobalValue *GV;
9467 if (Fn.Kind == ValID::t_GlobalName)
9468 GV = M->getNamedValue(Fn.StrVal);
9469 else if (Fn.Kind == ValID::t_GlobalID)
9470 GV = NumberedVals.get(Fn.UIntVal);
9471 else
9472 return error(Fn.Loc, "expected function name in uselistorder_bb");
9473 if (!GV)
9474 return error(Fn.Loc,
9475 "invalid function forward reference in uselistorder_bb");
9476 auto *F = dyn_cast<Function>(GV);
9477 if (!F)
9478 return error(Fn.Loc, "expected function name in uselistorder_bb");
9479 if (F->isDeclaration())
9480 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
9481
9482 // Check the basic block.
9483 if (Label.Kind == ValID::t_LocalID)
9484 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
9485 if (Label.Kind != ValID::t_LocalName)
9486 return error(Label.Loc, "expected basic block name in uselistorder_bb");
9487 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
9488 if (!V)
9489 return error(Label.Loc, "invalid basic block in uselistorder_bb");
9490 if (!isa<BasicBlock>(V))
9491 return error(Label.Loc, "expected basic block in uselistorder_bb");
9492
9493 return sortUseListOrder(V, Indexes, Loc);
9494}
9495
9496/// ModuleEntry
9497/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
9498/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
9499bool LLParser::parseModuleEntry(unsigned ID) {
9500 assert(Lex.getKind() == lltok::kw_module);
9501 Lex.Lex();
9502
9503 std::string Path;
9504 if (parseToken(lltok::colon, "expected ':' here") ||
9505 parseToken(lltok::lparen, "expected '(' here") ||
9506 parseToken(lltok::kw_path, "expected 'path' here") ||
9507 parseToken(lltok::colon, "expected ':' here") ||
9508 parseStringConstant(Path) ||
9509 parseToken(lltok::comma, "expected ',' here") ||
9510 parseToken(lltok::kw_hash, "expected 'hash' here") ||
9511 parseToken(lltok::colon, "expected ':' here") ||
9512 parseToken(lltok::lparen, "expected '(' here"))
9513 return true;
9514
9515 ModuleHash Hash;
9516 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
9517 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
9518 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
9519 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
9520 parseUInt32(Hash[4]))
9521 return true;
9522
9523 if (parseToken(lltok::rparen, "expected ')' here") ||
9524 parseToken(lltok::rparen, "expected ')' here"))
9525 return true;
9526
9527 auto ModuleEntry = Index->addModule(Path, Hash);
9528 ModuleIdMap[ID] = ModuleEntry->first();
9529
9530 return false;
9531}
9532
9533/// TypeIdEntry
9534/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
9535bool LLParser::parseTypeIdEntry(unsigned ID) {
9536 assert(Lex.getKind() == lltok::kw_typeid);
9537 Lex.Lex();
9538
9539 std::string Name;
9540 if (parseToken(lltok::colon, "expected ':' here") ||
9541 parseToken(lltok::lparen, "expected '(' here") ||
9542 parseToken(lltok::kw_name, "expected 'name' here") ||
9543 parseToken(lltok::colon, "expected ':' here") ||
9544 parseStringConstant(Name))
9545 return true;
9546
9547 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
9548 if (parseToken(lltok::comma, "expected ',' here") ||
9549 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
9550 return true;
9551
9552 // Check if this ID was forward referenced, and if so, update the
9553 // corresponding GUIDs.
9554 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9555 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9556 for (auto TIDRef : FwdRefTIDs->second) {
9557 assert(!*TIDRef.first &&
9558 "Forward referenced type id GUID expected to be 0");
9559 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9560 }
9561 ForwardRefTypeIds.erase(FwdRefTIDs);
9562 }
9563
9564 return false;
9565}
9566
9567/// TypeIdSummary
9568/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
9569bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
9570 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
9571 parseToken(lltok::colon, "expected ':' here") ||
9572 parseToken(lltok::lparen, "expected '(' here") ||
9573 parseTypeTestResolution(TIS.TTRes))
9574 return true;
9575
9576 if (EatIfPresent(lltok::comma)) {
9577 // Expect optional wpdResolutions field
9578 if (parseOptionalWpdResolutions(TIS.WPDRes))
9579 return true;
9580 }
9581
9582 if (parseToken(lltok::rparen, "expected ')' here"))
9583 return true;
9584
9585 return false;
9586}
9587
9589 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
9590
9591/// TypeIdCompatibleVtableEntry
9592/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
9593/// TypeIdCompatibleVtableInfo
9594/// ')'
9595bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
9597 Lex.Lex();
9598
9599 std::string Name;
9600 if (parseToken(lltok::colon, "expected ':' here") ||
9601 parseToken(lltok::lparen, "expected '(' here") ||
9602 parseToken(lltok::kw_name, "expected 'name' here") ||
9603 parseToken(lltok::colon, "expected ':' here") ||
9604 parseStringConstant(Name))
9605 return true;
9606
9608 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
9609 if (parseToken(lltok::comma, "expected ',' here") ||
9610 parseToken(lltok::kw_summary, "expected 'summary' here") ||
9611 parseToken(lltok::colon, "expected ':' here") ||
9612 parseToken(lltok::lparen, "expected '(' here"))
9613 return true;
9614
9615 IdToIndexMapType IdToIndexMap;
9616 // parse each call edge
9617 do {
9619 if (parseToken(lltok::lparen, "expected '(' here") ||
9620 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9621 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9622 parseToken(lltok::comma, "expected ',' here"))
9623 return true;
9624
9625 LocTy Loc = Lex.getLoc();
9626 unsigned GVId;
9627 ValueInfo VI;
9628 if (parseGVReference(VI, GVId))
9629 return true;
9630
9631 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
9632 // forward reference. We will save the location of the ValueInfo needing an
9633 // update, but can only do so once the std::vector is finalized.
9634 if (VI == EmptyVI)
9635 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
9636 TI.push_back({Offset, VI});
9637
9638 if (parseToken(lltok::rparen, "expected ')' in call"))
9639 return true;
9640 } while (EatIfPresent(lltok::comma));
9641
9642 // Now that the TI vector is finalized, it is safe to save the locations
9643 // of any forward GV references that need updating later.
9644 for (auto I : IdToIndexMap) {
9645 auto &Infos = ForwardRefValueInfos[I.first];
9646 for (auto P : I.second) {
9647 assert(TI[P.first].VTableVI == EmptyVI &&
9648 "Forward referenced ValueInfo expected to be empty");
9649 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
9650 }
9651 }
9652
9653 if (parseToken(lltok::rparen, "expected ')' here") ||
9654 parseToken(lltok::rparen, "expected ')' here"))
9655 return true;
9656
9657 // Check if this ID was forward referenced, and if so, update the
9658 // corresponding GUIDs.
9659 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
9660 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
9661 for (auto TIDRef : FwdRefTIDs->second) {
9662 assert(!*TIDRef.first &&
9663 "Forward referenced type id GUID expected to be 0");
9664 *TIDRef.first = GlobalValue::getGUIDAssumingExternalLinkage(Name);
9665 }
9666 ForwardRefTypeIds.erase(FwdRefTIDs);
9667 }
9668
9669 return false;
9670}
9671
9672/// TypeTestResolution
9673/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9674/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9675/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9676/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9677/// [',' 'inlinesBits' ':' UInt64]? ')'
9678bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9679 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9680 parseToken(lltok::colon, "expected ':' here") ||
9681 parseToken(lltok::lparen, "expected '(' here") ||
9682 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9683 parseToken(lltok::colon, "expected ':' here"))
9684 return true;
9685
9686 switch (Lex.getKind()) {
9687 case lltok::kw_unknown:
9689 break;
9690 case lltok::kw_unsat:
9692 break;
9695 break;
9696 case lltok::kw_inline:
9698 break;
9699 case lltok::kw_single:
9701 break;
9702 case lltok::kw_allOnes:
9704 break;
9705 default:
9706 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9707 }
9708 Lex.Lex();
9709
9710 if (parseToken(lltok::comma, "expected ',' here") ||
9711 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9712 parseToken(lltok::colon, "expected ':' here") ||
9713 parseUInt32(TTRes.SizeM1BitWidth))
9714 return true;
9715
9716 // parse optional fields
9717 while (EatIfPresent(lltok::comma)) {
9718 switch (Lex.getKind()) {
9720 Lex.Lex();
9721 if (parseToken(lltok::colon, "expected ':'") ||
9722 parseUInt64(TTRes.AlignLog2))
9723 return true;
9724 break;
9725 case lltok::kw_sizeM1:
9726 Lex.Lex();
9727 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9728 return true;
9729 break;
9730 case lltok::kw_bitMask: {
9731 unsigned Val;
9732 Lex.Lex();
9733 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9734 return true;
9735 assert(Val <= 0xff);
9736 TTRes.BitMask = (uint8_t)Val;
9737 break;
9738 }
9740 Lex.Lex();
9741 if (parseToken(lltok::colon, "expected ':'") ||
9742 parseUInt64(TTRes.InlineBits))
9743 return true;
9744 break;
9745 default:
9746 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9747 }
9748 }
9749
9750 if (parseToken(lltok::rparen, "expected ')' here"))
9751 return true;
9752
9753 return false;
9754}
9755
9756/// OptionalWpdResolutions
9757/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9758/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9759bool LLParser::parseOptionalWpdResolutions(
9760 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9761 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9762 parseToken(lltok::colon, "expected ':' here") ||
9763 parseToken(lltok::lparen, "expected '(' here"))
9764 return true;
9765
9766 do {
9767 uint64_t Offset;
9768 WholeProgramDevirtResolution WPDRes;
9769 if (parseToken(lltok::lparen, "expected '(' here") ||
9770 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9771 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9772 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9773 parseToken(lltok::rparen, "expected ')' here"))
9774 return true;
9775 WPDResMap[Offset] = WPDRes;
9776 } while (EatIfPresent(lltok::comma));
9777
9778 if (parseToken(lltok::rparen, "expected ')' here"))
9779 return true;
9780
9781 return false;
9782}
9783
9784/// WpdRes
9785/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9786/// [',' OptionalResByArg]? ')'
9787/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9788/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9789/// [',' OptionalResByArg]? ')'
9790/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9791/// [',' OptionalResByArg]? ')'
9792bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9793 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9794 parseToken(lltok::colon, "expected ':' here") ||
9795 parseToken(lltok::lparen, "expected '(' here") ||
9796 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9797 parseToken(lltok::colon, "expected ':' here"))
9798 return true;
9799
9800 switch (Lex.getKind()) {
9801 case lltok::kw_indir:
9803 break;
9806 break;
9809 break;
9810 default:
9811 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9812 }
9813 Lex.Lex();
9814
9815 // parse optional fields
9816 while (EatIfPresent(lltok::comma)) {
9817 switch (Lex.getKind()) {
9819 Lex.Lex();
9820 if (parseToken(lltok::colon, "expected ':' here") ||
9821 parseStringConstant(WPDRes.SingleImplName))
9822 return true;
9823 break;
9824 case lltok::kw_resByArg:
9825 if (parseOptionalResByArg(WPDRes.ResByArg))
9826 return true;
9827 break;
9828 default:
9829 return error(Lex.getLoc(),
9830 "expected optional WholeProgramDevirtResolution field");
9831 }
9832 }
9833
9834 if (parseToken(lltok::rparen, "expected ')' here"))
9835 return true;
9836
9837 return false;
9838}
9839
9840/// OptionalResByArg
9841/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9842/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9843/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9844/// 'virtualConstProp' )
9845/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9846/// [',' 'bit' ':' UInt32]? ')'
9847bool LLParser::parseOptionalResByArg(
9848 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9849 &ResByArg) {
9850 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9851 parseToken(lltok::colon, "expected ':' here") ||
9852 parseToken(lltok::lparen, "expected '(' here"))
9853 return true;
9854
9855 do {
9856 std::vector<uint64_t> Args;
9857 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9858 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9859 parseToken(lltok::colon, "expected ':' here") ||
9860 parseToken(lltok::lparen, "expected '(' here") ||
9861 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9862 parseToken(lltok::colon, "expected ':' here"))
9863 return true;
9864
9865 WholeProgramDevirtResolution::ByArg ByArg;
9866 switch (Lex.getKind()) {
9867 case lltok::kw_indir:
9869 break;
9872 break;
9875 break;
9878 break;
9879 default:
9880 return error(Lex.getLoc(),
9881 "unexpected WholeProgramDevirtResolution::ByArg kind");
9882 }
9883 Lex.Lex();
9884
9885 // parse optional fields
9886 while (EatIfPresent(lltok::comma)) {
9887 switch (Lex.getKind()) {
9888 case lltok::kw_info:
9889 Lex.Lex();
9890 if (parseToken(lltok::colon, "expected ':' here") ||
9891 parseUInt64(ByArg.Info))
9892 return true;
9893 break;
9894 case lltok::kw_byte:
9895 Lex.Lex();
9896 if (parseToken(lltok::colon, "expected ':' here") ||
9897 parseUInt32(ByArg.Byte))
9898 return true;
9899 break;
9900 case lltok::kw_bit:
9901 Lex.Lex();
9902 if (parseToken(lltok::colon, "expected ':' here") ||
9903 parseUInt32(ByArg.Bit))
9904 return true;
9905 break;
9906 default:
9907 return error(Lex.getLoc(),
9908 "expected optional whole program devirt field");
9909 }
9910 }
9911
9912 if (parseToken(lltok::rparen, "expected ')' here"))
9913 return true;
9914
9915 ResByArg[Args] = ByArg;
9916 } while (EatIfPresent(lltok::comma));
9917
9918 if (parseToken(lltok::rparen, "expected ')' here"))
9919 return true;
9920
9921 return false;
9922}
9923
9924/// OptionalResByArg
9925/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9926bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9927 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9928 parseToken(lltok::colon, "expected ':' here") ||
9929 parseToken(lltok::lparen, "expected '(' here"))
9930 return true;
9931
9932 do {
9933 uint64_t Val;
9934 if (parseUInt64(Val))
9935 return true;
9936 Args.push_back(Val);
9937 } while (EatIfPresent(lltok::comma));
9938
9939 if (parseToken(lltok::rparen, "expected ')' here"))
9940 return true;
9941
9942 return false;
9943}
9944
9945static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9946
9947static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9948 bool ReadOnly = Fwd->isReadOnly();
9949 bool WriteOnly = Fwd->isWriteOnly();
9950 assert(!(ReadOnly && WriteOnly));
9951 *Fwd = Resolved;
9952 if (ReadOnly)
9953 Fwd->setReadOnly();
9954 if (WriteOnly)
9955 Fwd->setWriteOnly();
9956}
9957
9958/// Stores the given Name/GUID and associated summary into the Index.
9959/// Also updates any forward references to the associated entry ID.
9960bool LLParser::addGlobalValueToIndex(
9961 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9962 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9963 // First create the ValueInfo utilizing the Name or GUID.
9964 ValueInfo VI;
9965 if (GUID != 0) {
9966 assert(Name.empty());
9967 VI = Index->getOrInsertValueInfo(GUID);
9968 } else {
9969 assert(!Name.empty());
9970 if (M) {
9971 auto *GV = M->getNamedValue(Name);
9972 if (!GV)
9973 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9974
9975 // Be a little lenient here, to accomodate older files without GUIDs
9976 // already computed and assigned as metadata.
9977 GUID = GV->getGUIDOrFallback();
9978
9979 VI = Index->getOrInsertValueInfo(GV, GUID);
9980 } else {
9981 assert(
9982 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9983 "Need a source_filename to compute GUID for local");
9985 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9986 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9987 }
9988 }
9989
9990 // Resolve forward references from calls/refs
9991 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9992 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9993 for (auto VIRef : FwdRefVIs->second) {
9994 assert(VIRef.first->getRef() == FwdVIRef &&
9995 "Forward referenced ValueInfo expected to be empty");
9996 resolveFwdRef(VIRef.first, VI);
9997 }
9998 ForwardRefValueInfos.erase(FwdRefVIs);
9999 }
10000
10001 // Resolve forward references from aliases
10002 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
10003 if (FwdRefAliasees != ForwardRefAliasees.end()) {
10004 for (auto AliaseeRef : FwdRefAliasees->second) {
10005 assert(!AliaseeRef.first->hasAliasee() &&
10006 "Forward referencing alias already has aliasee");
10007 assert(Summary && "Aliasee must be a definition");
10008 AliaseeRef.first->setAliasee(VI, Summary.get());
10009 }
10010 ForwardRefAliasees.erase(FwdRefAliasees);
10011 }
10012
10013 // Add the summary if one was provided.
10014 if (Summary)
10015 Index->addGlobalValueSummary(VI, std::move(Summary));
10016
10017 // Save the associated ValueInfo for use in later references by ID.
10018 if (ID == NumberedValueInfos.size())
10019 NumberedValueInfos.push_back(VI);
10020 else {
10021 // Handle non-continuous numbers (to make test simplification easier).
10022 if (ID > NumberedValueInfos.size())
10023 NumberedValueInfos.resize(ID + 1);
10024 NumberedValueInfos[ID] = VI;
10025 }
10026
10027 return false;
10028}
10029
10030/// parseSummaryIndexFlags
10031/// ::= 'flags' ':' UInt64
10032bool LLParser::parseSummaryIndexFlags() {
10033 assert(Lex.getKind() == lltok::kw_flags);
10034 Lex.Lex();
10035
10036 if (parseToken(lltok::colon, "expected ':' here"))
10037 return true;
10038 uint64_t Flags;
10039 if (parseUInt64(Flags))
10040 return true;
10041 if (Index)
10042 Index->setFlags(Flags);
10043 return false;
10044}
10045
10046/// parseBlockCount
10047/// ::= 'blockcount' ':' UInt64
10048bool LLParser::parseBlockCount() {
10049 assert(Lex.getKind() == lltok::kw_blockcount);
10050 Lex.Lex();
10051
10052 if (parseToken(lltok::colon, "expected ':' here"))
10053 return true;
10054 uint64_t BlockCount;
10055 if (parseUInt64(BlockCount))
10056 return true;
10057 if (Index)
10058 Index->setBlockCount(BlockCount);
10059 return false;
10060}
10061
10062/// parseGVEntry
10063/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
10064/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
10065/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
10066bool LLParser::parseGVEntry(unsigned ID) {
10067 assert(Lex.getKind() == lltok::kw_gv);
10068 Lex.Lex();
10069
10070 if (parseToken(lltok::colon, "expected ':' here") ||
10071 parseToken(lltok::lparen, "expected '(' here"))
10072 return true;
10073
10074 LocTy Loc = Lex.getLoc();
10075 std::string Name;
10077 switch (Lex.getKind()) {
10078 case lltok::kw_name:
10079 Lex.Lex();
10080 if (parseToken(lltok::colon, "expected ':' here") ||
10081 parseStringConstant(Name))
10082 return true;
10083 // Can't create GUID/ValueInfo until we have the linkage.
10084 break;
10085 case lltok::kw_guid:
10086 Lex.Lex();
10087 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
10088 return true;
10089 break;
10090 default:
10091 return error(Lex.getLoc(), "expected name or guid tag");
10092 }
10093
10094 if (!EatIfPresent(lltok::comma)) {
10095 // No summaries. Wrap up.
10096 if (parseToken(lltok::rparen, "expected ')' here"))
10097 return true;
10098 // This was created for a call to an external or indirect target.
10099 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
10100 // created for indirect calls with VP. A Name with no GUID came from
10101 // an external definition. We pass ExternalLinkage since that is only
10102 // used when the GUID must be computed from Name, and in that case
10103 // the symbol must have external linkage.
10104 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
10105 nullptr, Loc);
10106 }
10107
10108 // Have a list of summaries
10109 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
10110 parseToken(lltok::colon, "expected ':' here") ||
10111 parseToken(lltok::lparen, "expected '(' here"))
10112 return true;
10113 do {
10114 switch (Lex.getKind()) {
10115 case lltok::kw_function:
10116 if (parseFunctionSummary(Name, GUID, ID))
10117 return true;
10118 break;
10119 case lltok::kw_variable:
10120 if (parseVariableSummary(Name, GUID, ID))
10121 return true;
10122 break;
10123 case lltok::kw_alias:
10124 if (parseAliasSummary(Name, GUID, ID))
10125 return true;
10126 break;
10127 default:
10128 return error(Lex.getLoc(), "expected summary type");
10129 }
10130 } while (EatIfPresent(lltok::comma));
10131
10132 if (parseToken(lltok::rparen, "expected ')' here") ||
10133 parseToken(lltok::rparen, "expected ')' here"))
10134 return true;
10135
10136 return false;
10137}
10138
10139/// FunctionSummary
10140/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10141/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
10142/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
10143/// [',' OptionalRefs]? ')'
10144bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
10145 unsigned ID) {
10146 LocTy Loc = Lex.getLoc();
10147 assert(Lex.getKind() == lltok::kw_function);
10148 Lex.Lex();
10149
10150 StringRef ModulePath;
10151 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10153 /*NotEligibleToImport=*/false,
10154 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10155 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10156 unsigned InstCount;
10158 FunctionSummary::TypeIdInfo TypeIdInfo;
10159 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
10161 std::vector<CallsiteInfo> Callsites;
10162 std::vector<AllocInfo> Allocs;
10163 // Default is all-zeros (conservative values).
10164 FunctionSummary::FFlags FFlags = {};
10165 if (parseToken(lltok::colon, "expected ':' here") ||
10166 parseToken(lltok::lparen, "expected '(' here") ||
10167 parseModuleReference(ModulePath) ||
10168 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10169 parseToken(lltok::comma, "expected ',' here") ||
10170 parseToken(lltok::kw_insts, "expected 'insts' here") ||
10171 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
10172 return true;
10173
10174 // parse optional fields
10175 while (EatIfPresent(lltok::comma)) {
10176 switch (Lex.getKind()) {
10178 if (parseOptionalFFlags(FFlags))
10179 return true;
10180 break;
10181 case lltok::kw_calls:
10182 if (parseOptionalCalls(Calls))
10183 return true;
10184 break;
10186 if (parseOptionalTypeIdInfo(TypeIdInfo))
10187 return true;
10188 break;
10189 case lltok::kw_refs:
10190 if (parseOptionalRefs(Refs))
10191 return true;
10192 break;
10193 case lltok::kw_params:
10194 if (parseOptionalParamAccesses(ParamAccesses))
10195 return true;
10196 break;
10197 case lltok::kw_allocs:
10198 if (parseOptionalAllocs(Allocs))
10199 return true;
10200 break;
10202 if (parseOptionalCallsites(Callsites))
10203 return true;
10204 break;
10205 default:
10206 return error(Lex.getLoc(), "expected optional function summary field");
10207 }
10208 }
10209
10210 if (parseToken(lltok::rparen, "expected ')' here"))
10211 return true;
10212
10213 auto FS = std::make_unique<FunctionSummary>(
10214 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
10215 std::move(TypeIdInfo.TypeTests),
10216 std::move(TypeIdInfo.TypeTestAssumeVCalls),
10217 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
10218 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
10219 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
10220 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
10221
10222 FS->setModulePath(ModulePath);
10223
10224 return addGlobalValueToIndex(Name, GUID,
10226 std::move(FS), Loc);
10227}
10228
10229/// VariableSummary
10230/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
10231/// [',' OptionalRefs]? ')'
10232bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
10233 unsigned ID) {
10234 LocTy Loc = Lex.getLoc();
10235 assert(Lex.getKind() == lltok::kw_variable);
10236 Lex.Lex();
10237
10238 StringRef ModulePath;
10239 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10241 /*NotEligibleToImport=*/false,
10242 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10243 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10244 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
10245 /* WriteOnly */ false,
10246 /* Constant */ false,
10249 VTableFuncList VTableFuncs;
10250 if (parseToken(lltok::colon, "expected ':' here") ||
10251 parseToken(lltok::lparen, "expected '(' here") ||
10252 parseModuleReference(ModulePath) ||
10253 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10254 parseToken(lltok::comma, "expected ',' here") ||
10255 parseGVarFlags(GVarFlags))
10256 return true;
10257
10258 // parse optional fields
10259 while (EatIfPresent(lltok::comma)) {
10260 switch (Lex.getKind()) {
10262 if (parseOptionalVTableFuncs(VTableFuncs))
10263 return true;
10264 break;
10265 case lltok::kw_refs:
10266 if (parseOptionalRefs(Refs))
10267 return true;
10268 break;
10269 default:
10270 return error(Lex.getLoc(), "expected optional variable summary field");
10271 }
10272 }
10273
10274 if (parseToken(lltok::rparen, "expected ')' here"))
10275 return true;
10276
10277 auto GS =
10278 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
10279
10280 GS->setModulePath(ModulePath);
10281 GS->setVTableFuncs(std::move(VTableFuncs));
10282
10283 return addGlobalValueToIndex(Name, GUID,
10285 std::move(GS), Loc);
10286}
10287
10288/// AliasSummary
10289/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
10290/// 'aliasee' ':' GVReference ')'
10291bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
10292 unsigned ID) {
10293 assert(Lex.getKind() == lltok::kw_alias);
10294 LocTy Loc = Lex.getLoc();
10295 Lex.Lex();
10296
10297 StringRef ModulePath;
10298 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
10300 /*NotEligibleToImport=*/false,
10301 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
10302 GlobalValueSummary::Definition, /*NoRenameOnPromotion=*/false);
10303 if (parseToken(lltok::colon, "expected ':' here") ||
10304 parseToken(lltok::lparen, "expected '(' here") ||
10305 parseModuleReference(ModulePath) ||
10306 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
10307 parseToken(lltok::comma, "expected ',' here") ||
10308 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
10309 parseToken(lltok::colon, "expected ':' here"))
10310 return true;
10311
10312 ValueInfo AliaseeVI;
10313 unsigned GVId;
10314 auto AS = std::make_unique<AliasSummary>(GVFlags);
10315 AS->setModulePath(ModulePath);
10316
10317 if (!EatIfPresent(lltok::kw_null)) {
10318 if (parseGVReference(AliaseeVI, GVId))
10319 return true;
10320
10321 // Record forward reference if the aliasee is not parsed yet.
10322 if (AliaseeVI.getRef() == FwdVIRef) {
10323 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
10324 } else {
10325 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
10326 assert(Summary && "Aliasee must be a definition");
10327 AS->setAliasee(AliaseeVI, Summary);
10328 }
10329 }
10330
10331 if (parseToken(lltok::rparen, "expected ')' here"))
10332 return true;
10333
10334 return addGlobalValueToIndex(Name, GUID,
10336 std::move(AS), Loc);
10337}
10338
10339/// Flag
10340/// ::= [0|1]
10341bool LLParser::parseFlag(unsigned &Val) {
10342 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
10343 return tokError("expected integer");
10344 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
10345 Lex.Lex();
10346 return false;
10347}
10348
10349/// OptionalFFlags
10350/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
10351/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
10352/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
10353/// [',' 'noInline' ':' Flag]? ')'
10354/// [',' 'alwaysInline' ':' Flag]? ')'
10355/// [',' 'noUnwind' ':' Flag]? ')'
10356/// [',' 'mayThrow' ':' Flag]? ')'
10357/// [',' 'hasUnknownCall' ':' Flag]? ')'
10358/// [',' 'mustBeUnreachable' ':' Flag]? ')'
10359
10360bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
10361 assert(Lex.getKind() == lltok::kw_funcFlags);
10362 Lex.Lex();
10363
10364 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
10365 parseToken(lltok::lparen, "expected '(' in funcFlags"))
10366 return true;
10367
10368 do {
10369 unsigned Val = 0;
10370 switch (Lex.getKind()) {
10371 case lltok::kw_readNone:
10372 Lex.Lex();
10373 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10374 return true;
10375 FFlags.ReadNone = Val;
10376 break;
10377 case lltok::kw_readOnly:
10378 Lex.Lex();
10379 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10380 return true;
10381 FFlags.ReadOnly = Val;
10382 break;
10384 Lex.Lex();
10385 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10386 return true;
10387 FFlags.NoRecurse = Val;
10388 break;
10390 Lex.Lex();
10391 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10392 return true;
10393 FFlags.ReturnDoesNotAlias = Val;
10394 break;
10395 case lltok::kw_noInline:
10396 Lex.Lex();
10397 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10398 return true;
10399 FFlags.NoInline = Val;
10400 break;
10402 Lex.Lex();
10403 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10404 return true;
10405 FFlags.AlwaysInline = Val;
10406 break;
10407 case lltok::kw_noUnwind:
10408 Lex.Lex();
10409 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10410 return true;
10411 FFlags.NoUnwind = Val;
10412 break;
10413 case lltok::kw_mayThrow:
10414 Lex.Lex();
10415 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10416 return true;
10417 FFlags.MayThrow = Val;
10418 break;
10420 Lex.Lex();
10421 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10422 return true;
10423 FFlags.HasUnknownCall = Val;
10424 break;
10426 Lex.Lex();
10427 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
10428 return true;
10429 FFlags.MustBeUnreachable = Val;
10430 break;
10431 default:
10432 return error(Lex.getLoc(), "expected function flag type");
10433 }
10434 } while (EatIfPresent(lltok::comma));
10435
10436 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
10437 return true;
10438
10439 return false;
10440}
10441
10442/// OptionalCalls
10443/// := 'calls' ':' '(' Call [',' Call]* ')'
10444/// Call ::= '(' 'callee' ':' GVReference
10445/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
10446/// [ ',' 'tail' ]? ')'
10447bool LLParser::parseOptionalCalls(
10448 SmallVectorImpl<FunctionSummary::EdgeTy> &Calls) {
10449 assert(Lex.getKind() == lltok::kw_calls);
10450 Lex.Lex();
10451
10452 if (parseToken(lltok::colon, "expected ':' in calls") ||
10453 parseToken(lltok::lparen, "expected '(' in calls"))
10454 return true;
10455
10456 IdToIndexMapType IdToIndexMap;
10457 // parse each call edge
10458 do {
10459 ValueInfo VI;
10460 if (parseToken(lltok::lparen, "expected '(' in call") ||
10461 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
10462 parseToken(lltok::colon, "expected ':'"))
10463 return true;
10464
10465 LocTy Loc = Lex.getLoc();
10466 unsigned GVId;
10467 if (parseGVReference(VI, GVId))
10468 return true;
10469
10471 unsigned RelBF = 0;
10472 unsigned HasTailCall = false;
10473
10474 // parse optional fields
10475 while (EatIfPresent(lltok::comma)) {
10476 switch (Lex.getKind()) {
10477 case lltok::kw_hotness:
10478 Lex.Lex();
10479 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
10480 return true;
10481 break;
10482 // Deprecated, keep in order to support old files.
10483 case lltok::kw_relbf:
10484 Lex.Lex();
10485 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
10486 return true;
10487 break;
10488 case lltok::kw_tail:
10489 Lex.Lex();
10490 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
10491 return true;
10492 break;
10493 default:
10494 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
10495 }
10496 }
10497 // Keep track of the Call array index needing a forward reference.
10498 // We will save the location of the ValueInfo needing an update, but
10499 // can only do so once the std::vector is finalized.
10500 if (VI.getRef() == FwdVIRef)
10501 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
10502 Calls.push_back(
10503 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall)});
10504
10505 if (parseToken(lltok::rparen, "expected ')' in call"))
10506 return true;
10507 } while (EatIfPresent(lltok::comma));
10508
10509 // Now that the Calls vector is finalized, it is safe to save the locations
10510 // of any forward GV references that need updating later.
10511 for (auto I : IdToIndexMap) {
10512 auto &Infos = ForwardRefValueInfos[I.first];
10513 for (auto P : I.second) {
10514 assert(Calls[P.first].first.getRef() == FwdVIRef &&
10515 "Forward referenced ValueInfo expected to be empty");
10516 Infos.emplace_back(&Calls[P.first].first, P.second);
10517 }
10518 }
10519
10520 if (parseToken(lltok::rparen, "expected ')' in calls"))
10521 return true;
10522
10523 return false;
10524}
10525
10526/// Hotness
10527/// := ('unknown'|'cold'|'none'|'hot'|'critical')
10528bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
10529 switch (Lex.getKind()) {
10530 case lltok::kw_unknown:
10532 break;
10533 case lltok::kw_cold:
10535 break;
10536 case lltok::kw_none:
10538 break;
10539 case lltok::kw_hot:
10541 break;
10542 case lltok::kw_critical:
10544 break;
10545 default:
10546 return error(Lex.getLoc(), "invalid call edge hotness");
10547 }
10548 Lex.Lex();
10549 return false;
10550}
10551
10552/// OptionalVTableFuncs
10553/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
10554/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
10555bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
10556 assert(Lex.getKind() == lltok::kw_vTableFuncs);
10557 Lex.Lex();
10558
10559 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
10560 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
10561 return true;
10562
10563 IdToIndexMapType IdToIndexMap;
10564 // parse each virtual function pair
10565 do {
10566 ValueInfo VI;
10567 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
10568 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
10569 parseToken(lltok::colon, "expected ':'"))
10570 return true;
10571
10572 LocTy Loc = Lex.getLoc();
10573 unsigned GVId;
10574 if (parseGVReference(VI, GVId))
10575 return true;
10576
10577 uint64_t Offset;
10578 if (parseToken(lltok::comma, "expected comma") ||
10579 parseToken(lltok::kw_offset, "expected offset") ||
10580 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
10581 return true;
10582
10583 // Keep track of the VTableFuncs array index needing a forward reference.
10584 // We will save the location of the ValueInfo needing an update, but
10585 // can only do so once the std::vector is finalized.
10586 if (VI == EmptyVI)
10587 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
10588 VTableFuncs.push_back({VI, Offset});
10589
10590 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
10591 return true;
10592 } while (EatIfPresent(lltok::comma));
10593
10594 // Now that the VTableFuncs vector is finalized, it is safe to save the
10595 // locations of any forward GV references that need updating later.
10596 for (auto I : IdToIndexMap) {
10597 auto &Infos = ForwardRefValueInfos[I.first];
10598 for (auto P : I.second) {
10599 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
10600 "Forward referenced ValueInfo expected to be empty");
10601 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
10602 }
10603 }
10604
10605 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
10606 return true;
10607
10608 return false;
10609}
10610
10611/// ParamNo := 'param' ':' UInt64
10612bool LLParser::parseParamNo(uint64_t &ParamNo) {
10613 if (parseToken(lltok::kw_param, "expected 'param' here") ||
10614 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
10615 return true;
10616 return false;
10617}
10618
10619/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
10620bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
10621 APSInt Lower;
10622 APSInt Upper;
10623 auto ParseAPSInt = [&](APSInt &Val) {
10624 if (Lex.getKind() != lltok::APSInt)
10625 return tokError("expected integer");
10626 Val = Lex.getAPSIntVal();
10627 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
10628 Val.setIsSigned(true);
10629 Lex.Lex();
10630 return false;
10631 };
10632 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
10633 parseToken(lltok::colon, "expected ':' here") ||
10634 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
10635 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
10636 parseToken(lltok::rsquare, "expected ']' here"))
10637 return true;
10638
10639 ++Upper;
10640 Range =
10641 (Lower == Upper && !Lower.isMaxValue())
10642 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
10643 : ConstantRange(Lower, Upper);
10644
10645 return false;
10646}
10647
10648/// ParamAccessCall
10649/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
10650bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
10651 IdLocListType &IdLocList) {
10652 if (parseToken(lltok::lparen, "expected '(' here") ||
10653 parseToken(lltok::kw_callee, "expected 'callee' here") ||
10654 parseToken(lltok::colon, "expected ':' here"))
10655 return true;
10656
10657 unsigned GVId;
10658 ValueInfo VI;
10659 LocTy Loc = Lex.getLoc();
10660 if (parseGVReference(VI, GVId))
10661 return true;
10662
10663 Call.Callee = VI;
10664 IdLocList.emplace_back(GVId, Loc);
10665
10666 if (parseToken(lltok::comma, "expected ',' here") ||
10667 parseParamNo(Call.ParamNo) ||
10668 parseToken(lltok::comma, "expected ',' here") ||
10669 parseParamAccessOffset(Call.Offsets))
10670 return true;
10671
10672 if (parseToken(lltok::rparen, "expected ')' here"))
10673 return true;
10674
10675 return false;
10676}
10677
10678/// ParamAccess
10679/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10680/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10681bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10682 IdLocListType &IdLocList) {
10683 if (parseToken(lltok::lparen, "expected '(' here") ||
10684 parseParamNo(Param.ParamNo) ||
10685 parseToken(lltok::comma, "expected ',' here") ||
10686 parseParamAccessOffset(Param.Use))
10687 return true;
10688
10689 if (EatIfPresent(lltok::comma)) {
10690 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10691 parseToken(lltok::colon, "expected ':' here") ||
10692 parseToken(lltok::lparen, "expected '(' here"))
10693 return true;
10694 do {
10695 FunctionSummary::ParamAccess::Call Call;
10696 if (parseParamAccessCall(Call, IdLocList))
10697 return true;
10698 Param.Calls.push_back(Call);
10699 } while (EatIfPresent(lltok::comma));
10700
10701 if (parseToken(lltok::rparen, "expected ')' here"))
10702 return true;
10703 }
10704
10705 if (parseToken(lltok::rparen, "expected ')' here"))
10706 return true;
10707
10708 return false;
10709}
10710
10711/// OptionalParamAccesses
10712/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10713bool LLParser::parseOptionalParamAccesses(
10714 std::vector<FunctionSummary::ParamAccess> &Params) {
10715 assert(Lex.getKind() == lltok::kw_params);
10716 Lex.Lex();
10717
10718 if (parseToken(lltok::colon, "expected ':' here") ||
10719 parseToken(lltok::lparen, "expected '(' here"))
10720 return true;
10721
10722 IdLocListType VContexts;
10723 size_t CallsNum = 0;
10724 do {
10725 FunctionSummary::ParamAccess ParamAccess;
10726 if (parseParamAccess(ParamAccess, VContexts))
10727 return true;
10728 CallsNum += ParamAccess.Calls.size();
10729 assert(VContexts.size() == CallsNum);
10730 (void)CallsNum;
10731 Params.emplace_back(std::move(ParamAccess));
10732 } while (EatIfPresent(lltok::comma));
10733
10734 if (parseToken(lltok::rparen, "expected ')' here"))
10735 return true;
10736
10737 // Now that the Params is finalized, it is safe to save the locations
10738 // of any forward GV references that need updating later.
10739 IdLocListType::const_iterator ItContext = VContexts.begin();
10740 for (auto &PA : Params) {
10741 for (auto &C : PA.Calls) {
10742 if (C.Callee.getRef() == FwdVIRef)
10743 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10744 ItContext->second);
10745 ++ItContext;
10746 }
10747 }
10748 assert(ItContext == VContexts.end());
10749
10750 return false;
10751}
10752
10753/// OptionalRefs
10754/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10755bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10756 assert(Lex.getKind() == lltok::kw_refs);
10757 Lex.Lex();
10758
10759 if (parseToken(lltok::colon, "expected ':' in refs") ||
10760 parseToken(lltok::lparen, "expected '(' in refs"))
10761 return true;
10762
10763 struct ValueContext {
10764 ValueInfo VI;
10765 unsigned GVId;
10766 LocTy Loc;
10767 };
10768 std::vector<ValueContext> VContexts;
10769 // parse each ref edge
10770 do {
10771 ValueContext VC;
10772 VC.Loc = Lex.getLoc();
10773 if (parseGVReference(VC.VI, VC.GVId))
10774 return true;
10775 VContexts.push_back(VC);
10776 } while (EatIfPresent(lltok::comma));
10777
10778 // Sort value contexts so that ones with writeonly
10779 // and readonly ValueInfo are at the end of VContexts vector.
10780 // See FunctionSummary::specialRefCounts()
10781 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10782 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10783 });
10784
10785 IdToIndexMapType IdToIndexMap;
10786 for (auto &VC : VContexts) {
10787 // Keep track of the Refs array index needing a forward reference.
10788 // We will save the location of the ValueInfo needing an update, but
10789 // can only do so once the std::vector is finalized.
10790 if (VC.VI.getRef() == FwdVIRef)
10791 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10792 Refs.push_back(VC.VI);
10793 }
10794
10795 // Now that the Refs vector is finalized, it is safe to save the locations
10796 // of any forward GV references that need updating later.
10797 for (auto I : IdToIndexMap) {
10798 auto &Infos = ForwardRefValueInfos[I.first];
10799 for (auto P : I.second) {
10800 assert(Refs[P.first].getRef() == FwdVIRef &&
10801 "Forward referenced ValueInfo expected to be empty");
10802 Infos.emplace_back(&Refs[P.first], P.second);
10803 }
10804 }
10805
10806 if (parseToken(lltok::rparen, "expected ')' in refs"))
10807 return true;
10808
10809 return false;
10810}
10811
10812/// OptionalTypeIdInfo
10813/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10814/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10815/// [',' TypeCheckedLoadConstVCalls]? ')'
10816bool LLParser::parseOptionalTypeIdInfo(
10817 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10818 assert(Lex.getKind() == lltok::kw_typeIdInfo);
10819 Lex.Lex();
10820
10821 if (parseToken(lltok::colon, "expected ':' here") ||
10822 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10823 return true;
10824
10825 do {
10826 switch (Lex.getKind()) {
10828 if (parseTypeTests(TypeIdInfo.TypeTests))
10829 return true;
10830 break;
10832 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10833 TypeIdInfo.TypeTestAssumeVCalls))
10834 return true;
10835 break;
10837 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10838 TypeIdInfo.TypeCheckedLoadVCalls))
10839 return true;
10840 break;
10842 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10843 TypeIdInfo.TypeTestAssumeConstVCalls))
10844 return true;
10845 break;
10847 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10848 TypeIdInfo.TypeCheckedLoadConstVCalls))
10849 return true;
10850 break;
10851 default:
10852 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10853 }
10854 } while (EatIfPresent(lltok::comma));
10855
10856 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10857 return true;
10858
10859 return false;
10860}
10861
10862/// TypeTests
10863/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10864/// [',' (SummaryID | UInt64)]* ')'
10865bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10866 assert(Lex.getKind() == lltok::kw_typeTests);
10867 Lex.Lex();
10868
10869 if (parseToken(lltok::colon, "expected ':' here") ||
10870 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10871 return true;
10872
10873 IdToIndexMapType IdToIndexMap;
10874 do {
10876 if (Lex.getKind() == lltok::SummaryID) {
10877 unsigned ID = Lex.getUIntVal();
10878 LocTy Loc = Lex.getLoc();
10879 // Keep track of the TypeTests array index needing a forward reference.
10880 // We will save the location of the GUID needing an update, but
10881 // can only do so once the std::vector is finalized.
10882 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10883 Lex.Lex();
10884 } else if (parseUInt64(GUID))
10885 return true;
10886 TypeTests.push_back(GUID);
10887 } while (EatIfPresent(lltok::comma));
10888
10889 // Now that the TypeTests vector is finalized, it is safe to save the
10890 // locations of any forward GV references that need updating later.
10891 for (auto I : IdToIndexMap) {
10892 auto &Ids = ForwardRefTypeIds[I.first];
10893 for (auto P : I.second) {
10894 assert(TypeTests[P.first] == 0 &&
10895 "Forward referenced type id GUID expected to be 0");
10896 Ids.emplace_back(&TypeTests[P.first], P.second);
10897 }
10898 }
10899
10900 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10901 return true;
10902
10903 return false;
10904}
10905
10906/// VFuncIdList
10907/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10908bool LLParser::parseVFuncIdList(
10909 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10910 assert(Lex.getKind() == Kind);
10911 Lex.Lex();
10912
10913 if (parseToken(lltok::colon, "expected ':' here") ||
10914 parseToken(lltok::lparen, "expected '(' here"))
10915 return true;
10916
10917 IdToIndexMapType IdToIndexMap;
10918 do {
10919 FunctionSummary::VFuncId VFuncId;
10920 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10921 return true;
10922 VFuncIdList.push_back(VFuncId);
10923 } while (EatIfPresent(lltok::comma));
10924
10925 if (parseToken(lltok::rparen, "expected ')' here"))
10926 return true;
10927
10928 // Now that the VFuncIdList vector is finalized, it is safe to save the
10929 // locations of any forward GV references that need updating later.
10930 for (auto I : IdToIndexMap) {
10931 auto &Ids = ForwardRefTypeIds[I.first];
10932 for (auto P : I.second) {
10933 assert(VFuncIdList[P.first].GUID == 0 &&
10934 "Forward referenced type id GUID expected to be 0");
10935 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10936 }
10937 }
10938
10939 return false;
10940}
10941
10942/// ConstVCallList
10943/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10944bool LLParser::parseConstVCallList(
10945 lltok::Kind Kind,
10946 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10947 assert(Lex.getKind() == Kind);
10948 Lex.Lex();
10949
10950 if (parseToken(lltok::colon, "expected ':' here") ||
10951 parseToken(lltok::lparen, "expected '(' here"))
10952 return true;
10953
10954 IdToIndexMapType IdToIndexMap;
10955 do {
10956 FunctionSummary::ConstVCall ConstVCall;
10957 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10958 return true;
10959 ConstVCallList.push_back(ConstVCall);
10960 } while (EatIfPresent(lltok::comma));
10961
10962 if (parseToken(lltok::rparen, "expected ')' here"))
10963 return true;
10964
10965 // Now that the ConstVCallList vector is finalized, it is safe to save the
10966 // locations of any forward GV references that need updating later.
10967 for (auto I : IdToIndexMap) {
10968 auto &Ids = ForwardRefTypeIds[I.first];
10969 for (auto P : I.second) {
10970 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10971 "Forward referenced type id GUID expected to be 0");
10972 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10973 }
10974 }
10975
10976 return false;
10977}
10978
10979/// ConstVCall
10980/// ::= '(' VFuncId ',' Args ')'
10981bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10982 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10983 if (parseToken(lltok::lparen, "expected '(' here") ||
10984 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10985 return true;
10986
10987 if (EatIfPresent(lltok::comma))
10988 if (parseArgs(ConstVCall.Args))
10989 return true;
10990
10991 if (parseToken(lltok::rparen, "expected ')' here"))
10992 return true;
10993
10994 return false;
10995}
10996
10997/// VFuncId
10998/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10999/// 'offset' ':' UInt64 ')'
11000bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
11001 IdToIndexMapType &IdToIndexMap, unsigned Index) {
11002 assert(Lex.getKind() == lltok::kw_vFuncId);
11003 Lex.Lex();
11004
11005 if (parseToken(lltok::colon, "expected ':' here") ||
11006 parseToken(lltok::lparen, "expected '(' here"))
11007 return true;
11008
11009 if (Lex.getKind() == lltok::SummaryID) {
11010 VFuncId.GUID = 0;
11011 unsigned ID = Lex.getUIntVal();
11012 LocTy Loc = Lex.getLoc();
11013 // Keep track of the array index needing a forward reference.
11014 // We will save the location of the GUID needing an update, but
11015 // can only do so once the caller's std::vector is finalized.
11016 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
11017 Lex.Lex();
11018 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
11019 parseToken(lltok::colon, "expected ':' here") ||
11020 parseUInt64(VFuncId.GUID))
11021 return true;
11022
11023 if (parseToken(lltok::comma, "expected ',' here") ||
11024 parseToken(lltok::kw_offset, "expected 'offset' here") ||
11025 parseToken(lltok::colon, "expected ':' here") ||
11026 parseUInt64(VFuncId.Offset) ||
11027 parseToken(lltok::rparen, "expected ')' here"))
11028 return true;
11029
11030 return false;
11031}
11032
11033/// GVFlags
11034/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
11035/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
11036/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
11037/// 'canAutoHide' ':' Flag ',' ')'
11038bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
11039 assert(Lex.getKind() == lltok::kw_flags);
11040 Lex.Lex();
11041
11042 if (parseToken(lltok::colon, "expected ':' here") ||
11043 parseToken(lltok::lparen, "expected '(' here"))
11044 return true;
11045
11046 do {
11047 unsigned Flag = 0;
11048 switch (Lex.getKind()) {
11049 case lltok::kw_linkage:
11050 Lex.Lex();
11051 if (parseToken(lltok::colon, "expected ':'"))
11052 return true;
11053 bool HasLinkage;
11054 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
11055 assert(HasLinkage && "Linkage not optional in summary entry");
11056 Lex.Lex();
11057 break;
11059 Lex.Lex();
11060 if (parseToken(lltok::colon, "expected ':'"))
11061 return true;
11062 parseOptionalVisibility(Flag);
11063 GVFlags.Visibility = Flag;
11064 break;
11066 Lex.Lex();
11067 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11068 return true;
11069 GVFlags.NotEligibleToImport = Flag;
11070 break;
11071 case lltok::kw_live:
11072 Lex.Lex();
11073 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11074 return true;
11075 GVFlags.Live = Flag;
11076 break;
11077 case lltok::kw_dsoLocal:
11078 Lex.Lex();
11079 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11080 return true;
11081 GVFlags.DSOLocal = Flag;
11082 break;
11084 Lex.Lex();
11085 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11086 return true;
11087 GVFlags.CanAutoHide = Flag;
11088 break;
11090 Lex.Lex();
11091 if (parseToken(lltok::colon, "expected ':'"))
11092 return true;
11094 if (parseOptionalImportType(Lex.getKind(), IK))
11095 return true;
11096 GVFlags.ImportType = static_cast<unsigned>(IK);
11097 Lex.Lex();
11098 break;
11100 Lex.Lex();
11101 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
11102 return true;
11103 GVFlags.NoRenameOnPromotion = Flag;
11104 break;
11105 default:
11106 return error(Lex.getLoc(), "expected gv flag type");
11107 }
11108 } while (EatIfPresent(lltok::comma));
11109
11110 if (parseToken(lltok::rparen, "expected ')' here"))
11111 return true;
11112
11113 return false;
11114}
11115
11116/// GVarFlags
11117/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
11118/// ',' 'writeonly' ':' Flag
11119/// ',' 'constant' ':' Flag ')'
11120bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
11121 assert(Lex.getKind() == lltok::kw_varFlags);
11122 Lex.Lex();
11123
11124 if (parseToken(lltok::colon, "expected ':' here") ||
11125 parseToken(lltok::lparen, "expected '(' here"))
11126 return true;
11127
11128 auto ParseRest = [this](unsigned int &Val) {
11129 Lex.Lex();
11130 if (parseToken(lltok::colon, "expected ':'"))
11131 return true;
11132 return parseFlag(Val);
11133 };
11134
11135 do {
11136 unsigned Flag = 0;
11137 switch (Lex.getKind()) {
11138 case lltok::kw_readonly:
11139 if (ParseRest(Flag))
11140 return true;
11141 GVarFlags.MaybeReadOnly = Flag;
11142 break;
11143 case lltok::kw_writeonly:
11144 if (ParseRest(Flag))
11145 return true;
11146 GVarFlags.MaybeWriteOnly = Flag;
11147 break;
11148 case lltok::kw_constant:
11149 if (ParseRest(Flag))
11150 return true;
11151 GVarFlags.Constant = Flag;
11152 break;
11154 if (ParseRest(Flag))
11155 return true;
11156 GVarFlags.VCallVisibility = Flag;
11157 break;
11158 default:
11159 return error(Lex.getLoc(), "expected gvar flag type");
11160 }
11161 } while (EatIfPresent(lltok::comma));
11162 return parseToken(lltok::rparen, "expected ')' here");
11163}
11164
11165/// ModuleReference
11166/// ::= 'module' ':' UInt
11167bool LLParser::parseModuleReference(StringRef &ModulePath) {
11168 // parse module id.
11169 if (parseToken(lltok::kw_module, "expected 'module' here") ||
11170 parseToken(lltok::colon, "expected ':' here") ||
11171 parseToken(lltok::SummaryID, "expected module ID"))
11172 return true;
11173
11174 unsigned ModuleID = Lex.getUIntVal();
11175 auto I = ModuleIdMap.find(ModuleID);
11176 // We should have already parsed all module IDs
11177 assert(I != ModuleIdMap.end());
11178 ModulePath = I->second;
11179 return false;
11180}
11181
11182/// GVReference
11183/// ::= SummaryID
11184bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
11185 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
11186 if (!ReadOnly)
11187 WriteOnly = EatIfPresent(lltok::kw_writeonly);
11188 if (parseToken(lltok::SummaryID, "expected GV ID"))
11189 return true;
11190
11191 GVId = Lex.getUIntVal();
11192 // Check if we already have a VI for this GV
11193 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
11194 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
11195 VI = NumberedValueInfos[GVId];
11196 } else
11197 // We will create a forward reference to the stored location.
11198 VI = ValueInfo(false, FwdVIRef);
11199
11200 if (ReadOnly)
11201 VI.setReadOnly();
11202 if (WriteOnly)
11203 VI.setWriteOnly();
11204 return false;
11205}
11206
11207/// OptionalAllocs
11208/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
11209/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
11210/// ',' MemProfs ')'
11211/// Version ::= UInt32
11212bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
11213 assert(Lex.getKind() == lltok::kw_allocs);
11214 Lex.Lex();
11215
11216 if (parseToken(lltok::colon, "expected ':' in allocs") ||
11217 parseToken(lltok::lparen, "expected '(' in allocs"))
11218 return true;
11219
11220 // parse each alloc
11221 do {
11222 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
11223 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
11224 parseToken(lltok::colon, "expected ':'") ||
11225 parseToken(lltok::lparen, "expected '(' in versions"))
11226 return true;
11227
11228 SmallVector<uint8_t> Versions;
11229 do {
11230 uint8_t V = 0;
11231 if (parseAllocType(V))
11232 return true;
11233 Versions.push_back(V);
11234 } while (EatIfPresent(lltok::comma));
11235
11236 if (parseToken(lltok::rparen, "expected ')' in versions") ||
11237 parseToken(lltok::comma, "expected ',' in alloc"))
11238 return true;
11239
11240 std::vector<MIBInfo> MIBs;
11241 if (parseMemProfs(MIBs))
11242 return true;
11243
11244 Allocs.push_back({Versions, MIBs});
11245
11246 if (parseToken(lltok::rparen, "expected ')' in alloc"))
11247 return true;
11248 } while (EatIfPresent(lltok::comma));
11249
11250 if (parseToken(lltok::rparen, "expected ')' in allocs"))
11251 return true;
11252
11253 return false;
11254}
11255
11256/// MemProfs
11257/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
11258/// MemProf ::= '(' 'type' ':' AllocType
11259/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11260/// StackId ::= UInt64
11261bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
11262 assert(Lex.getKind() == lltok::kw_memProf);
11263 Lex.Lex();
11264
11265 if (parseToken(lltok::colon, "expected ':' in memprof") ||
11266 parseToken(lltok::lparen, "expected '(' in memprof"))
11267 return true;
11268
11269 // parse each MIB
11270 do {
11271 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
11272 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
11273 parseToken(lltok::colon, "expected ':'"))
11274 return true;
11275
11276 uint8_t AllocType;
11277 if (parseAllocType(AllocType))
11278 return true;
11279
11280 if (parseToken(lltok::comma, "expected ',' in memprof") ||
11281 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
11282 parseToken(lltok::colon, "expected ':'") ||
11283 parseToken(lltok::lparen, "expected '(' in stackIds"))
11284 return true;
11285
11286 SmallVector<unsigned> StackIdIndices;
11287 // Combined index alloc records may not have a stack id list.
11288 if (Lex.getKind() != lltok::rparen) {
11289 do {
11290 uint64_t StackId = 0;
11291 if (parseUInt64(StackId))
11292 return true;
11293 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11294 } while (EatIfPresent(lltok::comma));
11295 }
11296
11297 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11298 return true;
11299
11300 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
11301
11302 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11303 return true;
11304 } while (EatIfPresent(lltok::comma));
11305
11306 if (parseToken(lltok::rparen, "expected ')' in memprof"))
11307 return true;
11308
11309 return false;
11310}
11311
11312/// AllocType
11313/// := ('none'|'notcold'|'cold'|'hot')
11314bool LLParser::parseAllocType(uint8_t &AllocType) {
11315 switch (Lex.getKind()) {
11316 case lltok::kw_none:
11318 break;
11319 case lltok::kw_notcold:
11321 break;
11322 case lltok::kw_cold:
11324 break;
11325 case lltok::kw_hot:
11326 AllocType = (uint8_t)AllocationType::Hot;
11327 break;
11328 default:
11329 return error(Lex.getLoc(), "invalid alloc type");
11330 }
11331 Lex.Lex();
11332 return false;
11333}
11334
11335/// OptionalCallsites
11336/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
11337/// Callsite ::= '(' 'callee' ':' GVReference
11338/// ',' 'clones' ':' '(' Version [',' Version]* ')'
11339/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
11340/// Version ::= UInt32
11341/// StackId ::= UInt64
11342bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
11343 assert(Lex.getKind() == lltok::kw_callsites);
11344 Lex.Lex();
11345
11346 if (parseToken(lltok::colon, "expected ':' in callsites") ||
11347 parseToken(lltok::lparen, "expected '(' in callsites"))
11348 return true;
11349
11350 IdToIndexMapType IdToIndexMap;
11351 // parse each callsite
11352 do {
11353 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
11354 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
11355 parseToken(lltok::colon, "expected ':'"))
11356 return true;
11357
11358 ValueInfo VI;
11359 unsigned GVId = 0;
11360 LocTy Loc = Lex.getLoc();
11361 if (!EatIfPresent(lltok::kw_null)) {
11362 if (parseGVReference(VI, GVId))
11363 return true;
11364 }
11365
11366 if (parseToken(lltok::comma, "expected ',' in callsite") ||
11367 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
11368 parseToken(lltok::colon, "expected ':'") ||
11369 parseToken(lltok::lparen, "expected '(' in clones"))
11370 return true;
11371
11372 SmallVector<unsigned> Clones;
11373 do {
11374 unsigned V = 0;
11375 if (parseUInt32(V))
11376 return true;
11377 Clones.push_back(V);
11378 } while (EatIfPresent(lltok::comma));
11379
11380 if (parseToken(lltok::rparen, "expected ')' in clones") ||
11381 parseToken(lltok::comma, "expected ',' in callsite") ||
11382 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
11383 parseToken(lltok::colon, "expected ':'") ||
11384 parseToken(lltok::lparen, "expected '(' in stackIds"))
11385 return true;
11386
11387 SmallVector<unsigned> StackIdIndices;
11388 // Synthesized callsite records will not have a stack id list.
11389 if (Lex.getKind() != lltok::rparen) {
11390 do {
11391 uint64_t StackId = 0;
11392 if (parseUInt64(StackId))
11393 return true;
11394 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
11395 } while (EatIfPresent(lltok::comma));
11396 }
11397
11398 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
11399 return true;
11400
11401 // Keep track of the Callsites array index needing a forward reference.
11402 // We will save the location of the ValueInfo needing an update, but
11403 // can only do so once the SmallVector is finalized.
11404 if (VI.getRef() == FwdVIRef)
11405 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
11406 Callsites.push_back({VI, Clones, StackIdIndices});
11407
11408 if (parseToken(lltok::rparen, "expected ')' in callsite"))
11409 return true;
11410 } while (EatIfPresent(lltok::comma));
11411
11412 // Now that the Callsites vector is finalized, it is safe to save the
11413 // locations of any forward GV references that need updating later.
11414 for (auto I : IdToIndexMap) {
11415 auto &Infos = ForwardRefValueInfos[I.first];
11416 for (auto P : I.second) {
11417 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
11418 "Forward referenced ValueInfo expected to be empty");
11419 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
11420 }
11421 }
11422
11423 if (parseToken(lltok::rparen, "expected ')' in callsites"))
11424 return true;
11425
11426 return false;
11427}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
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< 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
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:308
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 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:152
#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)"
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 make_scope_exit function, which executes user-defined cleanup logic at scope ex...
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:297
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:291
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:360
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1244
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:831
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:474
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:1590
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:1462
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.
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, MDNode *DL)
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, MDNode *DI)
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:205
unsigned size() const
Definition DenseMap.h:114
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:469
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:464
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:168
Argument * arg_iterator
Definition Function.h:73
void setPrefixData(Constant *PrefixData)
void setGC(std::string Str)
Definition Function.cpp:823
void setPersonalityFn(Constant *Fn)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:449
arg_iterator arg_begin()
Definition Function.h:868
void setAlignment(Align Align)
Sets the alignment attribute of the Function.
Definition Function.h:1040
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:357
void setPreferredAlignment(MaybeAlign Align)
Sets the prefalign attribute of the Function.
Definition Function.h:1052
void setPrologueData(Constant *PrologueData)
void setCallingConv(CallingConv::ID CC)
Definition Function.h:276
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:676
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:733
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:278
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:339
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
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:309
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.
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:103
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:151
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:225
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
Definition Globals.cpp:315
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:292
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:597
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:644
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:72
LocTy getLoc() const
Definition LLLexer.h:71
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:124
LLLexer::LocTy LocTy
Definition LLParser.h:110
LLVMContext & getContext()
Definition LLParser.h:231
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition LLParser.cpp:108
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition LLParser.cpp:95
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition LLParser.cpp:76
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:1080
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1580
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
A single uniqued string.
Definition Metadata.h:722
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition Metadata.h:1540
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1529
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1549
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:110
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 LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:942
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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:224
iterator find(StringRef Key)
Definition StringMap.h:237
StringMapIterBase< Comdat, false > iterator
Definition StringMap.h:221
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:479
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:685
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition Type.cpp:769
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:604
LLVM_ABI bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition Type.cpp:506
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:980
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:509
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:798
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
Definition Value.cpp:107
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:318
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:599
LLVM_ABI unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition Dwarf.cpp:165
LLVM_ABI unsigned getAttributeEncoding(StringRef EncodingString)
Definition Dwarf.cpp:274
LLVM_ABI unsigned getLanguageDialect(StringRef LanguageDialectString)
Definition Dwarf.cpp:618
LLVM_ABI unsigned getTag(StringRef TagString)
Definition Dwarf.cpp:32
LLVM_ABI unsigned getCallingConvention(StringRef LanguageString)
Definition Dwarf.cpp:654
LLVM_ABI unsigned getLanguage(StringRef LanguageString)
Definition Dwarf.cpp:423
LLVM_ABI unsigned getVirtuality(StringRef VirtualityString)
Definition Dwarf.cpp:385
LLVM_ABI unsigned getEnumKind(StringRef EnumKindString)
Definition Dwarf.cpp:404
LLVM_ABI unsigned getMacinfo(StringRef MacinfoString)
Definition Dwarf.cpp:726
#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
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
@ 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.
@ 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:771
@ 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:821
@ DW_MACINFO_vendor_ext
Definition Dwarf.h:827
@ 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:513
@ DwarfLangDialect
Definition LLToken.h:516
@ 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:424
@ kw_internal
Definition LLToken.h:54
@ kw_target_mem
Definition LLToken.h:211
@ kw_no_sanitize_hwaddress
Definition LLToken.h:492
@ kw_datalayout
Definition LLToken.h:92
@ kw_wpdResolutions
Definition LLToken.h:463
@ kw_canAutoHide
Definition LLToken.h:407
@ kw_alwaysInline
Definition LLToken.h:420
@ 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:533
@ 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:403
@ kw_cheriot_compartmentcalleecc
Definition LLToken.h:193
@ kw_positivezero
Definition LLToken.h:231
@ kw_unordered
Definition LLToken.h:96
@ kw_singleImpl
Definition LLToken.h:466
@ kw_localexec
Definition LLToken.h:75
@ kw_cfguard_checkcc
Definition LLToken.h:141
@ kw_typeCheckedLoadConstVCalls
Definition LLToken.h:443
@ 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:401
@ kw_notEligibleToImport
Definition LLToken.h:404
@ 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:527
@ kw_declaration
Definition LLToken.h:410
@ kw_elementwise
Definition LLToken.h:94
@ DwarfAttEncoding
Definition LLToken.h:512
@ 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:423
@ kw_x86_intrcc
Definition LLToken.h:171
@ kw_addrspacecast
Definition LLToken.h:341
@ kw_zeroinitializer
Definition LLToken.h:76
@ StringConstant
Definition LLToken.h:510
@ kw_x86_thiscallcc
Definition LLToken.h:144
@ kw_cheriot_compartmentcallcc
Definition LLToken.h:192
@ kw_unnamed_addr
Definition LLToken.h:67
@ kw_uselistorder_bb
Definition LLToken.h:391
@ NameTableKind
Definition LLToken.h:519
@ kw_inlineBits
Definition LLToken.h:461
@ 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:442
@ FixedPointKind
Definition LLToken.h:520
@ 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:467
@ kw_typeidCompatibleVTable
Definition LLToken.h:448
@ kw_vTableFuncs
Definition LLToken.h:434
@ kw_volatile
Definition LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition LLToken.h:441
@ kw_no_sanitize_address
Definition LLToken.h:489
@ kw_inaccessiblemem_or_argmemonly
Definition LLToken.h:219
@ kw_externally_initialized
Definition LLToken.h:69
@ kw_sanitize_address_dyninit
Definition LLToken.h:495
@ DwarfSourceLangName
Definition LLToken.h:515
@ kw_noRenameOnPromotion
Definition LLToken.h:411
@ 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:468
@ kw_target_mem0
Definition LLToken.h:212
@ kw_swifttailcc
Definition LLToken.h:166
@ kw_monotonic
Definition LLToken.h:97
@ kw_typeTestAssumeVCalls
Definition LLToken.h:440
@ 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:471
@ kw_sideeffect
Definition LLToken.h:128
@ kw_sizeM1BitWidth
Definition LLToken.h:457
@ 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:418
@ kw_aarch64_sme_preservemost_from_x0
Definition LLToken.h:152
@ kw_preserve_allcc
Definition LLToken.h:168
@ kw_importType
Definition LLToken.h:408
@ 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:409
@ kw_virtualConstProp
Definition LLToken.h:473
@ kw_vcall_visibility
Definition LLToken.h:462
@ 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:450
@ kw_x86_regcallcc
Definition LLToken.h:146
@ kw_typeIdInfo
Definition LLToken.h:438
@ 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:526
@ 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:472
@ 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:558
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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:1668
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.
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:284
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
UWTableKind
Definition CodeGen.h:154
@ Async
"Asynchronous" unwind tables (instr precise)
Definition CodeGen.h:157
@ Sync
"Synchronous" unwind tables
Definition CodeGen.h:156
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:279
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1635
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:371
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:189
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:36
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:2011
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:1916
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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
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.