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