LLVM 20.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/AutoUpgrade.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/Comdat.h"
29#include "llvm/IR/Constants.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/GlobalIFunc.h"
35#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/Intrinsics.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/Metadata.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Operator.h"
44#include "llvm/IR/Value.h"
49#include "llvm/Support/ModRef.h"
52#include <algorithm>
53#include <cassert>
54#include <cstring>
55#include <optional>
56#include <vector>
57
58using namespace llvm;
59
61 "allow-incomplete-ir", cl::init(false), cl::Hidden,
63 "Allow incomplete IR on a best effort basis (references to unknown "
64 "metadata will be dropped)"));
65
70
71static std::string getTypeString(Type *T) {
72 std::string Result;
73 raw_string_ostream Tmp(Result);
74 Tmp << *T;
75 return Tmp.str();
76}
77
78/// Run: module ::= toplevelentity*
80 DataLayoutCallbackTy DataLayoutCallback) {
81 // Prime the lexer.
82 Lex.Lex();
83
84 if (Context.shouldDiscardValueNames())
85 return error(
86 Lex.getLoc(),
87 "Can't read textual IR with a Context that discards named Values");
88
89 if (M) {
90 if (parseTargetDefinitions(DataLayoutCallback))
91 return true;
92 }
93
94 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
95 validateEndOfIndex();
96}
97
99 const SlotMapping *Slots) {
100 restoreParsingState(Slots);
101 Lex.Lex();
102
103 Type *Ty = nullptr;
104 if (parseType(Ty) || parseConstantValue(Ty, C))
105 return true;
106 if (Lex.getKind() != lltok::Eof)
107 return error(Lex.getLoc(), "expected end of string");
108 return false;
109}
110
112 const SlotMapping *Slots) {
113 restoreParsingState(Slots);
114 Lex.Lex();
115
116 Read = 0;
117 SMLoc Start = Lex.getLoc();
118 Ty = nullptr;
119 if (parseType(Ty))
120 return true;
121 SMLoc End = Lex.getLoc();
122 Read = End.getPointer() - Start.getPointer();
123
124 return false;
125}
126
128 const SlotMapping *Slots) {
129 restoreParsingState(Slots);
130 Lex.Lex();
131
132 Read = 0;
133 SMLoc Start = Lex.getLoc();
134 Result = nullptr;
135 bool Status = parseDIExpressionBody(Result, /*IsDistinct=*/false);
136 SMLoc End = Lex.getLoc();
137 Read = End.getPointer() - Start.getPointer();
138
139 return Status;
140}
141
142void LLParser::restoreParsingState(const SlotMapping *Slots) {
143 if (!Slots)
144 return;
145 NumberedVals = Slots->GlobalValues;
146 NumberedMetadata = Slots->MetadataNodes;
147 for (const auto &I : Slots->NamedTypes)
148 NamedTypes.insert(
149 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
150 for (const auto &I : Slots->Types)
151 NumberedTypes.insert(
152 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
153}
154
156 // White-list intrinsics that are safe to drop.
157 if (!isa<DbgInfoIntrinsic>(II) &&
158 II->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl)
159 return;
160
162 for (Value *V : II->args())
163 if (auto *MV = dyn_cast<MetadataAsValue>(V))
164 if (auto *MD = dyn_cast<MDNode>(MV->getMetadata()))
165 if (MD->isTemporary())
166 MVs.push_back(MV);
167
168 if (!MVs.empty()) {
169 assert(II->use_empty() && "Cannot have uses");
170 II->eraseFromParent();
171
172 // Also remove no longer used MetadataAsValue wrappers.
173 for (MetadataAsValue *MV : MVs)
174 if (MV->use_empty())
175 delete MV;
176 }
177}
178
179void LLParser::dropUnknownMetadataReferences() {
180 auto Pred = [](unsigned MDKind, MDNode *Node) { return Node->isTemporary(); };
181 for (Function &F : *M) {
182 F.eraseMetadataIf(Pred);
184 I.eraseMetadataIf(Pred);
185
186 if (auto *II = dyn_cast<IntrinsicInst>(&I))
188 }
189 }
190
191 for (GlobalVariable &GV : M->globals())
192 GV.eraseMetadataIf(Pred);
193
194 for (const auto &[ID, Info] : make_early_inc_range(ForwardRefMDNodes)) {
195 // Check whether there is only a single use left, which would be in our
196 // own NumberedMetadata.
197 if (Info.first->getNumTemporaryUses() == 1) {
198 NumberedMetadata.erase(ID);
199 ForwardRefMDNodes.erase(ID);
200 }
201 }
202}
203
204/// validateEndOfModule - Do final validity and basic correctness checks at the
205/// end of the module.
206bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
207 if (!M)
208 return false;
209
210 // We should have already returned an error if we observed both intrinsics and
211 // records in this IR.
212 assert(!(SeenNewDbgInfoFormat && SeenOldDbgInfoFormat) &&
213 "Mixed debug intrinsics/records seen without a parsing error?");
215 UseNewDbgInfoFormat = SeenNewDbgInfoFormat;
216 WriteNewDbgInfoFormatToBitcode = SeenNewDbgInfoFormat;
217 WriteNewDbgInfoFormat = SeenNewDbgInfoFormat;
218 M->setNewDbgInfoFormatFlag(SeenNewDbgInfoFormat);
219 }
220
221 // Handle any function attribute group forward references.
222 for (const auto &RAG : ForwardRefAttrGroups) {
223 Value *V = RAG.first;
224 const std::vector<unsigned> &Attrs = RAG.second;
225 AttrBuilder B(Context);
226
227 for (const auto &Attr : Attrs) {
228 auto R = NumberedAttrBuilders.find(Attr);
229 if (R != NumberedAttrBuilders.end())
230 B.merge(R->second);
231 }
232
233 if (Function *Fn = dyn_cast<Function>(V)) {
234 AttributeList AS = Fn->getAttributes();
235 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
236 AS = AS.removeFnAttributes(Context);
237
238 FnAttrs.merge(B);
239
240 // If the alignment was parsed as an attribute, move to the alignment
241 // field.
242 if (MaybeAlign A = FnAttrs.getAlignment()) {
243 Fn->setAlignment(*A);
244 FnAttrs.removeAttribute(Attribute::Alignment);
245 }
246
247 AS = AS.addFnAttributes(Context, FnAttrs);
248 Fn->setAttributes(AS);
249 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
250 AttributeList AS = CI->getAttributes();
251 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
252 AS = AS.removeFnAttributes(Context);
253 FnAttrs.merge(B);
254 AS = AS.addFnAttributes(Context, FnAttrs);
255 CI->setAttributes(AS);
256 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
257 AttributeList AS = II->getAttributes();
258 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
259 AS = AS.removeFnAttributes(Context);
260 FnAttrs.merge(B);
261 AS = AS.addFnAttributes(Context, FnAttrs);
262 II->setAttributes(AS);
263 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
264 AttributeList AS = CBI->getAttributes();
265 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
266 AS = AS.removeFnAttributes(Context);
267 FnAttrs.merge(B);
268 AS = AS.addFnAttributes(Context, FnAttrs);
269 CBI->setAttributes(AS);
270 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
271 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
272 Attrs.merge(B);
273 GV->setAttributes(AttributeSet::get(Context,Attrs));
274 } else {
275 llvm_unreachable("invalid object with forward attribute group reference");
276 }
277 }
278
279 // If there are entries in ForwardRefBlockAddresses at this point, the
280 // function was never defined.
281 if (!ForwardRefBlockAddresses.empty())
282 return error(ForwardRefBlockAddresses.begin()->first.Loc,
283 "expected function name in blockaddress");
284
285 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
286 GlobalValue *FwdRef) {
287 GlobalValue *GV = nullptr;
288 if (GVRef.Kind == ValID::t_GlobalName) {
289 GV = M->getNamedValue(GVRef.StrVal);
290 } else {
291 GV = NumberedVals.get(GVRef.UIntVal);
292 }
293
294 if (!GV)
295 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
296 "' referenced by dso_local_equivalent");
297
298 if (!GV->getValueType()->isFunctionTy())
299 return error(GVRef.Loc,
300 "expected a function, alias to function, or ifunc "
301 "in dso_local_equivalent");
302
303 auto *Equiv = DSOLocalEquivalent::get(GV);
304 FwdRef->replaceAllUsesWith(Equiv);
305 FwdRef->eraseFromParent();
306 return false;
307 };
308
309 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
310 // point, they are references after the function was defined. Resolve those
311 // now.
312 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
313 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
314 return true;
315 }
316 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
317 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
318 return true;
319 }
320 ForwardRefDSOLocalEquivalentIDs.clear();
321 ForwardRefDSOLocalEquivalentNames.clear();
322
323 for (const auto &NT : NumberedTypes)
324 if (NT.second.second.isValid())
325 return error(NT.second.second,
326 "use of undefined type '%" + Twine(NT.first) + "'");
327
328 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
329 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
330 if (I->second.second.isValid())
331 return error(I->second.second,
332 "use of undefined type named '" + I->getKey() + "'");
333
334 if (!ForwardRefComdats.empty())
335 return error(ForwardRefComdats.begin()->second,
336 "use of undefined comdat '$" +
337 ForwardRefComdats.begin()->first + "'");
338
339 for (const auto &[Name, Info] : make_early_inc_range(ForwardRefVals)) {
340 if (StringRef(Name).starts_with("llvm.")) {
342 if (IID == Intrinsic::not_intrinsic)
343 // Don't do anything for unknown intrinsics.
344 continue;
345
346 // Automatically create declarations for intrinsics. Intrinsics can only
347 // be called directly, so the call function type directly determines the
348 // declaration function type.
349 //
350 // Additionally, automatically add the required mangling suffix to the
351 // intrinsic name. This means that we may replace a single forward
352 // declaration with multiple functions here.
353 for (Use &U : make_early_inc_range(Info.first->uses())) {
354 auto *CB = dyn_cast<CallBase>(U.getUser());
355 if (!CB || !CB->isCallee(&U))
356 return error(Info.second, "intrinsic can only be used as callee");
357
358 SmallVector<Type *> OverloadTys;
359 if (!Intrinsic::getIntrinsicSignature(IID, CB->getFunctionType(),
360 OverloadTys))
361 return error(Info.second, "invalid intrinsic signature");
362
363 U.set(Intrinsic::getOrInsertDeclaration(M, IID, OverloadTys));
364 }
365
366 Info.first->eraseFromParent();
367 ForwardRefVals.erase(Name);
368 continue;
369 }
370
371 // If incomplete IR is allowed, also add declarations for
372 // non-intrinsics.
374 continue;
375
376 auto GetCommonFunctionType = [](Value *V) -> FunctionType * {
377 FunctionType *FTy = nullptr;
378 for (Use &U : V->uses()) {
379 auto *CB = dyn_cast<CallBase>(U.getUser());
380 if (!CB || !CB->isCallee(&U) || (FTy && FTy != CB->getFunctionType()))
381 return nullptr;
382 FTy = CB->getFunctionType();
383 }
384 return FTy;
385 };
386
387 // First check whether this global is only used in calls with the same
388 // type, in which case we'll insert a function. Otherwise, fall back to
389 // using a dummy i8 type.
390 Type *Ty = GetCommonFunctionType(Info.first);
391 if (!Ty)
392 Ty = Type::getInt8Ty(Context);
393
394 GlobalValue *GV;
395 if (auto *FTy = dyn_cast<FunctionType>(Ty))
397 else
398 GV = new GlobalVariable(*M, Ty, /*isConstant*/ false,
400 /*Initializer*/ nullptr, Name);
401 Info.first->replaceAllUsesWith(GV);
402 Info.first->eraseFromParent();
403 ForwardRefVals.erase(Name);
404 }
405
406 if (!ForwardRefVals.empty())
407 return error(ForwardRefVals.begin()->second.second,
408 "use of undefined value '@" + ForwardRefVals.begin()->first +
409 "'");
410
411 if (!ForwardRefValIDs.empty())
412 return error(ForwardRefValIDs.begin()->second.second,
413 "use of undefined value '@" +
414 Twine(ForwardRefValIDs.begin()->first) + "'");
415
416 if (AllowIncompleteIR && !ForwardRefMDNodes.empty())
417 dropUnknownMetadataReferences();
418
419 if (!ForwardRefMDNodes.empty())
420 return error(ForwardRefMDNodes.begin()->second.second,
421 "use of undefined metadata '!" +
422 Twine(ForwardRefMDNodes.begin()->first) + "'");
423
424 // Resolve metadata cycles.
425 for (auto &N : NumberedMetadata) {
426 if (N.second && !N.second->isResolved())
427 N.second->resolveCycles();
428 }
429
430 for (auto *Inst : InstsWithTBAATag) {
431 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
432 // With incomplete IR, the tbaa metadata may have been dropped.
434 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
435 if (MD) {
436 auto *UpgradedMD = UpgradeTBAANode(*MD);
437 if (MD != UpgradedMD)
438 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
439 }
440 }
441
442 // Look for intrinsic functions and CallInst that need to be upgraded. We use
443 // make_early_inc_range here because we may remove some functions.
446
447 if (UpgradeDebugInfo)
449
452
454 M->setIsNewDbgInfoFormat(UseNewDbgInfoFormat);
455
456 if (!Slots)
457 return false;
458 // Initialize the slot mapping.
459 // Because by this point we've parsed and validated everything, we can "steal"
460 // the mapping from LLParser as it doesn't need it anymore.
461 Slots->GlobalValues = std::move(NumberedVals);
462 Slots->MetadataNodes = std::move(NumberedMetadata);
463 for (const auto &I : NamedTypes)
464 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
465 for (const auto &I : NumberedTypes)
466 Slots->Types.insert(std::make_pair(I.first, I.second.first));
467
468 return false;
469}
470
471/// Do final validity and basic correctness checks at the end of the index.
472bool LLParser::validateEndOfIndex() {
473 if (!Index)
474 return false;
475
476 if (!ForwardRefValueInfos.empty())
477 return error(ForwardRefValueInfos.begin()->second.front().second,
478 "use of undefined summary '^" +
479 Twine(ForwardRefValueInfos.begin()->first) + "'");
480
481 if (!ForwardRefAliasees.empty())
482 return error(ForwardRefAliasees.begin()->second.front().second,
483 "use of undefined summary '^" +
484 Twine(ForwardRefAliasees.begin()->first) + "'");
485
486 if (!ForwardRefTypeIds.empty())
487 return error(ForwardRefTypeIds.begin()->second.front().second,
488 "use of undefined type id summary '^" +
489 Twine(ForwardRefTypeIds.begin()->first) + "'");
490
491 return false;
492}
493
494//===----------------------------------------------------------------------===//
495// Top-Level Entities
496//===----------------------------------------------------------------------===//
497
498bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
499 // Delay parsing of the data layout string until the target triple is known.
500 // Then, pass both the the target triple and the tentative data layout string
501 // to DataLayoutCallback, allowing to override the DL string.
502 // This enables importing modules with invalid DL strings.
503 std::string TentativeDLStr = M->getDataLayoutStr();
504 LocTy DLStrLoc;
505
506 bool Done = false;
507 while (!Done) {
508 switch (Lex.getKind()) {
509 case lltok::kw_target:
510 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
511 return true;
512 break;
514 if (parseSourceFileName())
515 return true;
516 break;
517 default:
518 Done = true;
519 }
520 }
521 // Run the override callback to potentially change the data layout string, and
522 // parse the data layout string.
523 if (auto LayoutOverride =
524 DataLayoutCallback(M->getTargetTriple(), TentativeDLStr)) {
525 TentativeDLStr = *LayoutOverride;
526 DLStrLoc = {};
527 }
528 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
529 if (!MaybeDL)
530 return error(DLStrLoc, toString(MaybeDL.takeError()));
531 M->setDataLayout(MaybeDL.get());
532 return false;
533}
534
535bool LLParser::parseTopLevelEntities() {
536 // If there is no Module, then parse just the summary index entries.
537 if (!M) {
538 while (true) {
539 switch (Lex.getKind()) {
540 case lltok::Eof:
541 return false;
542 case lltok::SummaryID:
543 if (parseSummaryEntry())
544 return true;
545 break;
547 if (parseSourceFileName())
548 return true;
549 break;
550 default:
551 // Skip everything else
552 Lex.Lex();
553 }
554 }
555 }
556 while (true) {
557 switch (Lex.getKind()) {
558 default:
559 return tokError("expected top-level entity");
560 case lltok::Eof: return false;
562 if (parseDeclare())
563 return true;
564 break;
565 case lltok::kw_define:
566 if (parseDefine())
567 return true;
568 break;
569 case lltok::kw_module:
570 if (parseModuleAsm())
571 return true;
572 break;
574 if (parseUnnamedType())
575 return true;
576 break;
577 case lltok::LocalVar:
578 if (parseNamedType())
579 return true;
580 break;
581 case lltok::GlobalID:
582 if (parseUnnamedGlobal())
583 return true;
584 break;
585 case lltok::GlobalVar:
586 if (parseNamedGlobal())
587 return true;
588 break;
589 case lltok::ComdatVar: if (parseComdat()) return true; break;
590 case lltok::exclaim:
591 if (parseStandaloneMetadata())
592 return true;
593 break;
594 case lltok::SummaryID:
595 if (parseSummaryEntry())
596 return true;
597 break;
599 if (parseNamedMetadata())
600 return true;
601 break;
603 if (parseUnnamedAttrGrp())
604 return true;
605 break;
607 if (parseUseListOrder())
608 return true;
609 break;
611 if (parseUseListOrderBB())
612 return true;
613 break;
614 }
615 }
616}
617
618/// toplevelentity
619/// ::= 'module' 'asm' STRINGCONSTANT
620bool LLParser::parseModuleAsm() {
622 Lex.Lex();
623
624 std::string AsmStr;
625 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
626 parseStringConstant(AsmStr))
627 return true;
628
629 M->appendModuleInlineAsm(AsmStr);
630 return false;
631}
632
633/// toplevelentity
634/// ::= 'target' 'triple' '=' STRINGCONSTANT
635/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
636bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
637 LocTy &DLStrLoc) {
639 std::string Str;
640 switch (Lex.Lex()) {
641 default:
642 return tokError("unknown target property");
643 case lltok::kw_triple:
644 Lex.Lex();
645 if (parseToken(lltok::equal, "expected '=' after target triple") ||
646 parseStringConstant(Str))
647 return true;
648 M->setTargetTriple(Str);
649 return false;
651 Lex.Lex();
652 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
653 return true;
654 DLStrLoc = Lex.getLoc();
655 if (parseStringConstant(TentativeDLStr))
656 return true;
657 return false;
658 }
659}
660
661/// toplevelentity
662/// ::= 'source_filename' '=' STRINGCONSTANT
663bool LLParser::parseSourceFileName() {
665 Lex.Lex();
666 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
667 parseStringConstant(SourceFileName))
668 return true;
669 if (M)
670 M->setSourceFileName(SourceFileName);
671 return false;
672}
673
674/// parseUnnamedType:
675/// ::= LocalVarID '=' 'type' type
676bool LLParser::parseUnnamedType() {
677 LocTy TypeLoc = Lex.getLoc();
678 unsigned TypeID = Lex.getUIntVal();
679 Lex.Lex(); // eat LocalVarID;
680
681 if (parseToken(lltok::equal, "expected '=' after name") ||
682 parseToken(lltok::kw_type, "expected 'type' after '='"))
683 return true;
684
685 Type *Result = nullptr;
686 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
687 return true;
688
689 if (!isa<StructType>(Result)) {
690 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
691 if (Entry.first)
692 return error(TypeLoc, "non-struct types may not be recursive");
693 Entry.first = Result;
694 Entry.second = SMLoc();
695 }
696
697 return false;
698}
699
700/// toplevelentity
701/// ::= LocalVar '=' 'type' type
702bool LLParser::parseNamedType() {
703 std::string Name = Lex.getStrVal();
704 LocTy NameLoc = Lex.getLoc();
705 Lex.Lex(); // eat LocalVar.
706
707 if (parseToken(lltok::equal, "expected '=' after name") ||
708 parseToken(lltok::kw_type, "expected 'type' after name"))
709 return true;
710
711 Type *Result = nullptr;
712 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
713 return true;
714
715 if (!isa<StructType>(Result)) {
716 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
717 if (Entry.first)
718 return error(NameLoc, "non-struct types may not be recursive");
719 Entry.first = Result;
720 Entry.second = SMLoc();
721 }
722
723 return false;
724}
725
726/// toplevelentity
727/// ::= 'declare' FunctionHeader
728bool LLParser::parseDeclare() {
730 Lex.Lex();
731
732 std::vector<std::pair<unsigned, MDNode *>> MDs;
733 while (Lex.getKind() == lltok::MetadataVar) {
734 unsigned MDK;
735 MDNode *N;
736 if (parseMetadataAttachment(MDK, N))
737 return true;
738 MDs.push_back({MDK, N});
739 }
740
741 Function *F;
742 unsigned FunctionNumber = -1;
743 SmallVector<unsigned> UnnamedArgNums;
744 if (parseFunctionHeader(F, false, FunctionNumber, UnnamedArgNums))
745 return true;
746 for (auto &MD : MDs)
747 F->addMetadata(MD.first, *MD.second);
748 return false;
749}
750
751/// toplevelentity
752/// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
753bool LLParser::parseDefine() {
755 Lex.Lex();
756
757 Function *F;
758 unsigned FunctionNumber = -1;
759 SmallVector<unsigned> UnnamedArgNums;
760 return parseFunctionHeader(F, true, FunctionNumber, UnnamedArgNums) ||
761 parseOptionalFunctionMetadata(*F) ||
762 parseFunctionBody(*F, FunctionNumber, UnnamedArgNums);
763}
764
765/// parseGlobalType
766/// ::= 'constant'
767/// ::= 'global'
768bool LLParser::parseGlobalType(bool &IsConstant) {
769 if (Lex.getKind() == lltok::kw_constant)
770 IsConstant = true;
771 else if (Lex.getKind() == lltok::kw_global)
772 IsConstant = false;
773 else {
774 IsConstant = false;
775 return tokError("expected 'global' or 'constant'");
776 }
777 Lex.Lex();
778 return false;
779}
780
781bool LLParser::parseOptionalUnnamedAddr(
782 GlobalVariable::UnnamedAddr &UnnamedAddr) {
783 if (EatIfPresent(lltok::kw_unnamed_addr))
785 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
787 else
788 UnnamedAddr = GlobalValue::UnnamedAddr::None;
789 return false;
790}
791
792/// parseUnnamedGlobal:
793/// OptionalVisibility (ALIAS | IFUNC) ...
794/// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
795/// OptionalDLLStorageClass
796/// ... -> global variable
797/// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
798/// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
799/// OptionalVisibility
800/// OptionalDLLStorageClass
801/// ... -> global variable
802bool LLParser::parseUnnamedGlobal() {
803 unsigned VarID;
804 std::string Name;
805 LocTy NameLoc = Lex.getLoc();
806
807 // Handle the GlobalID form.
808 if (Lex.getKind() == lltok::GlobalID) {
809 VarID = Lex.getUIntVal();
810 if (checkValueID(NameLoc, "global", "@", NumberedVals.getNext(), VarID))
811 return true;
812
813 Lex.Lex(); // eat GlobalID;
814 if (parseToken(lltok::equal, "expected '=' after name"))
815 return true;
816 } else {
817 VarID = NumberedVals.getNext();
818 }
819
820 bool HasLinkage;
821 unsigned Linkage, Visibility, DLLStorageClass;
822 bool DSOLocal;
824 GlobalVariable::UnnamedAddr UnnamedAddr;
825 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
826 DSOLocal) ||
827 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
828 return true;
829
830 switch (Lex.getKind()) {
831 default:
832 return parseGlobal(Name, VarID, NameLoc, Linkage, HasLinkage, Visibility,
833 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
834 case lltok::kw_alias:
835 case lltok::kw_ifunc:
836 return parseAliasOrIFunc(Name, VarID, NameLoc, Linkage, Visibility,
837 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
838 }
839}
840
841/// parseNamedGlobal:
842/// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
843/// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
844/// OptionalVisibility OptionalDLLStorageClass
845/// ... -> global variable
846bool LLParser::parseNamedGlobal() {
848 LocTy NameLoc = Lex.getLoc();
849 std::string Name = Lex.getStrVal();
850 Lex.Lex();
851
852 bool HasLinkage;
853 unsigned Linkage, Visibility, DLLStorageClass;
854 bool DSOLocal;
856 GlobalVariable::UnnamedAddr UnnamedAddr;
857 if (parseToken(lltok::equal, "expected '=' in global variable") ||
858 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
859 DSOLocal) ||
860 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
861 return true;
862
863 switch (Lex.getKind()) {
864 default:
865 return parseGlobal(Name, -1, NameLoc, Linkage, HasLinkage, Visibility,
866 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
867 case lltok::kw_alias:
868 case lltok::kw_ifunc:
869 return parseAliasOrIFunc(Name, -1, NameLoc, Linkage, Visibility,
870 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
871 }
872}
873
874bool LLParser::parseComdat() {
876 std::string Name = Lex.getStrVal();
877 LocTy NameLoc = Lex.getLoc();
878 Lex.Lex();
879
880 if (parseToken(lltok::equal, "expected '=' here"))
881 return true;
882
883 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
884 return tokError("expected comdat type");
885
887 switch (Lex.getKind()) {
888 default:
889 return tokError("unknown selection kind");
890 case lltok::kw_any:
891 SK = Comdat::Any;
892 break;
895 break;
897 SK = Comdat::Largest;
898 break;
901 break;
903 SK = Comdat::SameSize;
904 break;
905 }
906 Lex.Lex();
907
908 // See if the comdat was forward referenced, if so, use the comdat.
909 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
911 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
912 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
913
914 Comdat *C;
915 if (I != ComdatSymTab.end())
916 C = &I->second;
917 else
918 C = M->getOrInsertComdat(Name);
919 C->setSelectionKind(SK);
920
921 return false;
922}
923
924// MDString:
925// ::= '!' STRINGCONSTANT
926bool LLParser::parseMDString(MDString *&Result) {
927 std::string Str;
928 if (parseStringConstant(Str))
929 return true;
930 Result = MDString::get(Context, Str);
931 return false;
932}
933
934// MDNode:
935// ::= '!' MDNodeNumber
936bool LLParser::parseMDNodeID(MDNode *&Result) {
937 // !{ ..., !42, ... }
938 LocTy IDLoc = Lex.getLoc();
939 unsigned MID = 0;
940 if (parseUInt32(MID))
941 return true;
942
943 // If not a forward reference, just return it now.
944 if (NumberedMetadata.count(MID)) {
945 Result = NumberedMetadata[MID];
946 return false;
947 }
948
949 // Otherwise, create MDNode forward reference.
950 auto &FwdRef = ForwardRefMDNodes[MID];
951 FwdRef = std::make_pair(MDTuple::getTemporary(Context, {}), IDLoc);
952
953 Result = FwdRef.first.get();
954 NumberedMetadata[MID].reset(Result);
955 return false;
956}
957
958/// parseNamedMetadata:
959/// !foo = !{ !1, !2 }
960bool LLParser::parseNamedMetadata() {
962 std::string Name = Lex.getStrVal();
963 Lex.Lex();
964
965 if (parseToken(lltok::equal, "expected '=' here") ||
966 parseToken(lltok::exclaim, "Expected '!' here") ||
967 parseToken(lltok::lbrace, "Expected '{' here"))
968 return true;
969
970 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
971 if (Lex.getKind() != lltok::rbrace)
972 do {
973 MDNode *N = nullptr;
974 // parse DIExpressions inline as a special case. They are still MDNodes,
975 // so they can still appear in named metadata. Remove this logic if they
976 // become plain Metadata.
977 if (Lex.getKind() == lltok::MetadataVar &&
978 Lex.getStrVal() == "DIExpression") {
979 if (parseDIExpression(N, /*IsDistinct=*/false))
980 return true;
981 // DIArgLists should only appear inline in a function, as they may
982 // contain LocalAsMetadata arguments which require a function context.
983 } else if (Lex.getKind() == lltok::MetadataVar &&
984 Lex.getStrVal() == "DIArgList") {
985 return tokError("found DIArgList outside of function");
986 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
987 parseMDNodeID(N)) {
988 return true;
989 }
990 NMD->addOperand(N);
991 } while (EatIfPresent(lltok::comma));
992
993 return parseToken(lltok::rbrace, "expected end of metadata node");
994}
995
996/// parseStandaloneMetadata:
997/// !42 = !{...}
998bool LLParser::parseStandaloneMetadata() {
999 assert(Lex.getKind() == lltok::exclaim);
1000 Lex.Lex();
1001 unsigned MetadataID = 0;
1002
1003 MDNode *Init;
1004 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
1005 return true;
1006
1007 // Detect common error, from old metadata syntax.
1008 if (Lex.getKind() == lltok::Type)
1009 return tokError("unexpected type in metadata definition");
1010
1011 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
1012 if (Lex.getKind() == lltok::MetadataVar) {
1013 if (parseSpecializedMDNode(Init, IsDistinct))
1014 return true;
1015 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
1016 parseMDTuple(Init, IsDistinct))
1017 return true;
1018
1019 // See if this was forward referenced, if so, handle it.
1020 auto FI = ForwardRefMDNodes.find(MetadataID);
1021 if (FI != ForwardRefMDNodes.end()) {
1022 auto *ToReplace = FI->second.first.get();
1023 // DIAssignID has its own special forward-reference "replacement" for
1024 // attachments (the temporary attachments are never actually attached).
1025 if (isa<DIAssignID>(Init)) {
1026 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
1027 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
1028 "Inst unexpectedly already has DIAssignID attachment");
1029 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
1030 }
1031 }
1032
1033 ToReplace->replaceAllUsesWith(Init);
1034 ForwardRefMDNodes.erase(FI);
1035
1036 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
1037 } else {
1038 if (NumberedMetadata.count(MetadataID))
1039 return tokError("Metadata id is already used");
1040 NumberedMetadata[MetadataID].reset(Init);
1041 }
1042
1043 return false;
1044}
1045
1046// Skips a single module summary entry.
1047bool LLParser::skipModuleSummaryEntry() {
1048 // Each module summary entry consists of a tag for the entry
1049 // type, followed by a colon, then the fields which may be surrounded by
1050 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
1051 // support is in place we will look for the tokens corresponding to the
1052 // expected tags.
1053 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
1054 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
1056 return tokError(
1057 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
1058 "start of summary entry");
1059 if (Lex.getKind() == lltok::kw_flags)
1060 return parseSummaryIndexFlags();
1061 if (Lex.getKind() == lltok::kw_blockcount)
1062 return parseBlockCount();
1063 Lex.Lex();
1064 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
1065 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
1066 return true;
1067 // Now walk through the parenthesized entry, until the number of open
1068 // parentheses goes back down to 0 (the first '(' was parsed above).
1069 unsigned NumOpenParen = 1;
1070 do {
1071 switch (Lex.getKind()) {
1072 case lltok::lparen:
1073 NumOpenParen++;
1074 break;
1075 case lltok::rparen:
1076 NumOpenParen--;
1077 break;
1078 case lltok::Eof:
1079 return tokError("found end of file while parsing summary entry");
1080 default:
1081 // Skip everything in between parentheses.
1082 break;
1083 }
1084 Lex.Lex();
1085 } while (NumOpenParen > 0);
1086 return false;
1087}
1088
1089/// SummaryEntry
1090/// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1091bool LLParser::parseSummaryEntry() {
1093 unsigned SummaryID = Lex.getUIntVal();
1094
1095 // For summary entries, colons should be treated as distinct tokens,
1096 // not an indication of the end of a label token.
1098
1099 Lex.Lex();
1100 if (parseToken(lltok::equal, "expected '=' here"))
1101 return true;
1102
1103 // If we don't have an index object, skip the summary entry.
1104 if (!Index)
1105 return skipModuleSummaryEntry();
1106
1107 bool result = false;
1108 switch (Lex.getKind()) {
1109 case lltok::kw_gv:
1110 result = parseGVEntry(SummaryID);
1111 break;
1112 case lltok::kw_module:
1113 result = parseModuleEntry(SummaryID);
1114 break;
1115 case lltok::kw_typeid:
1116 result = parseTypeIdEntry(SummaryID);
1117 break;
1119 result = parseTypeIdCompatibleVtableEntry(SummaryID);
1120 break;
1121 case lltok::kw_flags:
1122 result = parseSummaryIndexFlags();
1123 break;
1125 result = parseBlockCount();
1126 break;
1127 default:
1128 result = error(Lex.getLoc(), "unexpected summary kind");
1129 break;
1130 }
1131 Lex.setIgnoreColonInIdentifiers(false);
1132 return result;
1133}
1134
1135static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
1138}
1139static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L) {
1142}
1143
1144// If there was an explicit dso_local, update GV. In the absence of an explicit
1145// dso_local we keep the default value.
1146static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
1147 if (DSOLocal)
1148 GV.setDSOLocal(true);
1149}
1150
1151/// parseAliasOrIFunc:
1152/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1153/// OptionalVisibility OptionalDLLStorageClass
1154/// OptionalThreadLocal OptionalUnnamedAddr
1155/// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1156///
1157/// AliaseeOrResolver
1158/// ::= TypeAndValue
1159///
1160/// SymbolAttrs
1161/// ::= ',' 'partition' StringConstant
1162///
1163/// Everything through OptionalUnnamedAddr has already been parsed.
1164///
1165bool LLParser::parseAliasOrIFunc(const std::string &Name, unsigned NameID,
1166 LocTy NameLoc, unsigned L, unsigned Visibility,
1167 unsigned DLLStorageClass, bool DSOLocal,
1169 GlobalVariable::UnnamedAddr UnnamedAddr) {
1170 bool IsAlias;
1171 if (Lex.getKind() == lltok::kw_alias)
1172 IsAlias = true;
1173 else if (Lex.getKind() == lltok::kw_ifunc)
1174 IsAlias = false;
1175 else
1176 llvm_unreachable("Not an alias or ifunc!");
1177 Lex.Lex();
1178
1180
1181 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1182 return error(NameLoc, "invalid linkage type for alias");
1183
1184 if (!isValidVisibilityForLinkage(Visibility, L))
1185 return error(NameLoc,
1186 "symbol with local linkage must have default visibility");
1187
1188 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1189 return error(NameLoc,
1190 "symbol with local linkage cannot have a DLL storage class");
1191
1192 Type *Ty;
1193 LocTy ExplicitTypeLoc = Lex.getLoc();
1194 if (parseType(Ty) ||
1195 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1196 return true;
1197
1198 Constant *Aliasee;
1199 LocTy AliaseeLoc = Lex.getLoc();
1200 if (Lex.getKind() != lltok::kw_bitcast &&
1203 Lex.getKind() != lltok::kw_inttoptr) {
1204 if (parseGlobalTypeAndValue(Aliasee))
1205 return true;
1206 } else {
1207 // The bitcast dest type is not present, it is implied by the dest type.
1208 ValID ID;
1209 if (parseValID(ID, /*PFS=*/nullptr))
1210 return true;
1211 if (ID.Kind != ValID::t_Constant)
1212 return error(AliaseeLoc, "invalid aliasee");
1213 Aliasee = ID.ConstantVal;
1214 }
1215
1216 Type *AliaseeType = Aliasee->getType();
1217 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1218 if (!PTy)
1219 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1220 unsigned AddrSpace = PTy->getAddressSpace();
1221
1222 GlobalValue *GVal = nullptr;
1223
1224 // See if the alias was forward referenced, if so, prepare to replace the
1225 // forward reference.
1226 if (!Name.empty()) {
1227 auto I = ForwardRefVals.find(Name);
1228 if (I != ForwardRefVals.end()) {
1229 GVal = I->second.first;
1230 ForwardRefVals.erase(Name);
1231 } else if (M->getNamedValue(Name)) {
1232 return error(NameLoc, "redefinition of global '@" + Name + "'");
1233 }
1234 } else {
1235 auto I = ForwardRefValIDs.find(NameID);
1236 if (I != ForwardRefValIDs.end()) {
1237 GVal = I->second.first;
1238 ForwardRefValIDs.erase(I);
1239 }
1240 }
1241
1242 // Okay, create the alias/ifunc but do not insert it into the module yet.
1243 std::unique_ptr<GlobalAlias> GA;
1244 std::unique_ptr<GlobalIFunc> GI;
1245 GlobalValue *GV;
1246 if (IsAlias) {
1247 GA.reset(GlobalAlias::create(Ty, AddrSpace,
1249 Aliasee, /*Parent*/ nullptr));
1250 GV = GA.get();
1251 } else {
1252 GI.reset(GlobalIFunc::create(Ty, AddrSpace,
1254 Aliasee, /*Parent*/ nullptr));
1255 GV = GI.get();
1256 }
1257 GV->setThreadLocalMode(TLM);
1260 GV->setUnnamedAddr(UnnamedAddr);
1261 maybeSetDSOLocal(DSOLocal, *GV);
1262
1263 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1264 // Now parse them if there are any.
1265 while (Lex.getKind() == lltok::comma) {
1266 Lex.Lex();
1267
1268 if (Lex.getKind() == lltok::kw_partition) {
1269 Lex.Lex();
1270 GV->setPartition(Lex.getStrVal());
1271 if (parseToken(lltok::StringConstant, "expected partition string"))
1272 return true;
1273 } else {
1274 return tokError("unknown alias or ifunc property!");
1275 }
1276 }
1277
1278 if (Name.empty())
1279 NumberedVals.add(NameID, GV);
1280
1281 if (GVal) {
1282 // Verify that types agree.
1283 if (GVal->getType() != GV->getType())
1284 return error(
1285 ExplicitTypeLoc,
1286 "forward reference and definition of alias have different types");
1287
1288 // If they agree, just RAUW the old value with the alias and remove the
1289 // forward ref info.
1290 GVal->replaceAllUsesWith(GV);
1291 GVal->eraseFromParent();
1292 }
1293
1294 // Insert into the module, we know its name won't collide now.
1295 if (IsAlias)
1296 M->insertAlias(GA.release());
1297 else
1298 M->insertIFunc(GI.release());
1299 assert(GV->getName() == Name && "Should not be a name conflict!");
1300
1301 return false;
1302}
1303
1304static bool isSanitizer(lltok::Kind Kind) {
1305 switch (Kind) {
1308 case lltok::kw_sanitize_memtag:
1310 return true;
1311 default:
1312 return false;
1313 }
1314}
1315
1316bool LLParser::parseSanitizer(GlobalVariable *GV) {
1319 if (GV->hasSanitizerMetadata())
1320 Meta = GV->getSanitizerMetadata();
1321
1322 switch (Lex.getKind()) {
1324 Meta.NoAddress = true;
1325 break;
1327 Meta.NoHWAddress = true;
1328 break;
1329 case lltok::kw_sanitize_memtag:
1330 Meta.Memtag = true;
1331 break;
1333 Meta.IsDynInit = true;
1334 break;
1335 default:
1336 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1337 }
1338 GV->setSanitizerMetadata(Meta);
1339 Lex.Lex();
1340 return false;
1341}
1342
1343/// parseGlobal
1344/// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1345/// OptionalVisibility OptionalDLLStorageClass
1346/// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1347/// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1348/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1349/// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1350/// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1351/// Const OptionalAttrs
1352///
1353/// Everything up to and including OptionalUnnamedAddr has been parsed
1354/// already.
1355///
1356bool LLParser::parseGlobal(const std::string &Name, unsigned NameID,
1357 LocTy NameLoc, unsigned Linkage, bool HasLinkage,
1358 unsigned Visibility, unsigned DLLStorageClass,
1359 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1360 GlobalVariable::UnnamedAddr UnnamedAddr) {
1361 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1362 return error(NameLoc,
1363 "symbol with local linkage must have default visibility");
1364
1365 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1366 return error(NameLoc,
1367 "symbol with local linkage cannot have a DLL storage class");
1368
1369 unsigned AddrSpace;
1370 bool IsConstant, IsExternallyInitialized;
1371 LocTy IsExternallyInitializedLoc;
1372 LocTy TyLoc;
1373
1374 Type *Ty = nullptr;
1375 if (parseOptionalAddrSpace(AddrSpace) ||
1376 parseOptionalToken(lltok::kw_externally_initialized,
1377 IsExternallyInitialized,
1378 &IsExternallyInitializedLoc) ||
1379 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1380 return true;
1381
1382 // If the linkage is specified and is external, then no initializer is
1383 // present.
1384 Constant *Init = nullptr;
1385 if (!HasLinkage ||
1387 (GlobalValue::LinkageTypes)Linkage)) {
1388 if (parseGlobalValue(Ty, Init))
1389 return true;
1390 }
1391
1393 return error(TyLoc, "invalid type for global variable");
1394
1395 GlobalValue *GVal = nullptr;
1396
1397 // See if the global was forward referenced, if so, use the global.
1398 if (!Name.empty()) {
1399 auto I = ForwardRefVals.find(Name);
1400 if (I != ForwardRefVals.end()) {
1401 GVal = I->second.first;
1402 ForwardRefVals.erase(I);
1403 } else if (M->getNamedValue(Name)) {
1404 return error(NameLoc, "redefinition of global '@" + Name + "'");
1405 }
1406 } else {
1407 // Handle @"", where a name is syntactically specified, but semantically
1408 // missing.
1409 if (NameID == (unsigned)-1)
1410 NameID = NumberedVals.getNext();
1411
1412 auto I = ForwardRefValIDs.find(NameID);
1413 if (I != ForwardRefValIDs.end()) {
1414 GVal = I->second.first;
1415 ForwardRefValIDs.erase(I);
1416 }
1417 }
1418
1420 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1422
1423 if (Name.empty())
1424 NumberedVals.add(NameID, GV);
1425
1426 // Set the parsed properties on the global.
1427 if (Init)
1428 GV->setInitializer(Init);
1429 GV->setConstant(IsConstant);
1431 maybeSetDSOLocal(DSOLocal, *GV);
1434 GV->setExternallyInitialized(IsExternallyInitialized);
1435 GV->setThreadLocalMode(TLM);
1436 GV->setUnnamedAddr(UnnamedAddr);
1437
1438 if (GVal) {
1439 if (GVal->getAddressSpace() != AddrSpace)
1440 return error(
1441 TyLoc,
1442 "forward reference and definition of global have different types");
1443
1444 GVal->replaceAllUsesWith(GV);
1445 GVal->eraseFromParent();
1446 }
1447
1448 // parse attributes on the global.
1449 while (Lex.getKind() == lltok::comma) {
1450 Lex.Lex();
1451
1452 if (Lex.getKind() == lltok::kw_section) {
1453 Lex.Lex();
1454 GV->setSection(Lex.getStrVal());
1455 if (parseToken(lltok::StringConstant, "expected global section string"))
1456 return true;
1457 } else if (Lex.getKind() == lltok::kw_partition) {
1458 Lex.Lex();
1459 GV->setPartition(Lex.getStrVal());
1460 if (parseToken(lltok::StringConstant, "expected partition string"))
1461 return true;
1462 } else if (Lex.getKind() == lltok::kw_align) {
1463 MaybeAlign Alignment;
1464 if (parseOptionalAlignment(Alignment))
1465 return true;
1466 if (Alignment)
1467 GV->setAlignment(*Alignment);
1468 } else if (Lex.getKind() == lltok::kw_code_model) {
1470 if (parseOptionalCodeModel(CodeModel))
1471 return true;
1472 GV->setCodeModel(CodeModel);
1473 } else if (Lex.getKind() == lltok::MetadataVar) {
1474 if (parseGlobalObjectMetadataAttachment(*GV))
1475 return true;
1476 } else if (isSanitizer(Lex.getKind())) {
1477 if (parseSanitizer(GV))
1478 return true;
1479 } else {
1480 Comdat *C;
1481 if (parseOptionalComdat(Name, C))
1482 return true;
1483 if (C)
1484 GV->setComdat(C);
1485 else
1486 return tokError("unknown global variable property!");
1487 }
1488 }
1489
1490 AttrBuilder Attrs(M->getContext());
1491 LocTy BuiltinLoc;
1492 std::vector<unsigned> FwdRefAttrGrps;
1493 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1494 return true;
1495 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1496 GV->setAttributes(AttributeSet::get(Context, Attrs));
1497 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1498 }
1499
1500 return false;
1501}
1502
1503/// parseUnnamedAttrGrp
1504/// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1505bool LLParser::parseUnnamedAttrGrp() {
1507 LocTy AttrGrpLoc = Lex.getLoc();
1508 Lex.Lex();
1509
1510 if (Lex.getKind() != lltok::AttrGrpID)
1511 return tokError("expected attribute group id");
1512
1513 unsigned VarID = Lex.getUIntVal();
1514 std::vector<unsigned> unused;
1515 LocTy BuiltinLoc;
1516 Lex.Lex();
1517
1518 if (parseToken(lltok::equal, "expected '=' here") ||
1519 parseToken(lltok::lbrace, "expected '{' here"))
1520 return true;
1521
1522 auto R = NumberedAttrBuilders.find(VarID);
1523 if (R == NumberedAttrBuilders.end())
1524 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1525
1526 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1527 parseToken(lltok::rbrace, "expected end of attribute group"))
1528 return true;
1529
1530 if (!R->second.hasAttributes())
1531 return error(AttrGrpLoc, "attribute group has no attributes");
1532
1533 return false;
1534}
1535
1537 switch (Kind) {
1538#define GET_ATTR_NAMES
1539#define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1540 case lltok::kw_##DISPLAY_NAME: \
1541 return Attribute::ENUM_NAME;
1542#include "llvm/IR/Attributes.inc"
1543 default:
1544 return Attribute::None;
1545 }
1546}
1547
1548bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1549 bool InAttrGroup) {
1550 if (Attribute::isTypeAttrKind(Attr))
1551 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1552
1553 switch (Attr) {
1554 case Attribute::Alignment: {
1555 MaybeAlign Alignment;
1556 if (InAttrGroup) {
1557 uint32_t Value = 0;
1558 Lex.Lex();
1559 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1560 return true;
1561 Alignment = Align(Value);
1562 } else {
1563 if (parseOptionalAlignment(Alignment, true))
1564 return true;
1565 }
1566 B.addAlignmentAttr(Alignment);
1567 return false;
1568 }
1569 case Attribute::StackAlignment: {
1570 unsigned Alignment;
1571 if (InAttrGroup) {
1572 Lex.Lex();
1573 if (parseToken(lltok::equal, "expected '=' here") ||
1574 parseUInt32(Alignment))
1575 return true;
1576 } else {
1577 if (parseOptionalStackAlignment(Alignment))
1578 return true;
1579 }
1580 B.addStackAlignmentAttr(Alignment);
1581 return false;
1582 }
1583 case Attribute::AllocSize: {
1584 unsigned ElemSizeArg;
1585 std::optional<unsigned> NumElemsArg;
1586 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1587 return true;
1588 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1589 return false;
1590 }
1591 case Attribute::VScaleRange: {
1592 unsigned MinValue, MaxValue;
1593 if (parseVScaleRangeArguments(MinValue, MaxValue))
1594 return true;
1595 B.addVScaleRangeAttr(MinValue,
1596 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1597 return false;
1598 }
1599 case Attribute::Dereferenceable: {
1600 uint64_t Bytes;
1601 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1602 return true;
1603 B.addDereferenceableAttr(Bytes);
1604 return false;
1605 }
1606 case Attribute::DereferenceableOrNull: {
1607 uint64_t Bytes;
1608 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1609 return true;
1610 B.addDereferenceableOrNullAttr(Bytes);
1611 return false;
1612 }
1613 case Attribute::UWTable: {
1615 if (parseOptionalUWTableKind(Kind))
1616 return true;
1617 B.addUWTableAttr(Kind);
1618 return false;
1619 }
1620 case Attribute::AllocKind: {
1622 if (parseAllocKind(Kind))
1623 return true;
1624 B.addAllocKindAttr(Kind);
1625 return false;
1626 }
1627 case Attribute::Memory: {
1628 std::optional<MemoryEffects> ME = parseMemoryAttr();
1629 if (!ME)
1630 return true;
1631 B.addMemoryAttr(*ME);
1632 return false;
1633 }
1634 case Attribute::NoFPClass: {
1635 if (FPClassTest NoFPClass =
1636 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1637 B.addNoFPClassAttr(NoFPClass);
1638 return false;
1639 }
1640
1641 return true;
1642 }
1643 case Attribute::Range:
1644 return parseRangeAttr(B);
1645 case Attribute::Initializes:
1646 return parseInitializesAttr(B);
1647 case Attribute::Captures:
1648 return parseCapturesAttr(B);
1649 default:
1650 B.addAttribute(Attr);
1651 Lex.Lex();
1652 return false;
1653 }
1654}
1655
1657 switch (Kind) {
1658 case lltok::kw_readnone:
1659 ME &= MemoryEffects::none();
1660 return true;
1661 case lltok::kw_readonly:
1663 return true;
1664 case lltok::kw_writeonly:
1666 return true;
1669 return true;
1672 return true;
1675 return true;
1676 default:
1677 return false;
1678 }
1679}
1680
1681/// parseFnAttributeValuePairs
1682/// ::= <attr> | <attr> '=' <value>
1683bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1684 std::vector<unsigned> &FwdRefAttrGrps,
1685 bool InAttrGrp, LocTy &BuiltinLoc) {
1686 bool HaveError = false;
1687
1688 B.clear();
1689
1691 while (true) {
1692 lltok::Kind Token = Lex.getKind();
1693 if (Token == lltok::rbrace)
1694 break; // Finished.
1695
1696 if (Token == lltok::StringConstant) {
1697 if (parseStringAttribute(B))
1698 return true;
1699 continue;
1700 }
1701
1702 if (Token == lltok::AttrGrpID) {
1703 // Allow a function to reference an attribute group:
1704 //
1705 // define void @foo() #1 { ... }
1706 if (InAttrGrp) {
1707 HaveError |= error(
1708 Lex.getLoc(),
1709 "cannot have an attribute group reference in an attribute group");
1710 } else {
1711 // Save the reference to the attribute group. We'll fill it in later.
1712 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1713 }
1714 Lex.Lex();
1715 continue;
1716 }
1717
1718 SMLoc Loc = Lex.getLoc();
1719 if (Token == lltok::kw_builtin)
1720 BuiltinLoc = Loc;
1721
1722 if (upgradeMemoryAttr(ME, Token)) {
1723 Lex.Lex();
1724 continue;
1725 }
1726
1728 if (Attr == Attribute::None) {
1729 if (!InAttrGrp)
1730 break;
1731 return error(Lex.getLoc(), "unterminated attribute group");
1732 }
1733
1734 if (parseEnumAttribute(Attr, B, InAttrGrp))
1735 return true;
1736
1737 // As a hack, we allow function alignment to be initially parsed as an
1738 // attribute on a function declaration/definition or added to an attribute
1739 // group and later moved to the alignment field.
1740 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1741 HaveError |= error(Loc, "this attribute does not apply to functions");
1742 }
1743
1744 if (ME != MemoryEffects::unknown())
1745 B.addMemoryAttr(ME);
1746 return HaveError;
1747}
1748
1749//===----------------------------------------------------------------------===//
1750// GlobalValue Reference/Resolution Routines.
1751//===----------------------------------------------------------------------===//
1752
1754 // The used global type does not matter. We will later RAUW it with a
1755 // global/function of the correct type.
1756 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1759 PTy->getAddressSpace());
1760}
1761
1762Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1763 Value *Val) {
1764 Type *ValTy = Val->getType();
1765 if (ValTy == Ty)
1766 return Val;
1767 if (Ty->isLabelTy())
1768 error(Loc, "'" + Name + "' is not a basic block");
1769 else
1770 error(Loc, "'" + Name + "' defined with type '" +
1771 getTypeString(Val->getType()) + "' but expected '" +
1772 getTypeString(Ty) + "'");
1773 return nullptr;
1774}
1775
1776/// getGlobalVal - Get a value with the specified name or ID, creating a
1777/// forward reference record if needed. This can return null if the value
1778/// exists but does not have the right type.
1779GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1780 LocTy Loc) {
1781 PointerType *PTy = dyn_cast<PointerType>(Ty);
1782 if (!PTy) {
1783 error(Loc, "global variable reference must have pointer type");
1784 return nullptr;
1785 }
1786
1787 // Look this name up in the normal function symbol table.
1788 GlobalValue *Val =
1789 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1790
1791 // If this is a forward reference for the value, see if we already created a
1792 // forward ref record.
1793 if (!Val) {
1794 auto I = ForwardRefVals.find(Name);
1795 if (I != ForwardRefVals.end())
1796 Val = I->second.first;
1797 }
1798
1799 // If we have the value in the symbol table or fwd-ref table, return it.
1800 if (Val)
1801 return cast_or_null<GlobalValue>(
1802 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1803
1804 // Otherwise, create a new forward reference for this value and remember it.
1805 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1806 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1807 return FwdVal;
1808}
1809
1810GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1811 PointerType *PTy = dyn_cast<PointerType>(Ty);
1812 if (!PTy) {
1813 error(Loc, "global variable reference must have pointer type");
1814 return nullptr;
1815 }
1816
1817 GlobalValue *Val = NumberedVals.get(ID);
1818
1819 // If this is a forward reference for the value, see if we already created a
1820 // forward ref record.
1821 if (!Val) {
1822 auto I = ForwardRefValIDs.find(ID);
1823 if (I != ForwardRefValIDs.end())
1824 Val = I->second.first;
1825 }
1826
1827 // If we have the value in the symbol table or fwd-ref table, return it.
1828 if (Val)
1829 return cast_or_null<GlobalValue>(
1830 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1831
1832 // Otherwise, create a new forward reference for this value and remember it.
1833 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1834 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1835 return FwdVal;
1836}
1837
1838//===----------------------------------------------------------------------===//
1839// Comdat Reference/Resolution Routines.
1840//===----------------------------------------------------------------------===//
1841
1842Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1843 // Look this name up in the comdat symbol table.
1844 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1846 if (I != ComdatSymTab.end())
1847 return &I->second;
1848
1849 // Otherwise, create a new forward reference for this value and remember it.
1850 Comdat *C = M->getOrInsertComdat(Name);
1851 ForwardRefComdats[Name] = Loc;
1852 return C;
1853}
1854
1855//===----------------------------------------------------------------------===//
1856// Helper Routines.
1857//===----------------------------------------------------------------------===//
1858
1859/// parseToken - If the current token has the specified kind, eat it and return
1860/// success. Otherwise, emit the specified error and return failure.
1861bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1862 if (Lex.getKind() != T)
1863 return tokError(ErrMsg);
1864 Lex.Lex();
1865 return false;
1866}
1867
1868/// parseStringConstant
1869/// ::= StringConstant
1870bool LLParser::parseStringConstant(std::string &Result) {
1871 if (Lex.getKind() != lltok::StringConstant)
1872 return tokError("expected string constant");
1873 Result = Lex.getStrVal();
1874 Lex.Lex();
1875 return false;
1876}
1877
1878/// parseUInt32
1879/// ::= uint32
1880bool LLParser::parseUInt32(uint32_t &Val) {
1881 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1882 return tokError("expected integer");
1883 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1884 if (Val64 != unsigned(Val64))
1885 return tokError("expected 32-bit integer (too large)");
1886 Val = Val64;
1887 Lex.Lex();
1888 return false;
1889}
1890
1891/// parseUInt64
1892/// ::= uint64
1893bool LLParser::parseUInt64(uint64_t &Val) {
1894 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1895 return tokError("expected integer");
1896 Val = Lex.getAPSIntVal().getLimitedValue();
1897 Lex.Lex();
1898 return false;
1899}
1900
1901/// parseTLSModel
1902/// := 'localdynamic'
1903/// := 'initialexec'
1904/// := 'localexec'
1905bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1906 switch (Lex.getKind()) {
1907 default:
1908 return tokError("expected localdynamic, initialexec or localexec");
1911 break;
1914 break;
1917 break;
1918 }
1919
1920 Lex.Lex();
1921 return false;
1922}
1923
1924/// parseOptionalThreadLocal
1925/// := /*empty*/
1926/// := 'thread_local'
1927/// := 'thread_local' '(' tlsmodel ')'
1928bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1930 if (!EatIfPresent(lltok::kw_thread_local))
1931 return false;
1932
1934 if (Lex.getKind() == lltok::lparen) {
1935 Lex.Lex();
1936 return parseTLSModel(TLM) ||
1937 parseToken(lltok::rparen, "expected ')' after thread local model");
1938 }
1939 return false;
1940}
1941
1942/// parseOptionalAddrSpace
1943/// := /*empty*/
1944/// := 'addrspace' '(' uint32 ')'
1945bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1946 AddrSpace = DefaultAS;
1947 if (!EatIfPresent(lltok::kw_addrspace))
1948 return false;
1949
1950 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1951 if (Lex.getKind() == lltok::StringConstant) {
1952 auto AddrSpaceStr = Lex.getStrVal();
1953 if (AddrSpaceStr == "A") {
1954 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1955 } else if (AddrSpaceStr == "G") {
1956 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1957 } else if (AddrSpaceStr == "P") {
1958 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1959 } else {
1960 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1961 }
1962 Lex.Lex();
1963 return false;
1964 }
1965 if (Lex.getKind() != lltok::APSInt)
1966 return tokError("expected integer or string constant");
1967 SMLoc Loc = Lex.getLoc();
1968 if (parseUInt32(AddrSpace))
1969 return true;
1970 if (!isUInt<24>(AddrSpace))
1971 return error(Loc, "invalid address space, must be a 24-bit integer");
1972 return false;
1973 };
1974
1975 return parseToken(lltok::lparen, "expected '(' in address space") ||
1976 ParseAddrspaceValue(AddrSpace) ||
1977 parseToken(lltok::rparen, "expected ')' in address space");
1978}
1979
1980/// parseStringAttribute
1981/// := StringConstant
1982/// := StringConstant '=' StringConstant
1983bool LLParser::parseStringAttribute(AttrBuilder &B) {
1984 std::string Attr = Lex.getStrVal();
1985 Lex.Lex();
1986 std::string Val;
1987 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1988 return true;
1989 B.addAttribute(Attr, Val);
1990 return false;
1991}
1992
1993/// Parse a potentially empty list of parameter or return attributes.
1994bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1995 bool HaveError = false;
1996
1997 B.clear();
1998
1999 while (true) {
2000 lltok::Kind Token = Lex.getKind();
2001 if (Token == lltok::StringConstant) {
2002 if (parseStringAttribute(B))
2003 return true;
2004 continue;
2005 }
2006
2007 SMLoc Loc = Lex.getLoc();
2009 if (Attr == Attribute::None)
2010 return HaveError;
2011
2012 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
2013 return true;
2014
2015 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
2016 HaveError |= error(Loc, "this attribute does not apply to parameters");
2017 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
2018 HaveError |= error(Loc, "this attribute does not apply to return values");
2019 }
2020}
2021
2022static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
2023 HasLinkage = true;
2024 switch (Kind) {
2025 default:
2026 HasLinkage = false;
2028 case lltok::kw_private:
2030 case lltok::kw_internal:
2032 case lltok::kw_weak:
2034 case lltok::kw_weak_odr:
2036 case lltok::kw_linkonce:
2044 case lltok::kw_common:
2048 case lltok::kw_external:
2050 }
2051}
2052
2053/// parseOptionalLinkage
2054/// ::= /*empty*/
2055/// ::= 'private'
2056/// ::= 'internal'
2057/// ::= 'weak'
2058/// ::= 'weak_odr'
2059/// ::= 'linkonce'
2060/// ::= 'linkonce_odr'
2061/// ::= 'available_externally'
2062/// ::= 'appending'
2063/// ::= 'common'
2064/// ::= 'extern_weak'
2065/// ::= 'external'
2066bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
2067 unsigned &Visibility,
2068 unsigned &DLLStorageClass, bool &DSOLocal) {
2069 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
2070 if (HasLinkage)
2071 Lex.Lex();
2072 parseOptionalDSOLocal(DSOLocal);
2073 parseOptionalVisibility(Visibility);
2074 parseOptionalDLLStorageClass(DLLStorageClass);
2075
2076 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
2077 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
2078 }
2079
2080 return false;
2081}
2082
2083void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
2084 switch (Lex.getKind()) {
2085 default:
2086 DSOLocal = false;
2087 break;
2089 DSOLocal = true;
2090 Lex.Lex();
2091 break;
2093 DSOLocal = false;
2094 Lex.Lex();
2095 break;
2096 }
2097}
2098
2099/// parseOptionalVisibility
2100/// ::= /*empty*/
2101/// ::= 'default'
2102/// ::= 'hidden'
2103/// ::= 'protected'
2104///
2105void LLParser::parseOptionalVisibility(unsigned &Res) {
2106 switch (Lex.getKind()) {
2107 default:
2109 return;
2110 case lltok::kw_default:
2112 break;
2113 case lltok::kw_hidden:
2115 break;
2118 break;
2119 }
2120 Lex.Lex();
2121}
2122
2123bool LLParser::parseOptionalImportType(lltok::Kind Kind,
2125 switch (Kind) {
2126 default:
2127 return tokError("unknown import kind. Expect definition or declaration.");
2130 return false;
2133 return false;
2134 }
2135}
2136
2137/// parseOptionalDLLStorageClass
2138/// ::= /*empty*/
2139/// ::= 'dllimport'
2140/// ::= 'dllexport'
2141///
2142void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
2143 switch (Lex.getKind()) {
2144 default:
2146 return;
2149 break;
2152 break;
2153 }
2154 Lex.Lex();
2155}
2156
2157/// parseOptionalCallingConv
2158/// ::= /*empty*/
2159/// ::= 'ccc'
2160/// ::= 'fastcc'
2161/// ::= 'intel_ocl_bicc'
2162/// ::= 'coldcc'
2163/// ::= 'cfguard_checkcc'
2164/// ::= 'x86_stdcallcc'
2165/// ::= 'x86_fastcallcc'
2166/// ::= 'x86_thiscallcc'
2167/// ::= 'x86_vectorcallcc'
2168/// ::= 'arm_apcscc'
2169/// ::= 'arm_aapcscc'
2170/// ::= 'arm_aapcs_vfpcc'
2171/// ::= 'aarch64_vector_pcs'
2172/// ::= 'aarch64_sve_vector_pcs'
2173/// ::= 'aarch64_sme_preservemost_from_x0'
2174/// ::= 'aarch64_sme_preservemost_from_x1'
2175/// ::= 'aarch64_sme_preservemost_from_x2'
2176/// ::= 'msp430_intrcc'
2177/// ::= 'avr_intrcc'
2178/// ::= 'avr_signalcc'
2179/// ::= 'ptx_kernel'
2180/// ::= 'ptx_device'
2181/// ::= 'spir_func'
2182/// ::= 'spir_kernel'
2183/// ::= 'x86_64_sysvcc'
2184/// ::= 'win64cc'
2185/// ::= 'anyregcc'
2186/// ::= 'preserve_mostcc'
2187/// ::= 'preserve_allcc'
2188/// ::= 'preserve_nonecc'
2189/// ::= 'ghccc'
2190/// ::= 'swiftcc'
2191/// ::= 'swifttailcc'
2192/// ::= 'x86_intrcc'
2193/// ::= 'hhvmcc'
2194/// ::= 'hhvm_ccc'
2195/// ::= 'cxx_fast_tlscc'
2196/// ::= 'amdgpu_vs'
2197/// ::= 'amdgpu_ls'
2198/// ::= 'amdgpu_hs'
2199/// ::= 'amdgpu_es'
2200/// ::= 'amdgpu_gs'
2201/// ::= 'amdgpu_ps'
2202/// ::= 'amdgpu_cs'
2203/// ::= 'amdgpu_cs_chain'
2204/// ::= 'amdgpu_cs_chain_preserve'
2205/// ::= 'amdgpu_kernel'
2206/// ::= 'tailcc'
2207/// ::= 'm68k_rtdcc'
2208/// ::= 'graalcc'
2209/// ::= 'riscv_vector_cc'
2210/// ::= 'cc' UINT
2211///
2212bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2213 switch (Lex.getKind()) {
2214 default: CC = CallingConv::C; return false;
2215 case lltok::kw_ccc: CC = CallingConv::C; break;
2216 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2217 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2230 break;
2233 break;
2236 break;
2239 break;
2254 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2258 case lltok::kw_hhvmcc:
2260 break;
2261 case lltok::kw_hhvm_ccc:
2263 break;
2275 break;
2278 break;
2280 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2285 break;
2286 case lltok::kw_cc: {
2287 Lex.Lex();
2288 return parseUInt32(CC);
2289 }
2290 }
2291
2292 Lex.Lex();
2293 return false;
2294}
2295
2296/// parseMetadataAttachment
2297/// ::= !dbg !42
2298bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2299 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2300
2301 std::string Name = Lex.getStrVal();
2302 Kind = M->getMDKindID(Name);
2303 Lex.Lex();
2304
2305 return parseMDNode(MD);
2306}
2307
2308/// parseInstructionMetadata
2309/// ::= !dbg !42 (',' !dbg !57)*
2310bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2311 do {
2312 if (Lex.getKind() != lltok::MetadataVar)
2313 return tokError("expected metadata after comma");
2314
2315 unsigned MDK;
2316 MDNode *N;
2317 if (parseMetadataAttachment(MDK, N))
2318 return true;
2319
2320 if (MDK == LLVMContext::MD_DIAssignID)
2321 TempDIAssignIDAttachments[N].push_back(&Inst);
2322 else
2323 Inst.setMetadata(MDK, N);
2324
2325 if (MDK == LLVMContext::MD_tbaa)
2326 InstsWithTBAATag.push_back(&Inst);
2327
2328 // If this is the end of the list, we're done.
2329 } while (EatIfPresent(lltok::comma));
2330 return false;
2331}
2332
2333/// parseGlobalObjectMetadataAttachment
2334/// ::= !dbg !57
2335bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2336 unsigned MDK;
2337 MDNode *N;
2338 if (parseMetadataAttachment(MDK, N))
2339 return true;
2340
2341 GO.addMetadata(MDK, *N);
2342 return false;
2343}
2344
2345/// parseOptionalFunctionMetadata
2346/// ::= (!dbg !57)*
2347bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2348 while (Lex.getKind() == lltok::MetadataVar)
2349 if (parseGlobalObjectMetadataAttachment(F))
2350 return true;
2351 return false;
2352}
2353
2354/// parseOptionalAlignment
2355/// ::= /* empty */
2356/// ::= 'align' 4
2357bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2358 Alignment = std::nullopt;
2359 if (!EatIfPresent(lltok::kw_align))
2360 return false;
2361 LocTy AlignLoc = Lex.getLoc();
2362 uint64_t Value = 0;
2363
2364 LocTy ParenLoc = Lex.getLoc();
2365 bool HaveParens = false;
2366 if (AllowParens) {
2367 if (EatIfPresent(lltok::lparen))
2368 HaveParens = true;
2369 }
2370
2371 if (parseUInt64(Value))
2372 return true;
2373
2374 if (HaveParens && !EatIfPresent(lltok::rparen))
2375 return error(ParenLoc, "expected ')'");
2376
2377 if (!isPowerOf2_64(Value))
2378 return error(AlignLoc, "alignment is not a power of two");
2380 return error(AlignLoc, "huge alignments are not supported yet");
2381 Alignment = Align(Value);
2382 return false;
2383}
2384
2385/// parseOptionalCodeModel
2386/// ::= /* empty */
2387/// ::= 'code_model' "large"
2388bool LLParser::parseOptionalCodeModel(CodeModel::Model &model) {
2389 Lex.Lex();
2390 auto StrVal = Lex.getStrVal();
2391 auto ErrMsg = "expected global code model string";
2392 if (StrVal == "tiny")
2393 model = CodeModel::Tiny;
2394 else if (StrVal == "small")
2395 model = CodeModel::Small;
2396 else if (StrVal == "kernel")
2397 model = CodeModel::Kernel;
2398 else if (StrVal == "medium")
2399 model = CodeModel::Medium;
2400 else if (StrVal == "large")
2401 model = CodeModel::Large;
2402 else
2403 return tokError(ErrMsg);
2404 if (parseToken(lltok::StringConstant, ErrMsg))
2405 return true;
2406 return false;
2407}
2408
2409/// parseOptionalDerefAttrBytes
2410/// ::= /* empty */
2411/// ::= AttrKind '(' 4 ')'
2412///
2413/// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2414bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2415 uint64_t &Bytes) {
2416 assert((AttrKind == lltok::kw_dereferenceable ||
2417 AttrKind == lltok::kw_dereferenceable_or_null) &&
2418 "contract!");
2419
2420 Bytes = 0;
2421 if (!EatIfPresent(AttrKind))
2422 return false;
2423 LocTy ParenLoc = Lex.getLoc();
2424 if (!EatIfPresent(lltok::lparen))
2425 return error(ParenLoc, "expected '('");
2426 LocTy DerefLoc = Lex.getLoc();
2427 if (parseUInt64(Bytes))
2428 return true;
2429 ParenLoc = Lex.getLoc();
2430 if (!EatIfPresent(lltok::rparen))
2431 return error(ParenLoc, "expected ')'");
2432 if (!Bytes)
2433 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2434 return false;
2435}
2436
2437bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2438 Lex.Lex();
2440 if (!EatIfPresent(lltok::lparen))
2441 return false;
2442 LocTy KindLoc = Lex.getLoc();
2443 if (Lex.getKind() == lltok::kw_sync)
2445 else if (Lex.getKind() == lltok::kw_async)
2447 else
2448 return error(KindLoc, "expected unwind table kind");
2449 Lex.Lex();
2450 return parseToken(lltok::rparen, "expected ')'");
2451}
2452
2453bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2454 Lex.Lex();
2455 LocTy ParenLoc = Lex.getLoc();
2456 if (!EatIfPresent(lltok::lparen))
2457 return error(ParenLoc, "expected '('");
2458 LocTy KindLoc = Lex.getLoc();
2459 std::string Arg;
2460 if (parseStringConstant(Arg))
2461 return error(KindLoc, "expected allockind value");
2462 for (StringRef A : llvm::split(Arg, ",")) {
2463 if (A == "alloc") {
2465 } else if (A == "realloc") {
2467 } else if (A == "free") {
2469 } else if (A == "uninitialized") {
2471 } else if (A == "zeroed") {
2473 } else if (A == "aligned") {
2475 } else {
2476 return error(KindLoc, Twine("unknown allockind ") + A);
2477 }
2478 }
2479 ParenLoc = Lex.getLoc();
2480 if (!EatIfPresent(lltok::rparen))
2481 return error(ParenLoc, "expected ')'");
2482 if (Kind == AllocFnKind::Unknown)
2483 return error(KindLoc, "expected allockind value");
2484 return false;
2485}
2486
2487static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2488 switch (Tok) {
2489 case lltok::kw_argmem:
2490 return IRMemLocation::ArgMem;
2493 default:
2494 return std::nullopt;
2495 }
2496}
2497
2498static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2499 switch (Tok) {
2500 case lltok::kw_none:
2501 return ModRefInfo::NoModRef;
2502 case lltok::kw_read:
2503 return ModRefInfo::Ref;
2504 case lltok::kw_write:
2505 return ModRefInfo::Mod;
2507 return ModRefInfo::ModRef;
2508 default:
2509 return std::nullopt;
2510 }
2511}
2512
2513std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2515
2516 // We use syntax like memory(argmem: read), so the colon should not be
2517 // interpreted as a label terminator.
2519 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
2520
2521 Lex.Lex();
2522 if (!EatIfPresent(lltok::lparen)) {
2523 tokError("expected '('");
2524 return std::nullopt;
2525 }
2526
2527 bool SeenLoc = false;
2528 do {
2529 std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
2530 if (Loc) {
2531 Lex.Lex();
2532 if (!EatIfPresent(lltok::colon)) {
2533 tokError("expected ':' after location");
2534 return std::nullopt;
2535 }
2536 }
2537
2538 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2539 if (!MR) {
2540 if (!Loc)
2541 tokError("expected memory location (argmem, inaccessiblemem) "
2542 "or access kind (none, read, write, readwrite)");
2543 else
2544 tokError("expected access kind (none, read, write, readwrite)");
2545 return std::nullopt;
2546 }
2547
2548 Lex.Lex();
2549 if (Loc) {
2550 SeenLoc = true;
2551 ME = ME.getWithModRef(*Loc, *MR);
2552 } else {
2553 if (SeenLoc) {
2554 tokError("default access kind must be specified first");
2555 return std::nullopt;
2556 }
2557 ME = MemoryEffects(*MR);
2558 }
2559
2560 if (EatIfPresent(lltok::rparen))
2561 return ME;
2562 } while (EatIfPresent(lltok::comma));
2563
2564 tokError("unterminated memory attribute");
2565 return std::nullopt;
2566}
2567
2568static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2569 switch (Tok) {
2570 case lltok::kw_all:
2571 return fcAllFlags;
2572 case lltok::kw_nan:
2573 return fcNan;
2574 case lltok::kw_snan:
2575 return fcSNan;
2576 case lltok::kw_qnan:
2577 return fcQNan;
2578 case lltok::kw_inf:
2579 return fcInf;
2580 case lltok::kw_ninf:
2581 return fcNegInf;
2582 case lltok::kw_pinf:
2583 return fcPosInf;
2584 case lltok::kw_norm:
2585 return fcNormal;
2586 case lltok::kw_nnorm:
2587 return fcNegNormal;
2588 case lltok::kw_pnorm:
2589 return fcPosNormal;
2590 case lltok::kw_sub:
2591 return fcSubnormal;
2592 case lltok::kw_nsub:
2593 return fcNegSubnormal;
2594 case lltok::kw_psub:
2595 return fcPosSubnormal;
2596 case lltok::kw_zero:
2597 return fcZero;
2598 case lltok::kw_nzero:
2599 return fcNegZero;
2600 case lltok::kw_pzero:
2601 return fcPosZero;
2602 default:
2603 return 0;
2604 }
2605}
2606
2607unsigned LLParser::parseNoFPClassAttr() {
2608 unsigned Mask = fcNone;
2609
2610 Lex.Lex();
2611 if (!EatIfPresent(lltok::lparen)) {
2612 tokError("expected '('");
2613 return 0;
2614 }
2615
2616 do {
2617 uint64_t Value = 0;
2618 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2619 if (TestMask != 0) {
2620 Mask |= TestMask;
2621 // TODO: Disallow overlapping masks to avoid copy paste errors
2622 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2623 !parseUInt64(Value)) {
2624 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2625 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2626 return 0;
2627 }
2628
2629 if (!EatIfPresent(lltok::rparen)) {
2630 error(Lex.getLoc(), "expected ')'");
2631 return 0;
2632 }
2633
2634 return Value;
2635 } else {
2636 error(Lex.getLoc(), "expected nofpclass test mask");
2637 return 0;
2638 }
2639
2640 Lex.Lex();
2641 if (EatIfPresent(lltok::rparen))
2642 return Mask;
2643 } while (1);
2644
2645 llvm_unreachable("unterminated nofpclass attribute");
2646}
2647
2648/// parseOptionalCommaAlign
2649/// ::=
2650/// ::= ',' align 4
2651///
2652/// This returns with AteExtraComma set to true if it ate an excess comma at the
2653/// end.
2654bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2655 bool &AteExtraComma) {
2656 AteExtraComma = false;
2657 while (EatIfPresent(lltok::comma)) {
2658 // Metadata at the end is an early exit.
2659 if (Lex.getKind() == lltok::MetadataVar) {
2660 AteExtraComma = true;
2661 return false;
2662 }
2663
2664 if (Lex.getKind() != lltok::kw_align)
2665 return error(Lex.getLoc(), "expected metadata or 'align'");
2666
2667 if (parseOptionalAlignment(Alignment))
2668 return true;
2669 }
2670
2671 return false;
2672}
2673
2674/// parseOptionalCommaAddrSpace
2675/// ::=
2676/// ::= ',' addrspace(1)
2677///
2678/// This returns with AteExtraComma set to true if it ate an excess comma at the
2679/// end.
2680bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2681 bool &AteExtraComma) {
2682 AteExtraComma = false;
2683 while (EatIfPresent(lltok::comma)) {
2684 // Metadata at the end is an early exit.
2685 if (Lex.getKind() == lltok::MetadataVar) {
2686 AteExtraComma = true;
2687 return false;
2688 }
2689
2690 Loc = Lex.getLoc();
2691 if (Lex.getKind() != lltok::kw_addrspace)
2692 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2693
2694 if (parseOptionalAddrSpace(AddrSpace))
2695 return true;
2696 }
2697
2698 return false;
2699}
2700
2701bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2702 std::optional<unsigned> &HowManyArg) {
2703 Lex.Lex();
2704
2705 auto StartParen = Lex.getLoc();
2706 if (!EatIfPresent(lltok::lparen))
2707 return error(StartParen, "expected '('");
2708
2709 if (parseUInt32(BaseSizeArg))
2710 return true;
2711
2712 if (EatIfPresent(lltok::comma)) {
2713 auto HowManyAt = Lex.getLoc();
2714 unsigned HowMany;
2715 if (parseUInt32(HowMany))
2716 return true;
2717 if (HowMany == BaseSizeArg)
2718 return error(HowManyAt,
2719 "'allocsize' indices can't refer to the same parameter");
2720 HowManyArg = HowMany;
2721 } else
2722 HowManyArg = std::nullopt;
2723
2724 auto EndParen = Lex.getLoc();
2725 if (!EatIfPresent(lltok::rparen))
2726 return error(EndParen, "expected ')'");
2727 return false;
2728}
2729
2730bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2731 unsigned &MaxValue) {
2732 Lex.Lex();
2733
2734 auto StartParen = Lex.getLoc();
2735 if (!EatIfPresent(lltok::lparen))
2736 return error(StartParen, "expected '('");
2737
2738 if (parseUInt32(MinValue))
2739 return true;
2740
2741 if (EatIfPresent(lltok::comma)) {
2742 if (parseUInt32(MaxValue))
2743 return true;
2744 } else
2745 MaxValue = MinValue;
2746
2747 auto EndParen = Lex.getLoc();
2748 if (!EatIfPresent(lltok::rparen))
2749 return error(EndParen, "expected ')'");
2750 return false;
2751}
2752
2753/// parseScopeAndOrdering
2754/// if isAtomic: ::= SyncScope? AtomicOrdering
2755/// else: ::=
2756///
2757/// This sets Scope and Ordering to the parsed values.
2758bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2759 AtomicOrdering &Ordering) {
2760 if (!IsAtomic)
2761 return false;
2762
2763 return parseScope(SSID) || parseOrdering(Ordering);
2764}
2765
2766/// parseScope
2767/// ::= syncscope("singlethread" | "<target scope>")?
2768///
2769/// This sets synchronization scope ID to the ID of the parsed value.
2770bool LLParser::parseScope(SyncScope::ID &SSID) {
2771 SSID = SyncScope::System;
2772 if (EatIfPresent(lltok::kw_syncscope)) {
2773 auto StartParenAt = Lex.getLoc();
2774 if (!EatIfPresent(lltok::lparen))
2775 return error(StartParenAt, "Expected '(' in syncscope");
2776
2777 std::string SSN;
2778 auto SSNAt = Lex.getLoc();
2779 if (parseStringConstant(SSN))
2780 return error(SSNAt, "Expected synchronization scope name");
2781
2782 auto EndParenAt = Lex.getLoc();
2783 if (!EatIfPresent(lltok::rparen))
2784 return error(EndParenAt, "Expected ')' in syncscope");
2785
2786 SSID = Context.getOrInsertSyncScopeID(SSN);
2787 }
2788
2789 return false;
2790}
2791
2792/// parseOrdering
2793/// ::= AtomicOrdering
2794///
2795/// This sets Ordering to the parsed value.
2796bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2797 switch (Lex.getKind()) {
2798 default:
2799 return tokError("Expected ordering on atomic instruction");
2802 // Not specified yet:
2803 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2807 case lltok::kw_seq_cst:
2809 break;
2810 }
2811 Lex.Lex();
2812 return false;
2813}
2814
2815/// parseOptionalStackAlignment
2816/// ::= /* empty */
2817/// ::= 'alignstack' '(' 4 ')'
2818bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2819 Alignment = 0;
2820 if (!EatIfPresent(lltok::kw_alignstack))
2821 return false;
2822 LocTy ParenLoc = Lex.getLoc();
2823 if (!EatIfPresent(lltok::lparen))
2824 return error(ParenLoc, "expected '('");
2825 LocTy AlignLoc = Lex.getLoc();
2826 if (parseUInt32(Alignment))
2827 return true;
2828 ParenLoc = Lex.getLoc();
2829 if (!EatIfPresent(lltok::rparen))
2830 return error(ParenLoc, "expected ')'");
2831 if (!isPowerOf2_32(Alignment))
2832 return error(AlignLoc, "stack alignment is not a power of two");
2833 return false;
2834}
2835
2836/// parseIndexList - This parses the index list for an insert/extractvalue
2837/// instruction. This sets AteExtraComma in the case where we eat an extra
2838/// comma at the end of the line and find that it is followed by metadata.
2839/// Clients that don't allow metadata can call the version of this function that
2840/// only takes one argument.
2841///
2842/// parseIndexList
2843/// ::= (',' uint32)+
2844///
2845bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2846 bool &AteExtraComma) {
2847 AteExtraComma = false;
2848
2849 if (Lex.getKind() != lltok::comma)
2850 return tokError("expected ',' as start of index list");
2851
2852 while (EatIfPresent(lltok::comma)) {
2853 if (Lex.getKind() == lltok::MetadataVar) {
2854 if (Indices.empty())
2855 return tokError("expected index");
2856 AteExtraComma = true;
2857 return false;
2858 }
2859 unsigned Idx = 0;
2860 if (parseUInt32(Idx))
2861 return true;
2862 Indices.push_back(Idx);
2863 }
2864
2865 return false;
2866}
2867
2868//===----------------------------------------------------------------------===//
2869// Type Parsing.
2870//===----------------------------------------------------------------------===//
2871
2872/// parseType - parse a type.
2873bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2874 SMLoc TypeLoc = Lex.getLoc();
2875 switch (Lex.getKind()) {
2876 default:
2877 return tokError(Msg);
2878 case lltok::Type:
2879 // Type ::= 'float' | 'void' (etc)
2880 Result = Lex.getTyVal();
2881 Lex.Lex();
2882
2883 // Handle "ptr" opaque pointer type.
2884 //
2885 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2886 if (Result->isPointerTy()) {
2887 unsigned AddrSpace;
2888 if (parseOptionalAddrSpace(AddrSpace))
2889 return true;
2890 Result = PointerType::get(getContext(), AddrSpace);
2891
2892 // Give a nice error for 'ptr*'.
2893 if (Lex.getKind() == lltok::star)
2894 return tokError("ptr* is invalid - use ptr instead");
2895
2896 // Fall through to parsing the type suffixes only if this 'ptr' is a
2897 // function return. Otherwise, return success, implicitly rejecting other
2898 // suffixes.
2899 if (Lex.getKind() != lltok::lparen)
2900 return false;
2901 }
2902 break;
2903 case lltok::kw_target: {
2904 // Type ::= TargetExtType
2905 if (parseTargetExtType(Result))
2906 return true;
2907 break;
2908 }
2909 case lltok::lbrace:
2910 // Type ::= StructType
2911 if (parseAnonStructType(Result, false))
2912 return true;
2913 break;
2914 case lltok::lsquare:
2915 // Type ::= '[' ... ']'
2916 Lex.Lex(); // eat the lsquare.
2917 if (parseArrayVectorType(Result, false))
2918 return true;
2919 break;
2920 case lltok::less: // Either vector or packed struct.
2921 // Type ::= '<' ... '>'
2922 Lex.Lex();
2923 if (Lex.getKind() == lltok::lbrace) {
2924 if (parseAnonStructType(Result, true) ||
2925 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2926 return true;
2927 } else if (parseArrayVectorType(Result, true))
2928 return true;
2929 break;
2930 case lltok::LocalVar: {
2931 // Type ::= %foo
2932 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2933
2934 // If the type hasn't been defined yet, create a forward definition and
2935 // remember where that forward def'n was seen (in case it never is defined).
2936 if (!Entry.first) {
2937 Entry.first = StructType::create(Context, Lex.getStrVal());
2938 Entry.second = Lex.getLoc();
2939 }
2940 Result = Entry.first;
2941 Lex.Lex();
2942 break;
2943 }
2944
2945 case lltok::LocalVarID: {
2946 // Type ::= %4
2947 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2948
2949 // If the type hasn't been defined yet, create a forward definition and
2950 // remember where that forward def'n was seen (in case it never is defined).
2951 if (!Entry.first) {
2952 Entry.first = StructType::create(Context);
2953 Entry.second = Lex.getLoc();
2954 }
2955 Result = Entry.first;
2956 Lex.Lex();
2957 break;
2958 }
2959 }
2960
2961 // parse the type suffixes.
2962 while (true) {
2963 switch (Lex.getKind()) {
2964 // End of type.
2965 default:
2966 if (!AllowVoid && Result->isVoidTy())
2967 return error(TypeLoc, "void type only allowed for function results");
2968 return false;
2969
2970 // Type ::= Type '*'
2971 case lltok::star:
2972 if (Result->isLabelTy())
2973 return tokError("basic block pointers are invalid");
2974 if (Result->isVoidTy())
2975 return tokError("pointers to void are invalid - use i8* instead");
2977 return tokError("pointer to this type is invalid");
2979 Lex.Lex();
2980 break;
2981
2982 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2983 case lltok::kw_addrspace: {
2984 if (Result->isLabelTy())
2985 return tokError("basic block pointers are invalid");
2986 if (Result->isVoidTy())
2987 return tokError("pointers to void are invalid; use i8* instead");
2989 return tokError("pointer to this type is invalid");
2990 unsigned AddrSpace;
2991 if (parseOptionalAddrSpace(AddrSpace) ||
2992 parseToken(lltok::star, "expected '*' in address space"))
2993 return true;
2994
2995 Result = PointerType::get(Result, AddrSpace);
2996 break;
2997 }
2998
2999 /// Types '(' ArgTypeListI ')' OptFuncAttrs
3000 case lltok::lparen:
3001 if (parseFunctionType(Result))
3002 return true;
3003 break;
3004 }
3005 }
3006}
3007
3008/// parseParameterList
3009/// ::= '(' ')'
3010/// ::= '(' Arg (',' Arg)* ')'
3011/// Arg
3012/// ::= Type OptionalAttributes Value OptionalAttributes
3013bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
3014 PerFunctionState &PFS, bool IsMustTailCall,
3015 bool InVarArgsFunc) {
3016 if (parseToken(lltok::lparen, "expected '(' in call"))
3017 return true;
3018
3019 while (Lex.getKind() != lltok::rparen) {
3020 // If this isn't the first argument, we need a comma.
3021 if (!ArgList.empty() &&
3022 parseToken(lltok::comma, "expected ',' in argument list"))
3023 return true;
3024
3025 // parse an ellipsis if this is a musttail call in a variadic function.
3026 if (Lex.getKind() == lltok::dotdotdot) {
3027 const char *Msg = "unexpected ellipsis in argument list for ";
3028 if (!IsMustTailCall)
3029 return tokError(Twine(Msg) + "non-musttail call");
3030 if (!InVarArgsFunc)
3031 return tokError(Twine(Msg) + "musttail call in non-varargs function");
3032 Lex.Lex(); // Lex the '...', it is purely for readability.
3033 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3034 }
3035
3036 // parse the argument.
3037 LocTy ArgLoc;
3038 Type *ArgTy = nullptr;
3039 Value *V;
3040 if (parseType(ArgTy, ArgLoc))
3041 return true;
3042
3043 AttrBuilder ArgAttrs(M->getContext());
3044
3045 if (ArgTy->isMetadataTy()) {
3046 if (parseMetadataAsValue(V, PFS))
3047 return true;
3048 } else {
3049 // Otherwise, handle normal operands.
3050 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
3051 return true;
3052 }
3053 ArgList.push_back(ParamInfo(
3054 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
3055 }
3056
3057 if (IsMustTailCall && InVarArgsFunc)
3058 return tokError("expected '...' at end of argument list for musttail call "
3059 "in varargs function");
3060
3061 Lex.Lex(); // Lex the ')'.
3062 return false;
3063}
3064
3065/// parseRequiredTypeAttr
3066/// ::= attrname(<ty>)
3067bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
3068 Attribute::AttrKind AttrKind) {
3069 Type *Ty = nullptr;
3070 if (!EatIfPresent(AttrToken))
3071 return true;
3072 if (!EatIfPresent(lltok::lparen))
3073 return error(Lex.getLoc(), "expected '('");
3074 if (parseType(Ty))
3075 return true;
3076 if (!EatIfPresent(lltok::rparen))
3077 return error(Lex.getLoc(), "expected ')'");
3078
3079 B.addTypeAttr(AttrKind, Ty);
3080 return false;
3081}
3082
3083/// parseRangeAttr
3084/// ::= range(<ty> <n>,<n>)
3085bool LLParser::parseRangeAttr(AttrBuilder &B) {
3086 Lex.Lex();
3087
3088 APInt Lower;
3089 APInt Upper;
3090 Type *Ty = nullptr;
3091 LocTy TyLoc;
3092
3093 auto ParseAPSInt = [&](unsigned BitWidth, APInt &Val) {
3094 if (Lex.getKind() != lltok::APSInt)
3095 return tokError("expected integer");
3096 if (Lex.getAPSIntVal().getBitWidth() > BitWidth)
3097 return tokError(
3098 "integer is too large for the bit width of specified type");
3099 Val = Lex.getAPSIntVal().extend(BitWidth);
3100 Lex.Lex();
3101 return false;
3102 };
3103
3104 if (parseToken(lltok::lparen, "expected '('") || parseType(Ty, TyLoc))
3105 return true;
3106 if (!Ty->isIntegerTy())
3107 return error(TyLoc, "the range must have integer type!");
3108
3109 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
3110
3111 if (ParseAPSInt(BitWidth, Lower) ||
3112 parseToken(lltok::comma, "expected ','") || ParseAPSInt(BitWidth, Upper))
3113 return true;
3114 if (Lower == Upper && !Lower.isZero())
3115 return tokError("the range represent the empty set but limits aren't 0!");
3116
3117 if (parseToken(lltok::rparen, "expected ')'"))
3118 return true;
3119
3120 B.addRangeAttr(ConstantRange(Lower, Upper));
3121 return false;
3122}
3123
3124/// parseInitializesAttr
3125/// ::= initializes((Lo1,Hi1),(Lo2,Hi2),...)
3126bool LLParser::parseInitializesAttr(AttrBuilder &B) {
3127 Lex.Lex();
3128
3129 auto ParseAPSInt = [&](APInt &Val) {
3130 if (Lex.getKind() != lltok::APSInt)
3131 return tokError("expected integer");
3132 Val = Lex.getAPSIntVal().extend(64);
3133 Lex.Lex();
3134 return false;
3135 };
3136
3137 if (parseToken(lltok::lparen, "expected '('"))
3138 return true;
3139
3141 // Parse each constant range.
3142 do {
3143 APInt Lower, Upper;
3144 if (parseToken(lltok::lparen, "expected '('"))
3145 return true;
3146
3147 if (ParseAPSInt(Lower) || parseToken(lltok::comma, "expected ','") ||
3148 ParseAPSInt(Upper))
3149 return true;
3150
3151 if (Lower == Upper)
3152 return tokError("the range should not represent the full or empty set!");
3153
3154 if (parseToken(lltok::rparen, "expected ')'"))
3155 return true;
3156
3157 RangeList.push_back(ConstantRange(Lower, Upper));
3158 } while (EatIfPresent(lltok::comma));
3159
3160 if (parseToken(lltok::rparen, "expected ')'"))
3161 return true;
3162
3163 auto CRLOrNull = ConstantRangeList::getConstantRangeList(RangeList);
3164 if (!CRLOrNull.has_value())
3165 return tokError("Invalid (unordered or overlapping) range list");
3166 B.addInitializesAttr(*CRLOrNull);
3167 return false;
3168}
3169
3170bool LLParser::parseCapturesAttr(AttrBuilder &B) {
3172 std::optional<CaptureComponents> Ret;
3173
3174 // We use syntax like captures(ret: address, provenance), so the colon
3175 // should not be interpreted as a label terminator.
3177 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
3178
3179 Lex.Lex();
3180 if (parseToken(lltok::lparen, "expected '('"))
3181 return true;
3182
3183 CaptureComponents *Current = &Other;
3184 bool SeenComponent = false;
3185 while (true) {
3186 if (EatIfPresent(lltok::kw_ret)) {
3187 if (parseToken(lltok::colon, "expected ':'"))
3188 return true;
3189 if (Ret)
3190 return tokError("duplicate 'ret' location");
3192 Current = &*Ret;
3193 SeenComponent = false;
3194 }
3195
3196 if (EatIfPresent(lltok::kw_none)) {
3197 if (SeenComponent)
3198 return tokError("cannot use 'none' with other component");
3199 *Current = CaptureComponents::None;
3200 } else {
3201 if (SeenComponent && capturesNothing(*Current))
3202 return tokError("cannot use 'none' with other component");
3203
3204 if (EatIfPresent(lltok::kw_address_is_null))
3206 else if (EatIfPresent(lltok::kw_address))
3207 *Current |= CaptureComponents::Address;
3208 else if (EatIfPresent(lltok::kw_provenance))
3210 else if (EatIfPresent(lltok::kw_read_provenance))
3212 else
3213 return tokError("expected one of 'none', 'address', 'address_is_null', "
3214 "'provenance' or 'read_provenance'");
3215 }
3216
3217 SeenComponent = true;
3218 if (EatIfPresent(lltok::rparen))
3219 break;
3220
3221 if (parseToken(lltok::comma, "expected ',' or ')'"))
3222 return true;
3223 }
3224
3225 B.addCapturesAttr(CaptureInfo(Other, Ret.value_or(Other)));
3226 return false;
3227}
3228
3229/// parseOptionalOperandBundles
3230/// ::= /*empty*/
3231/// ::= '[' OperandBundle [, OperandBundle ]* ']'
3232///
3233/// OperandBundle
3234/// ::= bundle-tag '(' ')'
3235/// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
3236///
3237/// bundle-tag ::= String Constant
3238bool LLParser::parseOptionalOperandBundles(
3239 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
3240 LocTy BeginLoc = Lex.getLoc();
3241 if (!EatIfPresent(lltok::lsquare))
3242 return false;
3243
3244 while (Lex.getKind() != lltok::rsquare) {
3245 // If this isn't the first operand bundle, we need a comma.
3246 if (!BundleList.empty() &&
3247 parseToken(lltok::comma, "expected ',' in input list"))
3248 return true;
3249
3250 std::string Tag;
3251 if (parseStringConstant(Tag))
3252 return true;
3253
3254 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
3255 return true;
3256
3257 std::vector<Value *> Inputs;
3258 while (Lex.getKind() != lltok::rparen) {
3259 // If this isn't the first input, we need a comma.
3260 if (!Inputs.empty() &&
3261 parseToken(lltok::comma, "expected ',' in input list"))
3262 return true;
3263
3264 Type *Ty = nullptr;
3265 Value *Input = nullptr;
3266 if (parseType(Ty))
3267 return true;
3268 if (Ty->isMetadataTy()) {
3269 if (parseMetadataAsValue(Input, PFS))
3270 return true;
3271 } else if (parseValue(Ty, Input, PFS)) {
3272 return true;
3273 }
3274 Inputs.push_back(Input);
3275 }
3276
3277 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
3278
3279 Lex.Lex(); // Lex the ')'.
3280 }
3281
3282 if (BundleList.empty())
3283 return error(BeginLoc, "operand bundle set must not be empty");
3284
3285 Lex.Lex(); // Lex the ']'.
3286 return false;
3287}
3288
3289bool LLParser::checkValueID(LocTy Loc, StringRef Kind, StringRef Prefix,
3290 unsigned NextID, unsigned ID) {
3291 if (ID < NextID)
3292 return error(Loc, Kind + " expected to be numbered '" + Prefix +
3293 Twine(NextID) + "' or greater");
3294
3295 return false;
3296}
3297
3298/// parseArgumentList - parse the argument list for a function type or function
3299/// prototype.
3300/// ::= '(' ArgTypeListI ')'
3301/// ArgTypeListI
3302/// ::= /*empty*/
3303/// ::= '...'
3304/// ::= ArgTypeList ',' '...'
3305/// ::= ArgType (',' ArgType)*
3306///
3307bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
3308 SmallVectorImpl<unsigned> &UnnamedArgNums,
3309 bool &IsVarArg) {
3310 unsigned CurValID = 0;
3311 IsVarArg = false;
3312 assert(Lex.getKind() == lltok::lparen);
3313 Lex.Lex(); // eat the (.
3314
3315 if (Lex.getKind() != lltok::rparen) {
3316 do {
3317 // Handle ... at end of arg list.
3318 if (EatIfPresent(lltok::dotdotdot)) {
3319 IsVarArg = true;
3320 break;
3321 }
3322
3323 // Otherwise must be an argument type.
3324 LocTy TypeLoc = Lex.getLoc();
3325 Type *ArgTy = nullptr;
3326 AttrBuilder Attrs(M->getContext());
3327 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
3328 return true;
3329
3330 if (ArgTy->isVoidTy())
3331 return error(TypeLoc, "argument can not have void type");
3332
3333 std::string Name;
3334 if (Lex.getKind() == lltok::LocalVar) {
3335 Name = Lex.getStrVal();
3336 Lex.Lex();
3337 } else {
3338 unsigned ArgID;
3339 if (Lex.getKind() == lltok::LocalVarID) {
3340 ArgID = Lex.getUIntVal();
3341 if (checkValueID(TypeLoc, "argument", "%", CurValID, ArgID))
3342 return true;
3343 Lex.Lex();
3344 } else {
3345 ArgID = CurValID;
3346 }
3347 UnnamedArgNums.push_back(ArgID);
3348 CurValID = ArgID + 1;
3349 }
3350
3351 if (!ArgTy->isFirstClassType())
3352 return error(TypeLoc, "invalid type for function argument");
3353
3354 ArgList.emplace_back(TypeLoc, ArgTy,
3355 AttributeSet::get(ArgTy->getContext(), Attrs),
3356 std::move(Name));
3357 } while (EatIfPresent(lltok::comma));
3358 }
3359
3360 return parseToken(lltok::rparen, "expected ')' at end of argument list");
3361}
3362
3363/// parseFunctionType
3364/// ::= Type ArgumentList OptionalAttrs
3365bool LLParser::parseFunctionType(Type *&Result) {
3366 assert(Lex.getKind() == lltok::lparen);
3367
3369 return tokError("invalid function return type");
3370
3372 bool IsVarArg;
3373 SmallVector<unsigned> UnnamedArgNums;
3374 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg))
3375 return true;
3376
3377 // Reject names on the arguments lists.
3378 for (const ArgInfo &Arg : ArgList) {
3379 if (!Arg.Name.empty())
3380 return error(Arg.Loc, "argument name invalid in function type");
3381 if (Arg.Attrs.hasAttributes())
3382 return error(Arg.Loc, "argument attributes invalid in function type");
3383 }
3384
3385 SmallVector<Type*, 16> ArgListTy;
3386 for (const ArgInfo &Arg : ArgList)
3387 ArgListTy.push_back(Arg.Ty);
3388
3389 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3390 return false;
3391}
3392
3393/// parseAnonStructType - parse an anonymous struct type, which is inlined into
3394/// other structs.
3395bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3397 if (parseStructBody(Elts))
3398 return true;
3399
3400 Result = StructType::get(Context, Elts, Packed);
3401 return false;
3402}
3403
3404/// parseStructDefinition - parse a struct in a 'type' definition.
3405bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3406 std::pair<Type *, LocTy> &Entry,
3407 Type *&ResultTy) {
3408 // If the type was already defined, diagnose the redefinition.
3409 if (Entry.first && !Entry.second.isValid())
3410 return error(TypeLoc, "redefinition of type");
3411
3412 // If we have opaque, just return without filling in the definition for the
3413 // struct. This counts as a definition as far as the .ll file goes.
3414 if (EatIfPresent(lltok::kw_opaque)) {
3415 // This type is being defined, so clear the location to indicate this.
3416 Entry.second = SMLoc();
3417
3418 // If this type number has never been uttered, create it.
3419 if (!Entry.first)
3420 Entry.first = StructType::create(Context, Name);
3421 ResultTy = Entry.first;
3422 return false;
3423 }
3424
3425 // If the type starts with '<', then it is either a packed struct or a vector.
3426 bool isPacked = EatIfPresent(lltok::less);
3427
3428 // If we don't have a struct, then we have a random type alias, which we
3429 // accept for compatibility with old files. These types are not allowed to be
3430 // forward referenced and not allowed to be recursive.
3431 if (Lex.getKind() != lltok::lbrace) {
3432 if (Entry.first)
3433 return error(TypeLoc, "forward references to non-struct type");
3434
3435 ResultTy = nullptr;
3436 if (isPacked)
3437 return parseArrayVectorType(ResultTy, true);
3438 return parseType(ResultTy);
3439 }
3440
3441 // This type is being defined, so clear the location to indicate this.
3442 Entry.second = SMLoc();
3443
3444 // If this type number has never been uttered, create it.
3445 if (!Entry.first)
3446 Entry.first = StructType::create(Context, Name);
3447
3448 StructType *STy = cast<StructType>(Entry.first);
3449
3451 if (parseStructBody(Body) ||
3452 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3453 return true;
3454
3455 if (auto E = STy->setBodyOrError(Body, isPacked))
3456 return tokError(toString(std::move(E)));
3457
3458 ResultTy = STy;
3459 return false;
3460}
3461
3462/// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3463/// StructType
3464/// ::= '{' '}'
3465/// ::= '{' Type (',' Type)* '}'
3466/// ::= '<' '{' '}' '>'
3467/// ::= '<' '{' Type (',' Type)* '}' '>'
3468bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3469 assert(Lex.getKind() == lltok::lbrace);
3470 Lex.Lex(); // Consume the '{'
3471
3472 // Handle the empty struct.
3473 if (EatIfPresent(lltok::rbrace))
3474 return false;
3475
3476 LocTy EltTyLoc = Lex.getLoc();
3477 Type *Ty = nullptr;
3478 if (parseType(Ty))
3479 return true;
3480 Body.push_back(Ty);
3481
3483 return error(EltTyLoc, "invalid element type for struct");
3484
3485 while (EatIfPresent(lltok::comma)) {
3486 EltTyLoc = Lex.getLoc();
3487 if (parseType(Ty))
3488 return true;
3489
3491 return error(EltTyLoc, "invalid element type for struct");
3492
3493 Body.push_back(Ty);
3494 }
3495
3496 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3497}
3498
3499/// parseArrayVectorType - parse an array or vector type, assuming the first
3500/// token has already been consumed.
3501/// Type
3502/// ::= '[' APSINTVAL 'x' Types ']'
3503/// ::= '<' APSINTVAL 'x' Types '>'
3504/// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3505bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3506 bool Scalable = false;
3507
3508 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3509 Lex.Lex(); // consume the 'vscale'
3510 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3511 return true;
3512
3513 Scalable = true;
3514 }
3515
3516 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3517 Lex.getAPSIntVal().getBitWidth() > 64)
3518 return tokError("expected number in address space");
3519
3520 LocTy SizeLoc = Lex.getLoc();
3522 Lex.Lex();
3523
3524 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3525 return true;
3526
3527 LocTy TypeLoc = Lex.getLoc();
3528 Type *EltTy = nullptr;
3529 if (parseType(EltTy))
3530 return true;
3531
3532 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3533 "expected end of sequential type"))
3534 return true;
3535
3536 if (IsVector) {
3537 if (Size == 0)
3538 return error(SizeLoc, "zero element vector is illegal");
3539 if ((unsigned)Size != Size)
3540 return error(SizeLoc, "size too large for vector");
3542 return error(TypeLoc, "invalid vector element type");
3543 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3544 } else {
3546 return error(TypeLoc, "invalid array element type");
3547 Result = ArrayType::get(EltTy, Size);
3548 }
3549 return false;
3550}
3551
3552/// parseTargetExtType - handle target extension type syntax
3553/// TargetExtType
3554/// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3555///
3556/// TargetExtTypeParams
3557/// ::= /*empty*/
3558/// ::= ',' Type TargetExtTypeParams
3559///
3560/// TargetExtIntParams
3561/// ::= /*empty*/
3562/// ::= ',' uint32 TargetExtIntParams
3563bool LLParser::parseTargetExtType(Type *&Result) {
3564 Lex.Lex(); // Eat the 'target' keyword.
3565
3566 // Get the mandatory type name.
3567 std::string TypeName;
3568 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3569 parseStringConstant(TypeName))
3570 return true;
3571
3572 // Parse all of the integer and type parameters at the same time; the use of
3573 // SeenInt will allow us to catch cases where type parameters follow integer
3574 // parameters.
3575 SmallVector<Type *> TypeParams;
3576 SmallVector<unsigned> IntParams;
3577 bool SeenInt = false;
3578 while (Lex.getKind() == lltok::comma) {
3579 Lex.Lex(); // Eat the comma.
3580
3581 if (Lex.getKind() == lltok::APSInt) {
3582 SeenInt = true;
3583 unsigned IntVal;
3584 if (parseUInt32(IntVal))
3585 return true;
3586 IntParams.push_back(IntVal);
3587 } else if (SeenInt) {
3588 // The only other kind of parameter we support is type parameters, which
3589 // must precede the integer parameters. This is therefore an error.
3590 return tokError("expected uint32 param");
3591 } else {
3592 Type *TypeParam;
3593 if (parseType(TypeParam, /*AllowVoid=*/true))
3594 return true;
3595 TypeParams.push_back(TypeParam);
3596 }
3597 }
3598
3599 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3600 return true;
3601
3602 auto TTy =
3603 TargetExtType::getOrError(Context, TypeName, TypeParams, IntParams);
3604 if (auto E = TTy.takeError())
3605 return tokError(toString(std::move(E)));
3606
3607 Result = *TTy;
3608 return false;
3609}
3610
3611//===----------------------------------------------------------------------===//
3612// Function Semantic Analysis.
3613//===----------------------------------------------------------------------===//
3614
3615LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3616 int functionNumber,
3617 ArrayRef<unsigned> UnnamedArgNums)
3618 : P(p), F(f), FunctionNumber(functionNumber) {
3619
3620 // Insert unnamed arguments into the NumberedVals list.
3621 auto It = UnnamedArgNums.begin();
3622 for (Argument &A : F.args()) {
3623 if (!A.hasName()) {
3624 unsigned ArgNum = *It++;
3625 NumberedVals.add(ArgNum, &A);
3626 }
3627 }
3628}
3629
3630LLParser::PerFunctionState::~PerFunctionState() {
3631 // If there were any forward referenced non-basicblock values, delete them.
3632
3633 for (const auto &P : ForwardRefVals) {
3634 if (isa<BasicBlock>(P.second.first))
3635 continue;
3636 P.second.first->replaceAllUsesWith(
3637 PoisonValue::get(P.second.first->getType()));
3638 P.second.first->deleteValue();
3639 }
3640
3641 for (const auto &P : ForwardRefValIDs) {
3642 if (isa<BasicBlock>(P.second.first))
3643 continue;
3644 P.second.first->replaceAllUsesWith(
3645 PoisonValue::get(P.second.first->getType()));
3646 P.second.first->deleteValue();
3647 }
3648}
3649
3650bool LLParser::PerFunctionState::finishFunction() {
3651 if (!ForwardRefVals.empty())
3652 return P.error(ForwardRefVals.begin()->second.second,
3653 "use of undefined value '%" + ForwardRefVals.begin()->first +
3654 "'");
3655 if (!ForwardRefValIDs.empty())
3656 return P.error(ForwardRefValIDs.begin()->second.second,
3657 "use of undefined value '%" +
3658 Twine(ForwardRefValIDs.begin()->first) + "'");
3659 return false;
3660}
3661
3662/// getVal - Get a value with the specified name or ID, creating a
3663/// forward reference record if needed. This can return null if the value
3664/// exists but does not have the right type.
3665Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3666 LocTy Loc) {
3667 // Look this name up in the normal function symbol table.
3668 Value *Val = F.getValueSymbolTable()->lookup(Name);
3669
3670 // If this is a forward reference for the value, see if we already created a
3671 // forward ref record.
3672 if (!Val) {
3673 auto I = ForwardRefVals.find(Name);
3674 if (I != ForwardRefVals.end())
3675 Val = I->second.first;
3676 }
3677
3678 // If we have the value in the symbol table or fwd-ref table, return it.
3679 if (Val)
3680 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3681
3682 // Don't make placeholders with invalid type.
3683 if (!Ty->isFirstClassType()) {
3684 P.error(Loc, "invalid use of a non-first-class type");
3685 return nullptr;
3686 }
3687
3688 // Otherwise, create a new forward reference for this value and remember it.
3689 Value *FwdVal;
3690 if (Ty->isLabelTy()) {
3691 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3692 } else {
3693 FwdVal = new Argument(Ty, Name);
3694 }
3695 if (FwdVal->getName() != Name) {
3696 P.error(Loc, "name is too long which can result in name collisions, "
3697 "consider making the name shorter or "
3698 "increasing -non-global-value-max-name-size");
3699 return nullptr;
3700 }
3701
3702 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3703 return FwdVal;
3704}
3705
3706Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3707 // Look this name up in the normal function symbol table.
3708 Value *Val = NumberedVals.get(ID);
3709
3710 // If this is a forward reference for the value, see if we already created a
3711 // forward ref record.
3712 if (!Val) {
3713 auto I = ForwardRefValIDs.find(ID);
3714 if (I != ForwardRefValIDs.end())
3715 Val = I->second.first;
3716 }
3717
3718 // If we have the value in the symbol table or fwd-ref table, return it.
3719 if (Val)
3720 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3721
3722 if (!Ty->isFirstClassType()) {
3723 P.error(Loc, "invalid use of a non-first-class type");
3724 return nullptr;
3725 }
3726
3727 // Otherwise, create a new forward reference for this value and remember it.
3728 Value *FwdVal;
3729 if (Ty->isLabelTy()) {
3730 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3731 } else {
3732 FwdVal = new Argument(Ty);
3733 }
3734
3735 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3736 return FwdVal;
3737}
3738
3739/// setInstName - After an instruction is parsed and inserted into its
3740/// basic block, this installs its name.
3741bool LLParser::PerFunctionState::setInstName(int NameID,
3742 const std::string &NameStr,
3743 LocTy NameLoc, Instruction *Inst) {
3744 // If this instruction has void type, it cannot have a name or ID specified.
3745 if (Inst->getType()->isVoidTy()) {
3746 if (NameID != -1 || !NameStr.empty())
3747 return P.error(NameLoc, "instructions returning void cannot have a name");
3748 return false;
3749 }
3750
3751 // If this was a numbered instruction, verify that the instruction is the
3752 // expected value and resolve any forward references.
3753 if (NameStr.empty()) {
3754 // If neither a name nor an ID was specified, just use the next ID.
3755 if (NameID == -1)
3756 NameID = NumberedVals.getNext();
3757
3758 if (P.checkValueID(NameLoc, "instruction", "%", NumberedVals.getNext(),
3759 NameID))
3760 return true;
3761
3762 auto FI = ForwardRefValIDs.find(NameID);
3763 if (FI != ForwardRefValIDs.end()) {
3764 Value *Sentinel = FI->second.first;
3765 if (Sentinel->getType() != Inst->getType())
3766 return P.error(NameLoc, "instruction forward referenced with type '" +
3767 getTypeString(FI->second.first->getType()) +
3768 "'");
3769
3770 Sentinel->replaceAllUsesWith(Inst);
3771 Sentinel->deleteValue();
3772 ForwardRefValIDs.erase(FI);
3773 }
3774
3775 NumberedVals.add(NameID, Inst);
3776 return false;
3777 }
3778
3779 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3780 auto FI = ForwardRefVals.find(NameStr);
3781 if (FI != ForwardRefVals.end()) {
3782 Value *Sentinel = FI->second.first;
3783 if (Sentinel->getType() != Inst->getType())
3784 return P.error(NameLoc, "instruction forward referenced with type '" +
3785 getTypeString(FI->second.first->getType()) +
3786 "'");
3787
3788 Sentinel->replaceAllUsesWith(Inst);
3789 Sentinel->deleteValue();
3790 ForwardRefVals.erase(FI);
3791 }
3792
3793 // Set the name on the instruction.
3794 Inst->setName(NameStr);
3795
3796 if (Inst->getName() != NameStr)
3797 return P.error(NameLoc, "multiple definition of local value named '" +
3798 NameStr + "'");
3799 return false;
3800}
3801
3802/// getBB - Get a basic block with the specified name or ID, creating a
3803/// forward reference record if needed.
3804BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3805 LocTy Loc) {
3806 return dyn_cast_or_null<BasicBlock>(
3807 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3808}
3809
3810BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3811 return dyn_cast_or_null<BasicBlock>(
3812 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3813}
3814
3815/// defineBB - Define the specified basic block, which is either named or
3816/// unnamed. If there is an error, this returns null otherwise it returns
3817/// the block being defined.
3818BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3819 int NameID, LocTy Loc) {
3820 BasicBlock *BB;
3821 if (Name.empty()) {
3822 if (NameID != -1) {
3823 if (P.checkValueID(Loc, "label", "", NumberedVals.getNext(), NameID))
3824 return nullptr;
3825 } else {
3826 NameID = NumberedVals.getNext();
3827 }
3828 BB = getBB(NameID, Loc);
3829 if (!BB) {
3830 P.error(Loc, "unable to create block numbered '" + Twine(NameID) + "'");
3831 return nullptr;
3832 }
3833 } else {
3834 BB = getBB(Name, Loc);
3835 if (!BB) {
3836 P.error(Loc, "unable to create block named '" + Name + "'");
3837 return nullptr;
3838 }
3839 }
3840
3841 // Move the block to the end of the function. Forward ref'd blocks are
3842 // inserted wherever they happen to be referenced.
3843 F.splice(F.end(), &F, BB->getIterator());
3844
3845 // Remove the block from forward ref sets.
3846 if (Name.empty()) {
3847 ForwardRefValIDs.erase(NameID);
3848 NumberedVals.add(NameID, BB);
3849 } else {
3850 // BB forward references are already in the function symbol table.
3851 ForwardRefVals.erase(Name);
3852 }
3853
3854 return BB;
3855}
3856
3857//===----------------------------------------------------------------------===//
3858// Constants.
3859//===----------------------------------------------------------------------===//
3860
3861/// parseValID - parse an abstract value that doesn't necessarily have a
3862/// type implied. For example, if we parse "4" we don't know what integer type
3863/// it has. The value will later be combined with its type and checked for
3864/// basic correctness. PFS is used to convert function-local operands of
3865/// metadata (since metadata operands are not just parsed here but also
3866/// converted to values). PFS can be null when we are not parsing metadata
3867/// values inside a function.
3868bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3869 ID.Loc = Lex.getLoc();
3870 switch (Lex.getKind()) {
3871 default:
3872 return tokError("expected value token");
3873 case lltok::GlobalID: // @42
3874 ID.UIntVal = Lex.getUIntVal();
3875 ID.Kind = ValID::t_GlobalID;
3876 break;
3877 case lltok::GlobalVar: // @foo
3878 ID.StrVal = Lex.getStrVal();
3879 ID.Kind = ValID::t_GlobalName;
3880 break;
3881 case lltok::LocalVarID: // %42
3882 ID.UIntVal = Lex.getUIntVal();
3883 ID.Kind = ValID::t_LocalID;
3884 break;
3885 case lltok::LocalVar: // %foo
3886 ID.StrVal = Lex.getStrVal();
3887 ID.Kind = ValID::t_LocalName;
3888 break;
3889 case lltok::APSInt:
3890 ID.APSIntVal = Lex.getAPSIntVal();
3891 ID.Kind = ValID::t_APSInt;
3892 break;
3893 case lltok::APFloat:
3894 ID.APFloatVal = Lex.getAPFloatVal();
3895 ID.Kind = ValID::t_APFloat;
3896 break;
3897 case lltok::kw_true:
3898 ID.ConstantVal = ConstantInt::getTrue(Context);
3899 ID.Kind = ValID::t_Constant;
3900 break;
3901 case lltok::kw_false:
3902 ID.ConstantVal = ConstantInt::getFalse(Context);
3903 ID.Kind = ValID::t_Constant;
3904 break;
3905 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3906 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3907 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3908 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3909 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3910
3911 case lltok::lbrace: {
3912 // ValID ::= '{' ConstVector '}'
3913 Lex.Lex();
3915 if (parseGlobalValueVector(Elts) ||
3916 parseToken(lltok::rbrace, "expected end of struct constant"))
3917 return true;
3918
3919 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3920 ID.UIntVal = Elts.size();
3921 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3922 Elts.size() * sizeof(Elts[0]));
3924 return false;
3925 }
3926 case lltok::less: {
3927 // ValID ::= '<' ConstVector '>' --> Vector.
3928 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3929 Lex.Lex();
3930 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3931
3933 LocTy FirstEltLoc = Lex.getLoc();
3934 if (parseGlobalValueVector(Elts) ||
3935 (isPackedStruct &&
3936 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3937 parseToken(lltok::greater, "expected end of constant"))
3938 return true;
3939
3940 if (isPackedStruct) {
3941 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3942 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3943 Elts.size() * sizeof(Elts[0]));
3944 ID.UIntVal = Elts.size();
3946 return false;
3947 }
3948
3949 if (Elts.empty())
3950 return error(ID.Loc, "constant vector must not be empty");
3951
3952 if (!Elts[0]->getType()->isIntegerTy() &&
3953 !Elts[0]->getType()->isFloatingPointTy() &&
3954 !Elts[0]->getType()->isPointerTy())
3955 return error(
3956 FirstEltLoc,
3957 "vector elements must have integer, pointer or floating point type");
3958
3959 // Verify that all the vector elements have the same type.
3960 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3961 if (Elts[i]->getType() != Elts[0]->getType())
3962 return error(FirstEltLoc, "vector element #" + Twine(i) +
3963 " is not of type '" +
3964 getTypeString(Elts[0]->getType()));
3965
3966 ID.ConstantVal = ConstantVector::get(Elts);
3967 ID.Kind = ValID::t_Constant;
3968 return false;
3969 }
3970 case lltok::lsquare: { // Array Constant
3971 Lex.Lex();
3973 LocTy FirstEltLoc = Lex.getLoc();
3974 if (parseGlobalValueVector(Elts) ||
3975 parseToken(lltok::rsquare, "expected end of array constant"))
3976 return true;
3977
3978 // Handle empty element.
3979 if (Elts.empty()) {
3980 // Use undef instead of an array because it's inconvenient to determine
3981 // the element type at this point, there being no elements to examine.
3982 ID.Kind = ValID::t_EmptyArray;
3983 return false;
3984 }
3985
3986 if (!Elts[0]->getType()->isFirstClassType())
3987 return error(FirstEltLoc, "invalid array element type: " +
3988 getTypeString(Elts[0]->getType()));
3989
3990 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3991
3992 // Verify all elements are correct type!
3993 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3994 if (Elts[i]->getType() != Elts[0]->getType())
3995 return error(FirstEltLoc, "array element #" + Twine(i) +
3996 " is not of type '" +
3997 getTypeString(Elts[0]->getType()));
3998 }
3999
4000 ID.ConstantVal = ConstantArray::get(ATy, Elts);
4001 ID.Kind = ValID::t_Constant;
4002 return false;
4003 }
4004 case lltok::kw_c: // c "foo"
4005 Lex.Lex();
4006 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
4007 false);
4008 if (parseToken(lltok::StringConstant, "expected string"))
4009 return true;
4010 ID.Kind = ValID::t_Constant;
4011 return false;
4012
4013 case lltok::kw_asm: {
4014 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
4015 // STRINGCONSTANT
4016 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
4017 Lex.Lex();
4018 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
4019 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
4020 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
4021 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
4022 parseStringConstant(ID.StrVal) ||
4023 parseToken(lltok::comma, "expected comma in inline asm expression") ||
4024 parseToken(lltok::StringConstant, "expected constraint string"))
4025 return true;
4026 ID.StrVal2 = Lex.getStrVal();
4027 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
4028 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
4029 ID.Kind = ValID::t_InlineAsm;
4030 return false;
4031 }
4032
4034 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
4035 Lex.Lex();
4036
4037 ValID Fn, Label;
4038
4039 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
4040 parseValID(Fn, PFS) ||
4041 parseToken(lltok::comma,
4042 "expected comma in block address expression") ||
4043 parseValID(Label, PFS) ||
4044 parseToken(lltok::rparen, "expected ')' in block address expression"))
4045 return true;
4046
4048 return error(Fn.Loc, "expected function name in blockaddress");
4049 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
4050 return error(Label.Loc, "expected basic block name in blockaddress");
4051
4052 // Try to find the function (but skip it if it's forward-referenced).
4053 GlobalValue *GV = nullptr;
4054 if (Fn.Kind == ValID::t_GlobalID) {
4055 GV = NumberedVals.get(Fn.UIntVal);
4056 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4057 GV = M->getNamedValue(Fn.StrVal);
4058 }
4059 Function *F = nullptr;
4060 if (GV) {
4061 // Confirm that it's actually a function with a definition.
4062 if (!isa<Function>(GV))
4063 return error(Fn.Loc, "expected function name in blockaddress");
4064 F = cast<Function>(GV);
4065 if (F->isDeclaration())
4066 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
4067 }
4068
4069 if (!F) {
4070 // Make a global variable as a placeholder for this reference.
4071 GlobalValue *&FwdRef =
4072 ForwardRefBlockAddresses[std::move(Fn)][std::move(Label)];
4073 if (!FwdRef) {
4074 unsigned FwdDeclAS;
4075 if (ExpectedTy) {
4076 // If we know the type that the blockaddress is being assigned to,
4077 // we can use the address space of that type.
4078 if (!ExpectedTy->isPointerTy())
4079 return error(ID.Loc,
4080 "type of blockaddress must be a pointer and not '" +
4081 getTypeString(ExpectedTy) + "'");
4082 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
4083 } else if (PFS) {
4084 // Otherwise, we default the address space of the current function.
4085 FwdDeclAS = PFS->getFunction().getAddressSpace();
4086 } else {
4087 llvm_unreachable("Unknown address space for blockaddress");
4088 }
4089 FwdRef = new GlobalVariable(
4090 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
4091 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
4092 }
4093
4094 ID.ConstantVal = FwdRef;
4095 ID.Kind = ValID::t_Constant;
4096 return false;
4097 }
4098
4099 // We found the function; now find the basic block. Don't use PFS, since we
4100 // might be inside a constant expression.
4101 BasicBlock *BB;
4102 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
4103 if (Label.Kind == ValID::t_LocalID)
4104 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
4105 else
4106 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
4107 if (!BB)
4108 return error(Label.Loc, "referenced value is not a basic block");
4109 } else {
4110 if (Label.Kind == ValID::t_LocalID)
4111 return error(Label.Loc, "cannot take address of numeric label after "
4112 "the function is defined");
4113 BB = dyn_cast_or_null<BasicBlock>(
4114 F->getValueSymbolTable()->lookup(Label.StrVal));
4115 if (!BB)
4116 return error(Label.Loc, "referenced value is not a basic block");
4117 }
4118
4119 ID.ConstantVal = BlockAddress::get(F, BB);
4120 ID.Kind = ValID::t_Constant;
4121 return false;
4122 }
4123
4125 // ValID ::= 'dso_local_equivalent' @foo
4126 Lex.Lex();
4127
4128 ValID Fn;
4129
4130 if (parseValID(Fn, PFS))
4131 return true;
4132
4134 return error(Fn.Loc,
4135 "expected global value name in dso_local_equivalent");
4136
4137 // Try to find the function (but skip it if it's forward-referenced).
4138 GlobalValue *GV = nullptr;
4139 if (Fn.Kind == ValID::t_GlobalID) {
4140 GV = NumberedVals.get(Fn.UIntVal);
4141 } else if (!ForwardRefVals.count(Fn.StrVal)) {
4142 GV = M->getNamedValue(Fn.StrVal);
4143 }
4144
4145 if (!GV) {
4146 // Make a placeholder global variable as a placeholder for this reference.
4147 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
4148 ? ForwardRefDSOLocalEquivalentIDs
4149 : ForwardRefDSOLocalEquivalentNames;
4150 GlobalValue *&FwdRef = FwdRefMap[Fn];
4151 if (!FwdRef) {
4152 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
4153 GlobalValue::InternalLinkage, nullptr, "",
4155 }
4156
4157 ID.ConstantVal = FwdRef;
4158 ID.Kind = ValID::t_Constant;
4159 return false;
4160 }
4161
4162 if (!GV->getValueType()->isFunctionTy())
4163 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
4164 "in dso_local_equivalent");
4165
4166 ID.ConstantVal = DSOLocalEquivalent::get(GV);
4167 ID.Kind = ValID::t_Constant;
4168 return false;
4169 }
4170
4171 case lltok::kw_no_cfi: {
4172 // ValID ::= 'no_cfi' @foo
4173 Lex.Lex();
4174
4175 if (parseValID(ID, PFS))
4176 return true;
4177
4178 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
4179 return error(ID.Loc, "expected global value name in no_cfi");
4180
4181 ID.NoCFI = true;
4182 return false;
4183 }
4184 case lltok::kw_ptrauth: {
4185 // ValID ::= 'ptrauth' '(' ptr @foo ',' i32 <key>
4186 // (',' i64 <disc> (',' ptr addrdisc)? )? ')'
4187 Lex.Lex();
4188
4189 Constant *Ptr, *Key;
4190 Constant *Disc = nullptr, *AddrDisc = nullptr;
4191
4192 if (parseToken(lltok::lparen,
4193 "expected '(' in constant ptrauth expression") ||
4194 parseGlobalTypeAndValue(Ptr) ||
4195 parseToken(lltok::comma,
4196 "expected comma in constant ptrauth expression") ||
4197 parseGlobalTypeAndValue(Key))
4198 return true;
4199 // If present, parse the optional disc/addrdisc.
4200 if (EatIfPresent(lltok::comma))
4201 if (parseGlobalTypeAndValue(Disc) ||
4202 (EatIfPresent(lltok::comma) && parseGlobalTypeAndValue(AddrDisc)))
4203 return true;
4204 if (parseToken(lltok::rparen,
4205 "expected ')' in constant ptrauth expression"))
4206 return true;
4207
4208 if (!Ptr->getType()->isPointerTy())
4209 return error(ID.Loc, "constant ptrauth base pointer must be a pointer");
4210
4211 auto *KeyC = dyn_cast<ConstantInt>(Key);
4212 if (!KeyC || KeyC->getBitWidth() != 32)
4213 return error(ID.Loc, "constant ptrauth key must be i32 constant");
4214
4215 ConstantInt *DiscC = nullptr;
4216 if (Disc) {
4217 DiscC = dyn_cast<ConstantInt>(Disc);
4218 if (!DiscC || DiscC->getBitWidth() != 64)
4219 return error(
4220 ID.Loc,
4221 "constant ptrauth integer discriminator must be i64 constant");
4222 } else {
4223 DiscC = ConstantInt::get(Type::getInt64Ty(Context), 0);
4224 }
4225
4226 if (AddrDisc) {
4227 if (!AddrDisc->getType()->isPointerTy())
4228 return error(
4229 ID.Loc, "constant ptrauth address discriminator must be a pointer");
4230 } else {
4231 AddrDisc = ConstantPointerNull::get(PointerType::get(Context, 0));
4232 }
4233
4234 ID.ConstantVal = ConstantPtrAuth::get(Ptr, KeyC, DiscC, AddrDisc);
4235 ID.Kind = ValID::t_Constant;
4236 return false;
4237 }
4238
4239 case lltok::kw_trunc:
4240 case lltok::kw_bitcast:
4242 case lltok::kw_inttoptr:
4243 case lltok::kw_ptrtoint: {
4244 unsigned Opc = Lex.getUIntVal();
4245 Type *DestTy = nullptr;
4246 Constant *SrcVal;
4247 Lex.Lex();
4248 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
4249 parseGlobalTypeAndValue(SrcVal) ||
4250 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
4251 parseType(DestTy) ||
4252 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
4253 return true;
4254 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
4255 return error(ID.Loc, "invalid cast opcode for cast from '" +
4256 getTypeString(SrcVal->getType()) + "' to '" +
4257 getTypeString(DestTy) + "'");
4259 SrcVal, DestTy);
4260 ID.Kind = ValID::t_Constant;
4261 return false;
4262 }
4264 return error(ID.Loc, "extractvalue constexprs are no longer supported");
4266 return error(ID.Loc, "insertvalue constexprs are no longer supported");
4267 case lltok::kw_udiv:
4268 return error(ID.Loc, "udiv constexprs are no longer supported");
4269 case lltok::kw_sdiv:
4270 return error(ID.Loc, "sdiv constexprs are no longer supported");
4271 case lltok::kw_urem:
4272 return error(ID.Loc, "urem constexprs are no longer supported");
4273 case lltok::kw_srem:
4274 return error(ID.Loc, "srem constexprs are no longer supported");
4275 case lltok::kw_fadd:
4276 return error(ID.Loc, "fadd constexprs are no longer supported");
4277 case lltok::kw_fsub:
4278 return error(ID.Loc, "fsub constexprs are no longer supported");
4279 case lltok::kw_fmul:
4280 return error(ID.Loc, "fmul constexprs are no longer supported");
4281 case lltok::kw_fdiv:
4282 return error(ID.Loc, "fdiv constexprs are no longer supported");
4283 case lltok::kw_frem:
4284 return error(ID.Loc, "frem constexprs are no longer supported");
4285 case lltok::kw_and:
4286 return error(ID.Loc, "and constexprs are no longer supported");
4287 case lltok::kw_or:
4288 return error(ID.Loc, "or constexprs are no longer supported");
4289 case lltok::kw_lshr:
4290 return error(ID.Loc, "lshr constexprs are no longer supported");
4291 case lltok::kw_ashr:
4292 return error(ID.Loc, "ashr constexprs are no longer supported");
4293 case lltok::kw_shl:
4294 return error(ID.Loc, "shl constexprs are no longer supported");
4295 case lltok::kw_fneg:
4296 return error(ID.Loc, "fneg constexprs are no longer supported");
4297 case lltok::kw_select:
4298 return error(ID.Loc, "select constexprs are no longer supported");
4299 case lltok::kw_zext:
4300 return error(ID.Loc, "zext constexprs are no longer supported");
4301 case lltok::kw_sext:
4302 return error(ID.Loc, "sext constexprs are no longer supported");
4303 case lltok::kw_fptrunc:
4304 return error(ID.Loc, "fptrunc constexprs are no longer supported");
4305 case lltok::kw_fpext:
4306 return error(ID.Loc, "fpext constexprs are no longer supported");
4307 case lltok::kw_uitofp:
4308 return error(ID.Loc, "uitofp constexprs are no longer supported");
4309 case lltok::kw_sitofp:
4310 return error(ID.Loc, "sitofp constexprs are no longer supported");
4311 case lltok::kw_fptoui:
4312 return error(ID.Loc, "fptoui constexprs are no longer supported");
4313 case lltok::kw_fptosi:
4314 return error(ID.Loc, "fptosi constexprs are no longer supported");
4315 case lltok::kw_icmp:
4316 return error(ID.Loc, "icmp constexprs are no longer supported");
4317 case lltok::kw_fcmp:
4318 return error(ID.Loc, "fcmp constexprs are no longer supported");
4319
4320 // Binary Operators.
4321 case lltok::kw_add:
4322 case lltok::kw_sub:
4323 case lltok::kw_mul:
4324 case lltok::kw_xor: {
4325 bool NUW = false;
4326 bool NSW = false;
4327 unsigned Opc = Lex.getUIntVal();
4328 Constant *Val0, *Val1;
4329 Lex.Lex();
4330 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
4331 Opc == Instruction::Mul) {
4332 if (EatIfPresent(lltok::kw_nuw))
4333 NUW = true;
4334 if (EatIfPresent(lltok::kw_nsw)) {
4335 NSW = true;
4336 if (EatIfPresent(lltok::kw_nuw))
4337 NUW = true;
4338 }
4339 }
4340 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
4341 parseGlobalTypeAndValue(Val0) ||
4342 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
4343 parseGlobalTypeAndValue(Val1) ||
4344 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
4345 return true;
4346 if (Val0->getType() != Val1->getType())
4347 return error(ID.Loc, "operands of constexpr must have same type");
4348 // Check that the type is valid for the operator.
4349 if (!Val0->getType()->isIntOrIntVectorTy())
4350 return error(ID.Loc,
4351 "constexpr requires integer or integer vector operands");
4352 unsigned Flags = 0;
4355 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
4356 ID.Kind = ValID::t_Constant;
4357 return false;
4358 }
4359
4360 case lltok::kw_splat: {
4361 Lex.Lex();
4362 if (parseToken(lltok::lparen, "expected '(' after vector splat"))
4363 return true;
4364 Constant *C;
4365 if (parseGlobalTypeAndValue(C))
4366 return true;
4367 if (parseToken(lltok::rparen, "expected ')' at end of vector splat"))
4368 return true;
4369
4370 ID.ConstantVal = C;
4372 return false;
4373 }
4374
4379 unsigned Opc = Lex.getUIntVal();
4381 GEPNoWrapFlags NW;
4382 bool HasInRange = false;
4383 APSInt InRangeStart;
4384 APSInt InRangeEnd;
4385 Type *Ty;
4386 Lex.Lex();
4387
4388 if (Opc == Instruction::GetElementPtr) {
4389 while (true) {
4390 if (EatIfPresent(lltok::kw_inbounds))
4392 else if (EatIfPresent(lltok::kw_nusw))
4394 else if (EatIfPresent(lltok::kw_nuw))
4396 else
4397 break;
4398 }
4399
4400 if (EatIfPresent(lltok::kw_inrange)) {
4401 if (parseToken(lltok::lparen, "expected '('"))
4402 return true;
4403 if (Lex.getKind() != lltok::APSInt)
4404 return tokError("expected integer");
4405 InRangeStart = Lex.getAPSIntVal();
4406 Lex.Lex();
4407 if (parseToken(lltok::comma, "expected ','"))
4408 return true;
4409 if (Lex.getKind() != lltok::APSInt)
4410 return tokError("expected integer");
4411 InRangeEnd = Lex.getAPSIntVal();
4412 Lex.Lex();
4413 if (parseToken(lltok::rparen, "expected ')'"))
4414 return true;
4415 HasInRange = true;
4416 }
4417 }
4418
4419 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
4420 return true;
4421
4422 if (Opc == Instruction::GetElementPtr) {
4423 if (parseType(Ty) ||
4424 parseToken(lltok::comma, "expected comma after getelementptr's type"))
4425 return true;
4426 }
4427
4428 if (parseGlobalValueVector(Elts) ||
4429 parseToken(lltok::rparen, "expected ')' in constantexpr"))
4430 return true;
4431
4432 if (Opc == Instruction::GetElementPtr) {
4433 if (Elts.size() == 0 ||
4434 !Elts[0]->getType()->isPtrOrPtrVectorTy())
4435 return error(ID.Loc, "base of getelementptr must be a pointer");
4436
4437 Type *BaseType = Elts[0]->getType();
4438 std::optional<ConstantRange> InRange;
4439 if (HasInRange) {
4440 unsigned IndexWidth =
4441 M->getDataLayout().getIndexTypeSizeInBits(BaseType);
4442 InRangeStart = InRangeStart.extOrTrunc(IndexWidth);
4443 InRangeEnd = InRangeEnd.extOrTrunc(IndexWidth);
4444 if (InRangeStart.sge(InRangeEnd))
4445 return error(ID.Loc, "expected end to be larger than start");
4446 InRange = ConstantRange::getNonEmpty(InRangeStart, InRangeEnd);
4447 }
4448
4449 unsigned GEPWidth =
4450 BaseType->isVectorTy()
4451 ? cast<FixedVectorType>(BaseType)->getNumElements()
4452 : 0;
4453
4454 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
4455 for (Constant *Val : Indices) {
4456 Type *ValTy = Val->getType();
4457 if (!ValTy->isIntOrIntVectorTy())
4458 return error(ID.Loc, "getelementptr index must be an integer");
4459 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
4460 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
4461 if (GEPWidth && (ValNumEl != GEPWidth))
4462 return error(
4463 ID.Loc,
4464 "getelementptr vector index has a wrong number of elements");
4465 // GEPWidth may have been unknown because the base is a scalar,
4466 // but it is known now.
4467 GEPWidth = ValNumEl;
4468 }
4469 }
4470
4471 SmallPtrSet<Type*, 4> Visited;
4472 if (!Indices.empty() && !Ty->isSized(&Visited))
4473 return error(ID.Loc, "base element of getelementptr must be sized");
4474
4475 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4476 return error(ID.Loc, "invalid getelementptr indices");
4477
4478 ID.ConstantVal =
4479 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, NW, InRange);
4480 } else if (Opc == Instruction::ShuffleVector) {
4481 if (Elts.size() != 3)
4482 return error(ID.Loc, "expected three operands to shufflevector");
4483 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4484 return error(ID.Loc, "invalid operands to shufflevector");
4486 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
4487 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4488 } else if (Opc == Instruction::ExtractElement) {
4489 if (Elts.size() != 2)
4490 return error(ID.Loc, "expected two operands to extractelement");
4491 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4492 return error(ID.Loc, "invalid extractelement operands");
4493 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4494 } else {
4495 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4496 if (Elts.size() != 3)
4497 return error(ID.Loc, "expected three operands to insertelement");
4498 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4499 return error(ID.Loc, "invalid insertelement operands");
4500 ID.ConstantVal =
4501 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4502 }
4503
4504 ID.Kind = ValID::t_Constant;
4505 return false;
4506 }
4507 }
4508
4509 Lex.Lex();
4510 return false;
4511}
4512
4513/// parseGlobalValue - parse a global value with the specified type.
4514bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4515 C = nullptr;
4516 ValID ID;
4517 Value *V = nullptr;
4518 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4519 convertValIDToValue(Ty, ID, V, nullptr);
4520 if (V && !(C = dyn_cast<Constant>(V)))
4521 return error(ID.Loc, "global values must be constants");
4522 return Parsed;
4523}
4524
4525bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4526 Type *Ty = nullptr;
4527 return parseType(Ty) || parseGlobalValue(Ty, V);
4528}
4529
4530bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4531 C = nullptr;
4532
4533 LocTy KwLoc = Lex.getLoc();
4534 if (!EatIfPresent(lltok::kw_comdat))
4535 return false;
4536
4537 if (EatIfPresent(lltok::lparen)) {
4538 if (Lex.getKind() != lltok::ComdatVar)
4539 return tokError("expected comdat variable");
4540 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4541 Lex.Lex();
4542 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4543 return true;
4544 } else {
4545 if (GlobalName.empty())
4546 return tokError("comdat cannot be unnamed");
4547 C = getComdat(std::string(GlobalName), KwLoc);
4548 }
4549
4550 return false;
4551}
4552
4553/// parseGlobalValueVector
4554/// ::= /*empty*/
4555/// ::= TypeAndValue (',' TypeAndValue)*
4556bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
4557 // Empty list.
4558 if (Lex.getKind() == lltok::rbrace ||
4559 Lex.getKind() == lltok::rsquare ||
4560 Lex.getKind() == lltok::greater ||
4561 Lex.getKind() == lltok::rparen)
4562 return false;
4563
4564 do {
4565 // Let the caller deal with inrange.
4566 if (Lex.getKind() == lltok::kw_inrange)
4567 return false;
4568
4569 Constant *C;
4570 if (parseGlobalTypeAndValue(C))
4571 return true;
4572 Elts.push_back(C);
4573 } while (EatIfPresent(lltok::comma));
4574
4575 return false;
4576}
4577
4578bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4580 if (parseMDNodeVector(Elts))
4581 return true;
4582
4583 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4584 return false;
4585}
4586
4587/// MDNode:
4588/// ::= !{ ... }
4589/// ::= !7
4590/// ::= !DILocation(...)
4591bool LLParser::parseMDNode(MDNode *&N) {
4592 if (Lex.getKind() == lltok::MetadataVar)
4593 return parseSpecializedMDNode(N);
4594
4595 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4596}
4597
4598bool LLParser::parseMDNodeTail(MDNode *&N) {
4599 // !{ ... }
4600 if (Lex.getKind() == lltok::lbrace)
4601 return parseMDTuple(N);
4602
4603 // !42
4604 return parseMDNodeID(N);
4605}
4606
4607namespace {
4608
4609/// Structure to represent an optional metadata field.
4610template <class FieldTy> struct MDFieldImpl {
4611 typedef MDFieldImpl ImplTy;
4612 FieldTy Val;
4613 bool Seen;
4614
4615 void assign(FieldTy Val) {
4616 Seen = true;
4617 this->Val = std::move(Val);
4618 }
4619
4620 explicit MDFieldImpl(FieldTy Default)
4621 : Val(std::move(Default)), Seen(false) {}
4622};
4623
4624/// Structure to represent an optional metadata field that
4625/// can be of either type (A or B) and encapsulates the
4626/// MD<typeofA>Field and MD<typeofB>Field structs, so not
4627/// to reimplement the specifics for representing each Field.
4628template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4629 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4630 FieldTypeA A;
4631 FieldTypeB B;
4632 bool Seen;
4633
4634 enum {
4635 IsInvalid = 0,
4636 IsTypeA = 1,
4637 IsTypeB = 2
4638 } WhatIs;
4639
4640 void assign(FieldTypeA A) {
4641 Seen = true;
4642 this->A = std::move(A);
4643 WhatIs = IsTypeA;
4644 }
4645
4646 void assign(FieldTypeB B) {
4647 Seen = true;
4648 this->B = std::move(B);
4649 WhatIs = IsTypeB;
4650 }
4651
4652 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4653 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4654 WhatIs(IsInvalid) {}
4655};
4656
4657struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4658 uint64_t Max;
4659
4660 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4661 : ImplTy(Default), Max(Max) {}
4662};
4663
4664struct LineField : public MDUnsignedField {
4665 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4666};
4667
4668struct ColumnField : public MDUnsignedField {
4669 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4670};
4671
4672struct DwarfTagField : public MDUnsignedField {
4673 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4674 DwarfTagField(dwarf::Tag DefaultTag)
4675 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4676};
4677
4678struct DwarfMacinfoTypeField : public MDUnsignedField {
4679 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4680 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4681 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4682};
4683
4684struct DwarfAttEncodingField : public MDUnsignedField {
4685 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4686};
4687
4688struct DwarfVirtualityField : public MDUnsignedField {
4689 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4690};
4691
4692struct DwarfLangField : public MDUnsignedField {
4693 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4694};
4695
4696struct DwarfCCField : public MDUnsignedField {
4697 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4698};
4699
4700struct EmissionKindField : public MDUnsignedField {
4701 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4702};
4703
4704struct NameTableKindField : public MDUnsignedField {
4705 NameTableKindField()
4706 : MDUnsignedField(
4707 0, (unsigned)
4708 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4709};
4710
4711struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4712 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4713};
4714
4715struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4716 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4717};
4718
4719struct MDAPSIntField : public MDFieldImpl<APSInt> {
4720 MDAPSIntField() : ImplTy(APSInt()) {}
4721};
4722
4723struct MDSignedField : public MDFieldImpl<int64_t> {
4724 int64_t Min = INT64_MIN;
4725 int64_t Max = INT64_MAX;
4726
4727 MDSignedField(int64_t Default = 0)
4728 : ImplTy(Default) {}
4729 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4730 : ImplTy(Default), Min(Min), Max(Max) {}
4731};
4732
4733struct MDBoolField : public MDFieldImpl<bool> {
4734 MDBoolField(bool Default = false) : ImplTy(Default) {}
4735};
4736
4737struct MDField : public MDFieldImpl<Metadata *> {
4738 bool AllowNull;
4739
4740 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4741};
4742
4743struct MDStringField : public MDFieldImpl<MDString *> {
4744 bool AllowEmpty;
4745 MDStringField(bool AllowEmpty = true)
4746 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4747};
4748
4749struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4750 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4751};
4752
4753struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4754 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4755};
4756
4757struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4758 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4759 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4760
4761 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4762 bool AllowNull = true)
4763 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4764
4765 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4766 bool isMDField() const { return WhatIs == IsTypeB; }
4767 int64_t getMDSignedValue() const {
4768 assert(isMDSignedField() && "Wrong field type");
4769 return A.Val;
4770 }
4771 Metadata *getMDFieldValue() const {
4772 assert(isMDField() && "Wrong field type");
4773 return B.Val;
4774 }
4775};
4776
4777} // end anonymous namespace
4778
4779namespace llvm {
4780
4781template <>
4782bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4783 if (Lex.getKind() != lltok::APSInt)
4784 return tokError("expected integer");
4785
4786 Result.assign(Lex.getAPSIntVal());
4787 Lex.Lex();
4788 return false;
4789}
4790
4791template <>
4792bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4793 MDUnsignedField &Result) {
4794 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4795 return tokError("expected unsigned integer");
4796
4797 auto &U = Lex.getAPSIntVal();
4798 if (U.ugt(Result.Max))
4799 return tokError("value for '" + Name + "' too large, limit is " +
4800 Twine(Result.Max));
4801 Result.assign(U.getZExtValue());
4802 assert(Result.Val <= Result.Max && "Expected value in range");
4803 Lex.Lex();
4804 return false;
4805}
4806
4807template <>
4808bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4809 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4810}
4811template <>
4812bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4813 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4814}
4815
4816template <>
4817bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4818 if (Lex.getKind() == lltok::APSInt)
4819 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4820
4821 if (Lex.getKind() != lltok::DwarfTag)
4822 return tokError("expected DWARF tag");
4823
4824 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4826 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4827 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4828
4829 Result.assign(Tag);
4830 Lex.Lex();
4831 return false;
4832}
4833
4834template <>
4835bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4836 DwarfMacinfoTypeField &Result) {
4837 if (Lex.getKind() == lltok::APSInt)
4838 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4839
4840 if (Lex.getKind() != lltok::DwarfMacinfo)
4841 return tokError("expected DWARF macinfo type");
4842
4843 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4844 if (Macinfo == dwarf::DW_MACINFO_invalid)
4845 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4846 Lex.getStrVal() + "'");
4847 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4848
4849 Result.assign(Macinfo);
4850 Lex.Lex();
4851 return false;
4852}
4853
4854template <>
4855bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4856 DwarfVirtualityField &Result) {
4857 if (Lex.getKind() == lltok::APSInt)
4858 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4859
4860 if (Lex.getKind() != lltok::DwarfVirtuality)
4861 return tokError("expected DWARF virtuality code");
4862
4863 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4864 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4865 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4866 Lex.getStrVal() + "'");
4867 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4868 Result.assign(Virtuality);
4869 Lex.Lex();
4870 return false;
4871}
4872
4873template <>
4874bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4875 if (Lex.getKind() == lltok::APSInt)
4876 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4877
4878 if (Lex.getKind() != lltok::DwarfLang)
4879 return tokError("expected DWARF language");
4880
4881 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4882 if (!Lang)
4883 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4884 "'");
4885 assert(Lang <= Result.Max && "Expected valid DWARF language");
4886 Result.assign(Lang);
4887 Lex.Lex();
4888 return false;
4889}
4890
4891template <>
4892bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4893 if (Lex.getKind() == lltok::APSInt)
4894 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4895
4896 if (Lex.getKind() != lltok::DwarfCC)
4897 return tokError("expected DWARF calling convention");
4898
4899 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4900 if (!CC)
4901 return tokError("invalid DWARF calling convention" + Twine(" '") +
4902 Lex.getStrVal() + "'");
4903 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4904 Result.assign(CC);
4905 Lex.Lex();
4906 return false;
4907}
4908
4909template <>
4910bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4911 EmissionKindField &Result) {
4912 if (Lex.getKind() == lltok::APSInt)
4913 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4914
4915 if (Lex.getKind() != lltok::EmissionKind)
4916 return tokError("expected emission kind");
4917
4918 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4919 if (!Kind)
4920 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4921 "'");
4922 assert(*Kind <= Result.Max && "Expected valid emission kind");
4923 Result.assign(*Kind);
4924 Lex.Lex();
4925 return false;
4926}
4927
4928template <>
4929bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4930 NameTableKindField &Result) {
4931 if (Lex.getKind() == lltok::APSInt)
4932 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4933
4934 if (Lex.getKind() != lltok::NameTableKind)
4935 return tokError("expected nameTable kind");
4936
4937 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4938 if (!Kind)
4939 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4940 "'");
4941 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4942 Result.assign((unsigned)*Kind);
4943 Lex.Lex();
4944 return false;
4945}
4946
4947template <>
4948bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4949 DwarfAttEncodingField &Result) {
4950 if (Lex.getKind() == lltok::APSInt)
4951 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4952
4953 if (Lex.getKind() != lltok::DwarfAttEncoding)
4954 return tokError("expected DWARF type attribute encoding");
4955
4956 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4957 if (!Encoding)
4958 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4959 Lex.getStrVal() + "'");
4960 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4961 Result.assign(Encoding);
4962 Lex.Lex();
4963 return false;
4964}
4965
4966/// DIFlagField
4967/// ::= uint32
4968/// ::= DIFlagVector
4969/// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4970template <>
4971bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4972
4973 // parser for a single flag.
4974 auto parseFlag = [&](DINode::DIFlags &Val) {
4975 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4976 uint32_t TempVal = static_cast<uint32_t>(Val);
4977 bool Res = parseUInt32(TempVal);
4978 Val = static_cast<DINode::DIFlags>(TempVal);
4979 return Res;
4980 }
4981
4982 if (Lex.getKind() != lltok::DIFlag)
4983 return tokError("expected debug info flag");
4984
4985 Val = DINode::getFlag(Lex.getStrVal());
4986 if (!Val)
4987 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
4988 "'");
4989 Lex.Lex();
4990 return false;
4991 };
4992
4993 // parse the flags and combine them together.
4994 DINode::DIFlags Combined = DINode::FlagZero;
4995 do {
4996 DINode::DIFlags Val;
4997 if (parseFlag(Val))
4998 return true;
4999 Combined |= Val;
5000 } while (EatIfPresent(lltok::bar));
5001
5002 Result.assign(Combined);
5003 return false;
5004}
5005
5006/// DISPFlagField
5007/// ::= uint32
5008/// ::= DISPFlagVector
5009/// ::= DISPFlagVector '|' DISPFlag* '|' uint32
5010template <>
5011bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
5012
5013 // parser for a single flag.
5014 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
5015 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
5016 uint32_t TempVal = static_cast<uint32_t>(Val);
5017 bool Res = parseUInt32(TempVal);
5018 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
5019 return Res;
5020 }
5021
5022 if (Lex.getKind() != lltok::DISPFlag)
5023 return tokError("expected debug info flag");
5024
5025 Val = DISubprogram::getFlag(Lex.getStrVal());
5026 if (!Val)
5027 return tokError(Twine("invalid subprogram debug info flag '") +
5028 Lex.getStrVal() + "'");
5029 Lex.Lex();
5030 return false;
5031 };
5032
5033 // parse the flags and combine them together.
5034 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
5035 do {
5037 if (parseFlag(Val))
5038 return true;
5039 Combined |= Val;
5040 } while (EatIfPresent(lltok::bar));
5041
5042 Result.assign(Combined);
5043 return false;
5044}
5045
5046template <>
5047bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
5048 if (Lex.getKind() != lltok::APSInt)
5049 return tokError("expected signed integer");
5050
5051 auto &S = Lex.getAPSIntVal();
5052 if (S < Result.Min)
5053 return tokError("value for '" + Name + "' too small, limit is " +
5054 Twine(Result.Min));
5055 if (S > Result.Max)
5056 return tokError("value for '" + Name + "' too large, limit is " +
5057 Twine(Result.Max));
5058 Result.assign(S.getExtValue());
5059 assert(Result.Val >= Result.Min && "Expected value in range");
5060 assert(Result.Val <= Result.Max && "Expected value in range");
5061 Lex.Lex();
5062 return false;
5063}
5064
5065template <>
5066bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
5067 switch (Lex.getKind()) {
5068 default:
5069 return tokError("expected 'true' or 'false'");
5070 case lltok::kw_true:
5071 Result.assign(true);
5072 break;
5073 case lltok::kw_false:
5074 Result.assign(false);
5075 break;
5076 }
5077 Lex.Lex();
5078 return false;
5079}
5080
5081template <>
5082bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
5083 if (Lex.getKind() == lltok::kw_null) {
5084 if (!Result.AllowNull)
5085 return tokError("'" + Name + "' cannot be null");
5086 Lex.Lex();
5087 Result.assign(nullptr);
5088 return false;
5089 }
5090
5091 Metadata *MD;
5092 if (parseMetadata(MD, nullptr))
5093 return true;
5094
5095 Result.assign(MD);
5096 return false;
5097}
5098
5099template <>
5100bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5101 MDSignedOrMDField &Result) {
5102 // Try to parse a signed int.
5103 if (Lex.getKind() == lltok::APSInt) {
5104 MDSignedField Res = Result.A;
5105 if (!parseMDField(Loc, Name, Res)) {
5106 Result.assign(Res);
5107 return false;
5108 }
5109 return true;
5110 }
5111
5112 // Otherwise, try to parse as an MDField.
5113 MDField Res = Result.B;
5114 if (!parseMDField(Loc, Name, Res)) {
5115 Result.assign(Res);
5116 return false;
5117 }
5118
5119 return true;
5120}
5121
5122template <>
5123bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
5124 LocTy ValueLoc = Lex.getLoc();
5125 std::string S;
5126 if (parseStringConstant(S))
5127 return true;
5128
5129 if (!Result.AllowEmpty && S.empty())
5130 return error(ValueLoc, "'" + Name + "' cannot be empty");
5131
5132 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
5133 return false;
5134}
5135
5136template <>
5137bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
5139 if (parseMDNodeVector(MDs))
5140 return true;
5141
5142 Result.assign(std::move(MDs));
5143 return false;
5144}
5145
5146template <>
5147bool LLParser::parseMDField(LocTy Loc, StringRef Name,
5148 ChecksumKindField &Result) {
5149 std::optional<DIFile::ChecksumKind> CSKind =
5151
5152 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
5153 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
5154 "'");
5155
5156 Result.assign(*CSKind);
5157 Lex.Lex();
5158 return false;
5159}
5160
5161} // end namespace llvm
5162
5163template <class ParserTy>
5164bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
5165 do {
5166 if (Lex.getKind() != lltok::LabelStr)
5167 return tokError("expected field label here");
5168
5169 if (ParseField())
5170 return true;
5171 } while (EatIfPresent(lltok::comma));
5172
5173 return false;
5174}
5175
5176template <class ParserTy>
5177bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
5178 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5179 Lex.Lex();
5180
5181 if (parseToken(lltok::lparen, "expected '(' here"))
5182 return true;
5183 if (Lex.getKind() != lltok::rparen)
5184 if (parseMDFieldsImplBody(ParseField))
5185 return true;
5186
5187 ClosingLoc = Lex.getLoc();
5188 return parseToken(lltok::rparen, "expected ')' here");
5189}
5190
5191template <class FieldTy>
5192bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
5193 if (Result.Seen)
5194 return tokError("field '" + Name + "' cannot be specified more than once");
5195
5196 LocTy Loc = Lex.getLoc();
5197 Lex.Lex();
5198 return parseMDField(Loc, Name, Result);
5199}
5200
5201bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
5202 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5203
5204#define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
5205 if (Lex.getStrVal() == #CLASS) \
5206 return parse##CLASS(N, IsDistinct);
5207#include "llvm/IR/Metadata.def"
5208
5209 return tokError("expected metadata type");
5210}
5211
5212#define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
5213#define NOP_FIELD(NAME, TYPE, INIT)
5214#define REQUIRE_FIELD(NAME, TYPE, INIT) \
5215 if (!NAME.Seen) \
5216 return error(ClosingLoc, "missing required field '" #NAME "'");
5217#define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
5218 if (Lex.getStrVal() == #NAME) \
5219 return parseMDField(#NAME, NAME);
5220#define PARSE_MD_FIELDS() \
5221 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
5222 do { \
5223 LocTy ClosingLoc; \
5224 if (parseMDFieldsImpl( \
5225 [&]() -> bool { \
5226 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
5227 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
5228 "'"); \
5229 }, \
5230 ClosingLoc)) \
5231 return true; \
5232 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
5233 } while (false)
5234#define GET_OR_DISTINCT(CLASS, ARGS) \
5235 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
5236
5237/// parseDILocationFields:
5238/// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
5239/// isImplicitCode: true)
5240bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
5241#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5242 OPTIONAL(line, LineField, ); \
5243 OPTIONAL(column, ColumnField, ); \
5244 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5245 OPTIONAL(inlinedAt, MDField, ); \
5246 OPTIONAL(isImplicitCode, MDBoolField, (false));
5248#undef VISIT_MD_FIELDS
5249
5250 Result =
5251 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
5252 inlinedAt.Val, isImplicitCode.Val));
5253 return false;
5254}
5255
5256/// parseDIAssignID:
5257/// ::= distinct !DIAssignID()
5258bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
5259 if (!IsDistinct)
5260 return tokError("missing 'distinct', required for !DIAssignID()");
5261
5262 Lex.Lex();
5263
5264 // Now eat the parens.
5265 if (parseToken(lltok::lparen, "expected '(' here"))
5266 return true;
5267 if (parseToken(lltok::rparen, "expected ')' here"))
5268 return true;
5269
5271 return false;
5272}
5273
5274/// parseGenericDINode:
5275/// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
5276bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
5277#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5278 REQUIRED(tag, DwarfTagField, ); \
5279 OPTIONAL(header, MDStringField, ); \
5280 OPTIONAL(operands, MDFieldList, );
5282#undef VISIT_MD_FIELDS
5283
5285 (Context, tag.Val, header.Val, operands.Val));
5286 return false;
5287}
5288
5289/// parseDISubrange:
5290/// ::= !DISubrange(count: 30, lowerBound: 2)
5291/// ::= !DISubrange(count: !node, lowerBound: 2)
5292/// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
5293bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
5294#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5295 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
5296 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5297 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5298 OPTIONAL(stride, MDSignedOrMDField, );
5300#undef VISIT_MD_FIELDS
5301
5302 Metadata *Count = nullptr;
5303 Metadata *LowerBound = nullptr;
5304 Metadata *UpperBound = nullptr;
5305 Metadata *Stride = nullptr;
5306
5307 auto convToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5308 if (Bound.isMDSignedField())
5310 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
5311 if (Bound.isMDField())
5312 return Bound.getMDFieldValue();
5313 return nullptr;
5314 };
5315
5316 Count = convToMetadata(count);
5317 LowerBound = convToMetadata(lowerBound);
5318 UpperBound = convToMetadata(upperBound);
5319 Stride = convToMetadata(stride);
5320
5322 (Context, Count, LowerBound, UpperBound, Stride));
5323
5324 return false;
5325}
5326
5327/// parseDIGenericSubrange:
5328/// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5329/// !node3)
5330bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
5331#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5332 OPTIONAL(count, MDSignedOrMDField, ); \
5333 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5334 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5335 OPTIONAL(stride, MDSignedOrMDField, );
5337#undef VISIT_MD_FIELDS
5338
5339 auto ConvToMetadata = [&](const MDSignedOrMDField &Bound) -> Metadata * {
5340 if (Bound.isMDSignedField())
5341 return DIExpression::get(
5342 Context, {dwarf::DW_OP_consts,
5343 static_cast<uint64_t>(Bound.getMDSignedValue())});
5344 if (Bound.isMDField())
5345 return Bound.getMDFieldValue();
5346 return nullptr;
5347 };
5348
5349 Metadata *Count = ConvToMetadata(count);
5350 Metadata *LowerBound = ConvToMetadata(lowerBound);
5351 Metadata *UpperBound = ConvToMetadata(upperBound);
5352 Metadata *Stride = ConvToMetadata(stride);
5353
5355 (Context, Count, LowerBound, UpperBound, Stride));
5356
5357 return false;
5358}
5359
5360/// parseDIEnumerator:
5361/// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5362bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
5363#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5364 REQUIRED(name, MDStringField, ); \
5365 REQUIRED(value, MDAPSIntField, ); \
5366 OPTIONAL(isUnsigned, MDBoolField, (false));
5368#undef VISIT_MD_FIELDS
5369
5370 if (isUnsigned.Val && value.Val.isNegative())
5371 return tokError("unsigned enumerator with negative value");
5372
5373 APSInt Value(value.Val);
5374 // Add a leading zero so that unsigned values with the msb set are not
5375 // mistaken for negative values when used for signed enumerators.
5376 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
5377 Value = Value.zext(Value.getBitWidth() + 1);
5378
5379 Result =
5380 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
5381
5382 return false;
5383}
5384
5385/// parseDIBasicType:
5386/// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5387/// encoding: DW_ATE_encoding, flags: 0)
5388bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
5389#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5390 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5391 OPTIONAL(name, MDStringField, ); \
5392 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5393 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5394 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5395 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5396 OPTIONAL(flags, DIFlagField, );
5398#undef VISIT_MD_FIELDS
5399
5400 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
5401 align.Val, encoding.Val,
5402 num_extra_inhabitants.Val, flags.Val));
5403 return false;
5404}
5405
5406/// parseDIStringType:
5407/// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5408bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
5409#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5410 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5411 OPTIONAL(name, MDStringField, ); \
5412 OPTIONAL(stringLength, MDField, ); \
5413 OPTIONAL(stringLengthExpression, MDField, ); \
5414 OPTIONAL(stringLocationExpression, MDField, ); \
5415 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5416 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5417 OPTIONAL(encoding, DwarfAttEncodingField, );
5419#undef VISIT_MD_FIELDS
5420
5423 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
5424 stringLocationExpression.Val, size.Val, align.Val, encoding.Val));
5425 return false;
5426}
5427
5428/// parseDIDerivedType:
5429/// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5430/// line: 7, scope: !1, baseType: !2, size: 32,
5431/// align: 32, offset: 0, flags: 0, extraData: !3,
5432/// dwarfAddressSpace: 3, ptrAuthKey: 1,
5433/// ptrAuthIsAddressDiscriminated: true,
5434/// ptrAuthExtraDiscriminator: 0x1234,
5435/// ptrAuthIsaPointer: 1, ptrAuthAuthenticatesNullValues:1
5436/// )
5437bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
5438#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5439 REQUIRED(tag, DwarfTagField, ); \
5440 OPTIONAL(name, MDStringField, ); \
5441 OPTIONAL(file, MDField, ); \
5442 OPTIONAL(line, LineField, ); \
5443 OPTIONAL(scope, MDField, ); \
5444 REQUIRED(baseType, MDField, ); \
5445 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5446 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5447 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5448 OPTIONAL(flags, DIFlagField, ); \
5449 OPTIONAL(extraData, MDField, ); \
5450 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5451 OPTIONAL(annotations, MDField, ); \
5452 OPTIONAL(ptrAuthKey, MDUnsignedField, (0, 7)); \
5453 OPTIONAL(ptrAuthIsAddressDiscriminated, MDBoolField, ); \
5454 OPTIONAL(ptrAuthExtraDiscriminator, MDUnsignedField, (0, 0xffff)); \
5455 OPTIONAL(ptrAuthIsaPointer, MDBoolField, ); \
5456 OPTIONAL(ptrAuthAuthenticatesNullValues, MDBoolField, );
5458#undef VISIT_MD_FIELDS
5459
5460 std::optional<unsigned> DWARFAddressSpace;
5461 if (dwarfAddressSpace.Val != UINT32_MAX)
5462 DWARFAddressSpace = dwarfAddressSpace.Val;
5463 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
5464 if (ptrAuthKey.Val)
5465 PtrAuthData.emplace(
5466 (unsigned)ptrAuthKey.Val, ptrAuthIsAddressDiscriminated.Val,
5467 (unsigned)ptrAuthExtraDiscriminator.Val, ptrAuthIsaPointer.Val,
5468 ptrAuthAuthenticatesNullValues.Val);
5469
5471 (Context, tag.Val, name.Val, file.Val, line.Val,
5472 scope.Val, baseType.Val, size.Val, align.Val,
5473 offset.Val, DWARFAddressSpace, PtrAuthData,
5474 flags.Val, extraData.Val, annotations.Val));
5475 return false;
5476}
5477
5478bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5479#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5480 REQUIRED(tag, DwarfTagField, ); \
5481 OPTIONAL(name, MDStringField, ); \
5482 OPTIONAL(file, MDField, ); \
5483 OPTIONAL(line, LineField, ); \
5484 OPTIONAL(scope, MDField, ); \
5485 OPTIONAL(baseType, MDField, ); \
5486 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5487 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5488 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5489 OPTIONAL(flags, DIFlagField, ); \
5490 OPTIONAL(elements, MDField, ); \
5491 OPTIONAL(runtimeLang, DwarfLangField, ); \
5492 OPTIONAL(vtableHolder, MDField, ); \
5493 OPTIONAL(templateParams, MDField, ); \
5494 OPTIONAL(identifier, MDStringField, ); \
5495 OPTIONAL(discriminator, MDField, ); \
5496 OPTIONAL(dataLocation, MDField, ); \
5497 OPTIONAL(associated, MDField, ); \
5498 OPTIONAL(allocated, MDField, ); \
5499 OPTIONAL(rank, MDSignedOrMDField, ); \
5500 OPTIONAL(annotations, MDField, ); \
5501 OPTIONAL(num_extra_inhabitants, MDUnsignedField, (0, UINT32_MAX)); \
5502 OPTIONAL(specification, MDField, );
5504#undef VISIT_MD_FIELDS
5505
5506 Metadata *Rank = nullptr;
5507 if (rank.isMDSignedField())
5509 Type::getInt64Ty(Context), rank.getMDSignedValue()));
5510 else if (rank.isMDField())
5511 Rank = rank.getMDFieldValue();
5512
5513 // If this has an identifier try to build an ODR type.
5514 if (identifier.Val)
5515 if (auto *CT = DICompositeType::buildODRType(
5516 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5517 scope.Val, baseType.Val, size.Val, align.Val, offset.Val,
5518 specification.Val, num_extra_inhabitants.Val, flags.Val,
5519 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5520 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5521 Rank, annotations.Val)) {
5522 Result = CT;
5523 return false;
5524 }
5525
5526 // Create a new node, and save it in the context if it belongs in the type
5527 // map.
5530 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5531 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5532 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5533 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5534 annotations.Val, specification.Val, num_extra_inhabitants.Val));
5535 return false;
5536}
5537
5538bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5539#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5540 OPTIONAL(flags, DIFlagField, ); \
5541 OPTIONAL(cc, DwarfCCField, ); \
5542 REQUIRED(types, MDField, );
5544#undef VISIT_MD_FIELDS
5545
5547 (Context, flags.Val, cc.Val, types.Val));
5548 return false;
5549}
5550
5551/// parseDIFileType:
5552/// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5553/// checksumkind: CSK_MD5,
5554/// checksum: "000102030405060708090a0b0c0d0e0f",
5555/// source: "source file contents")
5556bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5557 // The default constructed value for checksumkind is required, but will never
5558 // be used, as the parser checks if the field was actually Seen before using
5559 // the Val.
5560#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5561 REQUIRED(filename, MDStringField, ); \
5562 REQUIRED(directory, MDStringField, ); \
5563 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5564 OPTIONAL(checksum, MDStringField, ); \
5565 OPTIONAL(source, MDStringField, );
5567#undef VISIT_MD_FIELDS
5568
5569 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5570 if (checksumkind.Seen && checksum.Seen)
5571 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5572 else if (checksumkind.Seen || checksum.Seen)
5573 return tokError("'checksumkind' and 'checksum' must be provided together");
5574
5575 MDString *Source = nullptr;
5576 if (source.Seen)
5577 Source = source.Val;
5579 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5580 return false;
5581}
5582
5583/// parseDICompileUnit:
5584/// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5585/// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5586/// splitDebugFilename: "abc.debug",
5587/// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5588/// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5589/// sysroot: "/", sdk: "MacOSX.sdk")
5590bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5591 if (!IsDistinct)
5592 return tokError("missing 'distinct', required for !DICompileUnit");
5593
5594#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5595 REQUIRED(language, DwarfLangField, ); \
5596 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5597 OPTIONAL(producer, MDStringField, ); \
5598 OPTIONAL(isOptimized, MDBoolField, ); \
5599 OPTIONAL(flags, MDStringField, ); \
5600 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5601 OPTIONAL(splitDebugFilename, MDStringField, ); \
5602 OPTIONAL(emissionKind, EmissionKindField, ); \
5603 OPTIONAL(enums, MDField, ); \
5604 OPTIONAL(retainedTypes, MDField, ); \
5605 OPTIONAL(globals, MDField, ); \
5606 OPTIONAL(imports, MDField, ); \
5607 OPTIONAL(macros, MDField, ); \
5608 OPTIONAL(dwoId, MDUnsignedField, ); \
5609 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5610 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5611 OPTIONAL(nameTableKind, NameTableKindField, ); \
5612 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5613 OPTIONAL(sysroot, MDStringField, ); \
5614 OPTIONAL(sdk, MDStringField, );
5616#undef VISIT_MD_FIELDS
5617
5619 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
5620 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5621 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
5622 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5623 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5624 return false;
5625}
5626
5627/// parseDISubprogram:
5628/// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5629/// file: !1, line: 7, type: !2, isLocal: false,
5630/// isDefinition: true, scopeLine: 8, containingType: !3,
5631/// virtuality: DW_VIRTUALTIY_pure_virtual,
5632/// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5633/// spFlags: 10, isOptimized: false, templateParams: !4,
5634/// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5635/// annotations: !8)
5636bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5637 auto Loc = Lex.getLoc();
5638#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5639 OPTIONAL(scope, MDField, ); \
5640 OPTIONAL(name, MDStringField, ); \
5641 OPTIONAL(linkageName, MDStringField, ); \
5642 OPTIONAL(file, MDField, ); \
5643 OPTIONAL(line, LineField, ); \
5644 OPTIONAL(type, MDField, ); \
5645 OPTIONAL(isLocal, MDBoolField, ); \
5646 OPTIONAL(isDefinition, MDBoolField, (true)); \
5647 OPTIONAL(scopeLine, LineField, ); \
5648 OPTIONAL(containingType, MDField, ); \
5649 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5650 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5651 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5652 OPTIONAL(flags, DIFlagField, ); \
5653 OPTIONAL(spFlags, DISPFlagField, ); \
5654 OPTIONAL(isOptimized, MDBoolField, ); \
5655 OPTIONAL(unit, MDField, ); \
5656 OPTIONAL(templateParams, MDField, ); \
5657 OPTIONAL(declaration, MDField, ); \
5658 OPTIONAL(retainedNodes, MDField, ); \
5659 OPTIONAL(thrownTypes, MDField, ); \
5660 OPTIONAL(annotations, MDField, ); \
5661 OPTIONAL(targetFuncName, MDStringField, );
5663#undef VISIT_MD_FIELDS
5664
5665 // An explicit spFlags field takes precedence over individual fields in
5666 // older IR versions.
5667 DISubprogram::DISPFlags SPFlags =
5668 spFlags.Seen ? spFlags.Val
5669 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5670 isOptimized.Val, virtuality.Val);
5671 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5672 return error(
5673 Loc,
5674 "missing 'distinct', required for !DISubprogram that is a Definition");
5677 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5678 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5679 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5680 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5681 targetFuncName.Val));
5682 return false;
5683}
5684
5685/// parseDILexicalBlock:
5686/// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5687bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5688#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5689 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5690 OPTIONAL(file, MDField, ); \
5691 OPTIONAL(line, LineField, ); \
5692 OPTIONAL(column, ColumnField, );
5694#undef VISIT_MD_FIELDS
5695
5697 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5698 return false;
5699}
5700
5701/// parseDILexicalBlockFile:
5702/// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5703bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5704#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5705 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5706 OPTIONAL(file, MDField, ); \
5707 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5709#undef VISIT_MD_FIELDS
5710
5712 (Context, scope.Val, file.Val, discriminator.Val));
5713 return false;
5714}
5715
5716/// parseDICommonBlock:
5717/// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
5718bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
5719#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5720 REQUIRED(scope, MDField, ); \
5721 OPTIONAL(declaration, MDField, ); \
5722 OPTIONAL(name, MDStringField, ); \
5723 OPTIONAL(file, MDField, ); \
5724 OPTIONAL(line, LineField, );
5726#undef VISIT_MD_FIELDS
5727
5729 (Context, scope.Val, declaration.Val, name.Val,
5730 file.Val, line.Val));
5731 return false;
5732}
5733
5734/// parseDINamespace:
5735/// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
5736bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
5737#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5738 REQUIRED(scope, MDField, ); \
5739 OPTIONAL(name, MDStringField, ); \
5740 OPTIONAL(exportSymbols, MDBoolField, );
5742#undef VISIT_MD_FIELDS
5743
5745 (Context, scope.Val, name.Val, exportSymbols.Val));
5746 return false;
5747}
5748
5749/// parseDIMacro:
5750/// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5751/// "SomeValue")
5752bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
5753#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5754 REQUIRED(type, DwarfMacinfoTypeField, ); \
5755 OPTIONAL(line, LineField, ); \
5756 REQUIRED(name, MDStringField, ); \
5757 OPTIONAL(value, MDStringField, );
5759#undef VISIT_MD_FIELDS
5760
5762 (Context, type.Val, line.Val, name.Val, value.Val));
5763 return false;
5764}
5765
5766/// parseDIMacroFile:
5767/// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
5768bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
5769#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5770 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5771 OPTIONAL(line, LineField, ); \
5772 REQUIRED(file, MDField, ); \
5773 OPTIONAL(nodes, MDField, );
5775#undef VISIT_MD_FIELDS
5776
5778 (Context, type.Val, line.Val, file.Val, nodes.Val));
5779 return false;
5780}
5781
5782/// parseDIModule:
5783/// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5784/// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5785/// file: !1, line: 4, isDecl: false)
5786bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5787#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5788 REQUIRED(scope, MDField, ); \
5789 REQUIRED(name, MDStringField, ); \
5790 OPTIONAL(configMacros, MDStringField, ); \
5791 OPTIONAL(includePath, MDStringField, ); \
5792 OPTIONAL(apinotes, MDStringField, ); \
5793 OPTIONAL(file, MDField, ); \
5794 OPTIONAL(line, LineField, ); \
5795 OPTIONAL(isDecl, MDBoolField, );
5797#undef VISIT_MD_FIELDS
5798
5799 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5800 configMacros.Val, includePath.Val,
5801 apinotes.Val, line.Val, isDecl.Val));
5802 return false;
5803}
5804
5805/// parseDITemplateTypeParameter:
5806/// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5807bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5808#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5809 OPTIONAL(name, MDStringField, ); \
5810 REQUIRED(type, MDField, ); \
5811 OPTIONAL(defaulted, MDBoolField, );
5813#undef VISIT_MD_FIELDS
5814
5816 (Context, name.Val, type.Val, defaulted.Val));
5817 return false;
5818}
5819
5820/// parseDITemplateValueParameter:
5821/// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5822/// name: "V", type: !1, defaulted: false,
5823/// value: i32 7)
5824bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5825#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5826 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5827 OPTIONAL(name, MDStringField, ); \
5828 OPTIONAL(type, MDField, ); \
5829 OPTIONAL(defaulted, MDBoolField, ); \
5830 REQUIRED(value, MDField, );
5831
5833#undef VISIT_MD_FIELDS
5834
5837 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5838 return false;
5839}
5840
5841/// parseDIGlobalVariable:
5842/// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5843/// file: !1, line: 7, type: !2, isLocal: false,
5844/// isDefinition: true, templateParams: !3,
5845/// declaration: !4, align: 8)
5846bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5847#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5848 OPTIONAL(name, MDStringField, (/* AllowEmpty */ false)); \
5849 OPTIONAL(scope, MDField, ); \
5850 OPTIONAL(linkageName, MDStringField, ); \
5851 OPTIONAL(file, MDField, ); \
5852 OPTIONAL(line, LineField, ); \
5853 OPTIONAL(type, MDField, ); \
5854 OPTIONAL(isLocal, MDBoolField, ); \
5855 OPTIONAL(isDefinition, MDBoolField, (true)); \
5856 OPTIONAL(templateParams, MDField, ); \
5857 OPTIONAL(declaration, MDField, ); \
5858 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5859 OPTIONAL(annotations, MDField, );
5861#undef VISIT_MD_FIELDS
5862
5863 Result =
5865 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5866 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5867 declaration.Val, templateParams.Val, align.Val,
5868 annotations.Val));
5869 return false;
5870}
5871
5872/// parseDILocalVariable:
5873/// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5874/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5875/// align: 8)
5876/// ::= !DILocalVariable(scope: !0, name: "foo",
5877/// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5878/// align: 8)
5879bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5880#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5881 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5882 OPTIONAL(name, MDStringField, ); \
5883 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5884 OPTIONAL(file, MDField, ); \
5885 OPTIONAL(line, LineField, ); \
5886 OPTIONAL(type, MDField, ); \
5887 OPTIONAL(flags, DIFlagField, ); \
5888 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5889 OPTIONAL(annotations, MDField, );
5891#undef VISIT_MD_FIELDS
5892
5894 (Context, scope.Val, name.Val, file.Val, line.Val,
5895 type.Val, arg.Val, flags.Val, align.Val,
5896 annotations.Val));
5897 return false;
5898}
5899
5900/// parseDILabel:
5901/// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5902bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5903#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5904 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5905 REQUIRED(name, MDStringField, ); \
5906 REQUIRED(file, MDField, ); \
5907 REQUIRED(line, LineField, );
5909#undef VISIT_MD_FIELDS
5910
5912 (Context, scope.Val, name.Val, file.Val, line.Val));
5913 return false;
5914}
5915
5916/// parseDIExpressionBody:
5917/// ::= (0, 7, -1)
5918bool LLParser::parseDIExpressionBody(MDNode *&Result, bool IsDistinct) {
5919 if (parseToken(lltok::lparen, "expected '(' here"))
5920 return true;
5921
5923 if (Lex.getKind() != lltok::rparen)
5924 do {
5925 if (Lex.getKind() == lltok::DwarfOp) {
5926 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5927 Lex.Lex();
5928 Elements.push_back(Op);
5929 continue;
5930 }
5931 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5932 }
5933
5934 if (Lex.getKind() == lltok::DwarfAttEncoding) {
5935 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5936 Lex.Lex();
5937 Elements.push_back(Op);
5938 continue;
5939 }
5940 return tokError(Twine("invalid DWARF attribute encoding '") +
5941 Lex.getStrVal() + "'");
5942 }
5943
5944 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5945 return tokError("expected unsigned integer");
5946
5947 auto &U = Lex.getAPSIntVal();
5948 if (U.ugt(UINT64_MAX))
5949 return tokError("element too large, limit is " + Twine(UINT64_MAX));
5950 Elements.push_back(U.getZExtValue());
5951 Lex.Lex();
5952 } while (EatIfPresent(lltok::comma));
5953
5954 if (parseToken(lltok::rparen, "expected ')' here"))
5955 return true;
5956
5957 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5958 return false;
5959}
5960
5961/// parseDIExpression:
5962/// ::= !DIExpression(0, 7, -1)
5963bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5964 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5965 assert(Lex.getStrVal() == "DIExpression" && "Expected '!DIExpression'");
5966 Lex.Lex();
5967
5968 return parseDIExpressionBody(Result, IsDistinct);
5969}
5970
5971/// ParseDIArgList:
5972/// ::= !DIArgList(i32 7, i64 %0)
5973bool LLParser::parseDIArgList(Metadata *&MD, PerFunctionState *PFS) {
5974 assert(PFS && "Expected valid function state");
5975 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5976 Lex.Lex();
5977
5978 if (parseToken(lltok::lparen, "expected '(' here"))
5979 return true;
5980
5982 if (Lex.getKind() != lltok::rparen)
5983 do {
5984 Metadata *MD;
5985 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5986 return true;
5987 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5988 } while (EatIfPresent(lltok::comma));
5989
5990 if (parseToken(lltok::rparen, "expected ')' here"))
5991 return true;
5992
5993 MD = DIArgList::get(Context, Args);
5994 return false;
5995}
5996
5997/// parseDIGlobalVariableExpression:
5998/// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5999bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
6000 bool IsDistinct) {
6001#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6002 REQUIRED(var, MDField, ); \
6003 REQUIRED(expr, MDField, );
6005#undef VISIT_MD_FIELDS
6006
6007 Result =
6008 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
6009 return false;
6010}
6011
6012/// parseDIObjCProperty:
6013/// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
6014/// getter: "getFoo", attributes: 7, type: !2)
6015bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
6016#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6017 OPTIONAL(name, MDStringField, ); \
6018 OPTIONAL(file, MDField, ); \
6019 OPTIONAL(line, LineField, ); \
6020 OPTIONAL(setter, MDStringField, ); \
6021 OPTIONAL(getter, MDStringField, ); \
6022 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
6023 OPTIONAL(type, MDField, );
6025#undef VISIT_MD_FIELDS
6026
6028 (Context, name.Val, file.Val, line.Val, setter.Val,
6029 getter.Val, attributes.Val, type.Val));
6030 return false;
6031}
6032
6033/// parseDIImportedEntity:
6034/// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
6035/// line: 7, name: "foo", elements: !2)
6036bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
6037#define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
6038 REQUIRED(tag, DwarfTagField, ); \
6039 REQUIRED(scope, MDField, ); \
6040 OPTIONAL(entity, MDField, ); \
6041 OPTIONAL(file, MDField, ); \
6042 OPTIONAL(line, LineField, ); \
6043 OPTIONAL(name, MDStringField, ); \
6044 OPTIONAL(elements, MDField, );
6046#undef VISIT_MD_FIELDS
6047
6049 (Context, tag.Val, scope.Val, entity.Val, file.Val,
6050 line.Val, name.Val, elements.Val));
6051 return false;
6052}
6053
6054#undef PARSE_MD_FIELD
6055#undef NOP_FIELD
6056#undef REQUIRE_FIELD
6057#undef DECLARE_FIELD
6058
6059/// parseMetadataAsValue
6060/// ::= metadata i32 %local
6061/// ::= metadata i32 @global
6062/// ::= metadata i32 7
6063/// ::= metadata !0
6064/// ::= metadata !{...}
6065/// ::= metadata !"string"
6066bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
6067 // Note: the type 'metadata' has already been parsed.
6068 Metadata *MD;
6069 if (parseMetadata(MD, &PFS))
6070 return true;
6071
6072 V = MetadataAsValue::get(Context, MD);
6073 return false;
6074}
6075
6076/// parseValueAsMetadata
6077/// ::= i32 %local
6078/// ::= i32 @global
6079/// ::= i32 7
6080bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
6081 PerFunctionState *PFS) {
6082 Type *Ty;
6083 LocTy Loc;
6084 if (parseType(Ty, TypeMsg, Loc))
6085 return true;
6086 if (Ty->isMetadataTy())
6087 return error(Loc, "invalid metadata-value-metadata roundtrip");
6088
6089 Value *V;
6090 if (parseValue(Ty, V, PFS))
6091 return true;
6092
6093 MD = ValueAsMetadata::get(V);
6094 return false;
6095}
6096
6097/// parseMetadata
6098/// ::= i32 %local
6099/// ::= i32 @global
6100/// ::= i32 7
6101/// ::= !42
6102/// ::= !{...}
6103/// ::= !"string"
6104/// ::= !DILocation(...)
6105bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
6106 if (Lex.getKind() == lltok::MetadataVar) {
6107 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
6108 // so parsing this requires a Function State.
6109 if (Lex.getStrVal() == "DIArgList") {
6110 Metadata *AL;
6111 if (parseDIArgList(AL, PFS))
6112 return true;
6113 MD = AL;
6114 return false;
6115 }
6116 MDNode *N;
6117 if (parseSpecializedMDNode(N)) {
6118 return true;
6119 }
6120 MD = N;
6121 return false;
6122 }
6123
6124 // ValueAsMetadata:
6125 // <type> <value>
6126 if (Lex.getKind() != lltok::exclaim)
6127 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
6128
6129 // '!'.
6130 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
6131 Lex.Lex();
6132
6133 // MDString:
6134 // ::= '!' STRINGCONSTANT
6135 if (Lex.getKind() == lltok::StringConstant) {
6136 MDString *S;
6137 if (parseMDString(S))
6138 return true;
6139 MD = S;
6140 return false;
6141 }
6142
6143 // MDNode:
6144 // !{ ... }
6145 // !7
6146 MDNode *N;
6147 if (parseMDNodeTail(N))
6148 return true;
6149 MD = N;
6150 return false;
6151}
6152
6153//===----------------------------------------------------------------------===//
6154// Function Parsing.
6155//===----------------------------------------------------------------------===//
6156
6157bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
6158 PerFunctionState *PFS) {
6159 if (Ty->isFunctionTy())
6160 return error(ID.Loc, "functions are not values, refer to them as pointers");
6161
6162 switch (ID.Kind) {
6163 case ValID::t_LocalID:
6164 if (!PFS)
6165 return error(ID.Loc, "invalid use of function-local name");
6166 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
6167 return V == nullptr;
6168 case ValID::t_LocalName:
6169 if (!PFS)
6170 return error(ID.Loc, "invalid use of function-local name");
6171 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
6172 return V == nullptr;
6173 case ValID::t_InlineAsm: {
6174 if (!ID.FTy)
6175 return error(ID.Loc, "invalid type for inline asm constraint string");
6176 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
6177 return error(ID.Loc, toString(std::move(Err)));
6178 V = InlineAsm::get(
6179 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
6180 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
6181 return false;
6182 }
6184 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
6185 if (V && ID.NoCFI)
6186 V = NoCFIValue::get(cast<GlobalValue>(V));
6187 return V == nullptr;
6188 case ValID::t_GlobalID:
6189 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
6190 if (V && ID.NoCFI)
6191 V = NoCFIValue::get(cast<GlobalValue>(V));
6192 return V == nullptr;
6193 case ValID::t_APSInt:
6194 if (!Ty->isIntegerTy())
6195 return error(ID.Loc, "integer constant must have integer type");
6196 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
6197 V = ConstantInt::get(Context, ID.APSIntVal);
6198 return false;
6199 case ValID::t_APFloat:
6200 if (!Ty->isFloatingPointTy() ||
6201 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
6202 return error(ID.Loc, "floating point constant invalid for type");
6203
6204 // The lexer has no type info, so builds all half, bfloat, float, and double
6205 // FP constants as double. Fix this here. Long double does not need this.
6206 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
6207 // Check for signaling before potentially converting and losing that info.
6208 bool IsSNAN = ID.APFloatVal.isSignaling();
6209 bool Ignored;
6210 if (Ty->isHalfTy())
6212 &Ignored);
6213 else if (Ty->isBFloatTy())
6214 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
6215 &Ignored);
6216 else if (Ty->isFloatTy())
6218 &Ignored);
6219 if (IsSNAN) {
6220 // The convert call above may quiet an SNaN, so manufacture another
6221 // SNaN. The bitcast works because the payload (significand) parameter
6222 // is truncated to fit.
6223 APInt Payload = ID.APFloatVal.bitcastToAPInt();
6224 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
6225 ID.APFloatVal.isNegative(), &Payload);
6226 }
6227 }
6228 V = ConstantFP::get(Context, ID.APFloatVal);
6229
6230 if (V->getType() != Ty)
6231 return error(ID.Loc, "floating point constant does not have type '" +
6232 getTypeString(Ty) + "'");
6233
6234 return false;
6235 case ValID::t_Null:
6236 if (!Ty->isPointerTy())
6237 return error(ID.Loc, "null must be a pointer type");
6238 V = ConstantPointerNull::get(cast<PointerType>(Ty));
6239 return false;
6240 case ValID::t_Undef:
6241 // FIXME: LabelTy should not be a first-class type.
6242 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6243 return error(ID.Loc, "invalid type for undef constant");
6244 V = UndefValue::get(Ty);
6245 return false;
6247 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
6248 return error(ID.Loc, "invalid empty array initializer");
6249 V = PoisonValue::get(Ty);
6250 return false;
6251 case ValID::t_Zero:
6252 // FIXME: LabelTy should not be a first-class type.
6253 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6254 return error(ID.Loc, "invalid type for null constant");
6255 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
6256 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
6257 return error(ID.Loc, "invalid type for null constant");
6259 return false;
6260 case ValID::t_None:
6261 if (!Ty->isTokenTy())
6262 return error(ID.Loc, "invalid type for none constant");
6264 return false;
6265 case ValID::t_Poison:
6266 // FIXME: LabelTy should not be a first-class type.
6267 if (!Ty->isFirstClassType() || Ty->isLabelTy())
6268 return error(ID.Loc, "invalid type for poison constant");
6269 V = PoisonValue::get(Ty);
6270 return false;
6271 case ValID::t_Constant:
6272 if (ID.ConstantVal->getType() != Ty)
6273 return error(ID.Loc, "constant expression type mismatch: got type '" +
6274 getTypeString(ID.ConstantVal->getType()) +
6275 "' but expected '" + getTypeString(Ty) + "'");
6276 V = ID.ConstantVal;
6277 return false;
6279 if (!Ty->isVectorTy())
6280 return error(ID.Loc, "vector constant must have vector type");
6281 if (ID.ConstantVal->getType() != Ty->getScalarType())
6282 return error(ID.Loc, "constant expression type mismatch: got type '" +
6283 getTypeString(ID.ConstantVal->getType()) +
6284 "' but expected '" +
6285 getTypeString(Ty->getScalarType()) + "'");
6286 V = ConstantVector::getSplat(cast<VectorType>(Ty)->getElementCount(),
6287 ID.ConstantVal);
6288 return false;
6291 if (StructType *ST = dyn_cast<StructType>(Ty)) {
6292 if (ST->getNumElements() != ID.UIntVal)
6293 return error(ID.Loc,
6294 "initializer with struct type has wrong # elements");
6295 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
6296 return error(ID.Loc, "packed'ness of initializer and type don't match");
6297
6298 // Verify that the elements are compatible with the structtype.
6299 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
6300 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
6301 return error(
6302 ID.Loc,
6303 "element " + Twine(i) +
6304 " of struct initializer doesn't match struct element type");
6305
6307 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
6308 } else
6309 return error(ID.Loc, "constant expression type mismatch");
6310 return false;
6311 }
6312 llvm_unreachable("Invalid ValID");
6313}
6314
6315bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
6316 C = nullptr;
6317 ValID ID;
6318 auto Loc = Lex.getLoc();
6319 if (parseValID(ID, /*PFS=*/nullptr))
6320 return true;
6321 switch (ID.Kind) {
6322 case ValID::t_APSInt:
6323 case ValID::t_APFloat:
6324 case ValID::t_Undef:
6325 case ValID::t_Poison:
6326 case ValID::t_Zero:
6327 case ValID::t_Constant:
6331 Value *V;
6332 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
6333 return true;
6334 assert(isa<Constant>(V) && "Expected a constant value");
6335 C = cast<Constant>(V);
6336 return false;
6337 }
6338 case ValID::t_Null:
6340 return false;
6341 default:
6342 return error(Loc, "expected a constant value");
6343 }
6344}
6345
6346bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
6347 V = nullptr;
6348 ValID ID;
6349 return parseValID(ID, PFS, Ty) ||
6350 convertValIDToValue(Ty, ID, V, PFS);
6351}
6352
6353bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
6354 Type *Ty = nullptr;
6355 return parseType(Ty) || parseValue(Ty, V, PFS);
6356}
6357
6358bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
6359 PerFunctionState &PFS) {
6360 Value *V;
6361 Loc = Lex.getLoc();
6362 if (parseTypeAndValue(V, PFS))
6363 return true;
6364 if (!isa<BasicBlock>(V))
6365 return error(Loc, "expected a basic block");
6366 BB = cast<BasicBlock>(V);
6367 return false;
6368}
6369
6371 // Exit early for the common (non-debug-intrinsic) case.
6372 // We can make this the only check when we begin supporting all "llvm.dbg"
6373 // intrinsics in the new debug info format.
6374 if (!Name.starts_with("llvm.dbg."))
6375 return false;
6377 return FnID == Intrinsic::dbg_declare || FnID == Intrinsic::dbg_value ||
6378 FnID == Intrinsic::dbg_assign;
6379}
6380
6381/// FunctionHeader
6382/// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6383/// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6384/// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6385/// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6386bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine,
6387 unsigned &FunctionNumber,
6388 SmallVectorImpl<unsigned> &UnnamedArgNums) {
6389 // parse the linkage.
6390 LocTy LinkageLoc = Lex.getLoc();
6391 unsigned Linkage;
6392 unsigned Visibility;
6393 unsigned DLLStorageClass;
6394 bool DSOLocal;
6395 AttrBuilder RetAttrs(M->getContext());
6396 unsigned CC;
6397 bool HasLinkage;
6398 Type *RetType = nullptr;
6399 LocTy RetTypeLoc = Lex.getLoc();
6400 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
6401 DSOLocal) ||
6402 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6403 parseType(RetType, RetTypeLoc, true /*void allowed*/))
6404 return true;
6405
6406 // Verify that the linkage is ok.
6407 switch ((GlobalValue::LinkageTypes)Linkage) {
6409 break; // always ok.
6411 if (IsDefine)
6412 return error(LinkageLoc, "invalid linkage for function definition");
6413 break;
6421 if (!IsDefine)
6422 return error(LinkageLoc, "invalid linkage for function declaration");
6423 break;
6426 return error(LinkageLoc, "invalid function linkage type");
6427 }
6428
6429 if (!isValidVisibilityForLinkage(Visibility, Linkage))
6430 return error(LinkageLoc,
6431 "symbol with local linkage must have default visibility");
6432
6433 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
6434 return error(LinkageLoc,
6435 "symbol with local linkage cannot have a DLL storage class");
6436
6437 if (!FunctionType::isValidReturnType(RetType))
6438 return error(RetTypeLoc, "invalid function return type");
6439
6440 LocTy NameLoc = Lex.getLoc();
6441
6442 std::string FunctionName;
6443 if (Lex.getKind() == lltok::GlobalVar) {
6444 FunctionName = Lex.getStrVal();
6445 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
6446 FunctionNumber = Lex.getUIntVal();
6447 if (checkValueID(NameLoc, "function", "@", NumberedVals.getNext(),
6448 FunctionNumber))
6449 return true;
6450 } else {
6451 return tokError("expected function name");
6452 }
6453
6454 Lex.Lex();
6455
6456 if (Lex.getKind() != lltok::lparen)
6457 return tokError("expected '(' in function argument list");
6458
6460 bool IsVarArg;
6461 AttrBuilder FuncAttrs(M->getContext());
6462 std::vector<unsigned> FwdRefAttrGrps;
6463 LocTy BuiltinLoc;
6464 std::string Section;
6465 std::string Partition;
6466 MaybeAlign Alignment;
6467 std::string GC;
6469 unsigned AddrSpace = 0;
6470 Constant *Prefix = nullptr;
6471 Constant *Prologue = nullptr;
6472 Constant *PersonalityFn = nullptr;
6473 Comdat *C;
6474
6475 if (parseArgumentList(ArgList, UnnamedArgNums, IsVarArg) ||
6476 parseOptionalUnnamedAddr(UnnamedAddr) ||
6477 parseOptionalProgramAddrSpace(AddrSpace) ||
6478 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
6479 BuiltinLoc) ||
6480 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
6481 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
6482 parseOptionalComdat(FunctionName, C) ||
6483 parseOptionalAlignment(Alignment) ||
6484 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
6485 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
6486 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
6487 (EatIfPresent(lltok::kw_personality) &&
6488 parseGlobalTypeAndValue(PersonalityFn)))
6489 return true;
6490
6491 if (FuncAttrs.contains(Attribute::Builtin))
6492 return error(BuiltinLoc, "'builtin' attribute not valid on function");
6493
6494 // If the alignment was parsed as an attribute, move to the alignment field.
6495 if (MaybeAlign A = FuncAttrs.getAlignment()) {
6496 Alignment = A;
6497 FuncAttrs.removeAttribute(Attribute::Alignment);
6498 }
6499
6500 // Okay, if we got here, the function is syntactically valid. Convert types
6501 // and do semantic checks.
6502 std::vector<Type*> ParamTypeList;
6504
6505 for (const ArgInfo &Arg : ArgList) {
6506 ParamTypeList.push_back(Arg.Ty);
6507 Attrs.push_back(Arg.Attrs);
6508 }
6509
6510 AttributeList PAL =
6511 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6512 AttributeSet::get(Context, RetAttrs), Attrs);
6513
6514 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6515 return error(RetTypeLoc, "functions with 'sret' argument must return void");
6516
6517 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6518 PointerType *PFT = PointerType::get(FT, AddrSpace);
6519
6520 Fn = nullptr;
6521 GlobalValue *FwdFn = nullptr;
6522 if (!FunctionName.empty()) {
6523 // If this was a definition of a forward reference, remove the definition
6524 // from the forward reference table and fill in the forward ref.
6525 auto FRVI = ForwardRefVals.find(FunctionName);
6526 if (FRVI != ForwardRefVals.end()) {
6527 FwdFn = FRVI->second.first;
6528 if (FwdFn->getType() != PFT)
6529 return error(FRVI->second.second,
6530 "invalid forward reference to "
6531 "function '" +
6532 FunctionName +
6533 "' with wrong type: "
6534 "expected '" +
6535 getTypeString(PFT) + "' but was '" +
6536 getTypeString(FwdFn->getType()) + "'");
6537 ForwardRefVals.erase(FRVI);
6538 } else if ((Fn = M->getFunction(FunctionName))) {
6539 // Reject redefinitions.
6540 return error(NameLoc,
6541 "invalid redefinition of function '" + FunctionName + "'");
6542 } else if (M->getNamedValue(FunctionName)) {
6543 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6544 }
6545
6546 } else {
6547 // Handle @"", where a name is syntactically specified, but semantically
6548 // missing.
6549 if (FunctionNumber == (unsigned)-1)
6550 FunctionNumber = NumberedVals.getNext();
6551
6552 // If this is a definition of a forward referenced function, make sure the
6553 // types agree.
6554 auto I = ForwardRefValIDs.find(FunctionNumber);
6555 if (I != ForwardRefValIDs.end()) {
6556 FwdFn = I->second.first;
6557 if (FwdFn->getType() != PFT)
6558 return error(NameLoc, "type of definition and forward reference of '@" +
6559 Twine(FunctionNumber) +
6560 "' disagree: "
6561 "expected '" +
6562 getTypeString(PFT) + "' but was '" +
6563 getTypeString(FwdFn->getType()) + "'");
6564 ForwardRefValIDs.erase(I);
6565 }
6566 }
6567
6569 FunctionName, M);
6570
6571 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6572
6573 if (FunctionName.empty())
6574 NumberedVals.add(FunctionNumber, Fn);
6575
6577 maybeSetDSOLocal(DSOLocal, *Fn);
6580 Fn->setCallingConv(CC);
6581 Fn->setAttributes(PAL);
6582 Fn->setUnnamedAddr(UnnamedAddr);
6583 if (Alignment)
6584 Fn->setAlignment(*Alignment);
6585 Fn->setSection(Section);
6586 Fn->setPartition(Partition);
6587 Fn->setComdat(C);
6588 Fn->setPersonalityFn(PersonalityFn);
6589 if (!GC.empty()) Fn->setGC(GC);
6590 Fn->setPrefixData(Prefix);
6591 Fn->setPrologueData(Prologue);
6592 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6593
6594 // Add all of the arguments we parsed to the function.
6595 Function::arg_iterator ArgIt = Fn->arg_begin();
6596 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6597 // If the argument has a name, insert it into the argument symbol table.
6598 if (ArgList[i].Name.empty()) continue;
6599
6600 // Set the name, if it conflicted, it will be auto-renamed.
6601 ArgIt->setName(ArgList[i].Name);
6602
6603 if (ArgIt->getName() != ArgList[i].Name)
6604 return error(ArgList[i].Loc,
6605 "redefinition of argument '%" + ArgList[i].Name + "'");
6606 }
6607
6608 if (FwdFn) {
6609 FwdFn->replaceAllUsesWith(Fn);
6610 FwdFn->eraseFromParent();
6611 }
6612
6613 if (IsDefine)
6614 return false;
6615
6616 // Check the declaration has no block address forward references.
6617 ValID ID;
6618 if (FunctionName.empty()) {
6619 ID.Kind = ValID::t_GlobalID;
6620 ID.UIntVal = FunctionNumber;
6621 } else {
6622 ID.Kind = ValID::t_GlobalName;
6623 ID.StrVal = FunctionName;
6624 }
6625 auto Blocks = ForwardRefBlockAddresses.find(ID);
6626 if (Blocks != ForwardRefBlockAddresses.end())
6627 return error(Blocks->first.Loc,
6628 "cannot take blockaddress inside a declaration");
6629 return false;
6630}
6631
6632bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6633 ValID ID;
6634 if (FunctionNumber == -1) {
6635 ID.Kind = ValID::t_GlobalName;
6636 ID.StrVal = std::string(F.getName());
6637 } else {
6638 ID.Kind = ValID::t_GlobalID;
6639 ID.UIntVal = FunctionNumber;
6640 }
6641
6642 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6643 if (Blocks == P.ForwardRefBlockAddresses.end())
6644 return false;
6645
6646 for (const auto &I : Blocks->second) {
6647 const ValID &BBID = I.first;
6648 GlobalValue *GV = I.second;
6649
6650 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6651 "Expected local id or name");
6652 BasicBlock *BB;
6653 if (BBID.Kind == ValID::t_LocalName)
6654 BB = getBB(BBID.StrVal, BBID.Loc);
6655 else
6656 BB = getBB(BBID.UIntVal, BBID.Loc);
6657 if (!BB)
6658 return P.error(BBID.Loc, "referenced value is not a basic block");
6659
6660 Value *ResolvedVal = BlockAddress::get(&F, BB);
6661 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
6662 ResolvedVal);
6663 if (!ResolvedVal)
6664 return true;
6665 GV->replaceAllUsesWith(ResolvedVal);
6666 GV->eraseFromParent();
6667 }
6668
6669 P.ForwardRefBlockAddresses.erase(Blocks);
6670 return false;
6671}
6672
6673/// parseFunctionBody
6674/// ::= '{' BasicBlock+ UseListOrderDirective* '}'
6675bool LLParser::parseFunctionBody(Function &Fn, unsigned FunctionNumber,
6676 ArrayRef<unsigned> UnnamedArgNums) {
6677 if (Lex.getKind() != lltok::lbrace)
6678 return tokError("expected '{' in function body");
6679 Lex.Lex(); // eat the {.
6680
6681 PerFunctionState PFS(*this, Fn, FunctionNumber, UnnamedArgNums);
6682
6683 // Resolve block addresses and allow basic blocks to be forward-declared
6684 // within this function.
6685 if (PFS.resolveForwardRefBlockAddresses())
6686 return true;
6687 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
6688
6689 // We need at least one basic block.
6690 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
6691 return tokError("function body requires at least one basic block");
6692
6693 while (Lex.getKind() != lltok::rbrace &&
6695 if (parseBasicBlock(PFS))
6696 return true;
6697
6698 while (Lex.getKind() != lltok::rbrace)
6699 if (parseUseListOrder(&PFS))
6700 return true;
6701
6702 // Eat the }.
6703 Lex.Lex();
6704
6705 // Verify function is ok.
6706 return PFS.finishFunction();
6707}
6708
6709/// parseBasicBlock
6710/// ::= (LabelStr|LabelID)? Instruction*
6711bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6712 // If this basic block starts out with a name, remember it.
6713 std::string Name;
6714 int NameID = -1;
6715 LocTy NameLoc = Lex.getLoc();
6716 if (Lex.getKind() == lltok::LabelStr) {
6717 Name = Lex.getStrVal();
6718 Lex.Lex();
6719 } else if (Lex.getKind() == lltok::LabelID) {
6720 NameID = Lex.getUIntVal();
6721 Lex.Lex();
6722 }
6723
6724 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
6725 if (!BB)
6726 return true;
6727
6728 std::string NameStr;
6729
6730 // Parse the instructions and debug values in this block until we get a
6731 // terminator.
6732 Instruction *Inst;
6733 auto DeleteDbgRecord = [](DbgRecord *DR) { DR->deleteRecord(); };
6734 using DbgRecordPtr = std::unique_ptr<DbgRecord, decltype(DeleteDbgRecord)>;
6735 SmallVector<DbgRecordPtr> TrailingDbgRecord;
6736 do {
6737 // Handle debug records first - there should always be an instruction
6738 // following the debug records, i.e. they cannot appear after the block
6739 // terminator.
6740 while (Lex.getKind() == lltok::hash) {
6741 if (SeenOldDbgInfoFormat)
6742 return error(Lex.getLoc(), "debug record should not appear in a module "
6743 "containing debug info intrinsics");
6744 if (!SeenNewDbgInfoFormat)
6745 M->setNewDbgInfoFormatFlag(true);
6746 SeenNewDbgInfoFormat = true;
6747 Lex.Lex();
6748
6749 DbgRecord *DR;
6750 if (parseDebugRecord(DR, PFS))
6751 return true;
6752 TrailingDbgRecord.emplace_back(DR, DeleteDbgRecord);
6753 }
6754
6755 // This instruction may have three possibilities for a name: a) none
6756 // specified, b) name specified "%foo =", c) number specified: "%4 =".
6757 LocTy NameLoc = Lex.getLoc();
6758 int NameID = -1;
6759 NameStr = "";
6760
6761 if (Lex.getKind() == lltok::LocalVarID) {
6762 NameID = Lex.getUIntVal();
6763 Lex.Lex();
6764 if (parseToken(lltok::equal, "expected '=' after instruction id"))
6765 return true;
6766 } else if (Lex.getKind() == lltok::LocalVar) {
6767 NameStr = Lex.getStrVal();
6768 Lex.Lex();
6769 if (parseToken(lltok::equal, "expected '=' after instruction name"))
6770 return true;
6771 }
6772
6773 switch (parseInstruction(Inst, BB, PFS)) {
6774 default:
6775 llvm_unreachable("Unknown parseInstruction result!");
6776 case InstError: return true;
6777 case InstNormal:
6778 Inst->insertInto(BB, BB->end());
6779
6780 // With a normal result, we check to see if the instruction is followed by
6781 // a comma and metadata.
6782 if (EatIfPresent(lltok::comma))
6783 if (parseInstructionMetadata(*Inst))
6784 return true;
6785 break;
6786 case InstExtraComma:
6787 Inst->insertInto(BB, BB->end());
6788
6789 // If the instruction parser ate an extra comma at the end of it, it
6790 // *must* be followed by metadata.
6791 if (parseInstructionMetadata(*Inst))
6792 return true;
6793 break;
6794 }
6795
6796 // Set the name on the instruction.
6797 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6798 return true;
6799
6800 // Attach any preceding debug values to this instruction.
6801 for (DbgRecordPtr &DR : TrailingDbgRecord)
6802 BB->insertDbgRecordBefore(DR.release(), Inst->getIterator());
6803 TrailingDbgRecord.clear();
6804 } while (!Inst->isTerminator());
6805
6806 assert(TrailingDbgRecord.empty() &&
6807 "All debug values should have been attached to an instruction.");
6808
6809 return false;
6810}
6811
6812/// parseDebugRecord
6813/// ::= #dbg_label '(' MDNode ')'
6814/// ::= #dbg_type '(' Metadata ',' MDNode ',' Metadata ','
6815/// (MDNode ',' Metadata ',' Metadata ',')? MDNode ')'
6816bool LLParser::parseDebugRecord(DbgRecord *&DR, PerFunctionState &PFS) {
6817 using RecordKind = DbgRecord::Kind;
6818 using LocType = DbgVariableRecord::LocationType;
6819 LocTy DVRLoc = Lex.getLoc();
6820 if (Lex.getKind() != lltok::DbgRecordType)
6821 return error(DVRLoc, "expected debug record type here");
6823 .Case("declare", RecordKind::ValueKind)
6824 .Case("value", RecordKind::ValueKind)
6825 .Case("assign", RecordKind::ValueKind)
6826 .Case("label", RecordKind::LabelKind);
6827
6828 // Parsing labels is trivial; parse here and early exit, otherwise go into the
6829 // full DbgVariableRecord processing stage.
6830 if (RecordType == RecordKind::LabelKind) {
6831 Lex.Lex();
6832 if (parseToken(lltok::lparen, "Expected '(' here"))
6833 return true;
6834 MDNode *Label;
6835 if (parseMDNode(Label))
6836 return true;
6837 if (parseToken(lltok::comma, "Expected ',' here"))
6838 return true;
6839 MDNode *DbgLoc;
6840 if (parseMDNode(DbgLoc))
6841 return true;
6842 if (parseToken(lltok::rparen, "Expected ')' here"))
6843 return true;
6845 return false;
6846 }
6847
6849 .Case("declare", LocType::Declare)
6850 .Case("value", LocType::Value)
6851 .Case("assign", LocType::Assign);
6852
6853 Lex.Lex();
6854 if (parseToken(lltok::lparen, "Expected '(' here"))
6855 return true;
6856
6857 // Parse Value field.
6858 Metadata *ValLocMD;
6859 if (parseMetadata(ValLocMD, &PFS))
6860 return true;
6861 if (parseToken(lltok::comma, "Expected ',' here"))
6862 return true;
6863
6864 // Parse Variable field.
6865 MDNode *Variable;
6866 if (parseMDNode(Variable))
6867 return true;
6868 if (parseToken(lltok::comma, "Expected ',' here"))
6869 return true;
6870
6871 // Parse Expression field.
6873 if (parseMDNode(Expression))
6874 return true;
6875 if (parseToken(lltok::comma, "Expected ',' here"))
6876 return true;
6877
6878 // Parse additional fields for #dbg_assign.
6879 MDNode *AssignID = nullptr;
6880 Metadata *AddressLocation = nullptr;
6881 MDNode *AddressExpression = nullptr;
6882 if (ValueType == LocType::Assign) {
6883 // Parse DIAssignID.
6884 if (parseMDNode(AssignID))
6885 return true;
6886 if (parseToken(lltok::comma, "Expected ',' here"))
6887 return true;
6888
6889 // Parse address ValueAsMetadata.
6890 if (parseMetadata(AddressLocation, &PFS))
6891 return true;
6892 if (parseToken(lltok::comma, "Expected ',' here"))
6893 return true;
6894
6895 // Parse address DIExpression.
6896 if (parseMDNode(AddressExpression))
6897 return true;
6898 if (parseToken(lltok::comma, "Expected ',' here"))
6899 return true;
6900 }
6901
6902 /// Parse DILocation.
6904 if (parseMDNode(DebugLoc))
6905 return true;
6906
6907 if (parseToken(lltok::rparen, "Expected ')' here"))
6908 return true;
6910 ValueType, ValLocMD, Variable, Expression, AssignID, AddressLocation,
6911 AddressExpression, DebugLoc);
6912 return false;
6913}
6914//===----------------------------------------------------------------------===//
6915// Instruction Parsing.
6916//===----------------------------------------------------------------------===//
6917
6918/// parseInstruction - parse one of the many different instructions.
6919///
6920int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
6921 PerFunctionState &PFS) {
6922 lltok::Kind Token = Lex.getKind();
6923 if (Token == lltok::Eof)
6924 return tokError("found end of file when expecting more instructions");
6925 LocTy Loc = Lex.getLoc();
6926 unsigned KeywordVal = Lex.getUIntVal();
6927 Lex.Lex(); // Eat the keyword.
6928
6929 switch (Token) {
6930 default:
6931 return error(Loc, "expected instruction opcode");
6932 // Terminator Instructions.
6933 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
6934 case lltok::kw_ret:
6935 return parseRet(Inst, BB, PFS);
6936 case lltok::kw_br:
6937 return parseBr(Inst, PFS);
6938 case lltok::kw_switch:
6939 return parseSwitch(Inst, PFS);
6941 return parseIndirectBr(Inst, PFS);
6942 case lltok::kw_invoke:
6943 return parseInvoke(Inst, PFS);
6944 case lltok::kw_resume:
6945 return parseResume(Inst, PFS);
6947 return parseCleanupRet(Inst, PFS);
6948 case lltok::kw_catchret:
6949 return parseCatchRet(Inst, PFS);
6951 return parseCatchSwitch(Inst, PFS);
6952 case lltok::kw_catchpad:
6953 return parseCatchPad(Inst, PFS);
6955 return parseCleanupPad(Inst, PFS);
6956 case lltok::kw_callbr:
6957 return parseCallBr(Inst, PFS);
6958 // Unary Operators.
6959 case lltok::kw_fneg: {
6960 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6961 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
6962 if (Res != 0)
6963 return Res;
6964 if (FMF.any())
6965 Inst->setFastMathFlags(FMF);
6966 return false;
6967 }
6968 // Binary Operators.
6969 case lltok::kw_add:
6970 case lltok::kw_sub:
6971 case lltok::kw_mul:
6972 case lltok::kw_shl: {
6973 bool NUW = EatIfPresent(lltok::kw_nuw);
6974 bool NSW = EatIfPresent(lltok::kw_nsw);
6975 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
6976
6977 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6978 return true;
6979
6980 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
6981 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
6982 return false;
6983 }
6984 case lltok::kw_fadd:
6985 case lltok::kw_fsub:
6986 case lltok::kw_fmul:
6987 case lltok::kw_fdiv:
6988 case lltok::kw_frem: {
6989 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6990 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
6991 if (Res != 0)
6992 return Res;
6993 if (FMF.any())
6994 Inst->setFastMathFlags(FMF);
6995 return 0;
6996 }
6997
6998 case lltok::kw_sdiv:
6999 case lltok::kw_udiv:
7000 case lltok::kw_lshr:
7001 case lltok::kw_ashr: {
7002 bool Exact = EatIfPresent(lltok::kw_exact);
7003
7004 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
7005 return true;
7006 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
7007 return false;
7008 }
7009
7010 case lltok::kw_urem:
7011 case lltok::kw_srem:
7012 return parseArithmetic(Inst, PFS, KeywordVal,
7013 /*IsFP*/ false);
7014 case lltok::kw_or: {
7015 bool Disjoint = EatIfPresent(lltok::kw_disjoint);
7016 if (parseLogical(Inst, PFS, KeywordVal))
7017 return true;
7018 if (Disjoint)
7019 cast<PossiblyDisjointInst>(Inst)->setIsDisjoint(true);
7020 return false;
7021 }
7022 case lltok::kw_and:
7023 case lltok::kw_xor:
7024 return parseLogical(Inst, PFS, KeywordVal);
7025 case lltok::kw_icmp: {
7026 bool SameSign = EatIfPresent(lltok::kw_samesign);
7027 if (parseCompare(Inst, PFS, KeywordVal))
7028 return true;
7029 if (SameSign)
7030 cast<ICmpInst>(Inst)->setSameSign();
7031 return false;
7032 }
7033 case lltok::kw_fcmp: {
7034 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7035 int Res = parseCompare(Inst, PFS, KeywordVal);
7036 if (Res != 0)
7037 return Res;
7038 if (FMF.any())
7039 Inst->setFastMathFlags(FMF);
7040 return 0;
7041 }
7042
7043 // Casts.
7044 case lltok::kw_uitofp:
7045 case lltok::kw_zext: {
7046 bool NonNeg = EatIfPresent(lltok::kw_nneg);
7047 bool Res = parseCast(Inst, PFS, KeywordVal);
7048 if (Res != 0)
7049 return Res;
7050 if (NonNeg)
7051 Inst->setNonNeg();
7052 return 0;
7053 }
7054 case lltok::kw_trunc: {
7055 bool NUW = EatIfPresent(lltok::kw_nuw);
7056 bool NSW = EatIfPresent(lltok::kw_nsw);
7057 if (!NUW)
7058 NUW = EatIfPresent(lltok::kw_nuw);
7059 if (parseCast(Inst, PFS, KeywordVal))
7060 return true;
7061 if (NUW)
7062 cast<TruncInst>(Inst)->setHasNoUnsignedWrap(true);
7063 if (NSW)
7064 cast<TruncInst>(Inst)->setHasNoSignedWrap(true);
7065 return false;
7066 }
7067 case lltok::kw_sext:
7068 case lltok::kw_bitcast:
7070 case lltok::kw_sitofp:
7071 case lltok::kw_fptoui:
7072 case lltok::kw_fptosi:
7073 case lltok::kw_inttoptr:
7074 case lltok::kw_ptrtoint:
7075 return parseCast(Inst, PFS, KeywordVal);
7076 case lltok::kw_fptrunc:
7077 case lltok::kw_fpext: {
7078 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7079 if (parseCast(Inst, PFS, KeywordVal))
7080 return true;
7081 if (FMF.any())
7082 Inst->setFastMathFlags(FMF);
7083 return false;
7084 }
7085
7086 // Other.
7087 case lltok::kw_select: {
7088 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7089 int Res = parseSelect(Inst, PFS);
7090 if (Res != 0)
7091 return Res;
7092 if (FMF.any()) {
7093 if (!isa<FPMathOperator>(Inst))
7094 return error(Loc, "fast-math-flags specified for select without "
7095 "floating-point scalar or vector return type");
7096 Inst->setFastMathFlags(FMF);
7097 }
7098 return 0;
7099 }
7100 case lltok::kw_va_arg:
7101 return parseVAArg(Inst, PFS);
7103 return parseExtractElement(Inst, PFS);
7105 return parseInsertElement(Inst, PFS);
7107 return parseShuffleVector(Inst, PFS);
7108 case lltok::kw_phi: {
7109 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7110 int Res = parsePHI(Inst, PFS);
7111 if (Res != 0)
7112 return Res;
7113 if (FMF.any()) {
7114 if (!isa<FPMathOperator>(Inst))
7115 return error(Loc, "fast-math-flags specified for phi without "
7116 "floating-point scalar or vector return type");
7117 Inst->setFastMathFlags(FMF);
7118 }
7119 return 0;
7120 }
7122 return parseLandingPad(Inst, PFS);
7123 case lltok::kw_freeze:
7124 return parseFreeze(Inst, PFS);
7125 // Call.
7126 case lltok::kw_call:
7127 return parseCall(Inst, PFS, CallInst::TCK_None);
7128 case lltok::kw_tail:
7129 return parseCall(Inst, PFS, CallInst::TCK_Tail);
7130 case lltok::kw_musttail:
7131 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
7132 case lltok::kw_notail:
7133 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
7134 // Memory.
7135 case lltok::kw_alloca:
7136 return parseAlloc(Inst, PFS);
7137 case lltok::kw_load:
7138 return parseLoad(Inst, PFS);
7139 case lltok::kw_store:
7140 return parseStore(Inst, PFS);
7141 case lltok::kw_cmpxchg:
7142 return parseCmpXchg(Inst, PFS);
7144 return parseAtomicRMW(Inst, PFS);
7145 case lltok::kw_fence:
7146 return parseFence(Inst, PFS);
7148 return parseGetElementPtr(Inst, PFS);
7150 return parseExtractValue(Inst, PFS);
7152 return parseInsertValue(Inst, PFS);
7153 }
7154}
7155
7156/// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
7157bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
7158 if (Opc == Instruction::FCmp) {
7159 switch (Lex.getKind()) {
7160 default:
7161 return tokError("expected fcmp predicate (e.g. 'oeq')");
7162 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
7163 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
7164 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
7165 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
7166 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
7167 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
7168 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
7169 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
7170 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
7171 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
7172 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
7173 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
7174 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
7175 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
7176 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
7177 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
7178 }
7179 } else {
7180 switch (Lex.getKind()) {
7181 default:
7182 return tokError("expected icmp predicate (e.g. 'eq')");
7183 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
7184 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
7185 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
7186 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
7187 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
7188 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
7189 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
7190 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
7191 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
7192 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
7193 }
7194 }
7195 Lex.Lex();
7196 return false;
7197}
7198
7199//===----------------------------------------------------------------------===//
7200// Terminator Instructions.
7201//===----------------------------------------------------------------------===//
7202
7203/// parseRet - parse a return instruction.
7204/// ::= 'ret' void (',' !dbg, !1)*
7205/// ::= 'ret' TypeAndValue (',' !dbg, !1)*
7206bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
7207 PerFunctionState &PFS) {
7208 SMLoc TypeLoc = Lex.getLoc();
7209 Type *Ty = nullptr;
7210 if (parseType(Ty, true /*void allowed*/))
7211 return true;
7212
7213 Type *ResType = PFS.getFunction().getReturnType();
7214
7215 if (Ty->isVoidTy()) {
7216 if (!ResType->isVoidTy())
7217 return error(TypeLoc, "value doesn't match function result type '" +
7218 getTypeString(ResType) + "'");
7219
7220 Inst = ReturnInst::Create(Context);
7221 return false;
7222 }
7223
7224 Value *RV;
7225 if (parseValue(Ty, RV, PFS))
7226 return true;
7227
7228 if (ResType != RV->getType())
7229 return error(TypeLoc, "value doesn't match function result type '" +
7230 getTypeString(ResType) + "'");
7231
7232 Inst = ReturnInst::Create(Context, RV);
7233 return false;
7234}
7235
7236/// parseBr
7237/// ::= 'br' TypeAndValue
7238/// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7239bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
7240 LocTy Loc, Loc2;
7241 Value *Op0;
7242 BasicBlock *Op1, *Op2;
7243 if (parseTypeAndValue(Op0, Loc, PFS))
7244 return true;
7245
7246 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
7247 Inst = BranchInst::Create(BB);
7248 return false;
7249 }
7250
7251 if (Op0->getType() != Type::getInt1Ty(Context))
7252 return error(Loc, "branch condition must have 'i1' type");
7253
7254 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
7255 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
7256 parseToken(lltok::comma, "expected ',' after true destination") ||
7257 parseTypeAndBasicBlock(Op2, Loc2, PFS))
7258 return true;
7259
7260 Inst = BranchInst::Create(Op1, Op2, Op0);
7261 return false;
7262}
7263
7264/// parseSwitch
7265/// Instruction
7266/// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
7267/// JumpTable
7268/// ::= (TypeAndValue ',' TypeAndValue)*
7269bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7270 LocTy CondLoc, BBLoc;
7271 Value *Cond;
7272 BasicBlock *DefaultBB;
7273 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
7274 parseToken(lltok::comma, "expected ',' after switch condition") ||
7275 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
7276 parseToken(lltok::lsquare, "expected '[' with switch table"))
7277 return true;
7278
7279 if (!Cond->getType()->isIntegerTy())
7280 return error(CondLoc, "switch condition must have integer type");
7281
7282 // parse the jump table pairs.
7283 SmallPtrSet<Value*, 32> SeenCases;
7285 while (Lex.getKind() != lltok::rsquare) {
7286 Value *Constant;
7287 BasicBlock *DestBB;
7288
7289 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
7290 parseToken(lltok::comma, "expected ',' after case value") ||
7291 parseTypeAndBasicBlock(DestBB, PFS))
7292 return true;
7293
7294 if (!SeenCases.insert(Constant).second)
7295 return error(CondLoc, "duplicate case value in switch");
7296 if (!isa<ConstantInt>(Constant))
7297 return error(CondLoc, "case value is not a constant integer");
7298
7299 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
7300 }
7301
7302 Lex.Lex(); // Eat the ']'.
7303
7304 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
7305 for (unsigned i = 0, e = Table.size(); i != e; ++i)
7306 SI->addCase(Table[i].first, Table[i].second);
7307 Inst = SI;
7308 return false;
7309}
7310
7311/// parseIndirectBr
7312/// Instruction
7313/// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
7314bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
7315 LocTy AddrLoc;
7316 Value *Address;
7317 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
7318 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
7319 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
7320 return true;
7321
7322 if (!Address->getType()->isPointerTy())
7323 return error(AddrLoc, "indirectbr address must have pointer type");
7324
7325 // parse the destination list.
7327
7328 if (Lex.getKind() != lltok::rsquare) {
7329 BasicBlock *DestBB;
7330 if (parseTypeAndBasicBlock(DestBB, PFS))
7331 return true;
7332 DestList.push_back(DestBB);
7333
7334 while (EatIfPresent(lltok::comma)) {
7335 if (parseTypeAndBasicBlock(DestBB, PFS))
7336 return true;
7337 DestList.push_back(DestBB);
7338 }
7339 }
7340
7341 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7342 return true;
7343
7345 for (BasicBlock *Dest : DestList)
7346 IBI->addDestination(Dest);
7347 Inst = IBI;
7348 return false;
7349}
7350
7351// If RetType is a non-function pointer type, then this is the short syntax
7352// for the call, which means that RetType is just the return type. Infer the
7353// rest of the function argument types from the arguments that are present.
7354bool LLParser::resolveFunctionType(Type *RetType, ArrayRef<ParamInfo> ArgList,
7355 FunctionType *&FuncTy) {
7356 FuncTy = dyn_cast<FunctionType>(RetType);
7357 if (!FuncTy) {
7358 // Pull out the types of all of the arguments...
7359 SmallVector<Type *, 8> ParamTypes;
7360 ParamTypes.reserve(ArgList.size());
7361 for (const ParamInfo &Arg : ArgList)
7362 ParamTypes.push_back(Arg.V->getType());
7363
7364 if (!FunctionType::isValidReturnType(RetType))
7365 return true;
7366
7367 FuncTy = FunctionType::get(RetType, ParamTypes, false);
7368 }
7369 return false;
7370}
7371
7372/// parseInvoke
7373/// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
7374/// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
7375bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
7376 LocTy CallLoc = Lex.getLoc();
7377 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7378 std::vector<unsigned> FwdRefAttrGrps;
7379 LocTy NoBuiltinLoc;
7380 unsigned CC;
7381 unsigned InvokeAddrSpace;
7382 Type *RetType = nullptr;
7383 LocTy RetTypeLoc;
7384 ValID CalleeID;
7387
7388 BasicBlock *NormalBB, *UnwindBB;
7389 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7390 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
7391 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7392 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7393 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7394 NoBuiltinLoc) ||
7395 parseOptionalOperandBundles(BundleList, PFS) ||
7396 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
7397 parseTypeAndBasicBlock(NormalBB, PFS) ||
7398 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
7399 parseTypeAndBasicBlock(UnwindBB, PFS))
7400 return true;
7401
7402 // If RetType is a non-function pointer type, then this is the short syntax
7403 // for the call, which means that RetType is just the return type. Infer the
7404 // rest of the function argument types from the arguments that are present.
7405 FunctionType *Ty;
7406 if (resolveFunctionType(RetType, ArgList, Ty))
7407 return error(RetTypeLoc, "Invalid result type for LLVM function");
7408
7409 CalleeID.FTy = Ty;
7410
7411 // Look up the callee.
7412 Value *Callee;
7413 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
7414 Callee, &PFS))
7415 return true;
7416
7417 // Set up the Attribute for the function.
7420
7421 // Loop through FunctionType's arguments and ensure they are specified
7422 // correctly. Also, gather any parameter attributes.
7423 FunctionType::param_iterator I = Ty->param_begin();
7424 FunctionType::param_iterator E = Ty->param_end();
7425 for (const ParamInfo &Arg : ArgList) {
7426 Type *ExpectedTy = nullptr;
7427 if (I != E) {
7428 ExpectedTy = *I++;
7429 } else if (!Ty->isVarArg()) {
7430 return error(Arg.Loc, "too many arguments specified");
7431 }
7432
7433 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7434 return error(Arg.Loc, "argument is not of expected type '" +
7435 getTypeString(ExpectedTy) + "'");
7436 Args.push_back(Arg.V);
7437 ArgAttrs.push_back(Arg.Attrs);
7438 }
7439
7440 if (I != E)
7441 return error(CallLoc, "not enough parameters specified for call");
7442
7443 // Finish off the Attribute and check them
7444 AttributeList PAL =
7445 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7446 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7447
7448 InvokeInst *II =
7449 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
7450 II->setCallingConv(CC);
7451 II->setAttributes(PAL);
7452 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
7453 Inst = II;
7454 return false;
7455}
7456
7457/// parseResume
7458/// ::= 'resume' TypeAndValue
7459bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
7460 Value *Exn; LocTy ExnLoc;
7461 if (parseTypeAndValue(Exn, ExnLoc, PFS))
7462 return true;
7463
7464 ResumeInst *RI = ResumeInst::Create(Exn);
7465 Inst = RI;
7466 return false;
7467}
7468
7469bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
7470 PerFunctionState &PFS) {
7471 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
7472 return true;
7473
7474 while (Lex.getKind() != lltok::rsquare) {
7475 // If this isn't the first argument, we need a comma.
7476 if (!Args.empty() &&
7477 parseToken(lltok::comma, "expected ',' in argument list"))
7478 return true;
7479
7480 // parse the argument.
7481 LocTy ArgLoc;
7482 Type *ArgTy = nullptr;
7483 if (parseType(ArgTy, ArgLoc))
7484 return true;
7485
7486 Value *V;
7487 if (ArgTy->isMetadataTy()) {
7488 if (parseMetadataAsValue(V, PFS))
7489 return true;
7490 } else {
7491 if (parseValue(ArgTy, V, PFS))
7492 return true;
7493 }
7494 Args.push_back(V);
7495 }
7496
7497 Lex.Lex(); // Lex the ']'.
7498 return false;
7499}
7500
7501/// parseCleanupRet
7502/// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
7503bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
7504 Value *CleanupPad = nullptr;
7505
7506 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
7507 return true;
7508
7509 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
7510 return true;
7511
7512 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
7513 return true;
7514
7515 BasicBlock *UnwindBB = nullptr;
7516 if (Lex.getKind() == lltok::kw_to) {
7517 Lex.Lex();
7518 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
7519 return true;
7520 } else {
7521 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
7522 return true;
7523 }
7524 }
7525
7526 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
7527 return false;
7528}
7529
7530/// parseCatchRet
7531/// ::= 'catchret' from Parent Value 'to' TypeAndValue
7532bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
7533 Value *CatchPad = nullptr;
7534
7535 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
7536 return true;
7537
7538 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
7539 return true;
7540
7541 BasicBlock *BB;
7542 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
7543 parseTypeAndBasicBlock(BB, PFS))
7544 return true;
7545
7546 Inst = CatchReturnInst::Create(CatchPad, BB);
7547 return false;
7548}
7549
7550/// parseCatchSwitch
7551/// ::= 'catchswitch' within Parent
7552bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
7553 Value *ParentPad;
7554
7555 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
7556 return true;
7557
7558 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7559 Lex.getKind() != lltok::LocalVarID)
7560 return tokError("expected scope value for catchswitch");
7561
7562 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7563 return true;
7564
7565 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
7566 return true;
7567
7569 do {
7570 BasicBlock *DestBB;
7571 if (parseTypeAndBasicBlock(DestBB, PFS))
7572 return true;
7573 Table.push_back(DestBB);
7574 } while (EatIfPresent(lltok::comma));
7575
7576 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
7577 return true;
7578
7579 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
7580 return true;
7581
7582 BasicBlock *UnwindBB = nullptr;
7583 if (EatIfPresent(lltok::kw_to)) {
7584 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
7585 return true;
7586 } else {
7587 if (parseTypeAndBasicBlock(UnwindBB, PFS))
7588 return true;
7589 }
7590
7591 auto *CatchSwitch =
7592 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
7593 for (BasicBlock *DestBB : Table)
7594 CatchSwitch->addHandler(DestBB);
7595 Inst = CatchSwitch;
7596 return false;
7597}
7598
7599/// parseCatchPad
7600/// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
7601bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
7602 Value *CatchSwitch = nullptr;
7603
7604 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
7605 return true;
7606
7607 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
7608 return tokError("expected scope value for catchpad");
7609
7610 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
7611 return true;
7612
7614 if (parseExceptionArgs(Args, PFS))
7615 return true;
7616
7617 Inst = CatchPadInst::Create(CatchSwitch, Args);
7618 return false;
7619}
7620
7621/// parseCleanupPad
7622/// ::= 'cleanuppad' within Parent ParamList
7623bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
7624 Value *ParentPad = nullptr;
7625
7626 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
7627 return true;
7628
7629 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
7630 Lex.getKind() != lltok::LocalVarID)
7631 return tokError("expected scope value for cleanuppad");
7632
7633 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
7634 return true;
7635
7637 if (parseExceptionArgs(Args, PFS))
7638 return true;
7639
7640 Inst = CleanupPadInst::Create(ParentPad, Args);
7641 return false;
7642}
7643
7644//===----------------------------------------------------------------------===//
7645// Unary Operators.
7646//===----------------------------------------------------------------------===//
7647
7648/// parseUnaryOp
7649/// ::= UnaryOp TypeAndValue ',' Value
7650///
7651/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7652/// operand is allowed.
7653bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
7654 unsigned Opc, bool IsFP) {
7655 LocTy Loc; Value *LHS;
7656 if (parseTypeAndValue(LHS, Loc, PFS))
7657 return true;
7658
7659 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7661
7662 if (!Valid)
7663 return error(Loc, "invalid operand type for instruction");
7664
7666 return false;
7667}
7668
7669/// parseCallBr
7670/// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
7671/// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
7672/// '[' LabelList ']'
7673bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
7674 LocTy CallLoc = Lex.getLoc();
7675 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7676 std::vector<unsigned> FwdRefAttrGrps;
7677 LocTy NoBuiltinLoc;
7678 unsigned CC;
7679 Type *RetType = nullptr;
7680 LocTy RetTypeLoc;
7681 ValID CalleeID;
7684
7685 BasicBlock *DefaultDest;
7686 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7687 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7688 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7689 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7690 NoBuiltinLoc) ||
7691 parseOptionalOperandBundles(BundleList, PFS) ||
7692 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
7693 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7694 parseToken(lltok::lsquare, "expected '[' in callbr"))
7695 return true;
7696
7697 // parse the destination list.
7698 SmallVector<BasicBlock *, 16> IndirectDests;
7699
7700 if (Lex.getKind() != lltok::rsquare) {
7701 BasicBlock *DestBB;
7702 if (parseTypeAndBasicBlock(DestBB, PFS))
7703 return true;
7704 IndirectDests.push_back(DestBB);
7705
7706 while (EatIfPresent(lltok::comma)) {
7707 if (parseTypeAndBasicBlock(DestBB, PFS))
7708 return true;
7709 IndirectDests.push_back(DestBB);
7710 }
7711 }
7712
7713 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7714 return true;
7715
7716 // If RetType is a non-function pointer type, then this is the short syntax
7717 // for the call, which means that RetType is just the return type. Infer the
7718 // rest of the function argument types from the arguments that are present.
7719 FunctionType *Ty;
7720 if (resolveFunctionType(RetType, ArgList, Ty))
7721 return error(RetTypeLoc, "Invalid result type for LLVM function");
7722
7723 CalleeID.FTy = Ty;
7724
7725 // Look up the callee.
7726 Value *Callee;
7727 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
7728 return true;
7729
7730 // Set up the Attribute for the function.
7733
7734 // Loop through FunctionType's arguments and ensure they are specified
7735 // correctly. Also, gather any parameter attributes.
7736 FunctionType::param_iterator I = Ty->param_begin();
7737 FunctionType::param_iterator E = Ty->param_end();
7738 for (const ParamInfo &Arg : ArgList) {
7739 Type *ExpectedTy = nullptr;
7740 if (I != E) {
7741 ExpectedTy = *I++;
7742 } else if (!Ty->isVarArg()) {
7743 return error(Arg.Loc, "too many arguments specified");
7744 }
7745
7746 if (ExpectedTy && ExpectedTy != Arg.V->getType())
7747 return error(Arg.Loc, "argument is not of expected type '" +
7748 getTypeString(ExpectedTy) + "'");
7749 Args.push_back(Arg.V);
7750 ArgAttrs.push_back(Arg.Attrs);
7751 }
7752
7753 if (I != E)
7754 return error(CallLoc, "not enough parameters specified for call");
7755
7756 // Finish off the Attribute and check them
7757 AttributeList PAL =
7758 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7759 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7760
7761 CallBrInst *CBI =
7762 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
7763 BundleList);
7764 CBI->setCallingConv(CC);
7765 CBI->setAttributes(PAL);
7766 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7767 Inst = CBI;
7768 return false;
7769}
7770
7771//===----------------------------------------------------------------------===//
7772// Binary Operators.
7773//===----------------------------------------------------------------------===//
7774
7775/// parseArithmetic
7776/// ::= ArithmeticOps TypeAndValue ',' Value
7777///
7778/// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7779/// operand is allowed.
7780bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
7781 unsigned Opc, bool IsFP) {
7782 LocTy Loc; Value *LHS, *RHS;
7783 if (parseTypeAndValue(LHS, Loc, PFS) ||
7784 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
7785 parseValue(LHS->getType(), RHS, PFS))
7786 return true;
7787
7788 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7790
7791 if (!Valid)
7792 return error(Loc, "invalid operand type for instruction");
7793
7794 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7795 return false;
7796}
7797
7798/// parseLogical
7799/// ::= ArithmeticOps TypeAndValue ',' Value {
7800bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
7801 unsigned Opc) {
7802 LocTy Loc; Value *LHS, *RHS;
7803 if (parseTypeAndValue(LHS, Loc, PFS) ||
7804 parseToken(lltok::comma, "expected ',' in logical operation") ||
7805 parseValue(LHS->getType(), RHS, PFS))
7806 return true;
7807
7808 if (!LHS->getType()->isIntOrIntVectorTy())
7809 return error(Loc,
7810 "instruction requires integer or integer vector operands");
7811
7812 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7813 return false;
7814}
7815
7816/// parseCompare
7817/// ::= 'icmp' IPredicates TypeAndValue ',' Value
7818/// ::= 'fcmp' FPredicates TypeAndValue ',' Value
7819bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
7820 unsigned Opc) {
7821 // parse the integer/fp comparison predicate.
7822 LocTy Loc;
7823 unsigned Pred;
7824 Value *LHS, *RHS;
7825 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7826 parseToken(lltok::comma, "expected ',' after compare value") ||
7827 parseValue(LHS->getType(), RHS, PFS))
7828 return true;
7829
7830 if (Opc == Instruction::FCmp) {
7831 if (!LHS->getType()->isFPOrFPVectorTy())
7832 return error(Loc, "fcmp requires floating point operands");
7833 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7834 } else {
7835 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
7836 if (!LHS->getType()->isIntOrIntVectorTy() &&
7838 return error(Loc, "icmp requires integer operands");
7839 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7840 }
7841 return false;
7842}
7843
7844//===----------------------------------------------------------------------===//
7845// Other Instructions.
7846//===----------------------------------------------------------------------===//
7847
7848/// parseCast
7849/// ::= CastOpc TypeAndValue 'to' Type
7850bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
7851 unsigned Opc) {
7852 LocTy Loc;
7853 Value *Op;
7854 Type *DestTy = nullptr;
7855 if (parseTypeAndValue(Op, Loc, PFS) ||
7856 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
7857 parseType(DestTy))
7858 return true;
7859
7860 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy))
7861 return error(Loc, "invalid cast opcode for cast from '" +
7862 getTypeString(Op->getType()) + "' to '" +
7863 getTypeString(DestTy) + "'");
7864 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
7865 return false;
7866}
7867
7868/// parseSelect
7869/// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7870bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
7871 LocTy Loc;
7872 Value *Op0, *Op1, *Op2;
7873 if (parseTypeAndValue(Op0, Loc, PFS) ||
7874 parseToken(lltok::comma, "expected ',' after select condition") ||
7875 parseTypeAndValue(Op1, PFS) ||
7876 parseToken(lltok::comma, "expected ',' after select value") ||
7877 parseTypeAndValue(Op2, PFS))
7878 return true;
7879
7880 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
7881 return error(Loc, Reason);
7882
7883 Inst = SelectInst::Create(Op0, Op1, Op2);
7884 return false;
7885}
7886
7887/// parseVAArg
7888/// ::= 'va_arg' TypeAndValue ',' Type
7889bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
7890 Value *Op;
7891 Type *EltTy = nullptr;
7892 LocTy TypeLoc;
7893 if (parseTypeAndValue(Op, PFS) ||
7894 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
7895 parseType(EltTy, TypeLoc))
7896 return true;
7897
7898 if (!EltTy->isFirstClassType())
7899 return error(TypeLoc, "va_arg requires operand with first class type");
7900
7901 Inst = new VAArgInst(Op, EltTy);
7902 return false;
7903}
7904
7905/// parseExtractElement
7906/// ::= 'extractelement' TypeAndValue ',' TypeAndValue
7907bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
7908 LocTy Loc;
7909 Value *Op0, *Op1;
7910 if (parseTypeAndValue(Op0, Loc, PFS) ||
7911 parseToken(lltok::comma, "expected ',' after extract value") ||
7912 parseTypeAndValue(Op1, PFS))
7913 return true;
7914
7916 return error(Loc, "invalid extractelement operands");
7917
7918 Inst = ExtractElementInst::Create(Op0, Op1);
7919 return false;
7920}
7921
7922/// parseInsertElement
7923/// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7924bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
7925 LocTy Loc;
7926 Value *Op0, *Op1, *Op2;
7927 if (parseTypeAndValue(Op0, Loc, PFS) ||
7928 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7929 parseTypeAndValue(Op1, PFS) ||
7930 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7931 parseTypeAndValue(Op2, PFS))
7932 return true;
7933
7934 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
7935 return error(Loc, "invalid insertelement operands");
7936
7937 Inst = InsertElementInst::Create(Op0, Op1, Op2);
7938 return false;
7939}
7940
7941/// parseShuffleVector
7942/// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7943bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
7944 LocTy Loc;
7945 Value *Op0, *Op1, *Op2;
7946 if (parseTypeAndValue(Op0, Loc, PFS) ||
7947 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
7948 parseTypeAndValue(Op1, PFS) ||
7949 parseToken(lltok::comma, "expected ',' after shuffle value") ||
7950 parseTypeAndValue(Op2, PFS))
7951 return true;
7952
7953 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
7954 return error(Loc, "invalid shufflevector operands");
7955
7956 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
7957 return false;
7958}
7959
7960/// parsePHI
7961/// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
7962int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
7963 Type *Ty = nullptr; LocTy TypeLoc;
7964 Value *Op0, *Op1;
7965
7966 if (parseType(Ty, TypeLoc))
7967 return true;
7968
7969 if (!Ty->isFirstClassType())
7970 return error(TypeLoc, "phi node must have first class type");
7971
7972 bool First = true;
7973 bool AteExtraComma = false;
7975
7976 while (true) {
7977 if (First) {
7978 if (Lex.getKind() != lltok::lsquare)
7979 break;
7980 First = false;
7981 } else if (!EatIfPresent(lltok::comma))
7982 break;
7983
7984 if (Lex.getKind() == lltok::MetadataVar) {
7985 AteExtraComma = true;
7986 break;
7987 }
7988
7989 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7990 parseValue(Ty, Op0, PFS) ||
7991 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7992 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7993 parseToken(lltok::rsquare, "expected ']' in phi value list"))
7994 return true;
7995
7996 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7997 }
7998
7999 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
8000 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
8001 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
8002 Inst = PN;
8003 return AteExtraComma ? InstExtraComma : InstNormal;
8004}
8005
8006/// parseLandingPad
8007/// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
8008/// Clause
8009/// ::= 'catch' TypeAndValue
8010/// ::= 'filter'
8011/// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
8012bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
8013 Type *Ty = nullptr; LocTy TyLoc;
8014
8015 if (parseType(Ty, TyLoc))
8016 return true;
8017
8018 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
8019 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
8020
8021 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
8023 if (EatIfPresent(lltok::kw_catch))
8025 else if (EatIfPresent(lltok::kw_filter))
8027 else
8028 return tokError("expected 'catch' or 'filter' clause type");
8029
8030 Value *V;
8031 LocTy VLoc;
8032 if (parseTypeAndValue(V, VLoc, PFS))
8033 return true;
8034
8035 // A 'catch' type expects a non-array constant. A filter clause expects an
8036 // array constant.
8037 if (CT == LandingPadInst::Catch) {
8038 if (isa<ArrayType>(V->getType()))
8039 return error(VLoc, "'catch' clause has an invalid type");
8040 } else {
8041 if (!isa<ArrayType>(V->getType()))
8042 return error(VLoc, "'filter' clause has an invalid type");
8043 }
8044
8045 Constant *CV = dyn_cast<Constant>(V);
8046 if (!CV)
8047 return error(VLoc, "clause argument must be a constant");
8048 LP->addClause(CV);
8049 }
8050
8051 Inst = LP.release();
8052 return false;
8053}
8054
8055/// parseFreeze
8056/// ::= 'freeze' Type Value
8057bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
8058 LocTy Loc;
8059 Value *Op;
8060 if (parseTypeAndValue(Op, Loc, PFS))
8061 return true;
8062
8063 Inst = new FreezeInst(Op);
8064 return false;
8065}
8066
8067/// parseCall
8068/// ::= 'call' OptionalFastMathFlags OptionalCallingConv
8069/// OptionalAttrs Type Value ParameterList OptionalAttrs
8070/// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
8071/// OptionalAttrs Type Value ParameterList OptionalAttrs
8072/// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
8073/// OptionalAttrs Type Value ParameterList OptionalAttrs
8074/// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
8075/// OptionalAttrs Type Value ParameterList OptionalAttrs
8076bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
8078 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
8079 std::vector<unsigned> FwdRefAttrGrps;
8080 LocTy BuiltinLoc;
8081 unsigned CallAddrSpace;
8082 unsigned CC;
8083 Type *RetType = nullptr;
8084 LocTy RetTypeLoc;
8085 ValID CalleeID;
8088 LocTy CallLoc = Lex.getLoc();
8089
8090 if (TCK != CallInst::TCK_None &&
8091 parseToken(lltok::kw_call,
8092 "expected 'tail call', 'musttail call', or 'notail call'"))
8093 return true;
8094
8095 FastMathFlags FMF = EatFastMathFlagsIfPresent();
8096
8097 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
8098 parseOptionalProgramAddrSpace(CallAddrSpace) ||
8099 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
8100 parseValID(CalleeID, &PFS) ||
8101 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
8102 PFS.getFunction().isVarArg()) ||
8103 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
8104 parseOptionalOperandBundles(BundleList, PFS))
8105 return true;
8106
8107 // If RetType is a non-function pointer type, then this is the short syntax
8108 // for the call, which means that RetType is just the return type. Infer the
8109 // rest of the function argument types from the arguments that are present.
8110 FunctionType *Ty;
8111 if (resolveFunctionType(RetType, ArgList, Ty))
8112 return error(RetTypeLoc, "Invalid result type for LLVM function");
8113
8114 CalleeID.FTy = Ty;
8115
8116 // Look up the callee.
8117 Value *Callee;
8118 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
8119 &PFS))
8120 return true;
8121
8122 // Set up the Attribute for the function.
8124
8126
8127 // Loop through FunctionType's arguments and ensure they are specified
8128 // correctly. Also, gather any parameter attributes.
8129 FunctionType::param_iterator I = Ty->param_begin();
8130 FunctionType::param_iterator E = Ty->param_end();
8131 for (const ParamInfo &Arg : ArgList) {
8132 Type *ExpectedTy = nullptr;
8133 if (I != E) {
8134 ExpectedTy = *I++;
8135 } else if (!Ty->isVarArg()) {
8136 return error(Arg.Loc, "too many arguments specified");
8137 }
8138
8139 if (ExpectedTy && ExpectedTy != Arg.V->getType())
8140 return error(Arg.Loc, "argument is not of expected type '" +
8141 getTypeString(ExpectedTy) + "'");
8142 Args.push_back(Arg.V);
8143 Attrs.push_back(Arg.Attrs);
8144 }
8145
8146 if (I != E)
8147 return error(CallLoc, "not enough parameters specified for call");
8148
8149 // Finish off the Attribute and check them
8150 AttributeList PAL =
8151 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
8152 AttributeSet::get(Context, RetAttrs), Attrs);
8153
8154 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
8155 CI->setTailCallKind(TCK);
8156 CI->setCallingConv(CC);
8157 if (FMF.any()) {
8158 if (!isa<FPMathOperator>(CI)) {
8159 CI->deleteValue();
8160 return error(CallLoc, "fast-math-flags specified for call without "
8161 "floating-point scalar or vector return type");
8162 }
8163 CI->setFastMathFlags(FMF);
8164 }
8165
8166 if (CalleeID.Kind == ValID::t_GlobalName &&
8167 isOldDbgFormatIntrinsic(CalleeID.StrVal)) {
8168 if (SeenNewDbgInfoFormat) {
8169 CI->deleteValue();
8170 return error(CallLoc, "llvm.dbg intrinsic should not appear in a module "
8171 "using non-intrinsic debug info");
8172 }
8173 if (!SeenOldDbgInfoFormat)
8174 M->setNewDbgInfoFormatFlag(false);
8175 SeenOldDbgInfoFormat = true;
8176 }
8177 CI->setAttributes(PAL);
8178 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
8179 Inst = CI;
8180 return false;
8181}
8182
8183//===----------------------------------------------------------------------===//
8184// Memory Instructions.
8185//===----------------------------------------------------------------------===//
8186
8187/// parseAlloc
8188/// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
8189/// (',' 'align' i32)? (',', 'addrspace(n))?
8190int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
8191 Value *Size = nullptr;
8192 LocTy SizeLoc, TyLoc, ASLoc;
8193 MaybeAlign Alignment;
8194 unsigned AddrSpace = 0;
8195 Type *Ty = nullptr;
8196
8197 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
8198 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
8199
8200 if (parseType(Ty, TyLoc))
8201 return true;
8202
8204 return error(TyLoc, "invalid type for alloca");
8205
8206 bool AteExtraComma = false;
8207 if (EatIfPresent(lltok::comma)) {
8208 if (Lex.getKind() == lltok::kw_align) {
8209 if (parseOptionalAlignment(Alignment))
8210 return true;
8211 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8212 return true;
8213 } else if (Lex.getKind() == lltok::kw_addrspace) {
8214 ASLoc = Lex.getLoc();
8215 if (parseOptionalAddrSpace(AddrSpace))
8216 return true;
8217 } else if (Lex.getKind() == lltok::MetadataVar) {
8218 AteExtraComma = true;
8219 } else {
8220 if (parseTypeAndValue(Size, SizeLoc, PFS))
8221 return true;
8222 if (EatIfPresent(lltok::comma)) {
8223 if (Lex.getKind() == lltok::kw_align) {
8224 if (parseOptionalAlignment(Alignment))
8225 return true;
8226 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
8227 return true;
8228 } else if (Lex.getKind() == lltok::kw_addrspace) {
8229 ASLoc = Lex.getLoc();
8230 if (parseOptionalAddrSpace(AddrSpace))
8231 return true;
8232 } else if (Lex.getKind() == lltok::MetadataVar) {
8233 AteExtraComma = true;
8234 }
8235 }
8236 }
8237 }
8238
8239 if (Size && !Size->getType()->isIntegerTy())
8240 return error(SizeLoc, "element count must have integer type");
8241
8242 SmallPtrSet<Type *, 4> Visited;
8243 if (!Alignment && !Ty->isSized(&Visited))
8244 return error(TyLoc, "Cannot allocate unsized type");
8245 if (!Alignment)
8246 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
8247 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
8248 AI->setUsedWithInAlloca(IsInAlloca);
8249 AI->setSwiftError(IsSwiftError);
8250 Inst = AI;
8251 return AteExtraComma ? InstExtraComma : InstNormal;
8252}
8253
8254/// parseLoad
8255/// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
8256/// ::= 'load' 'atomic' 'volatile'? TypeAndValue
8257/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8258int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
8259 Value *Val; LocTy Loc;
8260 MaybeAlign Alignment;
8261 bool AteExtraComma = false;
8262 bool isAtomic = false;
8265
8266 if (Lex.getKind() == lltok::kw_atomic) {
8267 isAtomic = true;
8268 Lex.Lex();
8269 }
8270
8271 bool isVolatile = false;
8272 if (Lex.getKind() == lltok::kw_volatile) {
8273 isVolatile = true;
8274 Lex.Lex();
8275 }
8276
8277 Type *Ty;
8278 LocTy ExplicitTypeLoc = Lex.getLoc();
8279 if (parseType(Ty) ||
8280 parseToken(lltok::comma, "expected comma after load's type") ||
8281 parseTypeAndValue(Val, Loc, PFS) ||
8282 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8283 parseOptionalCommaAlign(Alignment, AteExtraComma))
8284 return true;
8285
8286 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
8287 return error(Loc, "load operand must be a pointer to a first class type");
8288 if (isAtomic && !Alignment)
8289 return error(Loc, "atomic load must have explicit non-zero alignment");
8290 if (Ordering == AtomicOrdering::Release ||
8292 return error(Loc, "atomic load cannot use Release ordering");
8293
8294 SmallPtrSet<Type *, 4> Visited;
8295 if (!Alignment && !Ty->isSized(&Visited))
8296 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
8297 if (!Alignment)
8298 Alignment = M->getDataLayout().getABITypeAlign(Ty);
8299 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
8300 return AteExtraComma ? InstExtraComma : InstNormal;
8301}
8302
8303/// parseStore
8304
8305/// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
8306/// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
8307/// 'singlethread'? AtomicOrdering (',' 'align' i32)?
8308int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
8309 Value *Val, *Ptr; LocTy Loc, PtrLoc;
8310 MaybeAlign Alignment;
8311 bool AteExtraComma = false;
8312 bool isAtomic = false;
8315
8316 if (Lex.getKind() == lltok::kw_atomic) {
8317 isAtomic = true;
8318 Lex.Lex();
8319 }
8320
8321 bool isVolatile = false;
8322 if (Lex.getKind() == lltok::kw_volatile) {
8323 isVolatile = true;
8324 Lex.Lex();
8325 }
8326
8327 if (parseTypeAndValue(Val, Loc, PFS) ||
8328 parseToken(lltok::comma, "expected ',' after store operand") ||
8329 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8330 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
8331 parseOptionalCommaAlign(Alignment, AteExtraComma))
8332 return true;
8333
8334 if (!Ptr->getType()->isPointerTy())
8335 return error(PtrLoc, "store operand must be a pointer");
8336 if (!Val->getType()->isFirstClassType())
8337 return error(Loc, "store operand must be a first class value");
8338 if (isAtomic && !Alignment)
8339 return error(Loc, "atomic store must have explicit non-zero alignment");
8340 if (Ordering == AtomicOrdering::Acquire ||
8342 return error(Loc, "atomic store cannot use Acquire ordering");
8343 SmallPtrSet<Type *, 4> Visited;
8344 if (!Alignment && !Val->getType()->isSized(&Visited))
8345 return error(Loc, "storing unsized types is not allowed");
8346 if (!Alignment)
8347 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
8348
8349 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
8350 return AteExtraComma ? InstExtraComma : InstNormal;
8351}
8352
8353/// parseCmpXchg
8354/// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
8355/// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
8356/// 'Align'?
8357int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
8358 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
8359 bool AteExtraComma = false;
8360 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
8361 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
8363 bool isVolatile = false;
8364 bool isWeak = false;
8365 MaybeAlign Alignment;
8366
8367 if (EatIfPresent(lltok::kw_weak))
8368 isWeak = true;
8369
8370 if (EatIfPresent(lltok::kw_volatile))
8371 isVolatile = true;
8372
8373 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8374 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
8375 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
8376 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
8377 parseTypeAndValue(New, NewLoc, PFS) ||
8378 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
8379 parseOrdering(FailureOrdering) ||
8380 parseOptionalCommaAlign(Alignment, AteExtraComma))
8381 return true;
8382
8383 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
8384 return tokError("invalid cmpxchg success ordering");
8385 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
8386 return tokError("invalid cmpxchg failure ordering");
8387 if (!Ptr->getType()->isPointerTy())
8388 return error(PtrLoc, "cmpxchg operand must be a pointer");
8389 if (Cmp->getType() != New->getType())
8390 return error(NewLoc, "compare value and new value type do not match");
8391 if (!New->getType()->isFirstClassType())
8392 return error(NewLoc, "cmpxchg operand must be a first class value");
8393
8394 const Align DefaultAlignment(
8395 PFS.getFunction().getDataLayout().getTypeStoreSize(
8396 Cmp->getType()));
8397
8398 AtomicCmpXchgInst *CXI =
8399 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
8400 SuccessOrdering, FailureOrdering, SSID);
8401 CXI->setVolatile(isVolatile);
8402 CXI->setWeak(isWeak);
8403
8404 Inst = CXI;
8405 return AteExtraComma ? InstExtraComma : InstNormal;
8406}
8407
8408/// parseAtomicRMW
8409/// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
8410/// 'singlethread'? AtomicOrdering
8411int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
8412 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
8413 bool AteExtraComma = false;
8416 bool isVolatile = false;
8417 bool IsFP = false;
8419 MaybeAlign Alignment;
8420
8421 if (EatIfPresent(lltok::kw_volatile))
8422 isVolatile = true;
8423
8424 switch (Lex.getKind()) {
8425 default:
8426 return tokError("expected binary operation in atomicrmw");
8440 break;
8443 break;
8446 break;
8447 case lltok::kw_usub_sat:
8449 break;
8450 case lltok::kw_fadd:
8452 IsFP = true;
8453 break;
8454 case lltok::kw_fsub:
8456 IsFP = true;
8457 break;
8458 case lltok::kw_fmax:
8460 IsFP = true;
8461 break;
8462 case lltok::kw_fmin:
8464 IsFP = true;
8465 break;
8466 }
8467 Lex.Lex(); // Eat the operation.
8468
8469 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
8470 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
8471 parseTypeAndValue(Val, ValLoc, PFS) ||
8472 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
8473 parseOptionalCommaAlign(Alignment, AteExtraComma))
8474 return true;
8475
8476 if (Ordering == AtomicOrdering::Unordered)
8477 return tokError("atomicrmw cannot be unordered");
8478 if (!Ptr->getType()->isPointerTy())
8479 return error(PtrLoc, "atomicrmw operand must be a pointer");
8480 if (Val->getType()->isScalableTy())
8481 return error(ValLoc, "atomicrmw operand may not be scalable");
8482
8484 if (!Val->getType()->isIntegerTy() &&
8485 !Val->getType()->isFloatingPointTy() &&
8486 !Val->getType()->isPointerTy()) {
8487 return error(
8488 ValLoc,
8490 " operand must be an integer, floating point, or pointer type");
8491 }
8492 } else if (IsFP) {
8493 if (!Val->getType()->isFPOrFPVectorTy()) {
8494 return error(ValLoc, "atomicrmw " +
8496 " operand must be a floating point type");
8497 }
8498 } else {
8499 if (!Val->getType()->isIntegerTy()) {
8500 return error(ValLoc, "atomicrmw " +
8502 " operand must be an integer");
8503 }
8504 }
8505
8506 unsigned Size =
8507 PFS.getFunction().getDataLayout().getTypeStoreSizeInBits(
8508 Val->getType());
8509 if (Size < 8 || (Size & (Size - 1)))
8510 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
8511 " integer");
8512 const Align DefaultAlignment(
8513 PFS.getFunction().getDataLayout().getTypeStoreSize(
8514 Val->getType()));
8515 AtomicRMWInst *RMWI =
8516 new AtomicRMWInst(Operation, Ptr, Val,
8517 Alignment.value_or(DefaultAlignment), Ordering, SSID);
8518 RMWI->setVolatile(isVolatile);
8519 Inst = RMWI;
8520 return AteExtraComma ? InstExtraComma : InstNormal;
8521}
8522
8523/// parseFence
8524/// ::= 'fence' 'singlethread'? AtomicOrdering
8525int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
8528 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
8529 return true;
8530
8531 if (Ordering == AtomicOrdering::Unordered)
8532 return tokError("fence cannot be unordered");
8533 if (Ordering == AtomicOrdering::Monotonic)
8534 return tokError("fence cannot be monotonic");
8535
8536 Inst = new FenceInst(Context, Ordering, SSID);
8537 return InstNormal;
8538}
8539
8540/// parseGetElementPtr
8541/// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
8542int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
8543 Value *Ptr = nullptr;
8544 Value *Val = nullptr;
8545 LocTy Loc, EltLoc;
8546 GEPNoWrapFlags NW;
8547
8548 while (true) {
8549 if (EatIfPresent(lltok::kw_inbounds))
8551 else if (EatIfPresent(lltok::kw_nusw))
8553 else if (EatIfPresent(lltok::kw_nuw))
8555 else
8556 break;
8557 }
8558
8559 Type *Ty = nullptr;
8560 if (parseType(Ty) ||
8561 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
8562 parseTypeAndValue(Ptr, Loc, PFS))
8563 return true;
8564
8565 Type *BaseType = Ptr->getType();
8566 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
8567 if (!BasePointerType)
8568 return error(Loc, "base of getelementptr must be a pointer");
8569
8571 bool AteExtraComma = false;
8572 // GEP returns a vector of pointers if at least one of parameters is a vector.
8573 // All vector parameters should have the same vector width.
8574 ElementCount GEPWidth = BaseType->isVectorTy()
8575 ? cast<VectorType>(BaseType)->getElementCount()
8577
8578 while (EatIfPresent(lltok::comma)) {
8579 if (Lex.getKind() == lltok::MetadataVar) {
8580 AteExtraComma = true;
8581 break;
8582 }
8583 if (parseTypeAndValue(Val, EltLoc, PFS))
8584 return true;
8585 if (!Val->getType()->isIntOrIntVectorTy())
8586 return error(EltLoc, "getelementptr index must be an integer");
8587
8588 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
8589 ElementCount ValNumEl = ValVTy->getElementCount();
8590 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
8591 return error(
8592 EltLoc,
8593 "getelementptr vector index has a wrong number of elements");
8594 GEPWidth = ValNumEl;
8595 }
8596 Indices.push_back(Val);
8597 }
8598
8599 SmallPtrSet<Type*, 4> Visited;
8600 if (!Indices.empty() && !Ty->isSized(&Visited))
8601 return error(Loc, "base element of getelementptr must be sized");
8602
8603 auto *STy = dyn_cast<StructType>(Ty);
8604 if (STy && STy->isScalableTy())
8605 return error(Loc, "getelementptr cannot target structure that contains "
8606 "scalable vector type");
8607
8608 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
8609 return error(Loc, "invalid getelementptr indices");
8611 Inst = GEP;
8612 GEP->setNoWrapFlags(NW);
8613 return AteExtraComma ? InstExtraComma : InstNormal;
8614}
8615
8616/// parseExtractValue
8617/// ::= 'extractvalue' TypeAndValue (',' uint32)+
8618int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
8619 Value *Val; LocTy Loc;
8621 bool AteExtraComma;
8622 if (parseTypeAndValue(Val, Loc, PFS) ||
8623 parseIndexList(Indices, AteExtraComma))
8624 return true;
8625
8626 if (!Val->getType()->isAggregateType())
8627 return error(Loc, "extractvalue operand must be aggregate type");
8628
8629 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
8630 return error(Loc, "invalid indices for extractvalue");
8631 Inst = ExtractValueInst::Create(Val, Indices);
8632 return AteExtraComma ? InstExtraComma : InstNormal;
8633}
8634
8635/// parseInsertValue
8636/// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
8637int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
8638 Value *Val0, *Val1; LocTy Loc0, Loc1;
8640 bool AteExtraComma;
8641 if (parseTypeAndValue(Val0, Loc0, PFS) ||
8642 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
8643 parseTypeAndValue(Val1, Loc1, PFS) ||
8644 parseIndexList(Indices, AteExtraComma))
8645 return true;
8646
8647 if (!Val0->getType()->isAggregateType())
8648 return error(Loc0, "insertvalue operand must be aggregate type");
8649
8650 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
8651 if (!IndexedType)
8652 return error(Loc0, "invalid indices for insertvalue");
8653 if (IndexedType != Val1->getType())
8654 return error(Loc1, "insertvalue operand and field disagree in type: '" +
8655 getTypeString(Val1->getType()) + "' instead of '" +
8656 getTypeString(IndexedType) + "'");
8657 Inst = InsertValueInst::Create(Val0, Val1, Indices);
8658 return AteExtraComma ? InstExtraComma : InstNormal;
8659}
8660
8661//===----------------------------------------------------------------------===//
8662// Embedded metadata.
8663//===----------------------------------------------------------------------===//
8664
8665/// parseMDNodeVector
8666/// ::= { Element (',' Element)* }
8667/// Element
8668/// ::= 'null' | Metadata
8669bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
8670 if (parseToken(lltok::lbrace, "expected '{' here"))
8671 return true;
8672
8673 // Check for an empty list.
8674 if (EatIfPresent(lltok::rbrace))
8675 return false;
8676
8677 do {
8678 if (EatIfPresent(lltok::kw_null)) {
8679 Elts.push_back(nullptr);
8680 continue;
8681 }
8682
8683 Metadata *MD;
8684 if (parseMetadata(MD, nullptr))
8685 return true;
8686 Elts.push_back(MD);
8687 } while (EatIfPresent(lltok::comma));
8688
8689 return parseToken(lltok::rbrace, "expected end of metadata node");
8690}
8691
8692//===----------------------------------------------------------------------===//
8693// Use-list order directives.
8694//===----------------------------------------------------------------------===//
8695bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
8696 SMLoc Loc) {
8697 if (V->use_empty())
8698 return error(Loc, "value has no uses");
8699
8700 unsigned NumUses = 0;
8702 for (const Use &U : V->uses()) {
8703 if (++NumUses > Indexes.size())
8704 break;
8705 Order[&U] = Indexes[NumUses - 1];
8706 }
8707 if (NumUses < 2)
8708 return error(Loc, "value only has one use");
8709 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
8710 return error(Loc,
8711 "wrong number of indexes, expected " + Twine(V->getNumUses()));
8712
8713 V->sortUseList([&](const Use &L, const Use &R) {
8714 return Order.lookup(&L) < Order.lookup(&R);
8715 });
8716 return false;
8717}
8718
8719/// parseUseListOrderIndexes
8720/// ::= '{' uint32 (',' uint32)+ '}'
8721bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
8722 SMLoc Loc = Lex.getLoc();
8723 if (parseToken(lltok::lbrace, "expected '{' here"))
8724 return true;
8725 if (Lex.getKind() == lltok::rbrace)
8726 return tokError("expected non-empty list of uselistorder indexes");
8727
8728 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
8729 // indexes should be distinct numbers in the range [0, size-1], and should
8730 // not be in order.
8731 unsigned Offset = 0;
8732 unsigned Max = 0;
8733 bool IsOrdered = true;
8734 assert(Indexes.empty() && "Expected empty order vector");
8735 do {
8736 unsigned Index;
8737 if (parseUInt32(Index))
8738 return true;
8739
8740 // Update consistency checks.
8741 Offset += Index - Indexes.size();
8742 Max = std::max(Max, Index);
8743 IsOrdered &= Index == Indexes.size();
8744
8745 Indexes.push_back(Index);
8746 } while (EatIfPresent(lltok::comma));
8747
8748 if (parseToken(lltok::rbrace, "expected '}' here"))
8749 return true;
8750
8751 if (Indexes.size() < 2)
8752 return error(Loc, "expected >= 2 uselistorder indexes");
8753 if (Offset != 0 || Max >= Indexes.size())
8754 return error(Loc,
8755 "expected distinct uselistorder indexes in range [0, size)");
8756 if (IsOrdered)
8757 return error(Loc, "expected uselistorder indexes to change the order");
8758
8759 return false;
8760}
8761
8762/// parseUseListOrder
8763/// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
8764bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8765 SMLoc Loc = Lex.getLoc();
8766 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
8767 return true;
8768
8769 Value *V;
8771 if (parseTypeAndValue(V, PFS) ||
8772 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
8773 parseUseListOrderIndexes(Indexes))
8774 return true;
8775
8776 return sortUseListOrder(V, Indexes, Loc);
8777}
8778
8779/// parseUseListOrderBB
8780/// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
8781bool LLParser::parseUseListOrderBB() {
8783 SMLoc Loc = Lex.getLoc();
8784 Lex.Lex();
8785
8786 ValID Fn, Label;
8788 if (parseValID(Fn, /*PFS=*/nullptr) ||
8789 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
8790 parseValID(Label, /*PFS=*/nullptr) ||
8791 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
8792 parseUseListOrderIndexes(Indexes))
8793 return true;
8794
8795 // Check the function.
8796 GlobalValue *GV;
8797 if (Fn.Kind == ValID::t_GlobalName)
8798 GV = M->getNamedValue(Fn.StrVal);
8799 else if (Fn.Kind == ValID::t_GlobalID)
8800 GV = NumberedVals.get(Fn.UIntVal);
8801 else
8802 return error(Fn.Loc, "expected function name in uselistorder_bb");
8803 if (!GV)
8804 return error(Fn.Loc,
8805 "invalid function forward reference in uselistorder_bb");
8806 auto *F = dyn_cast<Function>(GV);
8807 if (!F)
8808 return error(Fn.Loc, "expected function name in uselistorder_bb");
8809 if (F->isDeclaration())
8810 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
8811
8812 // Check the basic block.
8813 if (Label.Kind == ValID::t_LocalID)
8814 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
8815 if (Label.Kind != ValID::t_LocalName)
8816 return error(Label.Loc, "expected basic block name in uselistorder_bb");
8817 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
8818 if (!V)
8819 return error(Label.Loc, "invalid basic block in uselistorder_bb");
8820 if (!isa<BasicBlock>(V))
8821 return error(Label.Loc, "expected basic block in uselistorder_bb");
8822
8823 return sortUseListOrder(V, Indexes, Loc);
8824}
8825
8826/// ModuleEntry
8827/// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
8828/// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
8829bool LLParser::parseModuleEntry(unsigned ID) {
8831 Lex.Lex();
8832
8833 std::string Path;
8834 if (parseToken(lltok::colon, "expected ':' here") ||
8835 parseToken(lltok::lparen, "expected '(' here") ||
8836 parseToken(lltok::kw_path, "expected 'path' here") ||
8837 parseToken(lltok::colon, "expected ':' here") ||
8838 parseStringConstant(Path) ||
8839 parseToken(lltok::comma, "expected ',' here") ||
8840 parseToken(lltok::kw_hash, "expected 'hash' here") ||
8841 parseToken(lltok::colon, "expected ':' here") ||
8842 parseToken(lltok::lparen, "expected '(' here"))
8843 return true;
8844
8845 ModuleHash Hash;
8846 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
8847 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
8848 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
8849 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
8850 parseUInt32(Hash[4]))
8851 return true;
8852
8853 if (parseToken(lltok::rparen, "expected ')' here") ||
8854 parseToken(lltok::rparen, "expected ')' here"))
8855 return true;
8856
8857 auto ModuleEntry = Index->addModule(Path, Hash);
8858 ModuleIdMap[ID] = ModuleEntry->first();
8859
8860 return false;
8861}
8862
8863/// TypeIdEntry
8864/// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
8865bool LLParser::parseTypeIdEntry(unsigned ID) {
8867 Lex.Lex();
8868
8869 std::string Name;
8870 if (parseToken(lltok::colon, "expected ':' here") ||
8871 parseToken(lltok::lparen, "expected '(' here") ||
8872 parseToken(lltok::kw_name, "expected 'name' here") ||
8873 parseToken(lltok::colon, "expected ':' here") ||
8874 parseStringConstant(Name))
8875 return true;
8876
8877 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
8878 if (parseToken(lltok::comma, "expected ',' here") ||
8879 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
8880 return true;
8881
8882 // Check if this ID was forward referenced, and if so, update the
8883 // corresponding GUIDs.
8884 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8885 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8886 for (auto TIDRef : FwdRefTIDs->second) {
8887 assert(!*TIDRef.first &&
8888 "Forward referenced type id GUID expected to be 0");
8889 *TIDRef.first = GlobalValue::getGUID(Name);
8890 }
8891 ForwardRefTypeIds.erase(FwdRefTIDs);
8892 }
8893
8894 return false;
8895}
8896
8897/// TypeIdSummary
8898/// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
8899bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
8900 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
8901 parseToken(lltok::colon, "expected ':' here") ||
8902 parseToken(lltok::lparen, "expected '(' here") ||
8903 parseTypeTestResolution(TIS.TTRes))
8904 return true;
8905
8906 if (EatIfPresent(lltok::comma)) {
8907 // Expect optional wpdResolutions field
8908 if (parseOptionalWpdResolutions(TIS.WPDRes))
8909 return true;
8910 }
8911
8912 if (parseToken(lltok::rparen, "expected ')' here"))
8913 return true;
8914
8915 return false;
8916}
8917
8919 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
8920
8921/// TypeIdCompatibleVtableEntry
8922/// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
8923/// TypeIdCompatibleVtableInfo
8924/// ')'
8925bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
8927 Lex.Lex();
8928
8929 std::string Name;
8930 if (parseToken(lltok::colon, "expected ':' here") ||
8931 parseToken(lltok::lparen, "expected '(' here") ||
8932 parseToken(lltok::kw_name, "expected 'name' here") ||
8933 parseToken(lltok::colon, "expected ':' here") ||
8934 parseStringConstant(Name))
8935 return true;
8936
8938 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
8939 if (parseToken(lltok::comma, "expected ',' here") ||
8940 parseToken(lltok::kw_summary, "expected 'summary' here") ||
8941 parseToken(lltok::colon, "expected ':' here") ||
8942 parseToken(lltok::lparen, "expected '(' here"))
8943 return true;
8944
8945 IdToIndexMapType IdToIndexMap;
8946 // parse each call edge
8947 do {
8949 if (parseToken(lltok::lparen, "expected '(' here") ||
8950 parseToken(lltok::kw_offset, "expected 'offset' here") ||
8951 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8952 parseToken(lltok::comma, "expected ',' here"))
8953 return true;
8954
8955 LocTy Loc = Lex.getLoc();
8956 unsigned GVId;
8957 ValueInfo VI;
8958 if (parseGVReference(VI, GVId))
8959 return true;
8960
8961 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
8962 // forward reference. We will save the location of the ValueInfo needing an
8963 // update, but can only do so once the std::vector is finalized.
8964 if (VI == EmptyVI)
8965 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8966 TI.push_back({Offset, VI});
8967
8968 if (parseToken(lltok::rparen, "expected ')' in call"))
8969 return true;
8970 } while (EatIfPresent(lltok::comma));
8971
8972 // Now that the TI vector is finalized, it is safe to save the locations
8973 // of any forward GV references that need updating later.
8974 for (auto I : IdToIndexMap) {
8975 auto &Infos = ForwardRefValueInfos[I.first];
8976 for (auto P : I.second) {
8977 assert(TI[P.first].VTableVI == EmptyVI &&
8978 "Forward referenced ValueInfo expected to be empty");
8979 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
8980 }
8981 }
8982
8983 if (parseToken(lltok::rparen, "expected ')' here") ||
8984 parseToken(lltok::rparen, "expected ')' here"))
8985 return true;
8986
8987 // Check if this ID was forward referenced, and if so, update the
8988 // corresponding GUIDs.
8989 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8990 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8991 for (auto TIDRef : FwdRefTIDs->second) {
8992 assert(!*TIDRef.first &&
8993 "Forward referenced type id GUID expected to be 0");
8994 *TIDRef.first = GlobalValue::getGUID(Name);
8995 }
8996 ForwardRefTypeIds.erase(FwdRefTIDs);
8997 }
8998
8999 return false;
9000}
9001
9002/// TypeTestResolution
9003/// ::= 'typeTestRes' ':' '(' 'kind' ':'
9004/// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
9005/// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
9006/// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
9007/// [',' 'inlinesBits' ':' UInt64]? ')'
9008bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
9009 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
9010 parseToken(lltok::colon, "expected ':' here") ||
9011 parseToken(lltok::lparen, "expected '(' here") ||
9012 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9013 parseToken(lltok::colon, "expected ':' here"))
9014 return true;
9015
9016 switch (Lex.getKind()) {
9017 case lltok::kw_unknown:
9019 break;
9020 case lltok::kw_unsat:
9022 break;
9025 break;
9026 case lltok::kw_inline:
9028 break;
9029 case lltok::kw_single:
9031 break;
9032 case lltok::kw_allOnes:
9034 break;
9035 default:
9036 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
9037 }
9038 Lex.Lex();
9039
9040 if (parseToken(lltok::comma, "expected ',' here") ||
9041 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
9042 parseToken(lltok::colon, "expected ':' here") ||
9043 parseUInt32(TTRes.SizeM1BitWidth))
9044 return true;
9045
9046 // parse optional fields
9047 while (EatIfPresent(lltok::comma)) {
9048 switch (Lex.getKind()) {
9050 Lex.Lex();
9051 if (parseToken(lltok::colon, "expected ':'") ||
9052 parseUInt64(TTRes.AlignLog2))
9053 return true;
9054 break;
9055 case lltok::kw_sizeM1:
9056 Lex.Lex();
9057 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
9058 return true;
9059 break;
9060 case lltok::kw_bitMask: {
9061 unsigned Val;
9062 Lex.Lex();
9063 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
9064 return true;
9065 assert(Val <= 0xff);
9066 TTRes.BitMask = (uint8_t)Val;
9067 break;
9068 }
9070 Lex.Lex();
9071 if (parseToken(lltok::colon, "expected ':'") ||
9072 parseUInt64(TTRes.InlineBits))
9073 return true;
9074 break;
9075 default:
9076 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
9077 }
9078 }
9079
9080 if (parseToken(lltok::rparen, "expected ')' here"))
9081 return true;
9082
9083 return false;
9084}
9085
9086/// OptionalWpdResolutions
9087/// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
9088/// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
9089bool LLParser::parseOptionalWpdResolutions(
9090 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
9091 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
9092 parseToken(lltok::colon, "expected ':' here") ||
9093 parseToken(lltok::lparen, "expected '(' here"))
9094 return true;
9095
9096 do {
9099 if (parseToken(lltok::lparen, "expected '(' here") ||
9100 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9101 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
9102 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
9103 parseToken(lltok::rparen, "expected ')' here"))
9104 return true;
9105 WPDResMap[Offset] = WPDRes;
9106 } while (EatIfPresent(lltok::comma));
9107
9108 if (parseToken(lltok::rparen, "expected ')' here"))
9109 return true;
9110
9111 return false;
9112}
9113
9114/// WpdRes
9115/// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
9116/// [',' OptionalResByArg]? ')'
9117/// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
9118/// ',' 'singleImplName' ':' STRINGCONSTANT ','
9119/// [',' OptionalResByArg]? ')'
9120/// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
9121/// [',' OptionalResByArg]? ')'
9122bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
9123 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
9124 parseToken(lltok::colon, "expected ':' here") ||
9125 parseToken(lltok::lparen, "expected '(' here") ||
9126 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9127 parseToken(lltok::colon, "expected ':' here"))
9128 return true;
9129
9130 switch (Lex.getKind()) {
9131 case lltok::kw_indir:
9133 break;
9136 break;
9139 break;
9140 default:
9141 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
9142 }
9143 Lex.Lex();
9144
9145 // parse optional fields
9146 while (EatIfPresent(lltok::comma)) {
9147 switch (Lex.getKind()) {
9149 Lex.Lex();
9150 if (parseToken(lltok::colon, "expected ':' here") ||
9151 parseStringConstant(WPDRes.SingleImplName))
9152 return true;
9153 break;
9154 case lltok::kw_resByArg:
9155 if (parseOptionalResByArg(WPDRes.ResByArg))
9156 return true;
9157 break;
9158 default:
9159 return error(Lex.getLoc(),
9160 "expected optional WholeProgramDevirtResolution field");
9161 }
9162 }
9163
9164 if (parseToken(lltok::rparen, "expected ')' here"))
9165 return true;
9166
9167 return false;
9168}
9169
9170/// OptionalResByArg
9171/// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
9172/// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
9173/// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
9174/// 'virtualConstProp' )
9175/// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
9176/// [',' 'bit' ':' UInt32]? ')'
9177bool LLParser::parseOptionalResByArg(
9178 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
9179 &ResByArg) {
9180 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
9181 parseToken(lltok::colon, "expected ':' here") ||
9182 parseToken(lltok::lparen, "expected '(' here"))
9183 return true;
9184
9185 do {
9186 std::vector<uint64_t> Args;
9187 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
9188 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
9189 parseToken(lltok::colon, "expected ':' here") ||
9190 parseToken(lltok::lparen, "expected '(' here") ||
9191 parseToken(lltok::kw_kind, "expected 'kind' here") ||
9192 parseToken(lltok::colon, "expected ':' here"))
9193 return true;
9194
9196 switch (Lex.getKind()) {
9197 case lltok::kw_indir:
9199 break;
9202 break;
9205 break;
9208 break;
9209 default:
9210 return error(Lex.getLoc(),
9211 "unexpected WholeProgramDevirtResolution::ByArg kind");
9212 }
9213 Lex.Lex();
9214
9215 // parse optional fields
9216 while (EatIfPresent(lltok::comma)) {
9217 switch (Lex.getKind()) {
9218 case lltok::kw_info:
9219 Lex.Lex();
9220 if (parseToken(lltok::colon, "expected ':' here") ||
9221 parseUInt64(ByArg.Info))
9222 return true;
9223 break;
9224 case lltok::kw_byte:
9225 Lex.Lex();
9226 if (parseToken(lltok::colon, "expected ':' here") ||
9227 parseUInt32(ByArg.Byte))
9228 return true;
9229 break;
9230 case lltok::kw_bit:
9231 Lex.Lex();
9232 if (parseToken(lltok::colon, "expected ':' here") ||
9233 parseUInt32(ByArg.Bit))
9234 return true;
9235 break;
9236 default:
9237 return error(Lex.getLoc(),
9238 "expected optional whole program devirt field");
9239 }
9240 }
9241
9242 if (parseToken(lltok::rparen, "expected ')' here"))
9243 return true;
9244
9245 ResByArg[Args] = ByArg;
9246 } while (EatIfPresent(lltok::comma));
9247
9248 if (parseToken(lltok::rparen, "expected ')' here"))
9249 return true;
9250
9251 return false;
9252}
9253
9254/// OptionalResByArg
9255/// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
9256bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
9257 if (parseToken(lltok::kw_args, "expected 'args' here") ||
9258 parseToken(lltok::colon, "expected ':' here") ||
9259 parseToken(lltok::lparen, "expected '(' here"))
9260 return true;
9261
9262 do {
9263 uint64_t Val;
9264 if (parseUInt64(Val))
9265 return true;
9266 Args.push_back(Val);
9267 } while (EatIfPresent(lltok::comma));
9268
9269 if (parseToken(lltok::rparen, "expected ')' here"))
9270 return true;
9271
9272 return false;
9273}
9274
9275static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
9276
9277static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
9278 bool ReadOnly = Fwd->isReadOnly();
9279 bool WriteOnly = Fwd->isWriteOnly();
9280 assert(!(ReadOnly && WriteOnly));
9281 *Fwd = Resolved;
9282 if (ReadOnly)
9283 Fwd->setReadOnly();
9284 if (WriteOnly)
9285 Fwd->setWriteOnly();
9286}
9287
9288/// Stores the given Name/GUID and associated summary into the Index.
9289/// Also updates any forward references to the associated entry ID.
9290bool LLParser::addGlobalValueToIndex(
9291 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
9292 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary, LocTy Loc) {
9293 // First create the ValueInfo utilizing the Name or GUID.
9294 ValueInfo VI;
9295 if (GUID != 0) {
9296 assert(Name.empty());
9297 VI = Index->getOrInsertValueInfo(GUID);
9298 } else {
9299 assert(!Name.empty());
9300 if (M) {
9301 auto *GV = M->getNamedValue(Name);
9302 if (!GV)
9303 return error(Loc, "Reference to undefined global \"" + Name + "\"");
9304
9305 VI = Index->getOrInsertValueInfo(GV);
9306 } else {
9307 assert(
9308 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
9309 "Need a source_filename to compute GUID for local");
9311 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
9312 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
9313 }
9314 }
9315
9316 // Resolve forward references from calls/refs
9317 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
9318 if (FwdRefVIs != ForwardRefValueInfos.end()) {
9319 for (auto VIRef : FwdRefVIs->second) {
9320 assert(VIRef.first->getRef() == FwdVIRef &&
9321 "Forward referenced ValueInfo expected to be empty");
9322 resolveFwdRef(VIRef.first, VI);
9323 }
9324 ForwardRefValueInfos.erase(FwdRefVIs);
9325 }
9326
9327 // Resolve forward references from aliases
9328 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
9329 if (FwdRefAliasees != ForwardRefAliasees.end()) {
9330 for (auto AliaseeRef : FwdRefAliasees->second) {
9331 assert(!AliaseeRef.first->hasAliasee() &&
9332 "Forward referencing alias already has aliasee");
9333 assert(Summary && "Aliasee must be a definition");
9334 AliaseeRef.first->setAliasee(VI, Summary.get());
9335 }
9336 ForwardRefAliasees.erase(FwdRefAliasees);
9337 }
9338
9339 // Add the summary if one was provided.
9340 if (Summary)
9341 Index->addGlobalValueSummary(VI, std::move(Summary));
9342
9343 // Save the associated ValueInfo for use in later references by ID.
9344 if (ID == NumberedValueInfos.size())
9345 NumberedValueInfos.push_back(VI);
9346 else {
9347 // Handle non-continuous numbers (to make test simplification easier).
9348 if (ID > NumberedValueInfos.size())
9349 NumberedValueInfos.resize(ID + 1);
9350 NumberedValueInfos[ID] = VI;
9351 }
9352
9353 return false;
9354}
9355
9356/// parseSummaryIndexFlags
9357/// ::= 'flags' ':' UInt64
9358bool LLParser::parseSummaryIndexFlags() {
9359 assert(Lex.getKind() == lltok::kw_flags);
9360 Lex.Lex();
9361
9362 if (parseToken(lltok::colon, "expected ':' here"))
9363 return true;
9365 if (parseUInt64(Flags))
9366 return true;
9367 if (Index)
9368 Index->setFlags(Flags);
9369 return false;
9370}
9371
9372/// parseBlockCount
9373/// ::= 'blockcount' ':' UInt64
9374bool LLParser::parseBlockCount() {
9376 Lex.Lex();
9377
9378 if (parseToken(lltok::colon, "expected ':' here"))
9379 return true;
9380 uint64_t BlockCount;
9381 if (parseUInt64(BlockCount))
9382 return true;
9383 if (Index)
9384 Index->setBlockCount(BlockCount);
9385 return false;
9386}
9387
9388/// parseGVEntry
9389/// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
9390/// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
9391/// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
9392bool LLParser::parseGVEntry(unsigned ID) {
9393 assert(Lex.getKind() == lltok::kw_gv);
9394 Lex.Lex();
9395
9396 if (parseToken(lltok::colon, "expected ':' here") ||
9397 parseToken(lltok::lparen, "expected '(' here"))
9398 return true;
9399
9400 LocTy Loc = Lex.getLoc();
9401 std::string Name;
9403 switch (Lex.getKind()) {
9404 case lltok::kw_name:
9405 Lex.Lex();
9406 if (parseToken(lltok::colon, "expected ':' here") ||
9407 parseStringConstant(Name))
9408 return true;
9409 // Can't create GUID/ValueInfo until we have the linkage.
9410 break;
9411 case lltok::kw_guid:
9412 Lex.Lex();
9413 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
9414 return true;
9415 break;
9416 default:
9417 return error(Lex.getLoc(), "expected name or guid tag");
9418 }
9419
9420 if (!EatIfPresent(lltok::comma)) {
9421 // No summaries. Wrap up.
9422 if (parseToken(lltok::rparen, "expected ')' here"))
9423 return true;
9424 // This was created for a call to an external or indirect target.
9425 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
9426 // created for indirect calls with VP. A Name with no GUID came from
9427 // an external definition. We pass ExternalLinkage since that is only
9428 // used when the GUID must be computed from Name, and in that case
9429 // the symbol must have external linkage.
9430 return addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
9431 nullptr, Loc);
9432 }
9433
9434 // Have a list of summaries
9435 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
9436 parseToken(lltok::colon, "expected ':' here") ||
9437 parseToken(lltok::lparen, "expected '(' here"))
9438 return true;
9439 do {
9440 switch (Lex.getKind()) {
9441 case lltok::kw_function:
9442 if (parseFunctionSummary(Name, GUID, ID))
9443 return true;
9444 break;
9445 case lltok::kw_variable:
9446 if (parseVariableSummary(Name, GUID, ID))
9447 return true;
9448 break;
9449 case lltok::kw_alias:
9450 if (parseAliasSummary(Name, GUID, ID))
9451 return true;
9452 break;
9453 default:
9454 return error(Lex.getLoc(), "expected summary type");
9455 }
9456 } while (EatIfPresent(lltok::comma));
9457
9458 if (parseToken(lltok::rparen, "expected ')' here") ||
9459 parseToken(lltok::rparen, "expected ')' here"))
9460 return true;
9461
9462 return false;
9463}
9464
9465/// FunctionSummary
9466/// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9467/// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
9468/// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
9469/// [',' OptionalRefs]? ')'
9470bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
9471 unsigned ID) {
9472 LocTy Loc = Lex.getLoc();
9474 Lex.Lex();
9475
9476 StringRef ModulePath;
9479 /*NotEligibleToImport=*/false,
9480 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9482 unsigned InstCount;
9484 FunctionSummary::TypeIdInfo TypeIdInfo;
9485 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
9487 std::vector<CallsiteInfo> Callsites;
9488 std::vector<AllocInfo> Allocs;
9489 // Default is all-zeros (conservative values).
9490 FunctionSummary::FFlags FFlags = {};
9491 if (parseToken(lltok::colon, "expected ':' here") ||
9492 parseToken(lltok::lparen, "expected '(' here") ||
9493 parseModuleReference(ModulePath) ||
9494 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9495 parseToken(lltok::comma, "expected ',' here") ||
9496 parseToken(lltok::kw_insts, "expected 'insts' here") ||
9497 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
9498 return true;
9499
9500 // parse optional fields
9501 while (EatIfPresent(lltok::comma)) {
9502 switch (Lex.getKind()) {
9504 if (parseOptionalFFlags(FFlags))
9505 return true;
9506 break;
9507 case lltok::kw_calls:
9508 if (parseOptionalCalls(Calls))
9509 return true;
9510 break;
9512 if (parseOptionalTypeIdInfo(TypeIdInfo))
9513 return true;
9514 break;
9515 case lltok::kw_refs:
9516 if (parseOptionalRefs(Refs))
9517 return true;
9518 break;
9519 case lltok::kw_params:
9520 if (parseOptionalParamAccesses(ParamAccesses))
9521 return true;
9522 break;
9523 case lltok::kw_allocs:
9524 if (parseOptionalAllocs(Allocs))
9525 return true;
9526 break;
9528 if (parseOptionalCallsites(Callsites))
9529 return true;
9530 break;
9531 default:
9532 return error(Lex.getLoc(), "expected optional function summary field");
9533 }
9534 }
9535
9536 if (parseToken(lltok::rparen, "expected ')' here"))
9537 return true;
9538
9539 auto FS = std::make_unique<FunctionSummary>(
9540 GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
9541 std::move(TypeIdInfo.TypeTests),
9542 std::move(TypeIdInfo.TypeTestAssumeVCalls),
9543 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
9544 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
9545 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
9546 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
9547
9548 FS->setModulePath(ModulePath);
9549
9550 return addGlobalValueToIndex(Name, GUID,
9552 std::move(FS), Loc);
9553}
9554
9555/// VariableSummary
9556/// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9557/// [',' OptionalRefs]? ')'
9558bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
9559 unsigned ID) {
9560 LocTy Loc = Lex.getLoc();
9562 Lex.Lex();
9563
9564 StringRef ModulePath;
9567 /*NotEligibleToImport=*/false,
9568 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9570 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
9571 /* WriteOnly */ false,
9572 /* Constant */ false,
9575 VTableFuncList VTableFuncs;
9576 if (parseToken(lltok::colon, "expected ':' here") ||
9577 parseToken(lltok::lparen, "expected '(' here") ||
9578 parseModuleReference(ModulePath) ||
9579 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9580 parseToken(lltok::comma, "expected ',' here") ||
9581 parseGVarFlags(GVarFlags))
9582 return true;
9583
9584 // parse optional fields
9585 while (EatIfPresent(lltok::comma)) {
9586 switch (Lex.getKind()) {
9588 if (parseOptionalVTableFuncs(VTableFuncs))
9589 return true;
9590 break;
9591 case lltok::kw_refs:
9592 if (parseOptionalRefs(Refs))
9593 return true;
9594 break;
9595 default:
9596 return error(Lex.getLoc(), "expected optional variable summary field");
9597 }
9598 }
9599
9600 if (parseToken(lltok::rparen, "expected ')' here"))
9601 return true;
9602
9603 auto GS =
9604 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
9605
9606 GS->setModulePath(ModulePath);
9607 GS->setVTableFuncs(std::move(VTableFuncs));
9608
9609 return addGlobalValueToIndex(Name, GUID,
9611 std::move(GS), Loc);
9612}
9613
9614/// AliasSummary
9615/// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9616/// 'aliasee' ':' GVReference ')'
9617bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
9618 unsigned ID) {
9619 assert(Lex.getKind() == lltok::kw_alias);
9620 LocTy Loc = Lex.getLoc();
9621 Lex.Lex();
9622
9623 StringRef ModulePath;
9626 /*NotEligibleToImport=*/false,
9627 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false,
9629 if (parseToken(lltok::colon, "expected ':' here") ||
9630 parseToken(lltok::lparen, "expected '(' here") ||
9631 parseModuleReference(ModulePath) ||
9632 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
9633 parseToken(lltok::comma, "expected ',' here") ||
9634 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
9635 parseToken(lltok::colon, "expected ':' here"))
9636 return true;
9637
9638 ValueInfo AliaseeVI;
9639 unsigned GVId;
9640 if (parseGVReference(AliaseeVI, GVId))
9641 return true;
9642
9643 if (parseToken(lltok::rparen, "expected ')' here"))
9644 return true;
9645
9646 auto AS = std::make_unique<AliasSummary>(GVFlags);
9647
9648 AS->setModulePath(ModulePath);
9649
9650 // Record forward reference if the aliasee is not parsed yet.
9651 if (AliaseeVI.getRef() == FwdVIRef) {
9652 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
9653 } else {
9654 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
9655 assert(Summary && "Aliasee must be a definition");
9656 AS->setAliasee(AliaseeVI, Summary);
9657 }
9658
9659 return addGlobalValueToIndex(Name, GUID,
9661 std::move(AS), Loc);
9662}
9663
9664/// Flag
9665/// ::= [0|1]
9666bool LLParser::parseFlag(unsigned &Val) {
9667 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
9668 return tokError("expected integer");
9669 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
9670 Lex.Lex();
9671 return false;
9672}
9673
9674/// OptionalFFlags
9675/// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
9676/// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
9677/// [',' 'returnDoesNotAlias' ':' Flag]? ')'
9678/// [',' 'noInline' ':' Flag]? ')'
9679/// [',' 'alwaysInline' ':' Flag]? ')'
9680/// [',' 'noUnwind' ':' Flag]? ')'
9681/// [',' 'mayThrow' ':' Flag]? ')'
9682/// [',' 'hasUnknownCall' ':' Flag]? ')'
9683/// [',' 'mustBeUnreachable' ':' Flag]? ')'
9684
9685bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
9687 Lex.Lex();
9688
9689 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
9690 parseToken(lltok::lparen, "expected '(' in funcFlags"))
9691 return true;
9692
9693 do {
9694 unsigned Val = 0;
9695 switch (Lex.getKind()) {
9696 case lltok::kw_readNone:
9697 Lex.Lex();
9698 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9699 return true;
9700 FFlags.ReadNone = Val;
9701 break;
9702 case lltok::kw_readOnly:
9703 Lex.Lex();
9704 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9705 return true;
9706 FFlags.ReadOnly = Val;
9707 break;
9709 Lex.Lex();
9710 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9711 return true;
9712 FFlags.NoRecurse = Val;
9713 break;
9715 Lex.Lex();
9716 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9717 return true;
9718 FFlags.ReturnDoesNotAlias = Val;
9719 break;
9720 case lltok::kw_noInline:
9721 Lex.Lex();
9722 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9723 return true;
9724 FFlags.NoInline = Val;
9725 break;
9727 Lex.Lex();
9728 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9729 return true;
9730 FFlags.AlwaysInline = Val;
9731 break;
9732 case lltok::kw_noUnwind:
9733 Lex.Lex();
9734 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9735 return true;
9736 FFlags.NoUnwind = Val;
9737 break;
9738 case lltok::kw_mayThrow:
9739 Lex.Lex();
9740 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9741 return true;
9742 FFlags.MayThrow = Val;
9743 break;
9745 Lex.Lex();
9746 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9747 return true;
9748 FFlags.HasUnknownCall = Val;
9749 break;
9751 Lex.Lex();
9752 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9753 return true;
9754 FFlags.MustBeUnreachable = Val;
9755 break;
9756 default:
9757 return error(Lex.getLoc(), "expected function flag type");
9758 }
9759 } while (EatIfPresent(lltok::comma));
9760
9761 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
9762 return true;
9763
9764 return false;
9765}
9766
9767/// OptionalCalls
9768/// := 'calls' ':' '(' Call [',' Call]* ')'
9769/// Call ::= '(' 'callee' ':' GVReference
9770/// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
9771/// [ ',' 'tail' ]? ')'
9772bool LLParser::parseOptionalCalls(
9774 assert(Lex.getKind() == lltok::kw_calls);
9775 Lex.Lex();
9776
9777 if (parseToken(lltok::colon, "expected ':' in calls") ||
9778 parseToken(lltok::lparen, "expected '(' in calls"))
9779 return true;
9780
9781 IdToIndexMapType IdToIndexMap;
9782 // parse each call edge
9783 do {
9784 ValueInfo VI;
9785 if (parseToken(lltok::lparen, "expected '(' in call") ||
9786 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
9787 parseToken(lltok::colon, "expected ':'"))
9788 return true;
9789
9790 LocTy Loc = Lex.getLoc();
9791 unsigned GVId;
9792 if (parseGVReference(VI, GVId))
9793 return true;
9794
9796 unsigned RelBF = 0;
9797 unsigned HasTailCall = false;
9798
9799 // parse optional fields
9800 while (EatIfPresent(lltok::comma)) {
9801 switch (Lex.getKind()) {
9802 case lltok::kw_hotness:
9803 Lex.Lex();
9804 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
9805 return true;
9806 break;
9807 case lltok::kw_relbf:
9808 Lex.Lex();
9809 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
9810 return true;
9811 break;
9812 case lltok::kw_tail:
9813 Lex.Lex();
9814 if (parseToken(lltok::colon, "expected ':'") || parseFlag(HasTailCall))
9815 return true;
9816 break;
9817 default:
9818 return error(Lex.getLoc(), "expected hotness, relbf, or tail");
9819 }
9820 }
9821 if (Hotness != CalleeInfo::HotnessType::Unknown && RelBF > 0)
9822 return tokError("Expected only one of hotness or relbf");
9823 // Keep track of the Call array index needing a forward reference.
9824 // We will save the location of the ValueInfo needing an update, but
9825 // can only do so once the std::vector is finalized.
9826 if (VI.getRef() == FwdVIRef)
9827 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
9828 Calls.push_back(
9829 FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, HasTailCall, RelBF)});
9830
9831 if (parseToken(lltok::rparen, "expected ')' in call"))
9832 return true;
9833 } while (EatIfPresent(lltok::comma));
9834
9835 // Now that the Calls vector is finalized, it is safe to save the locations
9836 // of any forward GV references that need updating later.
9837 for (auto I : IdToIndexMap) {
9838 auto &Infos = ForwardRefValueInfos[I.first];
9839 for (auto P : I.second) {
9840 assert(Calls[P.first].first.getRef() == FwdVIRef &&
9841 "Forward referenced ValueInfo expected to be empty");
9842 Infos.emplace_back(&Calls[P.first].first, P.second);
9843 }
9844 }
9845
9846 if (parseToken(lltok::rparen, "expected ')' in calls"))
9847 return true;
9848
9849 return false;
9850}
9851
9852/// Hotness
9853/// := ('unknown'|'cold'|'none'|'hot'|'critical')
9854bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
9855 switch (Lex.getKind()) {
9856 case lltok::kw_unknown:
9858 break;
9859 case lltok::kw_cold:
9861 break;
9862 case lltok::kw_none:
9864 break;
9865 case lltok::kw_hot:
9867 break;
9868 case lltok::kw_critical:
9870 break;
9871 default:
9872 return error(Lex.getLoc(), "invalid call edge hotness");
9873 }
9874 Lex.Lex();
9875 return false;
9876}
9877
9878/// OptionalVTableFuncs
9879/// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
9880/// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
9881bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
9883 Lex.Lex();
9884
9885 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
9886 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
9887 return true;
9888
9889 IdToIndexMapType IdToIndexMap;
9890 // parse each virtual function pair
9891 do {
9892 ValueInfo VI;
9893 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
9894 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
9895 parseToken(lltok::colon, "expected ':'"))
9896 return true;
9897
9898 LocTy Loc = Lex.getLoc();
9899 unsigned GVId;
9900 if (parseGVReference(VI, GVId))
9901 return true;
9902
9904 if (parseToken(lltok::comma, "expected comma") ||
9905 parseToken(lltok::kw_offset, "expected offset") ||
9906 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
9907 return true;
9908
9909 // Keep track of the VTableFuncs array index needing a forward reference.
9910 // We will save the location of the ValueInfo needing an update, but
9911 // can only do so once the std::vector is finalized.
9912 if (VI == EmptyVI)
9913 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9914 VTableFuncs.push_back({VI, Offset});
9915
9916 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
9917 return true;
9918 } while (EatIfPresent(lltok::comma));
9919
9920 // Now that the VTableFuncs vector is finalized, it is safe to save the
9921 // locations of any forward GV references that need updating later.
9922 for (auto I : IdToIndexMap) {
9923 auto &Infos = ForwardRefValueInfos[I.first];
9924 for (auto P : I.second) {
9925 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
9926 "Forward referenced ValueInfo expected to be empty");
9927 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
9928 }
9929 }
9930
9931 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
9932 return true;
9933
9934 return false;
9935}
9936
9937/// ParamNo := 'param' ':' UInt64
9938bool LLParser::parseParamNo(uint64_t &ParamNo) {
9939 if (parseToken(lltok::kw_param, "expected 'param' here") ||
9940 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
9941 return true;
9942 return false;
9943}
9944
9945/// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
9946bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
9947 APSInt Lower;
9948 APSInt Upper;
9949 auto ParseAPSInt = [&](APSInt &Val) {
9950 if (Lex.getKind() != lltok::APSInt)
9951 return tokError("expected integer");
9952 Val = Lex.getAPSIntVal();
9953 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
9954 Val.setIsSigned(true);
9955 Lex.Lex();
9956 return false;
9957 };
9958 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
9959 parseToken(lltok::colon, "expected ':' here") ||
9960 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
9961 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
9962 parseToken(lltok::rsquare, "expected ']' here"))
9963 return true;
9964
9965 ++Upper;
9966 Range =
9967 (Lower == Upper && !Lower.isMaxValue())
9968 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
9970
9971 return false;
9972}
9973
9974/// ParamAccessCall
9975/// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
9976bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
9977 IdLocListType &IdLocList) {
9978 if (parseToken(lltok::lparen, "expected '(' here") ||
9979 parseToken(lltok::kw_callee, "expected 'callee' here") ||
9980 parseToken(lltok::colon, "expected ':' here"))
9981 return true;
9982
9983 unsigned GVId;
9984 ValueInfo VI;
9985 LocTy Loc = Lex.getLoc();
9986 if (parseGVReference(VI, GVId))
9987 return true;
9988
9989 Call.Callee = VI;
9990 IdLocList.emplace_back(GVId, Loc);
9991
9992 if (parseToken(lltok::comma, "expected ',' here") ||
9993 parseParamNo(Call.ParamNo) ||
9994 parseToken(lltok::comma, "expected ',' here") ||
9995 parseParamAccessOffset(Call.Offsets))
9996 return true;
9997
9998 if (parseToken(lltok::rparen, "expected ')' here"))
9999 return true;
10000
10001 return false;
10002}
10003
10004/// ParamAccess
10005/// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
10006/// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
10007bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
10008 IdLocListType &IdLocList) {
10009 if (parseToken(lltok::lparen, "expected '(' here") ||
10010 parseParamNo(Param.ParamNo) ||
10011 parseToken(lltok::comma, "expected ',' here") ||
10012 parseParamAccessOffset(Param.Use))
10013 return true;
10014
10015 if (EatIfPresent(lltok::comma)) {
10016 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
10017 parseToken(lltok::colon, "expected ':' here") ||
10018 parseToken(lltok::lparen, "expected '(' here"))
10019 return true;
10020 do {
10022 if (parseParamAccessCall(Call, IdLocList))
10023 return true;
10024 Param.Calls.push_back(Call);
10025 } while (EatIfPresent(lltok::comma));
10026
10027 if (parseToken(lltok::rparen, "expected ')' here"))
10028 return true;
10029 }
10030
10031 if (parseToken(lltok::rparen, "expected ')' here"))
10032 return true;
10033
10034 return false;
10035}
10036
10037/// OptionalParamAccesses
10038/// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
10039bool LLParser::parseOptionalParamAccesses(
10040 std::vector<FunctionSummary::ParamAccess> &Params) {
10042 Lex.Lex();
10043
10044 if (parseToken(lltok::colon, "expected ':' here") ||
10045 parseToken(lltok::lparen, "expected '(' here"))
10046 return true;
10047
10048 IdLocListType VContexts;
10049 size_t CallsNum = 0;
10050 do {
10051 FunctionSummary::ParamAccess ParamAccess;
10052 if (parseParamAccess(ParamAccess, VContexts))
10053 return true;
10054 CallsNum += ParamAccess.Calls.size();
10055 assert(VContexts.size() == CallsNum);
10056 (void)CallsNum;
10057 Params.emplace_back(std::move(ParamAccess));
10058 } while (EatIfPresent(lltok::comma));
10059
10060 if (parseToken(lltok::rparen, "expected ')' here"))
10061 return true;
10062
10063 // Now that the Params is finalized, it is safe to save the locations
10064 // of any forward GV references that need updating later.
10065 IdLocListType::const_iterator ItContext = VContexts.begin();
10066 for (auto &PA : Params) {
10067 for (auto &C : PA.Calls) {
10068 if (C.Callee.getRef() == FwdVIRef)
10069 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
10070 ItContext->second);
10071 ++ItContext;
10072 }
10073 }
10074 assert(ItContext == VContexts.end());
10075
10076 return false;
10077}
10078
10079/// OptionalRefs
10080/// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
10081bool LLParser::parseOptionalRefs(SmallVectorImpl<ValueInfo> &Refs) {
10082 assert(Lex.getKind() == lltok::kw_refs);
10083 Lex.Lex();
10084
10085 if (parseToken(lltok::colon, "expected ':' in refs") ||
10086 parseToken(lltok::lparen, "expected '(' in refs"))
10087 return true;
10088
10089 struct ValueContext {
10090 ValueInfo VI;
10091 unsigned GVId;
10092 LocTy Loc;
10093 };
10094 std::vector<ValueContext> VContexts;
10095 // parse each ref edge
10096 do {
10097 ValueContext VC;
10098 VC.Loc = Lex.getLoc();
10099 if (parseGVReference(VC.VI, VC.GVId))
10100 return true;
10101 VContexts.push_back(VC);
10102 } while (EatIfPresent(lltok::comma));
10103
10104 // Sort value contexts so that ones with writeonly
10105 // and readonly ValueInfo are at the end of VContexts vector.
10106 // See FunctionSummary::specialRefCounts()
10107 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
10108 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
10109 });
10110
10111 IdToIndexMapType IdToIndexMap;
10112 for (auto &VC : VContexts) {
10113 // Keep track of the Refs array index needing a forward reference.
10114 // We will save the location of the ValueInfo needing an update, but
10115 // can only do so once the std::vector is finalized.
10116 if (VC.VI.getRef() == FwdVIRef)
10117 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
10118 Refs.push_back(VC.VI);
10119 }
10120
10121 // Now that the Refs vector is finalized, it is safe to save the locations
10122 // of any forward GV references that need updating later.
10123 for (auto I : IdToIndexMap) {
10124 auto &Infos = ForwardRefValueInfos[I.first];
10125 for (auto P : I.second) {
10126 assert(Refs[P.first].getRef() == FwdVIRef &&
10127 "Forward referenced ValueInfo expected to be empty");
10128 Infos.emplace_back(&Refs[P.first], P.second);
10129 }
10130 }
10131
10132 if (parseToken(lltok::rparen, "expected ')' in refs"))
10133 return true;
10134
10135 return false;
10136}
10137
10138/// OptionalTypeIdInfo
10139/// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
10140/// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
10141/// [',' TypeCheckedLoadConstVCalls]? ')'
10142bool LLParser::parseOptionalTypeIdInfo(
10143 FunctionSummary::TypeIdInfo &TypeIdInfo) {
10145 Lex.Lex();
10146
10147 if (parseToken(lltok::colon, "expected ':' here") ||
10148 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10149 return true;
10150
10151 do {
10152 switch (Lex.getKind()) {
10154 if (parseTypeTests(TypeIdInfo.TypeTests))
10155 return true;
10156 break;
10158 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
10159 TypeIdInfo.TypeTestAssumeVCalls))
10160 return true;
10161 break;
10163 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
10164 TypeIdInfo.TypeCheckedLoadVCalls))
10165 return true;
10166 break;
10168 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
10169 TypeIdInfo.TypeTestAssumeConstVCalls))
10170 return true;
10171 break;
10173 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
10174 TypeIdInfo.TypeCheckedLoadConstVCalls))
10175 return true;
10176 break;
10177 default:
10178 return error(Lex.getLoc(), "invalid typeIdInfo list type");
10179 }
10180 } while (EatIfPresent(lltok::comma));
10181
10182 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10183 return true;
10184
10185 return false;
10186}
10187
10188/// TypeTests
10189/// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
10190/// [',' (SummaryID | UInt64)]* ')'
10191bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
10193 Lex.Lex();
10194
10195 if (parseToken(lltok::colon, "expected ':' here") ||
10196 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
10197 return true;
10198
10199 IdToIndexMapType IdToIndexMap;
10200 do {
10202 if (Lex.getKind() == lltok::SummaryID) {
10203 unsigned ID = Lex.getUIntVal();
10204 LocTy Loc = Lex.getLoc();
10205 // Keep track of the TypeTests array index needing a forward reference.
10206 // We will save the location of the GUID needing an update, but
10207 // can only do so once the std::vector is finalized.
10208 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
10209 Lex.Lex();
10210 } else if (parseUInt64(GUID))
10211 return true;
10212 TypeTests.push_back(GUID);
10213 } while (EatIfPresent(lltok::comma));
10214
10215 // Now that the TypeTests vector is finalized, it is safe to save the
10216 // locations of any forward GV references that need updating later.
10217 for (auto I : IdToIndexMap) {
10218 auto &Ids = ForwardRefTypeIds[I.first];
10219 for (auto P : I.second) {
10220 assert(TypeTests[P.first] == 0 &&
10221 "Forward referenced type id GUID expected to be 0");
10222 Ids.emplace_back(&TypeTests[P.first], P.second);
10223 }
10224 }
10225
10226 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
10227 return true;
10228
10229 return false;
10230}
10231
10232/// VFuncIdList
10233/// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
10234bool LLParser::parseVFuncIdList(
10235 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
10236 assert(Lex.getKind() == Kind);
10237 Lex.Lex();
10238
10239 if (parseToken(lltok::colon, "expected ':' here") ||
10240 parseToken(lltok::lparen, "expected '(' here"))
10241 return true;
10242
10243 IdToIndexMapType IdToIndexMap;
10244 do {
10246 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
10247 return true;
10248 VFuncIdList.push_back(VFuncId);
10249 } while (EatIfPresent(lltok::comma));
10250
10251 if (parseToken(lltok::rparen, "expected ')' here"))
10252 return true;
10253
10254 // Now that the VFuncIdList vector is finalized, it is safe to save the
10255 // locations of any forward GV references that need updating later.
10256 for (auto I : IdToIndexMap) {
10257 auto &Ids = ForwardRefTypeIds[I.first];
10258 for (auto P : I.second) {
10259 assert(VFuncIdList[P.first].GUID == 0 &&
10260 "Forward referenced type id GUID expected to be 0");
10261 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
10262 }
10263 }
10264
10265 return false;
10266}
10267
10268/// ConstVCallList
10269/// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
10270bool LLParser::parseConstVCallList(
10271 lltok::Kind Kind,
10272 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
10273 assert(Lex.getKind() == Kind);
10274 Lex.Lex();
10275
10276 if (parseToken(lltok::colon, "expected ':' here") ||
10277 parseToken(lltok::lparen, "expected '(' here"))
10278 return true;
10279
10280 IdToIndexMapType IdToIndexMap;
10281 do {
10282 FunctionSummary::ConstVCall ConstVCall;
10283 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
10284 return true;
10285 ConstVCallList.push_back(ConstVCall);
10286 } while (EatIfPresent(lltok::comma));
10287
10288 if (parseToken(lltok::rparen, "expected ')' here"))
10289 return true;
10290
10291 // Now that the ConstVCallList vector is finalized, it is safe to save the
10292 // locations of any forward GV references that need updating later.
10293 for (auto I : IdToIndexMap) {
10294 auto &Ids = ForwardRefTypeIds[I.first];
10295 for (auto P : I.second) {
10296 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
10297 "Forward referenced type id GUID expected to be 0");
10298 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
10299 }
10300 }
10301
10302 return false;
10303}
10304
10305/// ConstVCall
10306/// ::= '(' VFuncId ',' Args ')'
10307bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
10308 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10309 if (parseToken(lltok::lparen, "expected '(' here") ||
10310 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
10311 return true;
10312
10313 if (EatIfPresent(lltok::comma))
10314 if (parseArgs(ConstVCall.Args))
10315 return true;
10316
10317 if (parseToken(lltok::rparen, "expected ')' here"))
10318 return true;
10319
10320 return false;
10321}
10322
10323/// VFuncId
10324/// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
10325/// 'offset' ':' UInt64 ')'
10326bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
10327 IdToIndexMapType &IdToIndexMap, unsigned Index) {
10329 Lex.Lex();
10330
10331 if (parseToken(lltok::colon, "expected ':' here") ||
10332 parseToken(lltok::lparen, "expected '(' here"))
10333 return true;
10334
10335 if (Lex.getKind() == lltok::SummaryID) {
10336 VFuncId.GUID = 0;
10337 unsigned ID = Lex.getUIntVal();
10338 LocTy Loc = Lex.getLoc();
10339 // Keep track of the array index needing a forward reference.
10340 // We will save the location of the GUID needing an update, but
10341 // can only do so once the caller's std::vector is finalized.
10342 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
10343 Lex.Lex();
10344 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
10345 parseToken(lltok::colon, "expected ':' here") ||
10346 parseUInt64(VFuncId.GUID))
10347 return true;
10348
10349 if (parseToken(lltok::comma, "expected ',' here") ||
10350 parseToken(lltok::kw_offset, "expected 'offset' here") ||
10351 parseToken(lltok::colon, "expected ':' here") ||
10352 parseUInt64(VFuncId.Offset) ||
10353 parseToken(lltok::rparen, "expected ')' here"))
10354 return true;
10355
10356 return false;
10357}
10358
10359/// GVFlags
10360/// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
10361/// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
10362/// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
10363/// 'canAutoHide' ':' Flag ',' ')'
10364bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
10365 assert(Lex.getKind() == lltok::kw_flags);
10366 Lex.Lex();
10367
10368 if (parseToken(lltok::colon, "expected ':' here") ||
10369 parseToken(lltok::lparen, "expected '(' here"))
10370 return true;
10371
10372 do {
10373 unsigned Flag = 0;
10374 switch (Lex.getKind()) {
10375 case lltok::kw_linkage:
10376 Lex.Lex();
10377 if (parseToken(lltok::colon, "expected ':'"))
10378 return true;
10379 bool HasLinkage;
10380 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
10381 assert(HasLinkage && "Linkage not optional in summary entry");
10382 Lex.Lex();
10383 break;
10385 Lex.Lex();
10386 if (parseToken(lltok::colon, "expected ':'"))
10387 return true;
10388 parseOptionalVisibility(Flag);
10389 GVFlags.Visibility = Flag;
10390 break;
10392 Lex.Lex();
10393 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10394 return true;
10395 GVFlags.NotEligibleToImport = Flag;
10396 break;
10397 case lltok::kw_live:
10398 Lex.Lex();
10399 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10400 return true;
10401 GVFlags.Live = Flag;
10402 break;
10403 case lltok::kw_dsoLocal:
10404 Lex.Lex();
10405 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10406 return true;
10407 GVFlags.DSOLocal = Flag;
10408 break;
10410 Lex.Lex();
10411 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
10412 return true;
10413 GVFlags.CanAutoHide = Flag;
10414 break;
10416 Lex.Lex();
10417 if (parseToken(lltok::colon, "expected ':'"))
10418 return true;
10420 if (parseOptionalImportType(Lex.getKind(), IK))
10421 return true;
10422 GVFlags.ImportType = static_cast<unsigned>(IK);
10423 Lex.Lex();
10424 break;
10425 default:
10426 return error(Lex.getLoc(), "expected gv flag type");
10427 }
10428 } while (EatIfPresent(lltok::comma));
10429
10430 if (parseToken(lltok::rparen, "expected ')' here"))
10431 return true;
10432
10433 return false;
10434}
10435
10436/// GVarFlags
10437/// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
10438/// ',' 'writeonly' ':' Flag
10439/// ',' 'constant' ':' Flag ')'
10440bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
10442 Lex.Lex();
10443
10444 if (parseToken(lltok::colon, "expected ':' here") ||
10445 parseToken(lltok::lparen, "expected '(' here"))
10446 return true;
10447
10448 auto ParseRest = [this](unsigned int &Val) {
10449 Lex.Lex();
10450 if (parseToken(lltok::colon, "expected ':'"))
10451 return true;
10452 return parseFlag(Val);
10453 };
10454
10455 do {
10456 unsigned Flag = 0;
10457 switch (Lex.getKind()) {
10458 case lltok::kw_readonly:
10459 if (ParseRest(Flag))
10460 return true;
10461 GVarFlags.MaybeReadOnly = Flag;
10462 break;
10463 case lltok::kw_writeonly:
10464 if (ParseRest(Flag))
10465 return true;
10466 GVarFlags.MaybeWriteOnly = Flag;
10467 break;
10468 case lltok::kw_constant:
10469 if (ParseRest(Flag))
10470 return true;
10471 GVarFlags.Constant = Flag;
10472 break;
10474 if (ParseRest(Flag))
10475 return true;
10476 GVarFlags.VCallVisibility = Flag;
10477 break;
10478 default:
10479 return error(Lex.getLoc(), "expected gvar flag type");
10480 }
10481 } while (EatIfPresent(lltok::comma));
10482 return parseToken(lltok::rparen, "expected ')' here");
10483}
10484
10485/// ModuleReference
10486/// ::= 'module' ':' UInt
10487bool LLParser::parseModuleReference(StringRef &ModulePath) {
10488 // parse module id.
10489 if (parseToken(lltok::kw_module, "expected 'module' here") ||
10490 parseToken(lltok::colon, "expected ':' here") ||
10491 parseToken(lltok::SummaryID, "expected module ID"))
10492 return true;
10493
10494 unsigned ModuleID = Lex.getUIntVal();
10495 auto I = ModuleIdMap.find(ModuleID);
10496 // We should have already parsed all module IDs
10497 assert(I != ModuleIdMap.end());
10498 ModulePath = I->second;
10499 return false;
10500}
10501
10502/// GVReference
10503/// ::= SummaryID
10504bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
10505 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
10506 if (!ReadOnly)
10507 WriteOnly = EatIfPresent(lltok::kw_writeonly);
10508 if (parseToken(lltok::SummaryID, "expected GV ID"))
10509 return true;
10510
10511 GVId = Lex.getUIntVal();
10512 // Check if we already have a VI for this GV
10513 if (GVId < NumberedValueInfos.size() && NumberedValueInfos[GVId]) {
10514 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
10515 VI = NumberedValueInfos[GVId];
10516 } else
10517 // We will create a forward reference to the stored location.
10518 VI = ValueInfo(false, FwdVIRef);
10519
10520 if (ReadOnly)
10521 VI.setReadOnly();
10522 if (WriteOnly)
10523 VI.setWriteOnly();
10524 return false;
10525}
10526
10527/// OptionalAllocs
10528/// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
10529/// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
10530/// ',' MemProfs ')'
10531/// Version ::= UInt32
10532bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
10534 Lex.Lex();
10535
10536 if (parseToken(lltok::colon, "expected ':' in allocs") ||
10537 parseToken(lltok::lparen, "expected '(' in allocs"))
10538 return true;
10539
10540 // parse each alloc
10541 do {
10542 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
10543 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
10544 parseToken(lltok::colon, "expected ':'") ||
10545 parseToken(lltok::lparen, "expected '(' in versions"))
10546 return true;
10547
10548 SmallVector<uint8_t> Versions;
10549 do {
10550 uint8_t V = 0;
10551 if (parseAllocType(V))
10552 return true;
10553 Versions.push_back(V);
10554 } while (EatIfPresent(lltok::comma));
10555
10556 if (parseToken(lltok::rparen, "expected ')' in versions") ||
10557 parseToken(lltok::comma, "expected ',' in alloc"))
10558 return true;
10559
10560 std::vector<MIBInfo> MIBs;
10561 if (parseMemProfs(MIBs))
10562 return true;
10563
10564 Allocs.push_back({Versions, MIBs});
10565
10566 if (parseToken(lltok::rparen, "expected ')' in alloc"))
10567 return true;
10568 } while (EatIfPresent(lltok::comma));
10569
10570 if (parseToken(lltok::rparen, "expected ')' in allocs"))
10571 return true;
10572
10573 return false;
10574}
10575
10576/// MemProfs
10577/// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
10578/// MemProf ::= '(' 'type' ':' AllocType
10579/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10580/// StackId ::= UInt64
10581bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
10583 Lex.Lex();
10584
10585 if (parseToken(lltok::colon, "expected ':' in memprof") ||
10586 parseToken(lltok::lparen, "expected '(' in memprof"))
10587 return true;
10588
10589 // parse each MIB
10590 do {
10591 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
10592 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
10593 parseToken(lltok::colon, "expected ':'"))
10594 return true;
10595
10597 if (parseAllocType(AllocType))
10598 return true;
10599
10600 if (parseToken(lltok::comma, "expected ',' in memprof") ||
10601 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
10602 parseToken(lltok::colon, "expected ':'") ||
10603 parseToken(lltok::lparen, "expected '(' in stackIds"))
10604 return true;
10605
10606 SmallVector<unsigned> StackIdIndices;
10607 do {
10608 uint64_t StackId = 0;
10609 if (parseUInt64(StackId))
10610 return true;
10611 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10612 } while (EatIfPresent(lltok::comma));
10613
10614 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10615 return true;
10616
10617 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
10618
10619 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10620 return true;
10621 } while (EatIfPresent(lltok::comma));
10622
10623 if (parseToken(lltok::rparen, "expected ')' in memprof"))
10624 return true;
10625
10626 return false;
10627}
10628
10629/// AllocType
10630/// := ('none'|'notcold'|'cold'|'hot')
10631bool LLParser::parseAllocType(uint8_t &AllocType) {
10632 switch (Lex.getKind()) {
10633 case lltok::kw_none:
10635 break;
10636 case lltok::kw_notcold:
10638 break;
10639 case lltok::kw_cold:
10641 break;
10642 case lltok::kw_hot:
10644 break;
10645 default:
10646 return error(Lex.getLoc(), "invalid alloc type");
10647 }
10648 Lex.Lex();
10649 return false;
10650}
10651
10652/// OptionalCallsites
10653/// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
10654/// Callsite ::= '(' 'callee' ':' GVReference
10655/// ',' 'clones' ':' '(' Version [',' Version]* ')'
10656/// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10657/// Version ::= UInt32
10658/// StackId ::= UInt64
10659bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
10661 Lex.Lex();
10662
10663 if (parseToken(lltok::colon, "expected ':' in callsites") ||
10664 parseToken(lltok::lparen, "expected '(' in callsites"))
10665 return true;
10666
10667 IdToIndexMapType IdToIndexMap;
10668 // parse each callsite
10669 do {
10670 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
10671 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
10672 parseToken(lltok::colon, "expected ':'"))
10673 return true;
10674
10675 ValueInfo VI;
10676 unsigned GVId = 0;
10677 LocTy Loc = Lex.getLoc();
10678 if (!EatIfPresent(lltok::kw_null)) {
10679 if (parseGVReference(VI, GVId))
10680 return true;
10681 }
10682
10683 if (parseToken(lltok::comma, "expected ',' in callsite") ||
10684 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
10685 parseToken(lltok::colon, "expected ':'") ||
10686 parseToken(lltok::lparen, "expected '(' in clones"))
10687 return true;
10688
10689 SmallVector<unsigned> Clones;
10690 do {
10691 unsigned V = 0;
10692 if (parseUInt32(V))
10693 return true;
10694 Clones.push_back(V);
10695 } while (EatIfPresent(lltok::comma));
10696
10697 if (parseToken(lltok::rparen, "expected ')' in clones") ||
10698 parseToken(lltok::comma, "expected ',' in callsite") ||
10699 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
10700 parseToken(lltok::colon, "expected ':'") ||
10701 parseToken(lltok::lparen, "expected '(' in stackIds"))
10702 return true;
10703
10704 SmallVector<unsigned> StackIdIndices;
10705 do {
10706 uint64_t StackId = 0;
10707 if (parseUInt64(StackId))
10708 return true;
10709 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
10710 } while (EatIfPresent(lltok::comma));
10711
10712 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
10713 return true;
10714
10715 // Keep track of the Callsites array index needing a forward reference.
10716 // We will save the location of the ValueInfo needing an update, but
10717 // can only do so once the SmallVector is finalized.
10718 if (VI.getRef() == FwdVIRef)
10719 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
10720 Callsites.push_back({VI, Clones, StackIdIndices});
10721
10722 if (parseToken(lltok::rparen, "expected ')' in callsite"))
10723 return true;
10724 } while (EatIfPresent(lltok::comma));
10725
10726 // Now that the Callsites vector is finalized, it is safe to save the
10727 // locations of any forward GV references that need updating later.
10728 for (auto I : IdToIndexMap) {
10729 auto &Infos = ForwardRefValueInfos[I.first];
10730 for (auto P : I.second) {
10731 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
10732 "Forward referenced ValueInfo expected to be empty");
10733 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
10734 }
10735 }
10736
10737 if (parseToken(lltok::rparen, "expected ')' in callsites"))
10738 return true;
10739
10740 return false;
10741}
static int64_t upperBound(StackOffset Size)
Unify divergent function exit nodes
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
Expand Atomic instructions
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil globals
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Given that RA is a live value
This file defines the DenseMap class.
@ Default
Definition: DwarfDebug.cpp:87
This file contains constants used for implementing Dwarf debug support.
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
DenseMap< Block *, BlockRelaxAux > Blocks
Definition: ELF_riscv.cpp:507
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Hexagon Common GEP
#define _
Module.h This file contains the declarations for the Module class.
static GlobalValue * createGlobalFwdRef(Module *M, PointerType *PTy)
Definition: LLParser.cpp:1753
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)
Definition: LLParser.cpp:1146
cl::opt< cl::boolOrDefault > PreserveInputDbgFormat
static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind)
Definition: LLParser.cpp:1656
static std::optional< MemoryEffects::Location > keywordToLoc(lltok::Kind Tok)
Definition: LLParser.cpp:2487
static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved)
Definition: LLParser.cpp:9277
cl::opt< bool > WriteNewDbgInfoFormat
static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage)
Definition: LLParser.cpp:2022
bool WriteNewDbgInfoFormatToBitcode
Definition: BasicBlock.cpp:47
static unsigned keywordToFPClassTest(lltok::Kind Tok)
Definition: LLParser.cpp:2568
llvm::cl::opt< bool > UseNewDbgInfoFormat
static std::optional< ModRefInfo > keywordToModRef(lltok::Kind Tok)
Definition: LLParser.cpp:2498
static bool isSanitizer(lltok::Kind Kind)
Definition: LLParser.cpp:1304
static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst *II)
Definition: LLParser.cpp:155
#define PARSE_MD_FIELDS()
Definition: LLParser.cpp:5220
static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind)
Definition: LLParser.cpp:1536
static ValueInfo EmptyVI
Definition: LLParser.cpp:8918
#define GET_OR_DISTINCT(CLASS, ARGS)
Definition: LLParser.cpp:5234
bool isOldDbgFormatIntrinsic(StringRef Name)
Definition: LLParser.cpp:6370
static bool isValidVisibilityForLinkage(unsigned V, unsigned L)
Definition: LLParser.cpp:1135
static std::string getTypeString(Type *T)
Definition: LLParser.cpp:71
static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L)
Definition: LLParser.cpp:1139
static const auto FwdVIRef
Definition: LLParser.cpp:9275
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
AllocType
This file contains the declarations for metadata subclasses.
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
llvm::cl::opt< bool > UseNewDbgInfoFormat
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val)
const SmallVectorImpl< MachineOperand > & Cond
dot regions Print regions of function to dot file(with no function bodies)"
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const char * name
Definition: SMEABIPass.cpp:46
This file contains some templates that are useful if you are working with the STL at all.
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.
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
Value * RHS
Value * LHS
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition: APFloat.h:1130
Class for arbitrary precision integers.
Definition: APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1520
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1468
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition: APInt.h:475
bool getBoolValue() const
Convert APInt to a boolean value.
Definition: APInt.h:471
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition: APInt.h:1237
An arbitrary precision integer that knows its signedness.
Definition: APSInt.h:23
APSInt extOrTrunc(uint32_t width) const
Definition: APSInt.h:119
APSInt extend(uint32_t width) const
Definition: APSInt.h:112
bool isSigned() const
Definition: APSInt.h:77
an instruction to allocate memory on the stack
Definition: Instructions.h:63
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
Definition: Instructions.h:151
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
Definition: Instructions.h:144
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
iterator begin() const
Definition: ArrayRef.h:156
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:758
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:501
void setWeak(bool IsWeak)
Definition: Instructions.h:564
static bool isValidFailureOrdering(AtomicOrdering Ordering)
Definition: Instructions.h:574
void setVolatile(bool V)
Specify whether this is a volatile cmpxchg.
Definition: Instructions.h:559
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
Definition: Instructions.h:569
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:704
void setVolatile(bool V)
Specify whether this is a volatile RMW or not.
Definition: Instructions.h:841
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Definition: Instructions.h:716
@ Add
*p = old + v
Definition: Instructions.h:720
@ FAdd
*p = old + v
Definition: Instructions.h:741
@ USubCond
Subtract only if no unsigned overflow.
Definition: Instructions.h:764
@ Min
*p = old <signed v ? old : v
Definition: Instructions.h:734
@ Or
*p = old | v
Definition: Instructions.h:728
@ Sub
*p = old - v
Definition: Instructions.h:722
@ And
*p = old & v
Definition: Instructions.h:724
@ Xor
*p = old ^ v
Definition: Instructions.h:730
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
Definition: Instructions.h:768
@ FSub
*p = old - v
Definition: Instructions.h:744
@ UIncWrap
Increment one up to a maximum value.
Definition: Instructions.h:756
@ Max
*p = old >signed v ? old : v
Definition: Instructions.h:732
@ UMin
*p = old <unsigned v ? old : v
Definition: Instructions.h:738
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
Definition: Instructions.h:752
@ UMax
*p = old >unsigned v ? old : v
Definition: Instructions.h:736
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
Definition: Instructions.h:748
@ UDecWrap
Decrement one until a minimum value or zero.
Definition: Instructions.h:760
@ Nand
*p = ~(old & v)
Definition: Instructions.h:726
static StringRef getOperationName(BinOp Op)
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
AttributeList removeAttribute(LLVMContext &C, unsigned Index, StringRef Kind) const
Definition: Attributes.h:664
AttributeList addFnAttributes(LLVMContext &C, const AttrBuilder &B) const
Add function attribute to the list.
Definition: Attributes.h:599
bool hasParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Return true if the attribute exists for the given argument.
Definition: Attributes.h:833
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
AttributeList removeFnAttributes(LLVMContext &C, const AttributeMask &AttrsToRemove) const
Remove the specified attribute at the function index from this attribute list.
Definition: Attributes.h:697
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
Definition: Attributes.cpp:910
static bool canUseAsRetAttr(AttrKind Kind)
Definition: Attributes.cpp:782
static bool isTypeAttrKind(AttrKind Kind)
Definition: Attributes.h:105
static bool canUseAsFnAttr(AttrKind Kind)
Definition: Attributes.cpp:774
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:86
@ None
No attributes have been set.
Definition: Attributes.h:88
static bool canUseAsParamAttr(AttrKind Kind)
Definition: Attributes.cpp:778
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator end()
Definition: BasicBlock.h:461
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:212
static 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 BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1897
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
void setCallingConv(CallingConv::ID CC)
Definition: InstrTypes.h:1403
void setAttributes(AttributeList A)
Set the attributes for this call.
Definition: InstrTypes.h:1420
CallBr instruction, tracking function calls that may not return control but instead transfer it to a ...
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Represents which components of the pointer may be captured in which location.
Definition: ModRef.h:318
static 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 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:673
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:676
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition: InstrTypes.h:690
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:702
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:703
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:679
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition: InstrTypes.h:688
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:677
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:678
@ ICMP_UGE
unsigned greater or equal
Definition: InstrTypes.h:697
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:696
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:700
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:687
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition: InstrTypes.h:681
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition: InstrTypes.h:684
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:698
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:685
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:680
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition: InstrTypes.h:682
@ ICMP_EQ
equal
Definition: InstrTypes.h:694
@ ICMP_NE
not equal
Definition: InstrTypes.h:695
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:701
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:689
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:699
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition: InstrTypes.h:686
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition: InstrTypes.h:675
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition: InstrTypes.h:683
@ Largest
The linker will choose the largest COMDAT.
Definition: Comdat.h:38
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:40
@ Any
The linker may choose any COMDAT.
Definition: Comdat.h:36
@ NoDeduplicate
No deduplication is performed.
Definition: Comdat.h:39
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:37
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1312
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:528
static Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
Definition: Constants.cpp:2990
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2554
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:2222
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2576
static Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2599
static 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.
Definition: Constants.cpp:2340
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:1267
static bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
Definition: Constants.cpp:1611
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:866
static ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
Definition: Constants.h:126
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:873
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition: Constants.h:151
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1826
static ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
Definition: Constants.cpp:2072
static std::optional< ConstantRangeList > getConstantRangeList(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
Definition: ConstantRange.h:47
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
Definition: ConstantRange.h:84
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1378
static Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
Definition: Constants.cpp:1472
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1421
This is an important base class in LLVM.
Definition: Constant.h:42
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:373
static DIArgList * get(LLVMContext &Context, ArrayRef< ValueAsMetadata * > Args)
static DIAssignID * getDistinct(LLVMContext &Context)
Basic type, like 'int' or 'float'.
Debug common block.
DebugEmissionKind getEmissionKind() const
DebugNameTableKind getNameTableKind() const
static DICompositeType * buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name, Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, Metadata *Specification, uint32_t NumExtraInhabitants, DIFlags Flags, Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator, Metadata *DataLocation, Metadata *Associated, Metadata *Allocated, Metadata *Rank, Metadata *Annotations)
Build a DICompositeType with the given ODR identifier.
Enumeration value.
DWARF expression.
static std::optional< ChecksumKind > getChecksumKind(StringRef CSKindStr)
ChecksumKind
Which algorithm (e.g.
A pair of DIGlobalVariable and DIExpression.
An imported module (C++ using directive or similar).
Debug lexical block.
Debug location.
Represents a module in the programming language, for example, a Clang module, or a Fortran module.
Debug lexical block.
Tagged DWARF-like metadata node.
static DIFlags getFlag(StringRef Flag)
DIFlags
Debug info flags.
String type, Fortran CHARACTER(n)
Subprogram description.
static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized, unsigned Virtuality=SPFlagNonvirtual, bool IsMainSubprogram=false)
static DISPFlags getFlag(StringRef Flag)
DISPFlags
Debug info subprogram flags.
Array subrange.
Type array for a subprogram.
static DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
Definition: Constants.cpp:1970
This class represents an Operation in the Expression.
static Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
Definition: DataLayout.cpp:264
static DbgLabelRecord * createUnresolvedDbgLabelRecord(MDNode *Label, MDNode *DL)
For use during parsing; creates a DbgLabelRecord from as-of-yet unresolved MDNodes.
Base class for non-instruction debug metadata records that have positions within IR.
Kind
Subclass discriminator.
static 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...
A debug info location.
Definition: DebugLoc.h:33
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:194
unsigned size() const
Definition: DenseMap.h:99
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition: TypeSize.h:311
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
reference get()
Returns a reference to the stored T value.
Definition: Error.h:578
Class representing an expression and its matching format.
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static bool isValidOperands(const Value *Vec, const Value *Idx)
Return true if an extractelement instruction can be formed with the specified operands.
static 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)
This instruction compares its operands according to the predicate given to the constructor.
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
bool any() const
Definition: FMF.h:57
An instruction for ordering other memory operations.
Definition: Instructions.h:424
This class represents a freeze function that returns random concrete value if an operand is either a ...
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
Type::subtype_iterator param_iterator
Definition: DerivedTypes.h:128
static bool isValidReturnType(Type *RetTy)
Return true if the specified type is valid as a return type.
Definition: Type.cpp:391
static 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:173
void setPrefixData(Constant *PrefixData)
Definition: Function.cpp:1063
void setGC(std::string Str)
Definition: Function.cpp:840
void setPersonalityFn(Constant *Fn)
Definition: Function.cpp:1053
arg_iterator arg_begin()
Definition: Function.h:868
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition: Function.h:356
void setPrologueData(Constant *PrologueData)
Definition: Function.cpp:1073
void setCallingConv(CallingConv::ID CC)
Definition: Function.h:281
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
Generic tagged DWARF-like metadata node.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:933
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Definition: Instructions.h:956
static 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:97
static 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:557
static 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:614
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:143
void setComdat(Comdat *C)
Definition: Globals.cpp:212
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:273
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1565
const SanitizerMetadata & getSanitizerMetadata() const
Definition: Globals.cpp:243
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:409
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:231
void setDLLStorageClass(DLLStorageClassTypes C)
Definition: GlobalValue.h:284
void setThreadLocalMode(ThreadLocalMode Val)
Definition: GlobalValue.h:267
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:537
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition: GlobalValue.h:73
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition: GlobalValue.h:76
@ DLLImportStorageClass
Function to be imported from DLL.
Definition: GlobalValue.h:75
bool hasSanitizerMetadata() const
Definition: GlobalValue.h:355
unsigned getAddressSpace() const
Definition: GlobalValue.h:205
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:595
void setDSOLocal(bool Local)
Definition: GlobalValue.h:303
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:91
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:294
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:66
@ DefaultVisibility
The GV is visible.
Definition: GlobalValue.h:67
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
@ ProtectedVisibility
The GV is protected.
Definition: GlobalValue.h:69
static bool isValidDeclarationLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:418
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:254
void setSanitizerMetadata(SanitizerMetadata Meta)
Definition: Globals.cpp:249
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e....
Definition: Globals.cpp:184
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ CommonLinkage
Tentative definitions.
Definition: GlobalValue.h:62
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:54
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:57
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:56
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:58
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:53
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:55
Type * getValueType() const
Definition: GlobalValue.h:296
void setPartition(StringRef Part)
Definition: Globals.cpp:226
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:492
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setConstant(bool Val)
void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
Definition: Globals.cpp:534
void setExternallyInitialized(bool Val)
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
static 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 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...
Definition: InlineAsm.cpp:273
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static 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)
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
bool isTerminator() const
Definition: Instruction.h:277
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1679
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.
Definition: IntrinsicInst.h:48
Invoke instruction.
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:65
unsigned getUIntVal() const
Definition: LLLexer.h:74
lltok::Kind getKind() const
Definition: LLLexer.h:71
const std::string & getStrVal() const
Definition: LLLexer.h:72
Type * getTyVal() const
Definition: LLLexer.h:73
LocTy getLoc() const
Definition: LLLexer.h:70
const APSInt & getAPSIntVal() const
Definition: LLLexer.h:75
void setIgnoreColonInIdentifiers(bool val)
Definition: LLLexer.h:78
const APFloat & getAPFloatVal() const
Definition: LLLexer.h:76
bool parseDIExpressionBodyAtBeginning(MDNode *&Result, unsigned &Read, const SlotMapping *Slots)
Definition: LLParser.cpp:127
LLLexer::LocTy LocTy
Definition: LLParser.h:109
LLVMContext & getContext()
Definition: LLParser.h:210
bool parseTypeAtBeginning(Type *&Ty, unsigned &Read, const SlotMapping *Slots)
Definition: LLParser.cpp:111
bool parseStandaloneConstantValue(Constant *&C, const SlotMapping *Slots)
Definition: LLParser.cpp:98
bool Run(bool UpgradeDebugInfo, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Run: module ::= toplevelentity*.
Definition: LLParser.cpp:79
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
static 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...
An instruction for reading from memory.
Definition: Instructions.h:176
Metadata node.
Definition: Metadata.h:1069
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1553
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1545
A single uniqued string.
Definition: Metadata.h:720
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:606
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition: Metadata.h:1513
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1502
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition: Metadata.h:1522
static MemoryEffectsBase readOnly()
Create MemoryEffectsBase that can read any memory.
Definition: ModRef.h:122
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
Definition: ModRef.h:170
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access argument memory.
Definition: ModRef.h:132
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible memory.
Definition: ModRef.h:138
static MemoryEffectsBase writeOnly()
Create MemoryEffectsBase that can write any memory.
Definition: ModRef.h:127
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible or argument memory.
Definition: ModRef.h:145
static MemoryEffectsBase none()
Create MemoryEffectsBase that cannot read or write any memory.
Definition: ModRef.h:117
static MemoryEffectsBase unknown()
Create MemoryEffectsBase that can read and write any memory.
Definition: ModRef.h:112
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:176
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:103
Root of the metadata hierarchy.
Definition: Metadata.h:62
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A tuple of MDNodes.
Definition: Metadata.h:1733
void addOperand(MDNode *M)
Definition: Metadata.cpp:1431
static NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
Definition: Constants.cpp:2028
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:863
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:686
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1878
Resume the propagation of an exception.
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:23
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, Instruction *MDFrom=nullptr)
static 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.
This instruction constructs a fixed permutation of two input vectors.
ArrayRef< int > getShuffleMask() const
static 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.
Definition: SmallPtrSet.h:384
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:937
void reserve(size_type N)
Definition: SmallVector.h:663
void push_back(const T &Elt)
Definition: SmallVector.h:413
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:286
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
An instruction for storing to memory.
Definition: Instructions.h:292
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
iterator end()
Definition: StringMap.h:220
iterator find(StringRef Key)
Definition: StringMap.h:233
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
Class to represent struct types.
Definition: DerivedTypes.h:218
static 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:406
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:612
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Definition: Type.cpp:696
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:531
bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Returns true if this struct contains a scalable vector.
Definition: Type.cpp:433
Multiway switch.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
@ HasZeroInit
zeroinitializer is valid for this target extension type.
Definition: DerivedTypes.h:806
static 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:901
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:270
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:261
bool isLabelTy() const
Return true if this is 'label'.
Definition: Type.h:228
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:243
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:264
static IntegerType * getInt1Ty(LLVMContext &C)
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:153
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition: Type.h:145
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
TypeID
Definitions of all of the base types for the Type system.
Definition: Type.h:54
static Type * getLabelTy(LLVMContext &C)
bool isFirstClassType() const
Return true if the type is "first class", meaning it is a valid type for a Value.
Definition: Type.h:289
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:310
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition: Type.h:303
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:142
bool isScalableTy(SmallPtrSetImpl< const Type * > &Visited) const
Return true if this is a type whose size is a known multiple of vscale.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
static IntegerType * getInt8Ty(LLVMContext &C)
static Type * getTokenTy(LLVMContext &C)
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:184
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:267
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:255
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:237
bool isTokenTy() const
Return true if this is 'token'.
Definition: Type.h:234
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:225
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVoidTy() const
Return true if this is 'void'.
Definition: Type.h:139
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:355
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition: Type.h:231
static UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1859
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:501
LLVM Value Representation.
Definition: Value.h:74
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:811
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
void deleteValue()
Delete a pointer to a generic Value.
Definition: Value.cpp:110
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition: ilist_node.h:132
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
std::string & str()
Returns the string's reference.
Definition: raw_ostream.h:679
unsigned getOperationEncoding(StringRef OperationEncodingString)
Definition: Dwarf.cpp:165
unsigned getAttributeEncoding(StringRef EncodingString)
Definition: Dwarf.cpp:274
unsigned getTag(StringRef TagString)
Definition: Dwarf.cpp:32
unsigned getCallingConvention(StringRef LanguageString)
Definition: Dwarf.cpp:481
unsigned getLanguage(StringRef LanguageString)
Definition: Dwarf.cpp:404
unsigned getVirtuality(StringRef VirtualityString)
Definition: Dwarf.cpp:385
unsigned getMacinfo(StringRef MacinfoString)
Definition: Dwarf.cpp:553
#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 TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Key
PAL metadata keys.
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.
Definition: BitmaskEnum.h:125
@ Entry
Definition: COFF.h:844
@ AArch64_VectorCall
Used between AArch64 Advanced SIMD functions.
Definition: CallingConv.h:221
@ X86_64_SysV
The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows ...
Definition: CallingConv.h:151
@ RISCV_VectorCall
Calling convention used for RISC-V V-extension.
Definition: CallingConv.h:268
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
Definition: CallingConv.h:197
@ AMDGPU_VS
Used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tess...
Definition: CallingConv.h:188
@ AVR_SIGNAL
Used for AVR signal routines.
Definition: CallingConv.h:179
@ Swift
Calling convention for Swift.
Definition: CallingConv.h:69
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
Definition: CallingConv.h:200
@ AArch64_SVE_VectorCall
Used between AArch64 SVE functions.
Definition: CallingConv.h:224
@ ARM_APCS
ARM Procedure Calling Standard (obsolete, but still used on some targets).
Definition: CallingConv.h:107
@ 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.
Definition: CallingConv.h:176
@ 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.
Definition: CallingConv.h:232
@ DUMMY_HHVM
Placeholders for HHVM calling conventions (deprecated, removed).
Definition: CallingConv.h:166
@ AMDGPU_CS_ChainPreserve
Used on AMDGPUs to give the middle-end more control over argument placement.
Definition: CallingConv.h:249
@ AMDGPU_HS
Used for Mesa/AMDPAL hull shaders (= tessellation control shaders).
Definition: CallingConv.h:206
@ ARM_AAPCS
ARM Architecture Procedure Calling Standard calling convention (aka EABI).
Definition: CallingConv.h:111
@ AMDGPU_GS
Used for Mesa/AMDPAL geometry shaders.
Definition: CallingConv.h:191
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
Preserve X2-X15, X19-X29, SP, Z0-Z31, P0-P15.
Definition: CallingConv.h:241
@ CXX_FAST_TLS
Used for access functions.
Definition: CallingConv.h:72
@ X86_INTR
x86 hardware interrupt context.
Definition: CallingConv.h:173
@ AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
Preserve X0-X13, X19-X29, SP, Z0-Z31, P0-P15.
Definition: CallingConv.h:238
@ AMDGPU_CS_Chain
Used on AMDGPUs to give the middle-end more control over argument placement.
Definition: CallingConv.h:245
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition: CallingConv.h:50
@ AMDGPU_PS
Used for Mesa/AMDPAL pixel shaders.
Definition: CallingConv.h:194
@ 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.
Definition: CallingConv.h:271
@ X86_ThisCall
Similar to X86_StdCall.
Definition: CallingConv.h:122
@ PTX_Device
Call to a PTX device function.
Definition: CallingConv.h:129
@ SPIR_KERNEL
Used for SPIR kernel functions.
Definition: CallingConv.h:144
@ 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.
Definition: CallingConv.h:138
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:41
@ MSP430_INTR
Used for MSP430 interrupt routines.
Definition: CallingConv.h:117
@ X86_VectorCall
MSVC calling convention that passes vectors and vector aggregates in SSE registers.
Definition: CallingConv.h:163
@ Intel_OCL_BI
Used for Intel OpenCL built-ins.
Definition: CallingConv.h:147
@ 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.
Definition: CallingConv.h:218
@ 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.
Definition: CallingConv.h:159
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
Definition: CallingConv.h:125
@ 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.
Definition: CallingConv.h:255
@ AMDGPU_LS
Used for AMDPAL vertex shader if tessellation is in use.
Definition: CallingConv.h:213
@ ARM_AAPCS_VFP
Same as ARM_AAPCS, but uses hard floating point ABI.
Definition: CallingConv.h:114
@ X86_RegCall
Register calling convention used for parameters transfer optimization.
Definition: CallingConv.h:203
@ M68k_RTD
Used for M68k rtd-based CC (similar to X86's stdcall).
Definition: CallingConv.h:252
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ X86_FastCall
'fast' analog of X86_StdCall.
Definition: CallingConv.h:103
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
Definition: Intrinsics.cpp:731
ID lookupIntrinsicID(StringRef Name)
This does the actual lookup of an intrinsic ID which matches the given function name.
Definition: Intrinsics.cpp:706
bool getIntrinsicSignature(Intrinsic::ID, FunctionType *FT, SmallVectorImpl< Type * > &ArgTys)
Gets the type arguments of an intrinsic call by matching type contraints specified by the ....
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:148
@ System
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:57
@ FS
Definition: X86.h:211
@ GS
Definition: X86.h:210
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
@ DW_CC_hi_user
Definition: Dwarf.h:750
@ DW_ATE_hi_user
Definition: Dwarf.h:161
@ DW_LANG_hi_user
Definition: Dwarf.h:212
MacinfoRecordType
Definition: Dwarf.h:794
@ DW_MACINFO_vendor_ext
Definition: Dwarf.h:800
@ DW_VIRTUALITY_max
Definition: Dwarf.h:198
@ DW_TAG_hi_user
Definition: Dwarf.h:107
@ DW_TAG_invalid
LLVM mock tags (see also llvm/BinaryFormat/Dwarf.def).
Definition: Dwarf.h:47
@ DW_MACINFO_invalid
Macinfo type for invalid results.
Definition: Dwarf.h:49
@ DW_VIRTUALITY_invalid
Virtuality for invalid results.
Definition: Dwarf.h:48
@ kw_samesize
Definition: LLToken.h:244
@ kw_msp430_intrcc
Definition: LLToken.h:153
@ kw_acquire
Definition: LLToken.h:97
@ kw_cxx_fast_tlscc
Definition: LLToken.h:172
@ kw_extractvalue
Definition: LLToken.h:354
@ kw_dso_preemptable
Definition: LLToken.h:51
@ DwarfVirtuality
Definition: LLToken.h:489
@ kw_arm_apcscc
Definition: LLToken.h:145
@ kw_inteldialect
Definition: LLToken.h:128
@ kw_x86_stdcallcc
Definition: LLToken.h:140
@ kw_constant
Definition: LLToken.h:48
@ kw_graalcc
Definition: LLToken.h:186
@ kw_initialexec
Definition: LLToken.h:74
@ kw_aarch64_sme_preservemost_from_x1
Definition: LLToken.h:151
@ kw_provenance
Definition: LLToken.h:213
@ kw_mustBeUnreachable
Definition: LLToken.h:400
@ kw_internal
Definition: LLToken.h:54
@ kw_hhvm_ccc
Definition: LLToken.h:171
@ kw_ptrtoint
Definition: LLToken.h:316
@ kw_anyregcc
Definition: LLToken.h:162
@ kw_no_sanitize_hwaddress
Definition: LLToken.h:468
@ kw_win64cc
Definition: LLToken.h:161
@ kw_datalayout
Definition: LLToken.h:92
@ kw_wpdResolutions
Definition: LLToken.h:439
@ kw_cleanup
Definition: LLToken.h:324
@ kw_ptrauth
Definition: LLToken.h:359
@ kw_canAutoHide
Definition: LLToken.h:384
@ kw_alwaysInline
Definition: LLToken.h:396
@ kw_notail
Definition: LLToken.h:87
@ kw_insertelement
Definition: LLToken.h:351
@ kw_linkonce
Definition: LLToken.h:55
@ kw_fptrunc
Definition: LLToken.h:309
@ kw_inaccessiblememonly
Definition: LLToken.h:207
@ kw_amdgpu_gfx
Definition: LLToken.h:183
@ kw_getelementptr
Definition: LLToken.h:348
@ kw_m68k_rtdcc
Definition: LLToken.h:185
@ kw_preserve_nonecc
Definition: LLToken.h:167
@ kw_x86_fastcallcc
Definition: LLToken.h:141
@ kw_readOnly
Definition: LLToken.h:392
@ kw_varFlags
Definition: LLToken.h:453
@ kw_partition
Definition: LLToken.h:121
@ kw_visibility
Definition: LLToken.h:380
@ kw_vFuncId
Definition: LLToken.h:420
@ kw_address
Definition: LLToken.h:211
@ kw_noUnwind
Definition: LLToken.h:397
@ kw_disjoint
Definition: LLToken.h:114
@ kw_bitMask
Definition: LLToken.h:436
@ kw_unordered
Definition: LLToken.h:95
@ kw_singleImpl
Definition: LLToken.h:442
@ kw_swiftcc
Definition: LLToken.h:163
@ kw_localexec
Definition: LLToken.h:75
@ kw_cfguard_checkcc
Definition: LLToken.h:139
@ kw_stackIds
Definition: LLToken.h:457
@ kw_typeCheckedLoadConstVCalls
Definition: LLToken.h:419
@ kw_private
Definition: LLToken.h:53
@ kw_aarch64_sve_vector_pcs
Definition: LLToken.h:149
@ kw_amdgpu_kernel
Definition: LLToken.h:182
@ kw_acq_rel
Definition: LLToken.h:99
@ kw_uselistorder
Definition: LLToken.h:367
@ MetadataVar
Definition: LLToken.h:485
@ kw_blockcount
Definition: LLToken.h:378
@ kw_notEligibleToImport
Definition: LLToken.h:381
@ kw_noRecurse
Definition: LLToken.h:393
@ kw_dsoLocal
Definition: LLToken.h:383
@ kw_linkonce_odr
Definition: LLToken.h:56
@ kw_protected
Definition: LLToken.h:66
@ kw_samesign
Definition: LLToken.h:117
@ kw_variable
Definition: LLToken.h:409
@ kw_dllexport
Definition: LLToken.h:61
@ kw_hotness
Definition: LLToken.h:405
@ kw_x86_vectorcallcc
Definition: LLToken.h:143
@ kw_ptx_device
Definition: LLToken.h:157
@ kw_personality
Definition: LLToken.h:323
@ kw_catchpad
Definition: LLToken.h:338
@ kw_spir_func
Definition: LLToken.h:159
@ kw_inbounds
Definition: LLToken.h:115
@ kw_atomic
Definition: LLToken.h:94
@ kw_readNone
Definition: LLToken.h:391
@ kw_declaration
Definition: LLToken.h:387
@ kw_define
Definition: LLToken.h:46
@ DwarfAttEncoding
Definition: LLToken.h:488
@ kw_critical
Definition: LLToken.h:407
@ kw_external
Definition: LLToken.h:71
@ kw_largest
Definition: LLToken.h:242
@ kw_amdgpu_hs
Definition: LLToken.h:175
@ kw_spir_kernel
Definition: LLToken.h:158
@ kw_local_unnamed_addr
Definition: LLToken.h:68
@ kw_amdgpu_es
Definition: LLToken.h:176
@ kw_hasUnknownCall
Definition: LLToken.h:399
@ LocalVarID
Definition: LLToken.h:476
@ kw_seq_cst
Definition: LLToken.h:100
@ kw_unwind
Definition: LLToken.h:91
@ kw_distinct
Definition: LLToken.h:364
@ kw_linkage
Definition: LLToken.h:379
@ kw_amdgpu_gs
Definition: LLToken.h:177
@ kw_x86_intrcc
Definition: LLToken.h:169
@ kw_addrspacecast
Definition: LLToken.h:318
@ kw_callsites
Definition: LLToken.h:455
@ kw_zeroinitializer
Definition: LLToken.h:76
@ StringConstant
Definition: LLToken.h:486
@ kw_x86_thiscallcc
Definition: LLToken.h:142
@ kw_false
Definition: LLToken.h:44
@ kw_unnamed_addr
Definition: LLToken.h:67
@ kw_uselistorder_bb
Definition: LLToken.h:368
@ NameTableKind
Definition: LLToken.h:493
@ kw_amdgpu_vs
Definition: LLToken.h:173
@ kw_inlineBits
Definition: LLToken.h:437
@ kw_weak_odr
Definition: LLToken.h:58
@ kw_udec_wrap
Definition: LLToken.h:277
@ kw_resByArg
Definition: LLToken.h:445
@ kw_inttoptr
Definition: LLToken.h:315
@ kw_dllimport
Definition: LLToken.h:60
@ kw_argmemonly
Definition: LLToken.h:206
@ kw_blockaddress
Definition: LLToken.h:356
@ kw_landingpad
Definition: LLToken.h:322
@ kw_aarch64_vector_pcs
Definition: LLToken.h:148
@ kw_amdgpu_cs
Definition: LLToken.h:179
@ kw_syncscope
Definition: LLToken.h:101
@ kw_noInline
Definition: LLToken.h:395
@ kw_source_filename
Definition: LLToken.h:90
@ kw_typeTestAssumeConstVCalls
Definition: LLToken.h:418
@ kw_inrange
Definition: LLToken.h:118
@ kw_ptx_kernel
Definition: LLToken.h:156
@ kw_summaries
Definition: LLToken.h:376
@ kw_extractelement
Definition: LLToken.h:350
@ kw_branchFunnel
Definition: LLToken.h:443
@ kw_typeidCompatibleVTable
Definition: LLToken.h:424
@ kw_bitcast
Definition: LLToken.h:317
@ kw_declare
Definition: LLToken.h:45
@ kw_allOnes
Definition: LLToken.h:432
@ kw_vTableFuncs
Definition: LLToken.h:410
@ ChecksumKind
Definition: LLToken.h:498
@ DwarfMacinfo
Definition: LLToken.h:497
@ kw_volatile
Definition: LLToken.h:93
@ kw_typeCheckedLoadVCalls
Definition: LLToken.h:417
@ kw_function
Definition: LLToken.h:388
@ kw_default
Definition: LLToken.h:64
@ kw_no_sanitize_address
Definition: LLToken.h:465
@ kw_inaccessiblemem_or_argmemonly
Definition: LLToken.h:208
@ kw_uinc_wrap
Definition: LLToken.h:276
@ kw_externally_initialized
Definition: LLToken.h:69
@ kw_sanitize_address_dyninit
Definition: LLToken.h:471
@ kw_atomicrmw
Definition: LLToken.h:347
@ kw_hidden
Definition: LLToken.h:65
@ EmissionKind
Definition: LLToken.h:492
@ kw_amdgpu_cs_chain_preserve
Definition: LLToken.h:181
@ kw_usub_sat
Definition: LLToken.h:279
@ kw_readwrite
Definition: LLToken.h:201
@ kw_within
Definition: LLToken.h:83
@ kw_section
Definition: LLToken.h:120
@ kw_triple
Definition: LLToken.h:89
@ kw_thread_local
Definition: LLToken.h:72
@ kw_catchswitch
Definition: LLToken.h:336
@ kw_extern_weak
Definition: LLToken.h:70
@ kw_arm_aapcscc
Definition: LLToken.h:146
@ kw_usub_cond
Definition: LLToken.h:278
@ kw_memProf
Definition: LLToken.h:460
@ kw_alignLog2
Definition: LLToken.h:434
@ kw_read_provenance
Definition: LLToken.h:214
@ kw_cleanuppad
Definition: LLToken.h:339
@ kw_available_externally
Definition: LLToken.h:63
@ kw_singleImplName
Definition: LLToken.h:444
@ kw_typeTests
Definition: LLToken.h:415
@ kw_versions
Definition: LLToken.h:459
@ kw_notcold
Definition: LLToken.h:461
@ kw_mayThrow
Definition: LLToken.h:398
@ kw_swifttailcc
Definition: LLToken.h:164
@ kw_monotonic
Definition: LLToken.h:96
@ kw_typeTestAssumeVCalls
Definition: LLToken.h:416
@ kw_amdgpu_ls
Definition: LLToken.h:174
@ kw_caller
Definition: LLToken.h:82
@ kw_vscale
Definition: LLToken.h:41
@ kw_target
Definition: LLToken.h:88
@ kw_attributes
Definition: LLToken.h:190
@ kw_code_model
Definition: LLToken.h:122
@ kw_cmpxchg
Definition: LLToken.h:346
@ kw_funcFlags
Definition: LLToken.h:390
@ kw_localdynamic
Definition: LLToken.h:73
@ kw_uniformRetVal
Definition: LLToken.h:447
@ kw_sideeffect
Definition: LLToken.h:127
@ kw_amdgpu_ps
Definition: LLToken.h:178
@ kw_sizeM1BitWidth
Definition: LLToken.h:433
@ kw_catchret
Definition: LLToken.h:337
@ kw_nodeduplicate
Definition: LLToken.h:243
@ kw_avr_signalcc
Definition: LLToken.h:155
@ kw_exactmatch
Definition: LLToken.h:241
@ kw_aliasee
Definition: LLToken.h:412
@ kw_common
Definition: LLToken.h:62
@ kw_unreachable
Definition: LLToken.h:334
@ kw_intel_ocl_bicc
Definition: LLToken.h:138
@ kw_global
Definition: LLToken.h:47
@ kw_dso_local
Definition: LLToken.h:50
@ kw_undef
Definition: LLToken.h:77
@ kw_addrspace
Definition: LLToken.h:119
@ kw_release
Definition: LLToken.h:98
@ kw_returnDoesNotAlias
Definition: LLToken.h:394
@ kw_aarch64_sme_preservemost_from_x0
Definition: LLToken.h:150
@ kw_preserve_allcc
Definition: LLToken.h:166
@ kw_importType
Definition: LLToken.h:385
@ dotdotdot
Definition: LLToken.h:24
@ kw_cleanupret
Definition: LLToken.h:335
@ kw_shufflevector
Definition: LLToken.h:352
@ kw_riscv_vector_cc
Definition: LLToken.h:187
@ kw_avr_intrcc
Definition: LLToken.h:154
@ kw_definition
Definition: LLToken.h:386
@ kw_prologue
Definition: LLToken.h:131
@ kw_virtualConstProp
Definition: LLToken.h:449
@ kw_vcall_visibility
Definition: LLToken.h:438
@ kw_poison
Definition: LLToken.h:78
@ kw_appending
Definition: LLToken.h:59
@ kw_inaccessiblemem
Definition: LLToken.h:203
@ kw_preserve_mostcc
Definition: LLToken.h:165
@ kw_arm_aapcs_vfpcc
Definition: LLToken.h:147
@ kw_typeTestRes
Definition: LLToken.h:426
@ kw_unknown
Definition: LLToken.h:406
@ kw_x86_regcallcc
Definition: LLToken.h:144
@ kw_typeIdInfo
Definition: LLToken.h:414
@ kw_amdgpu_cs_chain
Definition: LLToken.h:180
@ kw_dso_local_equivalent
Definition: LLToken.h:357
@ kw_x86_64_sysvcc
Definition: LLToken.h:160
@ DbgRecordType
Definition: LLToken.h:499
@ kw_summary
Definition: LLToken.h:425
@ kw_address_is_null
Definition: LLToken.h:212
@ kw_virtFunc
Definition: LLToken.h:411
@ kw_musttail
Definition: LLToken.h:86
@ kw_aarch64_sme_preservemost_from_x2
Definition: LLToken.h:152
@ kw_byteArray
Definition: LLToken.h:429
@ kw_uniqueRetVal
Definition: LLToken.h:448
@ kw_insertvalue
Definition: LLToken.h:355
@ kw_indirectbr
Definition: LLToken.h:331
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:577
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
void UpgradeSectionAttributes(Module &M)
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:1697
@ Read
Definition: CodeGenData.h:107
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
@ Done
Definition: Threading.h:61
AllocFnKind
Definition: Attributes.h:49
void UpgradeCallsToIntrinsic(Function *F)
This is an auto-upgrade hook for any old intrinsic function syntaxes which need to have both the func...
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:657
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:296
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
UWTableKind
Definition: CodeGen.h:120
@ Async
"Asynchronous" unwind tables (instr precise)
@ Sync
"Synchronous" unwind tables
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:291
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1664
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition: ModRef.h:268
std::tuple< const DIScope *, const DIScope *, const DILocalVariable * > VarID
A unique key that represents a debug variable.
bool isPointerTy(const Type *T)
Definition: SPIRVUtils.h:255
CaptureComponents
Components of the pointer that may be captured.
Definition: ModRef.h:277
AtomicOrdering
Atomic ordering for LLVM's memory model.
@ Ref
The access may reference the value stored in memory.
@ ModRef
The access may reference and may modify the value stored in memory.
@ Mod
The access may modify the value stored in memory.
@ NoModRef
The access neither references nor modifies the value stored in memory.
@ ArgMem
Access to memory via argument pointers.
@ Other
Any other memory.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
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:1938
DWARFExpression::Operation Op
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:217
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:1873
const char * toString(DWARFSectionKind Kind)
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
bool capturesNothing(CaptureComponents CC)
Definition: ModRef.h:287
MDNode * UpgradeTBAANode(MDNode &TBAANode)
If the given TBAA tag uses the scalar TBAA format, create a new node corresponding to the upgrade to ...
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition: APFloat.cpp:257
static constexpr roundingMode rmNearestTiesToEven
Definition: APFloat.h:302
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:258
static const fltSemantics & IEEEhalf() LLVM_READNONE
Definition: APFloat.cpp:255
static const fltSemantics & BFloat() LLVM_READNONE
Definition: APFloat.cpp:256
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Helper struct shared between Function Specialization and SCCP Solver.
Definition: SCCPSolver.h:41
Class to accumulate and hold information about a callee.
Helper object to track which of three possible relocation mechanisms are used for a particular value ...
A specification for a virtual function call with all constant integer arguments.
Flags specific to function summaries.
Describes the use of a value in a call instruction, specifying the call's target, the value's paramet...
Describes the uses of a parameter by the function.
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
static constexpr uint32_t RangeWidth
All type identifier related information.
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....
An "identifier" for a virtual function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
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:117
A utility class that uses RAII to save and restore the value of a variable.
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition: SlotMapping.h:33
std::map< unsigned, Type * > Types
Definition: SlotMapping.h:37
StringMap< Type * > NamedTypes
Definition: SlotMapping.h:36
std::map< unsigned, TrackingMDNodeRef > MetadataNodes
Definition: SlotMapping.h:35
NumberedValues< GlobalValue * > GlobalValues
Definition: SlotMapping.h:34
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:53
@ t_Constant
Definition: LLParser.h:67
@ t_PackedConstantStruct
Definition: LLParser.h:71
@ t_GlobalID
Definition: LLParser.h:56
@ t_EmptyArray
Definition: LLParser.h:66
@ t_GlobalName
Definition: LLParser.h:58
@ t_ConstantStruct
Definition: LLParser.h:70
@ t_LocalName
Definition: LLParser.h:57
@ t_ConstantSplat
Definition: LLParser.h:68
@ t_InlineAsm
Definition: LLParser.h:69
unsigned UIntVal
Definition: LLParser.h:75
enum llvm::ValID::@40 Kind
FunctionType * FTy
Definition: LLParser.h:76
LLLexer::LocTy Loc
Definition: LLParser.h:74
std::string StrVal
Definition: LLParser.h:77
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.
Utility type to build an inheritance chain that makes it easy to rank overload candidates.
Definition: STLExtras.h:1496