Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / lib / AsmParser / LLParser.cpp
blob42f306a99d5eefa0988fa5b7f4ee0fcabb15432a
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.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/AsmParser/LLParser.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/LLToken.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/BinaryFormat/Dwarf.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"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DebugInfoMetadata.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/IR/ValueSymbolTable.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/ModRef.h"
47 #include "llvm/Support/SaveAndRestore.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstring>
52 #include <optional>
53 #include <vector>
55 using namespace llvm;
57 static std::string getTypeString(Type *T) {
58 std::string Result;
59 raw_string_ostream Tmp(Result);
60 Tmp << *T;
61 return Tmp.str();
64 /// Run: module ::= toplevelentity*
65 bool LLParser::Run(bool UpgradeDebugInfo,
66 DataLayoutCallbackTy DataLayoutCallback) {
67 // Prime the lexer.
68 Lex.Lex();
70 if (Context.shouldDiscardValueNames())
71 return error(
72 Lex.getLoc(),
73 "Can't read textual IR with a Context that discards named Values");
75 if (M) {
76 if (parseTargetDefinitions(DataLayoutCallback))
77 return true;
80 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
81 validateEndOfIndex();
84 bool LLParser::parseStandaloneConstantValue(Constant *&C,
85 const SlotMapping *Slots) {
86 restoreParsingState(Slots);
87 Lex.Lex();
89 Type *Ty = nullptr;
90 if (parseType(Ty) || parseConstantValue(Ty, C))
91 return true;
92 if (Lex.getKind() != lltok::Eof)
93 return error(Lex.getLoc(), "expected end of string");
94 return false;
97 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
98 const SlotMapping *Slots) {
99 restoreParsingState(Slots);
100 Lex.Lex();
102 Read = 0;
103 SMLoc Start = Lex.getLoc();
104 Ty = nullptr;
105 if (parseType(Ty))
106 return true;
107 SMLoc End = Lex.getLoc();
108 Read = End.getPointer() - Start.getPointer();
110 return false;
113 void LLParser::restoreParsingState(const SlotMapping *Slots) {
114 if (!Slots)
115 return;
116 NumberedVals = Slots->GlobalValues;
117 NumberedMetadata = Slots->MetadataNodes;
118 for (const auto &I : Slots->NamedTypes)
119 NamedTypes.insert(
120 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
121 for (const auto &I : Slots->Types)
122 NumberedTypes.insert(
123 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
126 /// validateEndOfModule - Do final validity and basic correctness checks at the
127 /// end of the module.
128 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
129 if (!M)
130 return false;
131 // Handle any function attribute group forward references.
132 for (const auto &RAG : ForwardRefAttrGroups) {
133 Value *V = RAG.first;
134 const std::vector<unsigned> &Attrs = RAG.second;
135 AttrBuilder B(Context);
137 for (const auto &Attr : Attrs) {
138 auto R = NumberedAttrBuilders.find(Attr);
139 if (R != NumberedAttrBuilders.end())
140 B.merge(R->second);
143 if (Function *Fn = dyn_cast<Function>(V)) {
144 AttributeList AS = Fn->getAttributes();
145 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
146 AS = AS.removeFnAttributes(Context);
148 FnAttrs.merge(B);
150 // If the alignment was parsed as an attribute, move to the alignment
151 // field.
152 if (MaybeAlign A = FnAttrs.getAlignment()) {
153 Fn->setAlignment(*A);
154 FnAttrs.removeAttribute(Attribute::Alignment);
157 AS = AS.addFnAttributes(Context, FnAttrs);
158 Fn->setAttributes(AS);
159 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
160 AttributeList AS = CI->getAttributes();
161 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
162 AS = AS.removeFnAttributes(Context);
163 FnAttrs.merge(B);
164 AS = AS.addFnAttributes(Context, FnAttrs);
165 CI->setAttributes(AS);
166 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
167 AttributeList AS = II->getAttributes();
168 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
169 AS = AS.removeFnAttributes(Context);
170 FnAttrs.merge(B);
171 AS = AS.addFnAttributes(Context, FnAttrs);
172 II->setAttributes(AS);
173 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
174 AttributeList AS = CBI->getAttributes();
175 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
176 AS = AS.removeFnAttributes(Context);
177 FnAttrs.merge(B);
178 AS = AS.addFnAttributes(Context, FnAttrs);
179 CBI->setAttributes(AS);
180 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
181 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
182 Attrs.merge(B);
183 GV->setAttributes(AttributeSet::get(Context,Attrs));
184 } else {
185 llvm_unreachable("invalid object with forward attribute group reference");
189 // If there are entries in ForwardRefBlockAddresses at this point, the
190 // function was never defined.
191 if (!ForwardRefBlockAddresses.empty())
192 return error(ForwardRefBlockAddresses.begin()->first.Loc,
193 "expected function name in blockaddress");
195 auto ResolveForwardRefDSOLocalEquivalents = [&](const ValID &GVRef,
196 GlobalValue *FwdRef) {
197 GlobalValue *GV = nullptr;
198 if (GVRef.Kind == ValID::t_GlobalName) {
199 GV = M->getNamedValue(GVRef.StrVal);
200 } else if (GVRef.UIntVal < NumberedVals.size()) {
201 GV = dyn_cast<GlobalValue>(NumberedVals[GVRef.UIntVal]);
204 if (!GV)
205 return error(GVRef.Loc, "unknown function '" + GVRef.StrVal +
206 "' referenced by dso_local_equivalent");
208 if (!GV->getValueType()->isFunctionTy())
209 return error(GVRef.Loc,
210 "expected a function, alias to function, or ifunc "
211 "in dso_local_equivalent");
213 auto *Equiv = DSOLocalEquivalent::get(GV);
214 FwdRef->replaceAllUsesWith(Equiv);
215 FwdRef->eraseFromParent();
216 return false;
219 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
220 // point, they are references after the function was defined. Resolve those
221 // now.
222 for (auto &Iter : ForwardRefDSOLocalEquivalentIDs) {
223 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
224 return true;
226 for (auto &Iter : ForwardRefDSOLocalEquivalentNames) {
227 if (ResolveForwardRefDSOLocalEquivalents(Iter.first, Iter.second))
228 return true;
230 ForwardRefDSOLocalEquivalentIDs.clear();
231 ForwardRefDSOLocalEquivalentNames.clear();
233 for (const auto &NT : NumberedTypes)
234 if (NT.second.second.isValid())
235 return error(NT.second.second,
236 "use of undefined type '%" + Twine(NT.first) + "'");
238 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
239 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
240 if (I->second.second.isValid())
241 return error(I->second.second,
242 "use of undefined type named '" + I->getKey() + "'");
244 if (!ForwardRefComdats.empty())
245 return error(ForwardRefComdats.begin()->second,
246 "use of undefined comdat '$" +
247 ForwardRefComdats.begin()->first + "'");
249 if (!ForwardRefVals.empty())
250 return error(ForwardRefVals.begin()->second.second,
251 "use of undefined value '@" + ForwardRefVals.begin()->first +
252 "'");
254 if (!ForwardRefValIDs.empty())
255 return error(ForwardRefValIDs.begin()->second.second,
256 "use of undefined value '@" +
257 Twine(ForwardRefValIDs.begin()->first) + "'");
259 if (!ForwardRefMDNodes.empty())
260 return error(ForwardRefMDNodes.begin()->second.second,
261 "use of undefined metadata '!" +
262 Twine(ForwardRefMDNodes.begin()->first) + "'");
264 // Resolve metadata cycles.
265 for (auto &N : NumberedMetadata) {
266 if (N.second && !N.second->isResolved())
267 N.second->resolveCycles();
270 for (auto *Inst : InstsWithTBAATag) {
271 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
272 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
273 auto *UpgradedMD = UpgradeTBAANode(*MD);
274 if (MD != UpgradedMD)
275 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
278 // Look for intrinsic functions and CallInst that need to be upgraded. We use
279 // make_early_inc_range here because we may remove some functions.
280 for (Function &F : llvm::make_early_inc_range(*M))
281 UpgradeCallsToIntrinsic(&F);
283 if (UpgradeDebugInfo)
284 llvm::UpgradeDebugInfo(*M);
286 UpgradeModuleFlags(*M);
287 UpgradeSectionAttributes(*M);
289 if (!Slots)
290 return false;
291 // Initialize the slot mapping.
292 // Because by this point we've parsed and validated everything, we can "steal"
293 // the mapping from LLParser as it doesn't need it anymore.
294 Slots->GlobalValues = std::move(NumberedVals);
295 Slots->MetadataNodes = std::move(NumberedMetadata);
296 for (const auto &I : NamedTypes)
297 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
298 for (const auto &I : NumberedTypes)
299 Slots->Types.insert(std::make_pair(I.first, I.second.first));
301 return false;
304 /// Do final validity and basic correctness checks at the end of the index.
305 bool LLParser::validateEndOfIndex() {
306 if (!Index)
307 return false;
309 if (!ForwardRefValueInfos.empty())
310 return error(ForwardRefValueInfos.begin()->second.front().second,
311 "use of undefined summary '^" +
312 Twine(ForwardRefValueInfos.begin()->first) + "'");
314 if (!ForwardRefAliasees.empty())
315 return error(ForwardRefAliasees.begin()->second.front().second,
316 "use of undefined summary '^" +
317 Twine(ForwardRefAliasees.begin()->first) + "'");
319 if (!ForwardRefTypeIds.empty())
320 return error(ForwardRefTypeIds.begin()->second.front().second,
321 "use of undefined type id summary '^" +
322 Twine(ForwardRefTypeIds.begin()->first) + "'");
324 return false;
327 //===----------------------------------------------------------------------===//
328 // Top-Level Entities
329 //===----------------------------------------------------------------------===//
331 bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback) {
332 // Delay parsing of the data layout string until the target triple is known.
333 // Then, pass both the the target triple and the tentative data layout string
334 // to DataLayoutCallback, allowing to override the DL string.
335 // This enables importing modules with invalid DL strings.
336 std::string TentativeDLStr = M->getDataLayoutStr();
337 LocTy DLStrLoc;
339 bool Done = false;
340 while (!Done) {
341 switch (Lex.getKind()) {
342 case lltok::kw_target:
343 if (parseTargetDefinition(TentativeDLStr, DLStrLoc))
344 return true;
345 break;
346 case lltok::kw_source_filename:
347 if (parseSourceFileName())
348 return true;
349 break;
350 default:
351 Done = true;
354 // Run the override callback to potentially change the data layout string, and
355 // parse the data layout string.
356 if (auto LayoutOverride =
357 DataLayoutCallback(M->getTargetTriple(), TentativeDLStr)) {
358 TentativeDLStr = *LayoutOverride;
359 DLStrLoc = {};
361 Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDLStr);
362 if (!MaybeDL)
363 return error(DLStrLoc, toString(MaybeDL.takeError()));
364 M->setDataLayout(MaybeDL.get());
365 return false;
368 bool LLParser::parseTopLevelEntities() {
369 // If there is no Module, then parse just the summary index entries.
370 if (!M) {
371 while (true) {
372 switch (Lex.getKind()) {
373 case lltok::Eof:
374 return false;
375 case lltok::SummaryID:
376 if (parseSummaryEntry())
377 return true;
378 break;
379 case lltok::kw_source_filename:
380 if (parseSourceFileName())
381 return true;
382 break;
383 default:
384 // Skip everything else
385 Lex.Lex();
389 while (true) {
390 switch (Lex.getKind()) {
391 default:
392 return tokError("expected top-level entity");
393 case lltok::Eof: return false;
394 case lltok::kw_declare:
395 if (parseDeclare())
396 return true;
397 break;
398 case lltok::kw_define:
399 if (parseDefine())
400 return true;
401 break;
402 case lltok::kw_module:
403 if (parseModuleAsm())
404 return true;
405 break;
406 case lltok::LocalVarID:
407 if (parseUnnamedType())
408 return true;
409 break;
410 case lltok::LocalVar:
411 if (parseNamedType())
412 return true;
413 break;
414 case lltok::GlobalID:
415 if (parseUnnamedGlobal())
416 return true;
417 break;
418 case lltok::GlobalVar:
419 if (parseNamedGlobal())
420 return true;
421 break;
422 case lltok::ComdatVar: if (parseComdat()) return true; break;
423 case lltok::exclaim:
424 if (parseStandaloneMetadata())
425 return true;
426 break;
427 case lltok::SummaryID:
428 if (parseSummaryEntry())
429 return true;
430 break;
431 case lltok::MetadataVar:
432 if (parseNamedMetadata())
433 return true;
434 break;
435 case lltok::kw_attributes:
436 if (parseUnnamedAttrGrp())
437 return true;
438 break;
439 case lltok::kw_uselistorder:
440 if (parseUseListOrder())
441 return true;
442 break;
443 case lltok::kw_uselistorder_bb:
444 if (parseUseListOrderBB())
445 return true;
446 break;
451 /// toplevelentity
452 /// ::= 'module' 'asm' STRINGCONSTANT
453 bool LLParser::parseModuleAsm() {
454 assert(Lex.getKind() == lltok::kw_module);
455 Lex.Lex();
457 std::string AsmStr;
458 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
459 parseStringConstant(AsmStr))
460 return true;
462 M->appendModuleInlineAsm(AsmStr);
463 return false;
466 /// toplevelentity
467 /// ::= 'target' 'triple' '=' STRINGCONSTANT
468 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
469 bool LLParser::parseTargetDefinition(std::string &TentativeDLStr,
470 LocTy &DLStrLoc) {
471 assert(Lex.getKind() == lltok::kw_target);
472 std::string Str;
473 switch (Lex.Lex()) {
474 default:
475 return tokError("unknown target property");
476 case lltok::kw_triple:
477 Lex.Lex();
478 if (parseToken(lltok::equal, "expected '=' after target triple") ||
479 parseStringConstant(Str))
480 return true;
481 M->setTargetTriple(Str);
482 return false;
483 case lltok::kw_datalayout:
484 Lex.Lex();
485 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
486 return true;
487 DLStrLoc = Lex.getLoc();
488 if (parseStringConstant(TentativeDLStr))
489 return true;
490 return false;
494 /// toplevelentity
495 /// ::= 'source_filename' '=' STRINGCONSTANT
496 bool LLParser::parseSourceFileName() {
497 assert(Lex.getKind() == lltok::kw_source_filename);
498 Lex.Lex();
499 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
500 parseStringConstant(SourceFileName))
501 return true;
502 if (M)
503 M->setSourceFileName(SourceFileName);
504 return false;
507 /// parseUnnamedType:
508 /// ::= LocalVarID '=' 'type' type
509 bool LLParser::parseUnnamedType() {
510 LocTy TypeLoc = Lex.getLoc();
511 unsigned TypeID = Lex.getUIntVal();
512 Lex.Lex(); // eat LocalVarID;
514 if (parseToken(lltok::equal, "expected '=' after name") ||
515 parseToken(lltok::kw_type, "expected 'type' after '='"))
516 return true;
518 Type *Result = nullptr;
519 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
520 return true;
522 if (!isa<StructType>(Result)) {
523 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
524 if (Entry.first)
525 return error(TypeLoc, "non-struct types may not be recursive");
526 Entry.first = Result;
527 Entry.second = SMLoc();
530 return false;
533 /// toplevelentity
534 /// ::= LocalVar '=' 'type' type
535 bool LLParser::parseNamedType() {
536 std::string Name = Lex.getStrVal();
537 LocTy NameLoc = Lex.getLoc();
538 Lex.Lex(); // eat LocalVar.
540 if (parseToken(lltok::equal, "expected '=' after name") ||
541 parseToken(lltok::kw_type, "expected 'type' after name"))
542 return true;
544 Type *Result = nullptr;
545 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
546 return true;
548 if (!isa<StructType>(Result)) {
549 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
550 if (Entry.first)
551 return error(NameLoc, "non-struct types may not be recursive");
552 Entry.first = Result;
553 Entry.second = SMLoc();
556 return false;
559 /// toplevelentity
560 /// ::= 'declare' FunctionHeader
561 bool LLParser::parseDeclare() {
562 assert(Lex.getKind() == lltok::kw_declare);
563 Lex.Lex();
565 std::vector<std::pair<unsigned, MDNode *>> MDs;
566 while (Lex.getKind() == lltok::MetadataVar) {
567 unsigned MDK;
568 MDNode *N;
569 if (parseMetadataAttachment(MDK, N))
570 return true;
571 MDs.push_back({MDK, N});
574 Function *F;
575 if (parseFunctionHeader(F, false))
576 return true;
577 for (auto &MD : MDs)
578 F->addMetadata(MD.first, *MD.second);
579 return false;
582 /// toplevelentity
583 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
584 bool LLParser::parseDefine() {
585 assert(Lex.getKind() == lltok::kw_define);
586 Lex.Lex();
588 Function *F;
589 return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
590 parseFunctionBody(*F);
593 /// parseGlobalType
594 /// ::= 'constant'
595 /// ::= 'global'
596 bool LLParser::parseGlobalType(bool &IsConstant) {
597 if (Lex.getKind() == lltok::kw_constant)
598 IsConstant = true;
599 else if (Lex.getKind() == lltok::kw_global)
600 IsConstant = false;
601 else {
602 IsConstant = false;
603 return tokError("expected 'global' or 'constant'");
605 Lex.Lex();
606 return false;
609 bool LLParser::parseOptionalUnnamedAddr(
610 GlobalVariable::UnnamedAddr &UnnamedAddr) {
611 if (EatIfPresent(lltok::kw_unnamed_addr))
612 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
613 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
614 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
615 else
616 UnnamedAddr = GlobalValue::UnnamedAddr::None;
617 return false;
620 /// parseUnnamedGlobal:
621 /// OptionalVisibility (ALIAS | IFUNC) ...
622 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
623 /// OptionalDLLStorageClass
624 /// ... -> global variable
625 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
626 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
627 /// OptionalVisibility
628 /// OptionalDLLStorageClass
629 /// ... -> global variable
630 bool LLParser::parseUnnamedGlobal() {
631 unsigned VarID = NumberedVals.size();
632 std::string Name;
633 LocTy NameLoc = Lex.getLoc();
635 // Handle the GlobalID form.
636 if (Lex.getKind() == lltok::GlobalID) {
637 if (Lex.getUIntVal() != VarID)
638 return error(Lex.getLoc(),
639 "variable expected to be numbered '%" + Twine(VarID) + "'");
640 Lex.Lex(); // eat GlobalID;
642 if (parseToken(lltok::equal, "expected '=' after name"))
643 return true;
646 bool HasLinkage;
647 unsigned Linkage, Visibility, DLLStorageClass;
648 bool DSOLocal;
649 GlobalVariable::ThreadLocalMode TLM;
650 GlobalVariable::UnnamedAddr UnnamedAddr;
651 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
652 DSOLocal) ||
653 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
654 return true;
656 switch (Lex.getKind()) {
657 default:
658 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
659 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
660 case lltok::kw_alias:
661 case lltok::kw_ifunc:
662 return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility,
663 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
667 /// parseNamedGlobal:
668 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
669 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
670 /// OptionalVisibility OptionalDLLStorageClass
671 /// ... -> global variable
672 bool LLParser::parseNamedGlobal() {
673 assert(Lex.getKind() == lltok::GlobalVar);
674 LocTy NameLoc = Lex.getLoc();
675 std::string Name = Lex.getStrVal();
676 Lex.Lex();
678 bool HasLinkage;
679 unsigned Linkage, Visibility, DLLStorageClass;
680 bool DSOLocal;
681 GlobalVariable::ThreadLocalMode TLM;
682 GlobalVariable::UnnamedAddr UnnamedAddr;
683 if (parseToken(lltok::equal, "expected '=' in global variable") ||
684 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
685 DSOLocal) ||
686 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
687 return true;
689 switch (Lex.getKind()) {
690 default:
691 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
692 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
693 case lltok::kw_alias:
694 case lltok::kw_ifunc:
695 return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility,
696 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
700 bool LLParser::parseComdat() {
701 assert(Lex.getKind() == lltok::ComdatVar);
702 std::string Name = Lex.getStrVal();
703 LocTy NameLoc = Lex.getLoc();
704 Lex.Lex();
706 if (parseToken(lltok::equal, "expected '=' here"))
707 return true;
709 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
710 return tokError("expected comdat type");
712 Comdat::SelectionKind SK;
713 switch (Lex.getKind()) {
714 default:
715 return tokError("unknown selection kind");
716 case lltok::kw_any:
717 SK = Comdat::Any;
718 break;
719 case lltok::kw_exactmatch:
720 SK = Comdat::ExactMatch;
721 break;
722 case lltok::kw_largest:
723 SK = Comdat::Largest;
724 break;
725 case lltok::kw_nodeduplicate:
726 SK = Comdat::NoDeduplicate;
727 break;
728 case lltok::kw_samesize:
729 SK = Comdat::SameSize;
730 break;
732 Lex.Lex();
734 // See if the comdat was forward referenced, if so, use the comdat.
735 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
736 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
737 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
738 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
740 Comdat *C;
741 if (I != ComdatSymTab.end())
742 C = &I->second;
743 else
744 C = M->getOrInsertComdat(Name);
745 C->setSelectionKind(SK);
747 return false;
750 // MDString:
751 // ::= '!' STRINGCONSTANT
752 bool LLParser::parseMDString(MDString *&Result) {
753 std::string Str;
754 if (parseStringConstant(Str))
755 return true;
756 Result = MDString::get(Context, Str);
757 return false;
760 // MDNode:
761 // ::= '!' MDNodeNumber
762 bool LLParser::parseMDNodeID(MDNode *&Result) {
763 // !{ ..., !42, ... }
764 LocTy IDLoc = Lex.getLoc();
765 unsigned MID = 0;
766 if (parseUInt32(MID))
767 return true;
769 // If not a forward reference, just return it now.
770 if (NumberedMetadata.count(MID)) {
771 Result = NumberedMetadata[MID];
772 return false;
775 // Otherwise, create MDNode forward reference.
776 auto &FwdRef = ForwardRefMDNodes[MID];
777 FwdRef = std::make_pair(MDTuple::getTemporary(Context, std::nullopt), IDLoc);
779 Result = FwdRef.first.get();
780 NumberedMetadata[MID].reset(Result);
781 return false;
784 /// parseNamedMetadata:
785 /// !foo = !{ !1, !2 }
786 bool LLParser::parseNamedMetadata() {
787 assert(Lex.getKind() == lltok::MetadataVar);
788 std::string Name = Lex.getStrVal();
789 Lex.Lex();
791 if (parseToken(lltok::equal, "expected '=' here") ||
792 parseToken(lltok::exclaim, "Expected '!' here") ||
793 parseToken(lltok::lbrace, "Expected '{' here"))
794 return true;
796 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
797 if (Lex.getKind() != lltok::rbrace)
798 do {
799 MDNode *N = nullptr;
800 // parse DIExpressions inline as a special case. They are still MDNodes,
801 // so they can still appear in named metadata. Remove this logic if they
802 // become plain Metadata.
803 if (Lex.getKind() == lltok::MetadataVar &&
804 Lex.getStrVal() == "DIExpression") {
805 if (parseDIExpression(N, /*IsDistinct=*/false))
806 return true;
807 // DIArgLists should only appear inline in a function, as they may
808 // contain LocalAsMetadata arguments which require a function context.
809 } else if (Lex.getKind() == lltok::MetadataVar &&
810 Lex.getStrVal() == "DIArgList") {
811 return tokError("found DIArgList outside of function");
812 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
813 parseMDNodeID(N)) {
814 return true;
816 NMD->addOperand(N);
817 } while (EatIfPresent(lltok::comma));
819 return parseToken(lltok::rbrace, "expected end of metadata node");
822 /// parseStandaloneMetadata:
823 /// !42 = !{...}
824 bool LLParser::parseStandaloneMetadata() {
825 assert(Lex.getKind() == lltok::exclaim);
826 Lex.Lex();
827 unsigned MetadataID = 0;
829 MDNode *Init;
830 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
831 return true;
833 // Detect common error, from old metadata syntax.
834 if (Lex.getKind() == lltok::Type)
835 return tokError("unexpected type in metadata definition");
837 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
838 if (Lex.getKind() == lltok::MetadataVar) {
839 if (parseSpecializedMDNode(Init, IsDistinct))
840 return true;
841 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
842 parseMDTuple(Init, IsDistinct))
843 return true;
845 // See if this was forward referenced, if so, handle it.
846 auto FI = ForwardRefMDNodes.find(MetadataID);
847 if (FI != ForwardRefMDNodes.end()) {
848 auto *ToReplace = FI->second.first.get();
849 // DIAssignID has its own special forward-reference "replacement" for
850 // attachments (the temporary attachments are never actually attached).
851 if (isa<DIAssignID>(Init)) {
852 for (auto *Inst : TempDIAssignIDAttachments[ToReplace]) {
853 assert(!Inst->getMetadata(LLVMContext::MD_DIAssignID) &&
854 "Inst unexpectedly already has DIAssignID attachment");
855 Inst->setMetadata(LLVMContext::MD_DIAssignID, Init);
859 ToReplace->replaceAllUsesWith(Init);
860 ForwardRefMDNodes.erase(FI);
862 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
863 } else {
864 if (NumberedMetadata.count(MetadataID))
865 return tokError("Metadata id is already used");
866 NumberedMetadata[MetadataID].reset(Init);
869 return false;
872 // Skips a single module summary entry.
873 bool LLParser::skipModuleSummaryEntry() {
874 // Each module summary entry consists of a tag for the entry
875 // type, followed by a colon, then the fields which may be surrounded by
876 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
877 // support is in place we will look for the tokens corresponding to the
878 // expected tags.
879 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
880 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
881 Lex.getKind() != lltok::kw_blockcount)
882 return tokError(
883 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
884 "start of summary entry");
885 if (Lex.getKind() == lltok::kw_flags)
886 return parseSummaryIndexFlags();
887 if (Lex.getKind() == lltok::kw_blockcount)
888 return parseBlockCount();
889 Lex.Lex();
890 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
891 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
892 return true;
893 // Now walk through the parenthesized entry, until the number of open
894 // parentheses goes back down to 0 (the first '(' was parsed above).
895 unsigned NumOpenParen = 1;
896 do {
897 switch (Lex.getKind()) {
898 case lltok::lparen:
899 NumOpenParen++;
900 break;
901 case lltok::rparen:
902 NumOpenParen--;
903 break;
904 case lltok::Eof:
905 return tokError("found end of file while parsing summary entry");
906 default:
907 // Skip everything in between parentheses.
908 break;
910 Lex.Lex();
911 } while (NumOpenParen > 0);
912 return false;
915 /// SummaryEntry
916 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
917 bool LLParser::parseSummaryEntry() {
918 assert(Lex.getKind() == lltok::SummaryID);
919 unsigned SummaryID = Lex.getUIntVal();
921 // For summary entries, colons should be treated as distinct tokens,
922 // not an indication of the end of a label token.
923 Lex.setIgnoreColonInIdentifiers(true);
925 Lex.Lex();
926 if (parseToken(lltok::equal, "expected '=' here"))
927 return true;
929 // If we don't have an index object, skip the summary entry.
930 if (!Index)
931 return skipModuleSummaryEntry();
933 bool result = false;
934 switch (Lex.getKind()) {
935 case lltok::kw_gv:
936 result = parseGVEntry(SummaryID);
937 break;
938 case lltok::kw_module:
939 result = parseModuleEntry(SummaryID);
940 break;
941 case lltok::kw_typeid:
942 result = parseTypeIdEntry(SummaryID);
943 break;
944 case lltok::kw_typeidCompatibleVTable:
945 result = parseTypeIdCompatibleVtableEntry(SummaryID);
946 break;
947 case lltok::kw_flags:
948 result = parseSummaryIndexFlags();
949 break;
950 case lltok::kw_blockcount:
951 result = parseBlockCount();
952 break;
953 default:
954 result = error(Lex.getLoc(), "unexpected summary kind");
955 break;
957 Lex.setIgnoreColonInIdentifiers(false);
958 return result;
961 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
962 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
963 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
965 static bool isValidDLLStorageClassForLinkage(unsigned S, unsigned L) {
966 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
967 (GlobalValue::DLLStorageClassTypes)S == GlobalValue::DefaultStorageClass;
970 // If there was an explicit dso_local, update GV. In the absence of an explicit
971 // dso_local we keep the default value.
972 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
973 if (DSOLocal)
974 GV.setDSOLocal(true);
977 /// parseAliasOrIFunc:
978 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
979 /// OptionalVisibility OptionalDLLStorageClass
980 /// OptionalThreadLocal OptionalUnnamedAddr
981 /// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
983 /// AliaseeOrResolver
984 /// ::= TypeAndValue
986 /// SymbolAttrs
987 /// ::= ',' 'partition' StringConstant
989 /// Everything through OptionalUnnamedAddr has already been parsed.
991 bool LLParser::parseAliasOrIFunc(const std::string &Name, LocTy NameLoc,
992 unsigned L, unsigned Visibility,
993 unsigned DLLStorageClass, bool DSOLocal,
994 GlobalVariable::ThreadLocalMode TLM,
995 GlobalVariable::UnnamedAddr UnnamedAddr) {
996 bool IsAlias;
997 if (Lex.getKind() == lltok::kw_alias)
998 IsAlias = true;
999 else if (Lex.getKind() == lltok::kw_ifunc)
1000 IsAlias = false;
1001 else
1002 llvm_unreachable("Not an alias or ifunc!");
1003 Lex.Lex();
1005 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
1007 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
1008 return error(NameLoc, "invalid linkage type for alias");
1010 if (!isValidVisibilityForLinkage(Visibility, L))
1011 return error(NameLoc,
1012 "symbol with local linkage must have default visibility");
1014 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, L))
1015 return error(NameLoc,
1016 "symbol with local linkage cannot have a DLL storage class");
1018 Type *Ty;
1019 LocTy ExplicitTypeLoc = Lex.getLoc();
1020 if (parseType(Ty) ||
1021 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
1022 return true;
1024 Constant *Aliasee;
1025 LocTy AliaseeLoc = Lex.getLoc();
1026 if (Lex.getKind() != lltok::kw_bitcast &&
1027 Lex.getKind() != lltok::kw_getelementptr &&
1028 Lex.getKind() != lltok::kw_addrspacecast &&
1029 Lex.getKind() != lltok::kw_inttoptr) {
1030 if (parseGlobalTypeAndValue(Aliasee))
1031 return true;
1032 } else {
1033 // The bitcast dest type is not present, it is implied by the dest type.
1034 ValID ID;
1035 if (parseValID(ID, /*PFS=*/nullptr))
1036 return true;
1037 if (ID.Kind != ValID::t_Constant)
1038 return error(AliaseeLoc, "invalid aliasee");
1039 Aliasee = ID.ConstantVal;
1042 Type *AliaseeType = Aliasee->getType();
1043 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1044 if (!PTy)
1045 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1046 unsigned AddrSpace = PTy->getAddressSpace();
1048 GlobalValue *GVal = nullptr;
1050 // See if the alias was forward referenced, if so, prepare to replace the
1051 // forward reference.
1052 if (!Name.empty()) {
1053 auto I = ForwardRefVals.find(Name);
1054 if (I != ForwardRefVals.end()) {
1055 GVal = I->second.first;
1056 ForwardRefVals.erase(Name);
1057 } else if (M->getNamedValue(Name)) {
1058 return error(NameLoc, "redefinition of global '@" + Name + "'");
1060 } else {
1061 auto I = ForwardRefValIDs.find(NumberedVals.size());
1062 if (I != ForwardRefValIDs.end()) {
1063 GVal = I->second.first;
1064 ForwardRefValIDs.erase(I);
1068 // Okay, create the alias/ifunc but do not insert it into the module yet.
1069 std::unique_ptr<GlobalAlias> GA;
1070 std::unique_ptr<GlobalIFunc> GI;
1071 GlobalValue *GV;
1072 if (IsAlias) {
1073 GA.reset(GlobalAlias::create(Ty, AddrSpace,
1074 (GlobalValue::LinkageTypes)Linkage, Name,
1075 Aliasee, /*Parent*/ nullptr));
1076 GV = GA.get();
1077 } else {
1078 GI.reset(GlobalIFunc::create(Ty, AddrSpace,
1079 (GlobalValue::LinkageTypes)Linkage, Name,
1080 Aliasee, /*Parent*/ nullptr));
1081 GV = GI.get();
1083 GV->setThreadLocalMode(TLM);
1084 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1085 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1086 GV->setUnnamedAddr(UnnamedAddr);
1087 maybeSetDSOLocal(DSOLocal, *GV);
1089 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1090 // Now parse them if there are any.
1091 while (Lex.getKind() == lltok::comma) {
1092 Lex.Lex();
1094 if (Lex.getKind() == lltok::kw_partition) {
1095 Lex.Lex();
1096 GV->setPartition(Lex.getStrVal());
1097 if (parseToken(lltok::StringConstant, "expected partition string"))
1098 return true;
1099 } else {
1100 return tokError("unknown alias or ifunc property!");
1104 if (Name.empty())
1105 NumberedVals.push_back(GV);
1107 if (GVal) {
1108 // Verify that types agree.
1109 if (GVal->getType() != GV->getType())
1110 return error(
1111 ExplicitTypeLoc,
1112 "forward reference and definition of alias have different types");
1114 // If they agree, just RAUW the old value with the alias and remove the
1115 // forward ref info.
1116 GVal->replaceAllUsesWith(GV);
1117 GVal->eraseFromParent();
1120 // Insert into the module, we know its name won't collide now.
1121 if (IsAlias)
1122 M->insertAlias(GA.release());
1123 else
1124 M->insertIFunc(GI.release());
1125 assert(GV->getName() == Name && "Should not be a name conflict!");
1127 return false;
1130 static bool isSanitizer(lltok::Kind Kind) {
1131 switch (Kind) {
1132 case lltok::kw_no_sanitize_address:
1133 case lltok::kw_no_sanitize_hwaddress:
1134 case lltok::kw_sanitize_memtag:
1135 case lltok::kw_sanitize_address_dyninit:
1136 return true;
1137 default:
1138 return false;
1142 bool LLParser::parseSanitizer(GlobalVariable *GV) {
1143 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1144 SanitizerMetadata Meta;
1145 if (GV->hasSanitizerMetadata())
1146 Meta = GV->getSanitizerMetadata();
1148 switch (Lex.getKind()) {
1149 case lltok::kw_no_sanitize_address:
1150 Meta.NoAddress = true;
1151 break;
1152 case lltok::kw_no_sanitize_hwaddress:
1153 Meta.NoHWAddress = true;
1154 break;
1155 case lltok::kw_sanitize_memtag:
1156 Meta.Memtag = true;
1157 break;
1158 case lltok::kw_sanitize_address_dyninit:
1159 Meta.IsDynInit = true;
1160 break;
1161 default:
1162 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1164 GV->setSanitizerMetadata(Meta);
1165 Lex.Lex();
1166 return false;
1169 /// parseGlobal
1170 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1171 /// OptionalVisibility OptionalDLLStorageClass
1172 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1173 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1174 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1175 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1176 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1177 /// Const OptionalAttrs
1179 /// Everything up to and including OptionalUnnamedAddr has been parsed
1180 /// already.
1182 bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1183 unsigned Linkage, bool HasLinkage,
1184 unsigned Visibility, unsigned DLLStorageClass,
1185 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1186 GlobalVariable::UnnamedAddr UnnamedAddr) {
1187 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1188 return error(NameLoc,
1189 "symbol with local linkage must have default visibility");
1191 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
1192 return error(NameLoc,
1193 "symbol with local linkage cannot have a DLL storage class");
1195 unsigned AddrSpace;
1196 bool IsConstant, IsExternallyInitialized;
1197 LocTy IsExternallyInitializedLoc;
1198 LocTy TyLoc;
1200 Type *Ty = nullptr;
1201 if (parseOptionalAddrSpace(AddrSpace) ||
1202 parseOptionalToken(lltok::kw_externally_initialized,
1203 IsExternallyInitialized,
1204 &IsExternallyInitializedLoc) ||
1205 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1206 return true;
1208 // If the linkage is specified and is external, then no initializer is
1209 // present.
1210 Constant *Init = nullptr;
1211 if (!HasLinkage ||
1212 !GlobalValue::isValidDeclarationLinkage(
1213 (GlobalValue::LinkageTypes)Linkage)) {
1214 if (parseGlobalValue(Ty, Init))
1215 return true;
1218 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1219 return error(TyLoc, "invalid type for global variable");
1221 GlobalValue *GVal = nullptr;
1223 // See if the global was forward referenced, if so, use the global.
1224 if (!Name.empty()) {
1225 auto I = ForwardRefVals.find(Name);
1226 if (I != ForwardRefVals.end()) {
1227 GVal = I->second.first;
1228 ForwardRefVals.erase(I);
1229 } else if (M->getNamedValue(Name)) {
1230 return error(NameLoc, "redefinition of global '@" + Name + "'");
1232 } else {
1233 auto I = ForwardRefValIDs.find(NumberedVals.size());
1234 if (I != ForwardRefValIDs.end()) {
1235 GVal = I->second.first;
1236 ForwardRefValIDs.erase(I);
1240 GlobalVariable *GV = new GlobalVariable(
1241 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1242 GlobalVariable::NotThreadLocal, AddrSpace);
1244 if (Name.empty())
1245 NumberedVals.push_back(GV);
1247 // Set the parsed properties on the global.
1248 if (Init)
1249 GV->setInitializer(Init);
1250 GV->setConstant(IsConstant);
1251 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1252 maybeSetDSOLocal(DSOLocal, *GV);
1253 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1254 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1255 GV->setExternallyInitialized(IsExternallyInitialized);
1256 GV->setThreadLocalMode(TLM);
1257 GV->setUnnamedAddr(UnnamedAddr);
1259 if (GVal) {
1260 if (GVal->getAddressSpace() != AddrSpace)
1261 return error(
1262 TyLoc,
1263 "forward reference and definition of global have different types");
1265 GVal->replaceAllUsesWith(GV);
1266 GVal->eraseFromParent();
1269 // parse attributes on the global.
1270 while (Lex.getKind() == lltok::comma) {
1271 Lex.Lex();
1273 if (Lex.getKind() == lltok::kw_section) {
1274 Lex.Lex();
1275 GV->setSection(Lex.getStrVal());
1276 if (parseToken(lltok::StringConstant, "expected global section string"))
1277 return true;
1278 } else if (Lex.getKind() == lltok::kw_partition) {
1279 Lex.Lex();
1280 GV->setPartition(Lex.getStrVal());
1281 if (parseToken(lltok::StringConstant, "expected partition string"))
1282 return true;
1283 } else if (Lex.getKind() == lltok::kw_align) {
1284 MaybeAlign Alignment;
1285 if (parseOptionalAlignment(Alignment))
1286 return true;
1287 if (Alignment)
1288 GV->setAlignment(*Alignment);
1289 } else if (Lex.getKind() == lltok::MetadataVar) {
1290 if (parseGlobalObjectMetadataAttachment(*GV))
1291 return true;
1292 } else if (isSanitizer(Lex.getKind())) {
1293 if (parseSanitizer(GV))
1294 return true;
1295 } else {
1296 Comdat *C;
1297 if (parseOptionalComdat(Name, C))
1298 return true;
1299 if (C)
1300 GV->setComdat(C);
1301 else
1302 return tokError("unknown global variable property!");
1306 AttrBuilder Attrs(M->getContext());
1307 LocTy BuiltinLoc;
1308 std::vector<unsigned> FwdRefAttrGrps;
1309 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1310 return true;
1311 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1312 GV->setAttributes(AttributeSet::get(Context, Attrs));
1313 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1316 return false;
1319 /// parseUnnamedAttrGrp
1320 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1321 bool LLParser::parseUnnamedAttrGrp() {
1322 assert(Lex.getKind() == lltok::kw_attributes);
1323 LocTy AttrGrpLoc = Lex.getLoc();
1324 Lex.Lex();
1326 if (Lex.getKind() != lltok::AttrGrpID)
1327 return tokError("expected attribute group id");
1329 unsigned VarID = Lex.getUIntVal();
1330 std::vector<unsigned> unused;
1331 LocTy BuiltinLoc;
1332 Lex.Lex();
1334 if (parseToken(lltok::equal, "expected '=' here") ||
1335 parseToken(lltok::lbrace, "expected '{' here"))
1336 return true;
1338 auto R = NumberedAttrBuilders.find(VarID);
1339 if (R == NumberedAttrBuilders.end())
1340 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1342 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1343 parseToken(lltok::rbrace, "expected end of attribute group"))
1344 return true;
1346 if (!R->second.hasAttributes())
1347 return error(AttrGrpLoc, "attribute group has no attributes");
1349 return false;
1352 static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) {
1353 switch (Kind) {
1354 #define GET_ATTR_NAMES
1355 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1356 case lltok::kw_##DISPLAY_NAME: \
1357 return Attribute::ENUM_NAME;
1358 #include "llvm/IR/Attributes.inc"
1359 default:
1360 return Attribute::None;
1364 bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1365 bool InAttrGroup) {
1366 if (Attribute::isTypeAttrKind(Attr))
1367 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1369 switch (Attr) {
1370 case Attribute::Alignment: {
1371 MaybeAlign Alignment;
1372 if (InAttrGroup) {
1373 uint32_t Value = 0;
1374 Lex.Lex();
1375 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1376 return true;
1377 Alignment = Align(Value);
1378 } else {
1379 if (parseOptionalAlignment(Alignment, true))
1380 return true;
1382 B.addAlignmentAttr(Alignment);
1383 return false;
1385 case Attribute::StackAlignment: {
1386 unsigned Alignment;
1387 if (InAttrGroup) {
1388 Lex.Lex();
1389 if (parseToken(lltok::equal, "expected '=' here") ||
1390 parseUInt32(Alignment))
1391 return true;
1392 } else {
1393 if (parseOptionalStackAlignment(Alignment))
1394 return true;
1396 B.addStackAlignmentAttr(Alignment);
1397 return false;
1399 case Attribute::AllocSize: {
1400 unsigned ElemSizeArg;
1401 std::optional<unsigned> NumElemsArg;
1402 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1403 return true;
1404 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1405 return false;
1407 case Attribute::VScaleRange: {
1408 unsigned MinValue, MaxValue;
1409 if (parseVScaleRangeArguments(MinValue, MaxValue))
1410 return true;
1411 B.addVScaleRangeAttr(MinValue,
1412 MaxValue > 0 ? MaxValue : std::optional<unsigned>());
1413 return false;
1415 case Attribute::Dereferenceable: {
1416 uint64_t Bytes;
1417 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1418 return true;
1419 B.addDereferenceableAttr(Bytes);
1420 return false;
1422 case Attribute::DereferenceableOrNull: {
1423 uint64_t Bytes;
1424 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1425 return true;
1426 B.addDereferenceableOrNullAttr(Bytes);
1427 return false;
1429 case Attribute::UWTable: {
1430 UWTableKind Kind;
1431 if (parseOptionalUWTableKind(Kind))
1432 return true;
1433 B.addUWTableAttr(Kind);
1434 return false;
1436 case Attribute::AllocKind: {
1437 AllocFnKind Kind = AllocFnKind::Unknown;
1438 if (parseAllocKind(Kind))
1439 return true;
1440 B.addAllocKindAttr(Kind);
1441 return false;
1443 case Attribute::Memory: {
1444 std::optional<MemoryEffects> ME = parseMemoryAttr();
1445 if (!ME)
1446 return true;
1447 B.addMemoryAttr(*ME);
1448 return false;
1450 case Attribute::NoFPClass: {
1451 if (FPClassTest NoFPClass =
1452 static_cast<FPClassTest>(parseNoFPClassAttr())) {
1453 B.addNoFPClassAttr(NoFPClass);
1454 return false;
1457 return true;
1459 default:
1460 B.addAttribute(Attr);
1461 Lex.Lex();
1462 return false;
1466 static bool upgradeMemoryAttr(MemoryEffects &ME, lltok::Kind Kind) {
1467 switch (Kind) {
1468 case lltok::kw_readnone:
1469 ME &= MemoryEffects::none();
1470 return true;
1471 case lltok::kw_readonly:
1472 ME &= MemoryEffects::readOnly();
1473 return true;
1474 case lltok::kw_writeonly:
1475 ME &= MemoryEffects::writeOnly();
1476 return true;
1477 case lltok::kw_argmemonly:
1478 ME &= MemoryEffects::argMemOnly();
1479 return true;
1480 case lltok::kw_inaccessiblememonly:
1481 ME &= MemoryEffects::inaccessibleMemOnly();
1482 return true;
1483 case lltok::kw_inaccessiblemem_or_argmemonly:
1484 ME &= MemoryEffects::inaccessibleOrArgMemOnly();
1485 return true;
1486 default:
1487 return false;
1491 /// parseFnAttributeValuePairs
1492 /// ::= <attr> | <attr> '=' <value>
1493 bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1494 std::vector<unsigned> &FwdRefAttrGrps,
1495 bool InAttrGrp, LocTy &BuiltinLoc) {
1496 bool HaveError = false;
1498 B.clear();
1500 MemoryEffects ME = MemoryEffects::unknown();
1501 while (true) {
1502 lltok::Kind Token = Lex.getKind();
1503 if (Token == lltok::rbrace)
1504 break; // Finished.
1506 if (Token == lltok::StringConstant) {
1507 if (parseStringAttribute(B))
1508 return true;
1509 continue;
1512 if (Token == lltok::AttrGrpID) {
1513 // Allow a function to reference an attribute group:
1515 // define void @foo() #1 { ... }
1516 if (InAttrGrp) {
1517 HaveError |= error(
1518 Lex.getLoc(),
1519 "cannot have an attribute group reference in an attribute group");
1520 } else {
1521 // Save the reference to the attribute group. We'll fill it in later.
1522 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1524 Lex.Lex();
1525 continue;
1528 SMLoc Loc = Lex.getLoc();
1529 if (Token == lltok::kw_builtin)
1530 BuiltinLoc = Loc;
1532 if (upgradeMemoryAttr(ME, Token)) {
1533 Lex.Lex();
1534 continue;
1537 Attribute::AttrKind Attr = tokenToAttribute(Token);
1538 if (Attr == Attribute::None) {
1539 if (!InAttrGrp)
1540 break;
1541 return error(Lex.getLoc(), "unterminated attribute group");
1544 if (parseEnumAttribute(Attr, B, InAttrGrp))
1545 return true;
1547 // As a hack, we allow function alignment to be initially parsed as an
1548 // attribute on a function declaration/definition or added to an attribute
1549 // group and later moved to the alignment field.
1550 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1551 HaveError |= error(Loc, "this attribute does not apply to functions");
1554 if (ME != MemoryEffects::unknown())
1555 B.addMemoryAttr(ME);
1556 return HaveError;
1559 //===----------------------------------------------------------------------===//
1560 // GlobalValue Reference/Resolution Routines.
1561 //===----------------------------------------------------------------------===//
1563 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) {
1564 // The used global type does not matter. We will later RAUW it with a
1565 // global/function of the correct type.
1566 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1567 GlobalValue::ExternalWeakLinkage, nullptr, "",
1568 nullptr, GlobalVariable::NotThreadLocal,
1569 PTy->getAddressSpace());
1572 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1573 Value *Val) {
1574 Type *ValTy = Val->getType();
1575 if (ValTy == Ty)
1576 return Val;
1577 if (Ty->isLabelTy())
1578 error(Loc, "'" + Name + "' is not a basic block");
1579 else
1580 error(Loc, "'" + Name + "' defined with type '" +
1581 getTypeString(Val->getType()) + "' but expected '" +
1582 getTypeString(Ty) + "'");
1583 return nullptr;
1586 /// getGlobalVal - Get a value with the specified name or ID, creating a
1587 /// forward reference record if needed. This can return null if the value
1588 /// exists but does not have the right type.
1589 GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1590 LocTy Loc) {
1591 PointerType *PTy = dyn_cast<PointerType>(Ty);
1592 if (!PTy) {
1593 error(Loc, "global variable reference must have pointer type");
1594 return nullptr;
1597 // Look this name up in the normal function symbol table.
1598 GlobalValue *Val =
1599 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1601 // If this is a forward reference for the value, see if we already created a
1602 // forward ref record.
1603 if (!Val) {
1604 auto I = ForwardRefVals.find(Name);
1605 if (I != ForwardRefVals.end())
1606 Val = I->second.first;
1609 // If we have the value in the symbol table or fwd-ref table, return it.
1610 if (Val)
1611 return cast_or_null<GlobalValue>(
1612 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1614 // Otherwise, create a new forward reference for this value and remember it.
1615 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1616 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1617 return FwdVal;
1620 GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1621 PointerType *PTy = dyn_cast<PointerType>(Ty);
1622 if (!PTy) {
1623 error(Loc, "global variable reference must have pointer type");
1624 return nullptr;
1627 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1629 // If this is a forward reference for the value, see if we already created a
1630 // forward ref record.
1631 if (!Val) {
1632 auto I = ForwardRefValIDs.find(ID);
1633 if (I != ForwardRefValIDs.end())
1634 Val = I->second.first;
1637 // If we have the value in the symbol table or fwd-ref table, return it.
1638 if (Val)
1639 return cast_or_null<GlobalValue>(
1640 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1642 // Otherwise, create a new forward reference for this value and remember it.
1643 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1644 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1645 return FwdVal;
1648 //===----------------------------------------------------------------------===//
1649 // Comdat Reference/Resolution Routines.
1650 //===----------------------------------------------------------------------===//
1652 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1653 // Look this name up in the comdat symbol table.
1654 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1655 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1656 if (I != ComdatSymTab.end())
1657 return &I->second;
1659 // Otherwise, create a new forward reference for this value and remember it.
1660 Comdat *C = M->getOrInsertComdat(Name);
1661 ForwardRefComdats[Name] = Loc;
1662 return C;
1665 //===----------------------------------------------------------------------===//
1666 // Helper Routines.
1667 //===----------------------------------------------------------------------===//
1669 /// parseToken - If the current token has the specified kind, eat it and return
1670 /// success. Otherwise, emit the specified error and return failure.
1671 bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1672 if (Lex.getKind() != T)
1673 return tokError(ErrMsg);
1674 Lex.Lex();
1675 return false;
1678 /// parseStringConstant
1679 /// ::= StringConstant
1680 bool LLParser::parseStringConstant(std::string &Result) {
1681 if (Lex.getKind() != lltok::StringConstant)
1682 return tokError("expected string constant");
1683 Result = Lex.getStrVal();
1684 Lex.Lex();
1685 return false;
1688 /// parseUInt32
1689 /// ::= uint32
1690 bool LLParser::parseUInt32(uint32_t &Val) {
1691 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1692 return tokError("expected integer");
1693 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1694 if (Val64 != unsigned(Val64))
1695 return tokError("expected 32-bit integer (too large)");
1696 Val = Val64;
1697 Lex.Lex();
1698 return false;
1701 /// parseUInt64
1702 /// ::= uint64
1703 bool LLParser::parseUInt64(uint64_t &Val) {
1704 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1705 return tokError("expected integer");
1706 Val = Lex.getAPSIntVal().getLimitedValue();
1707 Lex.Lex();
1708 return false;
1711 /// parseTLSModel
1712 /// := 'localdynamic'
1713 /// := 'initialexec'
1714 /// := 'localexec'
1715 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1716 switch (Lex.getKind()) {
1717 default:
1718 return tokError("expected localdynamic, initialexec or localexec");
1719 case lltok::kw_localdynamic:
1720 TLM = GlobalVariable::LocalDynamicTLSModel;
1721 break;
1722 case lltok::kw_initialexec:
1723 TLM = GlobalVariable::InitialExecTLSModel;
1724 break;
1725 case lltok::kw_localexec:
1726 TLM = GlobalVariable::LocalExecTLSModel;
1727 break;
1730 Lex.Lex();
1731 return false;
1734 /// parseOptionalThreadLocal
1735 /// := /*empty*/
1736 /// := 'thread_local'
1737 /// := 'thread_local' '(' tlsmodel ')'
1738 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1739 TLM = GlobalVariable::NotThreadLocal;
1740 if (!EatIfPresent(lltok::kw_thread_local))
1741 return false;
1743 TLM = GlobalVariable::GeneralDynamicTLSModel;
1744 if (Lex.getKind() == lltok::lparen) {
1745 Lex.Lex();
1746 return parseTLSModel(TLM) ||
1747 parseToken(lltok::rparen, "expected ')' after thread local model");
1749 return false;
1752 /// parseOptionalAddrSpace
1753 /// := /*empty*/
1754 /// := 'addrspace' '(' uint32 ')'
1755 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1756 AddrSpace = DefaultAS;
1757 if (!EatIfPresent(lltok::kw_addrspace))
1758 return false;
1760 auto ParseAddrspaceValue = [&](unsigned &AddrSpace) -> bool {
1761 if (Lex.getKind() == lltok::StringConstant) {
1762 auto AddrSpaceStr = Lex.getStrVal();
1763 if (AddrSpaceStr == "A") {
1764 AddrSpace = M->getDataLayout().getAllocaAddrSpace();
1765 } else if (AddrSpaceStr == "G") {
1766 AddrSpace = M->getDataLayout().getDefaultGlobalsAddressSpace();
1767 } else if (AddrSpaceStr == "P") {
1768 AddrSpace = M->getDataLayout().getProgramAddressSpace();
1769 } else {
1770 return tokError("invalid symbolic addrspace '" + AddrSpaceStr + "'");
1772 Lex.Lex();
1773 return false;
1775 if (Lex.getKind() != lltok::APSInt)
1776 return tokError("expected integer or string constant");
1777 SMLoc Loc = Lex.getLoc();
1778 if (parseUInt32(AddrSpace))
1779 return true;
1780 if (!isUInt<24>(AddrSpace))
1781 return error(Loc, "invalid address space, must be a 24-bit integer");
1782 return false;
1785 return parseToken(lltok::lparen, "expected '(' in address space") ||
1786 ParseAddrspaceValue(AddrSpace) ||
1787 parseToken(lltok::rparen, "expected ')' in address space");
1790 /// parseStringAttribute
1791 /// := StringConstant
1792 /// := StringConstant '=' StringConstant
1793 bool LLParser::parseStringAttribute(AttrBuilder &B) {
1794 std::string Attr = Lex.getStrVal();
1795 Lex.Lex();
1796 std::string Val;
1797 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1798 return true;
1799 B.addAttribute(Attr, Val);
1800 return false;
1803 /// Parse a potentially empty list of parameter or return attributes.
1804 bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1805 bool HaveError = false;
1807 B.clear();
1809 while (true) {
1810 lltok::Kind Token = Lex.getKind();
1811 if (Token == lltok::StringConstant) {
1812 if (parseStringAttribute(B))
1813 return true;
1814 continue;
1817 SMLoc Loc = Lex.getLoc();
1818 Attribute::AttrKind Attr = tokenToAttribute(Token);
1819 if (Attr == Attribute::None)
1820 return HaveError;
1822 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
1823 return true;
1825 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
1826 HaveError |= error(Loc, "this attribute does not apply to parameters");
1827 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
1828 HaveError |= error(Loc, "this attribute does not apply to return values");
1832 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1833 HasLinkage = true;
1834 switch (Kind) {
1835 default:
1836 HasLinkage = false;
1837 return GlobalValue::ExternalLinkage;
1838 case lltok::kw_private:
1839 return GlobalValue::PrivateLinkage;
1840 case lltok::kw_internal:
1841 return GlobalValue::InternalLinkage;
1842 case lltok::kw_weak:
1843 return GlobalValue::WeakAnyLinkage;
1844 case lltok::kw_weak_odr:
1845 return GlobalValue::WeakODRLinkage;
1846 case lltok::kw_linkonce:
1847 return GlobalValue::LinkOnceAnyLinkage;
1848 case lltok::kw_linkonce_odr:
1849 return GlobalValue::LinkOnceODRLinkage;
1850 case lltok::kw_available_externally:
1851 return GlobalValue::AvailableExternallyLinkage;
1852 case lltok::kw_appending:
1853 return GlobalValue::AppendingLinkage;
1854 case lltok::kw_common:
1855 return GlobalValue::CommonLinkage;
1856 case lltok::kw_extern_weak:
1857 return GlobalValue::ExternalWeakLinkage;
1858 case lltok::kw_external:
1859 return GlobalValue::ExternalLinkage;
1863 /// parseOptionalLinkage
1864 /// ::= /*empty*/
1865 /// ::= 'private'
1866 /// ::= 'internal'
1867 /// ::= 'weak'
1868 /// ::= 'weak_odr'
1869 /// ::= 'linkonce'
1870 /// ::= 'linkonce_odr'
1871 /// ::= 'available_externally'
1872 /// ::= 'appending'
1873 /// ::= 'common'
1874 /// ::= 'extern_weak'
1875 /// ::= 'external'
1876 bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1877 unsigned &Visibility,
1878 unsigned &DLLStorageClass, bool &DSOLocal) {
1879 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1880 if (HasLinkage)
1881 Lex.Lex();
1882 parseOptionalDSOLocal(DSOLocal);
1883 parseOptionalVisibility(Visibility);
1884 parseOptionalDLLStorageClass(DLLStorageClass);
1886 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1887 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1890 return false;
1893 void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
1894 switch (Lex.getKind()) {
1895 default:
1896 DSOLocal = false;
1897 break;
1898 case lltok::kw_dso_local:
1899 DSOLocal = true;
1900 Lex.Lex();
1901 break;
1902 case lltok::kw_dso_preemptable:
1903 DSOLocal = false;
1904 Lex.Lex();
1905 break;
1909 /// parseOptionalVisibility
1910 /// ::= /*empty*/
1911 /// ::= 'default'
1912 /// ::= 'hidden'
1913 /// ::= 'protected'
1915 void LLParser::parseOptionalVisibility(unsigned &Res) {
1916 switch (Lex.getKind()) {
1917 default:
1918 Res = GlobalValue::DefaultVisibility;
1919 return;
1920 case lltok::kw_default:
1921 Res = GlobalValue::DefaultVisibility;
1922 break;
1923 case lltok::kw_hidden:
1924 Res = GlobalValue::HiddenVisibility;
1925 break;
1926 case lltok::kw_protected:
1927 Res = GlobalValue::ProtectedVisibility;
1928 break;
1930 Lex.Lex();
1933 /// parseOptionalDLLStorageClass
1934 /// ::= /*empty*/
1935 /// ::= 'dllimport'
1936 /// ::= 'dllexport'
1938 void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
1939 switch (Lex.getKind()) {
1940 default:
1941 Res = GlobalValue::DefaultStorageClass;
1942 return;
1943 case lltok::kw_dllimport:
1944 Res = GlobalValue::DLLImportStorageClass;
1945 break;
1946 case lltok::kw_dllexport:
1947 Res = GlobalValue::DLLExportStorageClass;
1948 break;
1950 Lex.Lex();
1953 /// parseOptionalCallingConv
1954 /// ::= /*empty*/
1955 /// ::= 'ccc'
1956 /// ::= 'fastcc'
1957 /// ::= 'intel_ocl_bicc'
1958 /// ::= 'coldcc'
1959 /// ::= 'cfguard_checkcc'
1960 /// ::= 'x86_stdcallcc'
1961 /// ::= 'x86_fastcallcc'
1962 /// ::= 'x86_thiscallcc'
1963 /// ::= 'x86_vectorcallcc'
1964 /// ::= 'arm_apcscc'
1965 /// ::= 'arm_aapcscc'
1966 /// ::= 'arm_aapcs_vfpcc'
1967 /// ::= 'aarch64_vector_pcs'
1968 /// ::= 'aarch64_sve_vector_pcs'
1969 /// ::= 'aarch64_sme_preservemost_from_x0'
1970 /// ::= 'aarch64_sme_preservemost_from_x2'
1971 /// ::= 'msp430_intrcc'
1972 /// ::= 'avr_intrcc'
1973 /// ::= 'avr_signalcc'
1974 /// ::= 'ptx_kernel'
1975 /// ::= 'ptx_device'
1976 /// ::= 'spir_func'
1977 /// ::= 'spir_kernel'
1978 /// ::= 'x86_64_sysvcc'
1979 /// ::= 'win64cc'
1980 /// ::= 'webkit_jscc'
1981 /// ::= 'anyregcc'
1982 /// ::= 'preserve_mostcc'
1983 /// ::= 'preserve_allcc'
1984 /// ::= 'ghccc'
1985 /// ::= 'swiftcc'
1986 /// ::= 'swifttailcc'
1987 /// ::= 'x86_intrcc'
1988 /// ::= 'hhvmcc'
1989 /// ::= 'hhvm_ccc'
1990 /// ::= 'cxx_fast_tlscc'
1991 /// ::= 'amdgpu_vs'
1992 /// ::= 'amdgpu_ls'
1993 /// ::= 'amdgpu_hs'
1994 /// ::= 'amdgpu_es'
1995 /// ::= 'amdgpu_gs'
1996 /// ::= 'amdgpu_ps'
1997 /// ::= 'amdgpu_cs'
1998 /// ::= 'amdgpu_cs_chain'
1999 /// ::= 'amdgpu_cs_chain_preserve'
2000 /// ::= 'amdgpu_kernel'
2001 /// ::= 'tailcc'
2002 /// ::= 'm68k_rtdcc'
2003 /// ::= 'cc' UINT
2005 bool LLParser::parseOptionalCallingConv(unsigned &CC) {
2006 switch (Lex.getKind()) {
2007 default: CC = CallingConv::C; return false;
2008 case lltok::kw_ccc: CC = CallingConv::C; break;
2009 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
2010 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
2011 case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
2012 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
2013 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
2014 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
2015 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
2016 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
2017 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
2018 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
2019 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
2020 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
2021 case lltok::kw_aarch64_sve_vector_pcs:
2022 CC = CallingConv::AArch64_SVE_VectorCall;
2023 break;
2024 case lltok::kw_aarch64_sme_preservemost_from_x0:
2025 CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0;
2026 break;
2027 case lltok::kw_aarch64_sme_preservemost_from_x2:
2028 CC = CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2;
2029 break;
2030 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
2031 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
2032 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
2033 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
2034 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
2035 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
2036 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
2037 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
2038 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
2039 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
2040 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
2041 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
2042 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
2043 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
2044 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
2045 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
2046 case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; break;
2047 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
2048 case lltok::kw_hhvmcc:
2049 CC = CallingConv::DUMMY_HHVM;
2050 break;
2051 case lltok::kw_hhvm_ccc:
2052 CC = CallingConv::DUMMY_HHVM_C;
2053 break;
2054 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
2055 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
2056 case lltok::kw_amdgpu_gfx: CC = CallingConv::AMDGPU_Gfx; break;
2057 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
2058 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
2059 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
2060 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
2061 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
2062 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
2063 case lltok::kw_amdgpu_cs_chain:
2064 CC = CallingConv::AMDGPU_CS_Chain;
2065 break;
2066 case lltok::kw_amdgpu_cs_chain_preserve:
2067 CC = CallingConv::AMDGPU_CS_ChainPreserve;
2068 break;
2069 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
2070 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2071 case lltok::kw_m68k_rtdcc: CC = CallingConv::M68k_RTD; break;
2072 case lltok::kw_cc: {
2073 Lex.Lex();
2074 return parseUInt32(CC);
2078 Lex.Lex();
2079 return false;
2082 /// parseMetadataAttachment
2083 /// ::= !dbg !42
2084 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2085 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2087 std::string Name = Lex.getStrVal();
2088 Kind = M->getMDKindID(Name);
2089 Lex.Lex();
2091 return parseMDNode(MD);
2094 /// parseInstructionMetadata
2095 /// ::= !dbg !42 (',' !dbg !57)*
2096 bool LLParser::parseInstructionMetadata(Instruction &Inst) {
2097 do {
2098 if (Lex.getKind() != lltok::MetadataVar)
2099 return tokError("expected metadata after comma");
2101 unsigned MDK;
2102 MDNode *N;
2103 if (parseMetadataAttachment(MDK, N))
2104 return true;
2106 if (MDK == LLVMContext::MD_DIAssignID)
2107 TempDIAssignIDAttachments[N].push_back(&Inst);
2108 else
2109 Inst.setMetadata(MDK, N);
2111 if (MDK == LLVMContext::MD_tbaa)
2112 InstsWithTBAATag.push_back(&Inst);
2114 // If this is the end of the list, we're done.
2115 } while (EatIfPresent(lltok::comma));
2116 return false;
2119 /// parseGlobalObjectMetadataAttachment
2120 /// ::= !dbg !57
2121 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2122 unsigned MDK;
2123 MDNode *N;
2124 if (parseMetadataAttachment(MDK, N))
2125 return true;
2127 GO.addMetadata(MDK, *N);
2128 return false;
2131 /// parseOptionalFunctionMetadata
2132 /// ::= (!dbg !57)*
2133 bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2134 while (Lex.getKind() == lltok::MetadataVar)
2135 if (parseGlobalObjectMetadataAttachment(F))
2136 return true;
2137 return false;
2140 /// parseOptionalAlignment
2141 /// ::= /* empty */
2142 /// ::= 'align' 4
2143 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2144 Alignment = std::nullopt;
2145 if (!EatIfPresent(lltok::kw_align))
2146 return false;
2147 LocTy AlignLoc = Lex.getLoc();
2148 uint64_t Value = 0;
2150 LocTy ParenLoc = Lex.getLoc();
2151 bool HaveParens = false;
2152 if (AllowParens) {
2153 if (EatIfPresent(lltok::lparen))
2154 HaveParens = true;
2157 if (parseUInt64(Value))
2158 return true;
2160 if (HaveParens && !EatIfPresent(lltok::rparen))
2161 return error(ParenLoc, "expected ')'");
2163 if (!isPowerOf2_64(Value))
2164 return error(AlignLoc, "alignment is not a power of two");
2165 if (Value > Value::MaximumAlignment)
2166 return error(AlignLoc, "huge alignments are not supported yet");
2167 Alignment = Align(Value);
2168 return false;
2171 /// parseOptionalDerefAttrBytes
2172 /// ::= /* empty */
2173 /// ::= AttrKind '(' 4 ')'
2175 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2176 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2177 uint64_t &Bytes) {
2178 assert((AttrKind == lltok::kw_dereferenceable ||
2179 AttrKind == lltok::kw_dereferenceable_or_null) &&
2180 "contract!");
2182 Bytes = 0;
2183 if (!EatIfPresent(AttrKind))
2184 return false;
2185 LocTy ParenLoc = Lex.getLoc();
2186 if (!EatIfPresent(lltok::lparen))
2187 return error(ParenLoc, "expected '('");
2188 LocTy DerefLoc = Lex.getLoc();
2189 if (parseUInt64(Bytes))
2190 return true;
2191 ParenLoc = Lex.getLoc();
2192 if (!EatIfPresent(lltok::rparen))
2193 return error(ParenLoc, "expected ')'");
2194 if (!Bytes)
2195 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2196 return false;
2199 bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2200 Lex.Lex();
2201 Kind = UWTableKind::Default;
2202 if (!EatIfPresent(lltok::lparen))
2203 return false;
2204 LocTy KindLoc = Lex.getLoc();
2205 if (Lex.getKind() == lltok::kw_sync)
2206 Kind = UWTableKind::Sync;
2207 else if (Lex.getKind() == lltok::kw_async)
2208 Kind = UWTableKind::Async;
2209 else
2210 return error(KindLoc, "expected unwind table kind");
2211 Lex.Lex();
2212 return parseToken(lltok::rparen, "expected ')'");
2215 bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2216 Lex.Lex();
2217 LocTy ParenLoc = Lex.getLoc();
2218 if (!EatIfPresent(lltok::lparen))
2219 return error(ParenLoc, "expected '('");
2220 LocTy KindLoc = Lex.getLoc();
2221 std::string Arg;
2222 if (parseStringConstant(Arg))
2223 return error(KindLoc, "expected allockind value");
2224 for (StringRef A : llvm::split(Arg, ",")) {
2225 if (A == "alloc") {
2226 Kind |= AllocFnKind::Alloc;
2227 } else if (A == "realloc") {
2228 Kind |= AllocFnKind::Realloc;
2229 } else if (A == "free") {
2230 Kind |= AllocFnKind::Free;
2231 } else if (A == "uninitialized") {
2232 Kind |= AllocFnKind::Uninitialized;
2233 } else if (A == "zeroed") {
2234 Kind |= AllocFnKind::Zeroed;
2235 } else if (A == "aligned") {
2236 Kind |= AllocFnKind::Aligned;
2237 } else {
2238 return error(KindLoc, Twine("unknown allockind ") + A);
2241 ParenLoc = Lex.getLoc();
2242 if (!EatIfPresent(lltok::rparen))
2243 return error(ParenLoc, "expected ')'");
2244 if (Kind == AllocFnKind::Unknown)
2245 return error(KindLoc, "expected allockind value");
2246 return false;
2249 static std::optional<MemoryEffects::Location> keywordToLoc(lltok::Kind Tok) {
2250 switch (Tok) {
2251 case lltok::kw_argmem:
2252 return IRMemLocation::ArgMem;
2253 case lltok::kw_inaccessiblemem:
2254 return IRMemLocation::InaccessibleMem;
2255 default:
2256 return std::nullopt;
2260 static std::optional<ModRefInfo> keywordToModRef(lltok::Kind Tok) {
2261 switch (Tok) {
2262 case lltok::kw_none:
2263 return ModRefInfo::NoModRef;
2264 case lltok::kw_read:
2265 return ModRefInfo::Ref;
2266 case lltok::kw_write:
2267 return ModRefInfo::Mod;
2268 case lltok::kw_readwrite:
2269 return ModRefInfo::ModRef;
2270 default:
2271 return std::nullopt;
2275 std::optional<MemoryEffects> LLParser::parseMemoryAttr() {
2276 MemoryEffects ME = MemoryEffects::none();
2278 // We use syntax like memory(argmem: read), so the colon should not be
2279 // interpreted as a label terminator.
2280 Lex.setIgnoreColonInIdentifiers(true);
2281 auto _ = make_scope_exit([&] { Lex.setIgnoreColonInIdentifiers(false); });
2283 Lex.Lex();
2284 if (!EatIfPresent(lltok::lparen)) {
2285 tokError("expected '('");
2286 return std::nullopt;
2289 bool SeenLoc = false;
2290 do {
2291 std::optional<IRMemLocation> Loc = keywordToLoc(Lex.getKind());
2292 if (Loc) {
2293 Lex.Lex();
2294 if (!EatIfPresent(lltok::colon)) {
2295 tokError("expected ':' after location");
2296 return std::nullopt;
2300 std::optional<ModRefInfo> MR = keywordToModRef(Lex.getKind());
2301 if (!MR) {
2302 if (!Loc)
2303 tokError("expected memory location (argmem, inaccessiblemem) "
2304 "or access kind (none, read, write, readwrite)");
2305 else
2306 tokError("expected access kind (none, read, write, readwrite)");
2307 return std::nullopt;
2310 Lex.Lex();
2311 if (Loc) {
2312 SeenLoc = true;
2313 ME = ME.getWithModRef(*Loc, *MR);
2314 } else {
2315 if (SeenLoc) {
2316 tokError("default access kind must be specified first");
2317 return std::nullopt;
2319 ME = MemoryEffects(*MR);
2322 if (EatIfPresent(lltok::rparen))
2323 return ME;
2324 } while (EatIfPresent(lltok::comma));
2326 tokError("unterminated memory attribute");
2327 return std::nullopt;
2330 static unsigned keywordToFPClassTest(lltok::Kind Tok) {
2331 switch (Tok) {
2332 case lltok::kw_all:
2333 return fcAllFlags;
2334 case lltok::kw_nan:
2335 return fcNan;
2336 case lltok::kw_snan:
2337 return fcSNan;
2338 case lltok::kw_qnan:
2339 return fcQNan;
2340 case lltok::kw_inf:
2341 return fcInf;
2342 case lltok::kw_ninf:
2343 return fcNegInf;
2344 case lltok::kw_pinf:
2345 return fcPosInf;
2346 case lltok::kw_norm:
2347 return fcNormal;
2348 case lltok::kw_nnorm:
2349 return fcNegNormal;
2350 case lltok::kw_pnorm:
2351 return fcPosNormal;
2352 case lltok::kw_sub:
2353 return fcSubnormal;
2354 case lltok::kw_nsub:
2355 return fcNegSubnormal;
2356 case lltok::kw_psub:
2357 return fcPosSubnormal;
2358 case lltok::kw_zero:
2359 return fcZero;
2360 case lltok::kw_nzero:
2361 return fcNegZero;
2362 case lltok::kw_pzero:
2363 return fcPosZero;
2364 default:
2365 return 0;
2369 unsigned LLParser::parseNoFPClassAttr() {
2370 unsigned Mask = fcNone;
2372 Lex.Lex();
2373 if (!EatIfPresent(lltok::lparen)) {
2374 tokError("expected '('");
2375 return 0;
2378 do {
2379 uint64_t Value = 0;
2380 unsigned TestMask = keywordToFPClassTest(Lex.getKind());
2381 if (TestMask != 0) {
2382 Mask |= TestMask;
2383 // TODO: Disallow overlapping masks to avoid copy paste errors
2384 } else if (Mask == 0 && Lex.getKind() == lltok::APSInt &&
2385 !parseUInt64(Value)) {
2386 if (Value == 0 || (Value & ~static_cast<unsigned>(fcAllFlags)) != 0) {
2387 error(Lex.getLoc(), "invalid mask value for 'nofpclass'");
2388 return 0;
2391 if (!EatIfPresent(lltok::rparen)) {
2392 error(Lex.getLoc(), "expected ')'");
2393 return 0;
2396 return Value;
2397 } else {
2398 error(Lex.getLoc(), "expected nofpclass test mask");
2399 return 0;
2402 Lex.Lex();
2403 if (EatIfPresent(lltok::rparen))
2404 return Mask;
2405 } while (1);
2407 llvm_unreachable("unterminated nofpclass attribute");
2410 /// parseOptionalCommaAlign
2411 /// ::=
2412 /// ::= ',' align 4
2414 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2415 /// end.
2416 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2417 bool &AteExtraComma) {
2418 AteExtraComma = false;
2419 while (EatIfPresent(lltok::comma)) {
2420 // Metadata at the end is an early exit.
2421 if (Lex.getKind() == lltok::MetadataVar) {
2422 AteExtraComma = true;
2423 return false;
2426 if (Lex.getKind() != lltok::kw_align)
2427 return error(Lex.getLoc(), "expected metadata or 'align'");
2429 if (parseOptionalAlignment(Alignment))
2430 return true;
2433 return false;
2436 /// parseOptionalCommaAddrSpace
2437 /// ::=
2438 /// ::= ',' addrspace(1)
2440 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2441 /// end.
2442 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2443 bool &AteExtraComma) {
2444 AteExtraComma = false;
2445 while (EatIfPresent(lltok::comma)) {
2446 // Metadata at the end is an early exit.
2447 if (Lex.getKind() == lltok::MetadataVar) {
2448 AteExtraComma = true;
2449 return false;
2452 Loc = Lex.getLoc();
2453 if (Lex.getKind() != lltok::kw_addrspace)
2454 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2456 if (parseOptionalAddrSpace(AddrSpace))
2457 return true;
2460 return false;
2463 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2464 std::optional<unsigned> &HowManyArg) {
2465 Lex.Lex();
2467 auto StartParen = Lex.getLoc();
2468 if (!EatIfPresent(lltok::lparen))
2469 return error(StartParen, "expected '('");
2471 if (parseUInt32(BaseSizeArg))
2472 return true;
2474 if (EatIfPresent(lltok::comma)) {
2475 auto HowManyAt = Lex.getLoc();
2476 unsigned HowMany;
2477 if (parseUInt32(HowMany))
2478 return true;
2479 if (HowMany == BaseSizeArg)
2480 return error(HowManyAt,
2481 "'allocsize' indices can't refer to the same parameter");
2482 HowManyArg = HowMany;
2483 } else
2484 HowManyArg = std::nullopt;
2486 auto EndParen = Lex.getLoc();
2487 if (!EatIfPresent(lltok::rparen))
2488 return error(EndParen, "expected ')'");
2489 return false;
2492 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2493 unsigned &MaxValue) {
2494 Lex.Lex();
2496 auto StartParen = Lex.getLoc();
2497 if (!EatIfPresent(lltok::lparen))
2498 return error(StartParen, "expected '('");
2500 if (parseUInt32(MinValue))
2501 return true;
2503 if (EatIfPresent(lltok::comma)) {
2504 if (parseUInt32(MaxValue))
2505 return true;
2506 } else
2507 MaxValue = MinValue;
2509 auto EndParen = Lex.getLoc();
2510 if (!EatIfPresent(lltok::rparen))
2511 return error(EndParen, "expected ')'");
2512 return false;
2515 /// parseScopeAndOrdering
2516 /// if isAtomic: ::= SyncScope? AtomicOrdering
2517 /// else: ::=
2519 /// This sets Scope and Ordering to the parsed values.
2520 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2521 AtomicOrdering &Ordering) {
2522 if (!IsAtomic)
2523 return false;
2525 return parseScope(SSID) || parseOrdering(Ordering);
2528 /// parseScope
2529 /// ::= syncscope("singlethread" | "<target scope>")?
2531 /// This sets synchronization scope ID to the ID of the parsed value.
2532 bool LLParser::parseScope(SyncScope::ID &SSID) {
2533 SSID = SyncScope::System;
2534 if (EatIfPresent(lltok::kw_syncscope)) {
2535 auto StartParenAt = Lex.getLoc();
2536 if (!EatIfPresent(lltok::lparen))
2537 return error(StartParenAt, "Expected '(' in syncscope");
2539 std::string SSN;
2540 auto SSNAt = Lex.getLoc();
2541 if (parseStringConstant(SSN))
2542 return error(SSNAt, "Expected synchronization scope name");
2544 auto EndParenAt = Lex.getLoc();
2545 if (!EatIfPresent(lltok::rparen))
2546 return error(EndParenAt, "Expected ')' in syncscope");
2548 SSID = Context.getOrInsertSyncScopeID(SSN);
2551 return false;
2554 /// parseOrdering
2555 /// ::= AtomicOrdering
2557 /// This sets Ordering to the parsed value.
2558 bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2559 switch (Lex.getKind()) {
2560 default:
2561 return tokError("Expected ordering on atomic instruction");
2562 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2563 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2564 // Not specified yet:
2565 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2566 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2567 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2568 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2569 case lltok::kw_seq_cst:
2570 Ordering = AtomicOrdering::SequentiallyConsistent;
2571 break;
2573 Lex.Lex();
2574 return false;
2577 /// parseOptionalStackAlignment
2578 /// ::= /* empty */
2579 /// ::= 'alignstack' '(' 4 ')'
2580 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2581 Alignment = 0;
2582 if (!EatIfPresent(lltok::kw_alignstack))
2583 return false;
2584 LocTy ParenLoc = Lex.getLoc();
2585 if (!EatIfPresent(lltok::lparen))
2586 return error(ParenLoc, "expected '('");
2587 LocTy AlignLoc = Lex.getLoc();
2588 if (parseUInt32(Alignment))
2589 return true;
2590 ParenLoc = Lex.getLoc();
2591 if (!EatIfPresent(lltok::rparen))
2592 return error(ParenLoc, "expected ')'");
2593 if (!isPowerOf2_32(Alignment))
2594 return error(AlignLoc, "stack alignment is not a power of two");
2595 return false;
2598 /// parseIndexList - This parses the index list for an insert/extractvalue
2599 /// instruction. This sets AteExtraComma in the case where we eat an extra
2600 /// comma at the end of the line and find that it is followed by metadata.
2601 /// Clients that don't allow metadata can call the version of this function that
2602 /// only takes one argument.
2604 /// parseIndexList
2605 /// ::= (',' uint32)+
2607 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2608 bool &AteExtraComma) {
2609 AteExtraComma = false;
2611 if (Lex.getKind() != lltok::comma)
2612 return tokError("expected ',' as start of index list");
2614 while (EatIfPresent(lltok::comma)) {
2615 if (Lex.getKind() == lltok::MetadataVar) {
2616 if (Indices.empty())
2617 return tokError("expected index");
2618 AteExtraComma = true;
2619 return false;
2621 unsigned Idx = 0;
2622 if (parseUInt32(Idx))
2623 return true;
2624 Indices.push_back(Idx);
2627 return false;
2630 //===----------------------------------------------------------------------===//
2631 // Type Parsing.
2632 //===----------------------------------------------------------------------===//
2634 /// parseType - parse a type.
2635 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2636 SMLoc TypeLoc = Lex.getLoc();
2637 switch (Lex.getKind()) {
2638 default:
2639 return tokError(Msg);
2640 case lltok::Type:
2641 // Type ::= 'float' | 'void' (etc)
2642 Result = Lex.getTyVal();
2643 Lex.Lex();
2645 // Handle "ptr" opaque pointer type.
2647 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2648 if (Result->isPointerTy()) {
2649 unsigned AddrSpace;
2650 if (parseOptionalAddrSpace(AddrSpace))
2651 return true;
2652 Result = PointerType::get(getContext(), AddrSpace);
2654 // Give a nice error for 'ptr*'.
2655 if (Lex.getKind() == lltok::star)
2656 return tokError("ptr* is invalid - use ptr instead");
2658 // Fall through to parsing the type suffixes only if this 'ptr' is a
2659 // function return. Otherwise, return success, implicitly rejecting other
2660 // suffixes.
2661 if (Lex.getKind() != lltok::lparen)
2662 return false;
2664 break;
2665 case lltok::kw_target: {
2666 // Type ::= TargetExtType
2667 if (parseTargetExtType(Result))
2668 return true;
2669 break;
2671 case lltok::lbrace:
2672 // Type ::= StructType
2673 if (parseAnonStructType(Result, false))
2674 return true;
2675 break;
2676 case lltok::lsquare:
2677 // Type ::= '[' ... ']'
2678 Lex.Lex(); // eat the lsquare.
2679 if (parseArrayVectorType(Result, false))
2680 return true;
2681 break;
2682 case lltok::less: // Either vector or packed struct.
2683 // Type ::= '<' ... '>'
2684 Lex.Lex();
2685 if (Lex.getKind() == lltok::lbrace) {
2686 if (parseAnonStructType(Result, true) ||
2687 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2688 return true;
2689 } else if (parseArrayVectorType(Result, true))
2690 return true;
2691 break;
2692 case lltok::LocalVar: {
2693 // Type ::= %foo
2694 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2696 // If the type hasn't been defined yet, create a forward definition and
2697 // remember where that forward def'n was seen (in case it never is defined).
2698 if (!Entry.first) {
2699 Entry.first = StructType::create(Context, Lex.getStrVal());
2700 Entry.second = Lex.getLoc();
2702 Result = Entry.first;
2703 Lex.Lex();
2704 break;
2707 case lltok::LocalVarID: {
2708 // Type ::= %4
2709 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2711 // If the type hasn't been defined yet, create a forward definition and
2712 // remember where that forward def'n was seen (in case it never is defined).
2713 if (!Entry.first) {
2714 Entry.first = StructType::create(Context);
2715 Entry.second = Lex.getLoc();
2717 Result = Entry.first;
2718 Lex.Lex();
2719 break;
2723 // parse the type suffixes.
2724 while (true) {
2725 switch (Lex.getKind()) {
2726 // End of type.
2727 default:
2728 if (!AllowVoid && Result->isVoidTy())
2729 return error(TypeLoc, "void type only allowed for function results");
2730 return false;
2732 // Type ::= Type '*'
2733 case lltok::star:
2734 if (Result->isLabelTy())
2735 return tokError("basic block pointers are invalid");
2736 if (Result->isVoidTy())
2737 return tokError("pointers to void are invalid - use i8* instead");
2738 if (!PointerType::isValidElementType(Result))
2739 return tokError("pointer to this type is invalid");
2740 Result = PointerType::getUnqual(Result);
2741 Lex.Lex();
2742 break;
2744 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2745 case lltok::kw_addrspace: {
2746 if (Result->isLabelTy())
2747 return tokError("basic block pointers are invalid");
2748 if (Result->isVoidTy())
2749 return tokError("pointers to void are invalid; use i8* instead");
2750 if (!PointerType::isValidElementType(Result))
2751 return tokError("pointer to this type is invalid");
2752 unsigned AddrSpace;
2753 if (parseOptionalAddrSpace(AddrSpace) ||
2754 parseToken(lltok::star, "expected '*' in address space"))
2755 return true;
2757 Result = PointerType::get(Result, AddrSpace);
2758 break;
2761 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2762 case lltok::lparen:
2763 if (parseFunctionType(Result))
2764 return true;
2765 break;
2770 /// parseParameterList
2771 /// ::= '(' ')'
2772 /// ::= '(' Arg (',' Arg)* ')'
2773 /// Arg
2774 /// ::= Type OptionalAttributes Value OptionalAttributes
2775 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2776 PerFunctionState &PFS, bool IsMustTailCall,
2777 bool InVarArgsFunc) {
2778 if (parseToken(lltok::lparen, "expected '(' in call"))
2779 return true;
2781 while (Lex.getKind() != lltok::rparen) {
2782 // If this isn't the first argument, we need a comma.
2783 if (!ArgList.empty() &&
2784 parseToken(lltok::comma, "expected ',' in argument list"))
2785 return true;
2787 // parse an ellipsis if this is a musttail call in a variadic function.
2788 if (Lex.getKind() == lltok::dotdotdot) {
2789 const char *Msg = "unexpected ellipsis in argument list for ";
2790 if (!IsMustTailCall)
2791 return tokError(Twine(Msg) + "non-musttail call");
2792 if (!InVarArgsFunc)
2793 return tokError(Twine(Msg) + "musttail call in non-varargs function");
2794 Lex.Lex(); // Lex the '...', it is purely for readability.
2795 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2798 // parse the argument.
2799 LocTy ArgLoc;
2800 Type *ArgTy = nullptr;
2801 Value *V;
2802 if (parseType(ArgTy, ArgLoc))
2803 return true;
2805 AttrBuilder ArgAttrs(M->getContext());
2807 if (ArgTy->isMetadataTy()) {
2808 if (parseMetadataAsValue(V, PFS))
2809 return true;
2810 } else {
2811 // Otherwise, handle normal operands.
2812 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2813 return true;
2815 ArgList.push_back(ParamInfo(
2816 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2819 if (IsMustTailCall && InVarArgsFunc)
2820 return tokError("expected '...' at end of argument list for musttail call "
2821 "in varargs function");
2823 Lex.Lex(); // Lex the ')'.
2824 return false;
2827 /// parseRequiredTypeAttr
2828 /// ::= attrname(<ty>)
2829 bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
2830 Attribute::AttrKind AttrKind) {
2831 Type *Ty = nullptr;
2832 if (!EatIfPresent(AttrToken))
2833 return true;
2834 if (!EatIfPresent(lltok::lparen))
2835 return error(Lex.getLoc(), "expected '('");
2836 if (parseType(Ty))
2837 return true;
2838 if (!EatIfPresent(lltok::rparen))
2839 return error(Lex.getLoc(), "expected ')'");
2841 B.addTypeAttr(AttrKind, Ty);
2842 return false;
2845 /// parseOptionalOperandBundles
2846 /// ::= /*empty*/
2847 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2849 /// OperandBundle
2850 /// ::= bundle-tag '(' ')'
2851 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2853 /// bundle-tag ::= String Constant
2854 bool LLParser::parseOptionalOperandBundles(
2855 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2856 LocTy BeginLoc = Lex.getLoc();
2857 if (!EatIfPresent(lltok::lsquare))
2858 return false;
2860 while (Lex.getKind() != lltok::rsquare) {
2861 // If this isn't the first operand bundle, we need a comma.
2862 if (!BundleList.empty() &&
2863 parseToken(lltok::comma, "expected ',' in input list"))
2864 return true;
2866 std::string Tag;
2867 if (parseStringConstant(Tag))
2868 return true;
2870 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
2871 return true;
2873 std::vector<Value *> Inputs;
2874 while (Lex.getKind() != lltok::rparen) {
2875 // If this isn't the first input, we need a comma.
2876 if (!Inputs.empty() &&
2877 parseToken(lltok::comma, "expected ',' in input list"))
2878 return true;
2880 Type *Ty = nullptr;
2881 Value *Input = nullptr;
2882 if (parseType(Ty) || parseValue(Ty, Input, PFS))
2883 return true;
2884 Inputs.push_back(Input);
2887 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2889 Lex.Lex(); // Lex the ')'.
2892 if (BundleList.empty())
2893 return error(BeginLoc, "operand bundle set must not be empty");
2895 Lex.Lex(); // Lex the ']'.
2896 return false;
2899 /// parseArgumentList - parse the argument list for a function type or function
2900 /// prototype.
2901 /// ::= '(' ArgTypeListI ')'
2902 /// ArgTypeListI
2903 /// ::= /*empty*/
2904 /// ::= '...'
2905 /// ::= ArgTypeList ',' '...'
2906 /// ::= ArgType (',' ArgType)*
2908 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2909 bool &IsVarArg) {
2910 unsigned CurValID = 0;
2911 IsVarArg = false;
2912 assert(Lex.getKind() == lltok::lparen);
2913 Lex.Lex(); // eat the (.
2915 if (Lex.getKind() == lltok::rparen) {
2916 // empty
2917 } else if (Lex.getKind() == lltok::dotdotdot) {
2918 IsVarArg = true;
2919 Lex.Lex();
2920 } else {
2921 LocTy TypeLoc = Lex.getLoc();
2922 Type *ArgTy = nullptr;
2923 AttrBuilder Attrs(M->getContext());
2924 std::string Name;
2926 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2927 return true;
2929 if (ArgTy->isVoidTy())
2930 return error(TypeLoc, "argument can not have void type");
2932 if (Lex.getKind() == lltok::LocalVar) {
2933 Name = Lex.getStrVal();
2934 Lex.Lex();
2935 } else if (Lex.getKind() == lltok::LocalVarID) {
2936 if (Lex.getUIntVal() != CurValID)
2937 return error(TypeLoc, "argument expected to be numbered '%" +
2938 Twine(CurValID) + "'");
2939 ++CurValID;
2940 Lex.Lex();
2943 if (!FunctionType::isValidArgumentType(ArgTy))
2944 return error(TypeLoc, "invalid type for function argument");
2946 ArgList.emplace_back(TypeLoc, ArgTy,
2947 AttributeSet::get(ArgTy->getContext(), Attrs),
2948 std::move(Name));
2950 while (EatIfPresent(lltok::comma)) {
2951 // Handle ... at end of arg list.
2952 if (EatIfPresent(lltok::dotdotdot)) {
2953 IsVarArg = true;
2954 break;
2957 // Otherwise must be an argument type.
2958 TypeLoc = Lex.getLoc();
2959 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2960 return true;
2962 if (ArgTy->isVoidTy())
2963 return error(TypeLoc, "argument can not have void type");
2965 if (Lex.getKind() == lltok::LocalVar) {
2966 Name = Lex.getStrVal();
2967 Lex.Lex();
2968 } else {
2969 if (Lex.getKind() == lltok::LocalVarID) {
2970 if (Lex.getUIntVal() != CurValID)
2971 return error(TypeLoc, "argument expected to be numbered '%" +
2972 Twine(CurValID) + "'");
2973 Lex.Lex();
2975 ++CurValID;
2976 Name = "";
2979 if (!ArgTy->isFirstClassType())
2980 return error(TypeLoc, "invalid type for function argument");
2982 ArgList.emplace_back(TypeLoc, ArgTy,
2983 AttributeSet::get(ArgTy->getContext(), Attrs),
2984 std::move(Name));
2988 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2991 /// parseFunctionType
2992 /// ::= Type ArgumentList OptionalAttrs
2993 bool LLParser::parseFunctionType(Type *&Result) {
2994 assert(Lex.getKind() == lltok::lparen);
2996 if (!FunctionType::isValidReturnType(Result))
2997 return tokError("invalid function return type");
2999 SmallVector<ArgInfo, 8> ArgList;
3000 bool IsVarArg;
3001 if (parseArgumentList(ArgList, IsVarArg))
3002 return true;
3004 // Reject names on the arguments lists.
3005 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3006 if (!ArgList[i].Name.empty())
3007 return error(ArgList[i].Loc, "argument name invalid in function type");
3008 if (ArgList[i].Attrs.hasAttributes())
3009 return error(ArgList[i].Loc,
3010 "argument attributes invalid in function type");
3013 SmallVector<Type*, 16> ArgListTy;
3014 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3015 ArgListTy.push_back(ArgList[i].Ty);
3017 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
3018 return false;
3021 /// parseAnonStructType - parse an anonymous struct type, which is inlined into
3022 /// other structs.
3023 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
3024 SmallVector<Type*, 8> Elts;
3025 if (parseStructBody(Elts))
3026 return true;
3028 Result = StructType::get(Context, Elts, Packed);
3029 return false;
3032 /// parseStructDefinition - parse a struct in a 'type' definition.
3033 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
3034 std::pair<Type *, LocTy> &Entry,
3035 Type *&ResultTy) {
3036 // If the type was already defined, diagnose the redefinition.
3037 if (Entry.first && !Entry.second.isValid())
3038 return error(TypeLoc, "redefinition of type");
3040 // If we have opaque, just return without filling in the definition for the
3041 // struct. This counts as a definition as far as the .ll file goes.
3042 if (EatIfPresent(lltok::kw_opaque)) {
3043 // This type is being defined, so clear the location to indicate this.
3044 Entry.second = SMLoc();
3046 // If this type number has never been uttered, create it.
3047 if (!Entry.first)
3048 Entry.first = StructType::create(Context, Name);
3049 ResultTy = Entry.first;
3050 return false;
3053 // If the type starts with '<', then it is either a packed struct or a vector.
3054 bool isPacked = EatIfPresent(lltok::less);
3056 // If we don't have a struct, then we have a random type alias, which we
3057 // accept for compatibility with old files. These types are not allowed to be
3058 // forward referenced and not allowed to be recursive.
3059 if (Lex.getKind() != lltok::lbrace) {
3060 if (Entry.first)
3061 return error(TypeLoc, "forward references to non-struct type");
3063 ResultTy = nullptr;
3064 if (isPacked)
3065 return parseArrayVectorType(ResultTy, true);
3066 return parseType(ResultTy);
3069 // This type is being defined, so clear the location to indicate this.
3070 Entry.second = SMLoc();
3072 // If this type number has never been uttered, create it.
3073 if (!Entry.first)
3074 Entry.first = StructType::create(Context, Name);
3076 StructType *STy = cast<StructType>(Entry.first);
3078 SmallVector<Type*, 8> Body;
3079 if (parseStructBody(Body) ||
3080 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
3081 return true;
3083 STy->setBody(Body, isPacked);
3084 ResultTy = STy;
3085 return false;
3088 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3089 /// StructType
3090 /// ::= '{' '}'
3091 /// ::= '{' Type (',' Type)* '}'
3092 /// ::= '<' '{' '}' '>'
3093 /// ::= '<' '{' Type (',' Type)* '}' '>'
3094 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
3095 assert(Lex.getKind() == lltok::lbrace);
3096 Lex.Lex(); // Consume the '{'
3098 // Handle the empty struct.
3099 if (EatIfPresent(lltok::rbrace))
3100 return false;
3102 LocTy EltTyLoc = Lex.getLoc();
3103 Type *Ty = nullptr;
3104 if (parseType(Ty))
3105 return true;
3106 Body.push_back(Ty);
3108 if (!StructType::isValidElementType(Ty))
3109 return error(EltTyLoc, "invalid element type for struct");
3111 while (EatIfPresent(lltok::comma)) {
3112 EltTyLoc = Lex.getLoc();
3113 if (parseType(Ty))
3114 return true;
3116 if (!StructType::isValidElementType(Ty))
3117 return error(EltTyLoc, "invalid element type for struct");
3119 Body.push_back(Ty);
3122 return parseToken(lltok::rbrace, "expected '}' at end of struct");
3125 /// parseArrayVectorType - parse an array or vector type, assuming the first
3126 /// token has already been consumed.
3127 /// Type
3128 /// ::= '[' APSINTVAL 'x' Types ']'
3129 /// ::= '<' APSINTVAL 'x' Types '>'
3130 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3131 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
3132 bool Scalable = false;
3134 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
3135 Lex.Lex(); // consume the 'vscale'
3136 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
3137 return true;
3139 Scalable = true;
3142 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
3143 Lex.getAPSIntVal().getBitWidth() > 64)
3144 return tokError("expected number in address space");
3146 LocTy SizeLoc = Lex.getLoc();
3147 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
3148 Lex.Lex();
3150 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
3151 return true;
3153 LocTy TypeLoc = Lex.getLoc();
3154 Type *EltTy = nullptr;
3155 if (parseType(EltTy))
3156 return true;
3158 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
3159 "expected end of sequential type"))
3160 return true;
3162 if (IsVector) {
3163 if (Size == 0)
3164 return error(SizeLoc, "zero element vector is illegal");
3165 if ((unsigned)Size != Size)
3166 return error(SizeLoc, "size too large for vector");
3167 if (!VectorType::isValidElementType(EltTy))
3168 return error(TypeLoc, "invalid vector element type");
3169 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
3170 } else {
3171 if (!ArrayType::isValidElementType(EltTy))
3172 return error(TypeLoc, "invalid array element type");
3173 Result = ArrayType::get(EltTy, Size);
3175 return false;
3178 /// parseTargetExtType - handle target extension type syntax
3179 /// TargetExtType
3180 /// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3182 /// TargetExtTypeParams
3183 /// ::= /*empty*/
3184 /// ::= ',' Type TargetExtTypeParams
3186 /// TargetExtIntParams
3187 /// ::= /*empty*/
3188 /// ::= ',' uint32 TargetExtIntParams
3189 bool LLParser::parseTargetExtType(Type *&Result) {
3190 Lex.Lex(); // Eat the 'target' keyword.
3192 // Get the mandatory type name.
3193 std::string TypeName;
3194 if (parseToken(lltok::lparen, "expected '(' in target extension type") ||
3195 parseStringConstant(TypeName))
3196 return true;
3198 // Parse all of the integer and type parameters at the same time; the use of
3199 // SeenInt will allow us to catch cases where type parameters follow integer
3200 // parameters.
3201 SmallVector<Type *> TypeParams;
3202 SmallVector<unsigned> IntParams;
3203 bool SeenInt = false;
3204 while (Lex.getKind() == lltok::comma) {
3205 Lex.Lex(); // Eat the comma.
3207 if (Lex.getKind() == lltok::APSInt) {
3208 SeenInt = true;
3209 unsigned IntVal;
3210 if (parseUInt32(IntVal))
3211 return true;
3212 IntParams.push_back(IntVal);
3213 } else if (SeenInt) {
3214 // The only other kind of parameter we support is type parameters, which
3215 // must precede the integer parameters. This is therefore an error.
3216 return tokError("expected uint32 param");
3217 } else {
3218 Type *TypeParam;
3219 if (parseType(TypeParam, /*AllowVoid=*/true))
3220 return true;
3221 TypeParams.push_back(TypeParam);
3225 if (parseToken(lltok::rparen, "expected ')' in target extension type"))
3226 return true;
3228 Result = TargetExtType::get(Context, TypeName, TypeParams, IntParams);
3229 return false;
3232 //===----------------------------------------------------------------------===//
3233 // Function Semantic Analysis.
3234 //===----------------------------------------------------------------------===//
3236 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
3237 int functionNumber)
3238 : P(p), F(f), FunctionNumber(functionNumber) {
3240 // Insert unnamed arguments into the NumberedVals list.
3241 for (Argument &A : F.args())
3242 if (!A.hasName())
3243 NumberedVals.push_back(&A);
3246 LLParser::PerFunctionState::~PerFunctionState() {
3247 // If there were any forward referenced non-basicblock values, delete them.
3249 for (const auto &P : ForwardRefVals) {
3250 if (isa<BasicBlock>(P.second.first))
3251 continue;
3252 P.second.first->replaceAllUsesWith(
3253 UndefValue::get(P.second.first->getType()));
3254 P.second.first->deleteValue();
3257 for (const auto &P : ForwardRefValIDs) {
3258 if (isa<BasicBlock>(P.second.first))
3259 continue;
3260 P.second.first->replaceAllUsesWith(
3261 UndefValue::get(P.second.first->getType()));
3262 P.second.first->deleteValue();
3266 bool LLParser::PerFunctionState::finishFunction() {
3267 if (!ForwardRefVals.empty())
3268 return P.error(ForwardRefVals.begin()->second.second,
3269 "use of undefined value '%" + ForwardRefVals.begin()->first +
3270 "'");
3271 if (!ForwardRefValIDs.empty())
3272 return P.error(ForwardRefValIDs.begin()->second.second,
3273 "use of undefined value '%" +
3274 Twine(ForwardRefValIDs.begin()->first) + "'");
3275 return false;
3278 /// getVal - Get a value with the specified name or ID, creating a
3279 /// forward reference record if needed. This can return null if the value
3280 /// exists but does not have the right type.
3281 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
3282 LocTy Loc) {
3283 // Look this name up in the normal function symbol table.
3284 Value *Val = F.getValueSymbolTable()->lookup(Name);
3286 // If this is a forward reference for the value, see if we already created a
3287 // forward ref record.
3288 if (!Val) {
3289 auto I = ForwardRefVals.find(Name);
3290 if (I != ForwardRefVals.end())
3291 Val = I->second.first;
3294 // If we have the value in the symbol table or fwd-ref table, return it.
3295 if (Val)
3296 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
3298 // Don't make placeholders with invalid type.
3299 if (!Ty->isFirstClassType()) {
3300 P.error(Loc, "invalid use of a non-first-class type");
3301 return nullptr;
3304 // Otherwise, create a new forward reference for this value and remember it.
3305 Value *FwdVal;
3306 if (Ty->isLabelTy()) {
3307 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
3308 } else {
3309 FwdVal = new Argument(Ty, Name);
3311 if (FwdVal->getName() != Name) {
3312 P.error(Loc, "name is too long which can result in name collisions, "
3313 "consider making the name shorter or "
3314 "increasing -non-global-value-max-name-size");
3315 return nullptr;
3318 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
3319 return FwdVal;
3322 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
3323 // Look this name up in the normal function symbol table.
3324 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
3326 // If this is a forward reference for the value, see if we already created a
3327 // forward ref record.
3328 if (!Val) {
3329 auto I = ForwardRefValIDs.find(ID);
3330 if (I != ForwardRefValIDs.end())
3331 Val = I->second.first;
3334 // If we have the value in the symbol table or fwd-ref table, return it.
3335 if (Val)
3336 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
3338 if (!Ty->isFirstClassType()) {
3339 P.error(Loc, "invalid use of a non-first-class type");
3340 return nullptr;
3343 // Otherwise, create a new forward reference for this value and remember it.
3344 Value *FwdVal;
3345 if (Ty->isLabelTy()) {
3346 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3347 } else {
3348 FwdVal = new Argument(Ty);
3351 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3352 return FwdVal;
3355 /// setInstName - After an instruction is parsed and inserted into its
3356 /// basic block, this installs its name.
3357 bool LLParser::PerFunctionState::setInstName(int NameID,
3358 const std::string &NameStr,
3359 LocTy NameLoc, Instruction *Inst) {
3360 // If this instruction has void type, it cannot have a name or ID specified.
3361 if (Inst->getType()->isVoidTy()) {
3362 if (NameID != -1 || !NameStr.empty())
3363 return P.error(NameLoc, "instructions returning void cannot have a name");
3364 return false;
3367 // If this was a numbered instruction, verify that the instruction is the
3368 // expected value and resolve any forward references.
3369 if (NameStr.empty()) {
3370 // If neither a name nor an ID was specified, just use the next ID.
3371 if (NameID == -1)
3372 NameID = NumberedVals.size();
3374 if (unsigned(NameID) != NumberedVals.size())
3375 return P.error(NameLoc, "instruction expected to be numbered '%" +
3376 Twine(NumberedVals.size()) + "'");
3378 auto FI = ForwardRefValIDs.find(NameID);
3379 if (FI != ForwardRefValIDs.end()) {
3380 Value *Sentinel = FI->second.first;
3381 if (Sentinel->getType() != Inst->getType())
3382 return P.error(NameLoc, "instruction forward referenced with type '" +
3383 getTypeString(FI->second.first->getType()) +
3384 "'");
3386 Sentinel->replaceAllUsesWith(Inst);
3387 Sentinel->deleteValue();
3388 ForwardRefValIDs.erase(FI);
3391 NumberedVals.push_back(Inst);
3392 return false;
3395 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3396 auto FI = ForwardRefVals.find(NameStr);
3397 if (FI != ForwardRefVals.end()) {
3398 Value *Sentinel = FI->second.first;
3399 if (Sentinel->getType() != Inst->getType())
3400 return P.error(NameLoc, "instruction forward referenced with type '" +
3401 getTypeString(FI->second.first->getType()) +
3402 "'");
3404 Sentinel->replaceAllUsesWith(Inst);
3405 Sentinel->deleteValue();
3406 ForwardRefVals.erase(FI);
3409 // Set the name on the instruction.
3410 Inst->setName(NameStr);
3412 if (Inst->getName() != NameStr)
3413 return P.error(NameLoc, "multiple definition of local value named '" +
3414 NameStr + "'");
3415 return false;
3418 /// getBB - Get a basic block with the specified name or ID, creating a
3419 /// forward reference record if needed.
3420 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3421 LocTy Loc) {
3422 return dyn_cast_or_null<BasicBlock>(
3423 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3426 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3427 return dyn_cast_or_null<BasicBlock>(
3428 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3431 /// defineBB - Define the specified basic block, which is either named or
3432 /// unnamed. If there is an error, this returns null otherwise it returns
3433 /// the block being defined.
3434 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3435 int NameID, LocTy Loc) {
3436 BasicBlock *BB;
3437 if (Name.empty()) {
3438 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3439 P.error(Loc, "label expected to be numbered '" +
3440 Twine(NumberedVals.size()) + "'");
3441 return nullptr;
3443 BB = getBB(NumberedVals.size(), Loc);
3444 if (!BB) {
3445 P.error(Loc, "unable to create block numbered '" +
3446 Twine(NumberedVals.size()) + "'");
3447 return nullptr;
3449 } else {
3450 BB = getBB(Name, Loc);
3451 if (!BB) {
3452 P.error(Loc, "unable to create block named '" + Name + "'");
3453 return nullptr;
3457 // Move the block to the end of the function. Forward ref'd blocks are
3458 // inserted wherever they happen to be referenced.
3459 F.splice(F.end(), &F, BB->getIterator());
3461 // Remove the block from forward ref sets.
3462 if (Name.empty()) {
3463 ForwardRefValIDs.erase(NumberedVals.size());
3464 NumberedVals.push_back(BB);
3465 } else {
3466 // BB forward references are already in the function symbol table.
3467 ForwardRefVals.erase(Name);
3470 return BB;
3473 //===----------------------------------------------------------------------===//
3474 // Constants.
3475 //===----------------------------------------------------------------------===//
3477 /// parseValID - parse an abstract value that doesn't necessarily have a
3478 /// type implied. For example, if we parse "4" we don't know what integer type
3479 /// it has. The value will later be combined with its type and checked for
3480 /// basic correctness. PFS is used to convert function-local operands of
3481 /// metadata (since metadata operands are not just parsed here but also
3482 /// converted to values). PFS can be null when we are not parsing metadata
3483 /// values inside a function.
3484 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3485 ID.Loc = Lex.getLoc();
3486 switch (Lex.getKind()) {
3487 default:
3488 return tokError("expected value token");
3489 case lltok::GlobalID: // @42
3490 ID.UIntVal = Lex.getUIntVal();
3491 ID.Kind = ValID::t_GlobalID;
3492 break;
3493 case lltok::GlobalVar: // @foo
3494 ID.StrVal = Lex.getStrVal();
3495 ID.Kind = ValID::t_GlobalName;
3496 break;
3497 case lltok::LocalVarID: // %42
3498 ID.UIntVal = Lex.getUIntVal();
3499 ID.Kind = ValID::t_LocalID;
3500 break;
3501 case lltok::LocalVar: // %foo
3502 ID.StrVal = Lex.getStrVal();
3503 ID.Kind = ValID::t_LocalName;
3504 break;
3505 case lltok::APSInt:
3506 ID.APSIntVal = Lex.getAPSIntVal();
3507 ID.Kind = ValID::t_APSInt;
3508 break;
3509 case lltok::APFloat:
3510 ID.APFloatVal = Lex.getAPFloatVal();
3511 ID.Kind = ValID::t_APFloat;
3512 break;
3513 case lltok::kw_true:
3514 ID.ConstantVal = ConstantInt::getTrue(Context);
3515 ID.Kind = ValID::t_Constant;
3516 break;
3517 case lltok::kw_false:
3518 ID.ConstantVal = ConstantInt::getFalse(Context);
3519 ID.Kind = ValID::t_Constant;
3520 break;
3521 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3522 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3523 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3524 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3525 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3527 case lltok::lbrace: {
3528 // ValID ::= '{' ConstVector '}'
3529 Lex.Lex();
3530 SmallVector<Constant*, 16> Elts;
3531 if (parseGlobalValueVector(Elts) ||
3532 parseToken(lltok::rbrace, "expected end of struct constant"))
3533 return true;
3535 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3536 ID.UIntVal = Elts.size();
3537 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3538 Elts.size() * sizeof(Elts[0]));
3539 ID.Kind = ValID::t_ConstantStruct;
3540 return false;
3542 case lltok::less: {
3543 // ValID ::= '<' ConstVector '>' --> Vector.
3544 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3545 Lex.Lex();
3546 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3548 SmallVector<Constant*, 16> Elts;
3549 LocTy FirstEltLoc = Lex.getLoc();
3550 if (parseGlobalValueVector(Elts) ||
3551 (isPackedStruct &&
3552 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3553 parseToken(lltok::greater, "expected end of constant"))
3554 return true;
3556 if (isPackedStruct) {
3557 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3558 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3559 Elts.size() * sizeof(Elts[0]));
3560 ID.UIntVal = Elts.size();
3561 ID.Kind = ValID::t_PackedConstantStruct;
3562 return false;
3565 if (Elts.empty())
3566 return error(ID.Loc, "constant vector must not be empty");
3568 if (!Elts[0]->getType()->isIntegerTy() &&
3569 !Elts[0]->getType()->isFloatingPointTy() &&
3570 !Elts[0]->getType()->isPointerTy())
3571 return error(
3572 FirstEltLoc,
3573 "vector elements must have integer, pointer or floating point type");
3575 // Verify that all the vector elements have the same type.
3576 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3577 if (Elts[i]->getType() != Elts[0]->getType())
3578 return error(FirstEltLoc, "vector element #" + Twine(i) +
3579 " is not of type '" +
3580 getTypeString(Elts[0]->getType()));
3582 ID.ConstantVal = ConstantVector::get(Elts);
3583 ID.Kind = ValID::t_Constant;
3584 return false;
3586 case lltok::lsquare: { // Array Constant
3587 Lex.Lex();
3588 SmallVector<Constant*, 16> Elts;
3589 LocTy FirstEltLoc = Lex.getLoc();
3590 if (parseGlobalValueVector(Elts) ||
3591 parseToken(lltok::rsquare, "expected end of array constant"))
3592 return true;
3594 // Handle empty element.
3595 if (Elts.empty()) {
3596 // Use undef instead of an array because it's inconvenient to determine
3597 // the element type at this point, there being no elements to examine.
3598 ID.Kind = ValID::t_EmptyArray;
3599 return false;
3602 if (!Elts[0]->getType()->isFirstClassType())
3603 return error(FirstEltLoc, "invalid array element type: " +
3604 getTypeString(Elts[0]->getType()));
3606 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3608 // Verify all elements are correct type!
3609 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3610 if (Elts[i]->getType() != Elts[0]->getType())
3611 return error(FirstEltLoc, "array element #" + Twine(i) +
3612 " is not of type '" +
3613 getTypeString(Elts[0]->getType()));
3616 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3617 ID.Kind = ValID::t_Constant;
3618 return false;
3620 case lltok::kw_c: // c "foo"
3621 Lex.Lex();
3622 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3623 false);
3624 if (parseToken(lltok::StringConstant, "expected string"))
3625 return true;
3626 ID.Kind = ValID::t_Constant;
3627 return false;
3629 case lltok::kw_asm: {
3630 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3631 // STRINGCONSTANT
3632 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3633 Lex.Lex();
3634 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3635 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3636 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3637 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
3638 parseStringConstant(ID.StrVal) ||
3639 parseToken(lltok::comma, "expected comma in inline asm expression") ||
3640 parseToken(lltok::StringConstant, "expected constraint string"))
3641 return true;
3642 ID.StrVal2 = Lex.getStrVal();
3643 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
3644 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
3645 ID.Kind = ValID::t_InlineAsm;
3646 return false;
3649 case lltok::kw_blockaddress: {
3650 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3651 Lex.Lex();
3653 ValID Fn, Label;
3655 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3656 parseValID(Fn, PFS) ||
3657 parseToken(lltok::comma,
3658 "expected comma in block address expression") ||
3659 parseValID(Label, PFS) ||
3660 parseToken(lltok::rparen, "expected ')' in block address expression"))
3661 return true;
3663 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3664 return error(Fn.Loc, "expected function name in blockaddress");
3665 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3666 return error(Label.Loc, "expected basic block name in blockaddress");
3668 // Try to find the function (but skip it if it's forward-referenced).
3669 GlobalValue *GV = nullptr;
3670 if (Fn.Kind == ValID::t_GlobalID) {
3671 if (Fn.UIntVal < NumberedVals.size())
3672 GV = NumberedVals[Fn.UIntVal];
3673 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3674 GV = M->getNamedValue(Fn.StrVal);
3676 Function *F = nullptr;
3677 if (GV) {
3678 // Confirm that it's actually a function with a definition.
3679 if (!isa<Function>(GV))
3680 return error(Fn.Loc, "expected function name in blockaddress");
3681 F = cast<Function>(GV);
3682 if (F->isDeclaration())
3683 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3686 if (!F) {
3687 // Make a global variable as a placeholder for this reference.
3688 GlobalValue *&FwdRef =
3689 ForwardRefBlockAddresses.insert(std::make_pair(
3690 std::move(Fn),
3691 std::map<ValID, GlobalValue *>()))
3692 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3693 .first->second;
3694 if (!FwdRef) {
3695 unsigned FwdDeclAS;
3696 if (ExpectedTy) {
3697 // If we know the type that the blockaddress is being assigned to,
3698 // we can use the address space of that type.
3699 if (!ExpectedTy->isPointerTy())
3700 return error(ID.Loc,
3701 "type of blockaddress must be a pointer and not '" +
3702 getTypeString(ExpectedTy) + "'");
3703 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
3704 } else if (PFS) {
3705 // Otherwise, we default the address space of the current function.
3706 FwdDeclAS = PFS->getFunction().getAddressSpace();
3707 } else {
3708 llvm_unreachable("Unknown address space for blockaddress");
3710 FwdRef = new GlobalVariable(
3711 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
3712 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
3715 ID.ConstantVal = FwdRef;
3716 ID.Kind = ValID::t_Constant;
3717 return false;
3720 // We found the function; now find the basic block. Don't use PFS, since we
3721 // might be inside a constant expression.
3722 BasicBlock *BB;
3723 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3724 if (Label.Kind == ValID::t_LocalID)
3725 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3726 else
3727 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3728 if (!BB)
3729 return error(Label.Loc, "referenced value is not a basic block");
3730 } else {
3731 if (Label.Kind == ValID::t_LocalID)
3732 return error(Label.Loc, "cannot take address of numeric label after "
3733 "the function is defined");
3734 BB = dyn_cast_or_null<BasicBlock>(
3735 F->getValueSymbolTable()->lookup(Label.StrVal));
3736 if (!BB)
3737 return error(Label.Loc, "referenced value is not a basic block");
3740 ID.ConstantVal = BlockAddress::get(F, BB);
3741 ID.Kind = ValID::t_Constant;
3742 return false;
3745 case lltok::kw_dso_local_equivalent: {
3746 // ValID ::= 'dso_local_equivalent' @foo
3747 Lex.Lex();
3749 ValID Fn;
3751 if (parseValID(Fn, PFS))
3752 return true;
3754 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3755 return error(Fn.Loc,
3756 "expected global value name in dso_local_equivalent");
3758 // Try to find the function (but skip it if it's forward-referenced).
3759 GlobalValue *GV = nullptr;
3760 if (Fn.Kind == ValID::t_GlobalID) {
3761 if (Fn.UIntVal < NumberedVals.size())
3762 GV = NumberedVals[Fn.UIntVal];
3763 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3764 GV = M->getNamedValue(Fn.StrVal);
3767 if (!GV) {
3768 // Make a placeholder global variable as a placeholder for this reference.
3769 auto &FwdRefMap = (Fn.Kind == ValID::t_GlobalID)
3770 ? ForwardRefDSOLocalEquivalentIDs
3771 : ForwardRefDSOLocalEquivalentNames;
3772 GlobalValue *&FwdRef = FwdRefMap.try_emplace(Fn, nullptr).first->second;
3773 if (!FwdRef) {
3774 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3775 GlobalValue::InternalLinkage, nullptr, "",
3776 nullptr, GlobalValue::NotThreadLocal);
3779 ID.ConstantVal = FwdRef;
3780 ID.Kind = ValID::t_Constant;
3781 return false;
3784 if (!GV->getValueType()->isFunctionTy())
3785 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
3786 "in dso_local_equivalent");
3788 ID.ConstantVal = DSOLocalEquivalent::get(GV);
3789 ID.Kind = ValID::t_Constant;
3790 return false;
3793 case lltok::kw_no_cfi: {
3794 // ValID ::= 'no_cfi' @foo
3795 Lex.Lex();
3797 if (parseValID(ID, PFS))
3798 return true;
3800 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
3801 return error(ID.Loc, "expected global value name in no_cfi");
3803 ID.NoCFI = true;
3804 return false;
3807 case lltok::kw_trunc:
3808 case lltok::kw_zext:
3809 case lltok::kw_sext:
3810 case lltok::kw_fptrunc:
3811 case lltok::kw_fpext:
3812 case lltok::kw_bitcast:
3813 case lltok::kw_addrspacecast:
3814 case lltok::kw_uitofp:
3815 case lltok::kw_sitofp:
3816 case lltok::kw_fptoui:
3817 case lltok::kw_fptosi:
3818 case lltok::kw_inttoptr:
3819 case lltok::kw_ptrtoint: {
3820 unsigned Opc = Lex.getUIntVal();
3821 Type *DestTy = nullptr;
3822 Constant *SrcVal;
3823 Lex.Lex();
3824 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3825 parseGlobalTypeAndValue(SrcVal) ||
3826 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3827 parseType(DestTy) ||
3828 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3829 return true;
3830 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3831 return error(ID.Loc, "invalid cast opcode for cast from '" +
3832 getTypeString(SrcVal->getType()) + "' to '" +
3833 getTypeString(DestTy) + "'");
3834 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3835 SrcVal, DestTy);
3836 ID.Kind = ValID::t_Constant;
3837 return false;
3839 case lltok::kw_extractvalue:
3840 return error(ID.Loc, "extractvalue constexprs are no longer supported");
3841 case lltok::kw_insertvalue:
3842 return error(ID.Loc, "insertvalue constexprs are no longer supported");
3843 case lltok::kw_udiv:
3844 return error(ID.Loc, "udiv constexprs are no longer supported");
3845 case lltok::kw_sdiv:
3846 return error(ID.Loc, "sdiv constexprs are no longer supported");
3847 case lltok::kw_urem:
3848 return error(ID.Loc, "urem constexprs are no longer supported");
3849 case lltok::kw_srem:
3850 return error(ID.Loc, "srem constexprs are no longer supported");
3851 case lltok::kw_fadd:
3852 return error(ID.Loc, "fadd constexprs are no longer supported");
3853 case lltok::kw_fsub:
3854 return error(ID.Loc, "fsub constexprs are no longer supported");
3855 case lltok::kw_fmul:
3856 return error(ID.Loc, "fmul constexprs are no longer supported");
3857 case lltok::kw_fdiv:
3858 return error(ID.Loc, "fdiv constexprs are no longer supported");
3859 case lltok::kw_frem:
3860 return error(ID.Loc, "frem constexprs are no longer supported");
3861 case lltok::kw_and:
3862 return error(ID.Loc, "and constexprs are no longer supported");
3863 case lltok::kw_or:
3864 return error(ID.Loc, "or constexprs are no longer supported");
3865 case lltok::kw_fneg:
3866 return error(ID.Loc, "fneg constexprs are no longer supported");
3867 case lltok::kw_select:
3868 return error(ID.Loc, "select constexprs are no longer supported");
3869 case lltok::kw_icmp:
3870 case lltok::kw_fcmp: {
3871 unsigned PredVal, Opc = Lex.getUIntVal();
3872 Constant *Val0, *Val1;
3873 Lex.Lex();
3874 if (parseCmpPredicate(PredVal, Opc) ||
3875 parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3876 parseGlobalTypeAndValue(Val0) ||
3877 parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3878 parseGlobalTypeAndValue(Val1) ||
3879 parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3880 return true;
3882 if (Val0->getType() != Val1->getType())
3883 return error(ID.Loc, "compare operands must have the same type");
3885 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3887 if (Opc == Instruction::FCmp) {
3888 if (!Val0->getType()->isFPOrFPVectorTy())
3889 return error(ID.Loc, "fcmp requires floating point operands");
3890 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3891 } else {
3892 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3893 if (!Val0->getType()->isIntOrIntVectorTy() &&
3894 !Val0->getType()->isPtrOrPtrVectorTy())
3895 return error(ID.Loc, "icmp requires pointer or integer operands");
3896 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3898 ID.Kind = ValID::t_Constant;
3899 return false;
3902 // Binary Operators.
3903 case lltok::kw_add:
3904 case lltok::kw_sub:
3905 case lltok::kw_mul:
3906 case lltok::kw_shl:
3907 case lltok::kw_lshr:
3908 case lltok::kw_ashr:
3909 case lltok::kw_xor: {
3910 bool NUW = false;
3911 bool NSW = false;
3912 bool Exact = false;
3913 unsigned Opc = Lex.getUIntVal();
3914 Constant *Val0, *Val1;
3915 Lex.Lex();
3916 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3917 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3918 if (EatIfPresent(lltok::kw_nuw))
3919 NUW = true;
3920 if (EatIfPresent(lltok::kw_nsw)) {
3921 NSW = true;
3922 if (EatIfPresent(lltok::kw_nuw))
3923 NUW = true;
3925 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3926 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3927 if (EatIfPresent(lltok::kw_exact))
3928 Exact = true;
3930 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3931 parseGlobalTypeAndValue(Val0) ||
3932 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3933 parseGlobalTypeAndValue(Val1) ||
3934 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3935 return true;
3936 if (Val0->getType() != Val1->getType())
3937 return error(ID.Loc, "operands of constexpr must have same type");
3938 // Check that the type is valid for the operator.
3939 if (!Val0->getType()->isIntOrIntVectorTy())
3940 return error(ID.Loc,
3941 "constexpr requires integer or integer vector operands");
3942 unsigned Flags = 0;
3943 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3944 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3945 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3946 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1, Flags);
3947 ID.Kind = ValID::t_Constant;
3948 return false;
3951 case lltok::kw_getelementptr:
3952 case lltok::kw_shufflevector:
3953 case lltok::kw_insertelement:
3954 case lltok::kw_extractelement: {
3955 unsigned Opc = Lex.getUIntVal();
3956 SmallVector<Constant*, 16> Elts;
3957 bool InBounds = false;
3958 Type *Ty;
3959 Lex.Lex();
3961 if (Opc == Instruction::GetElementPtr)
3962 InBounds = EatIfPresent(lltok::kw_inbounds);
3964 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
3965 return true;
3967 if (Opc == Instruction::GetElementPtr) {
3968 if (parseType(Ty) ||
3969 parseToken(lltok::comma, "expected comma after getelementptr's type"))
3970 return true;
3973 std::optional<unsigned> InRangeOp;
3974 if (parseGlobalValueVector(
3975 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3976 parseToken(lltok::rparen, "expected ')' in constantexpr"))
3977 return true;
3979 if (Opc == Instruction::GetElementPtr) {
3980 if (Elts.size() == 0 ||
3981 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3982 return error(ID.Loc, "base of getelementptr must be a pointer");
3984 Type *BaseType = Elts[0]->getType();
3985 unsigned GEPWidth =
3986 BaseType->isVectorTy()
3987 ? cast<FixedVectorType>(BaseType)->getNumElements()
3988 : 0;
3990 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3991 for (Constant *Val : Indices) {
3992 Type *ValTy = Val->getType();
3993 if (!ValTy->isIntOrIntVectorTy())
3994 return error(ID.Loc, "getelementptr index must be an integer");
3995 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
3996 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
3997 if (GEPWidth && (ValNumEl != GEPWidth))
3998 return error(
3999 ID.Loc,
4000 "getelementptr vector index has a wrong number of elements");
4001 // GEPWidth may have been unknown because the base is a scalar,
4002 // but it is known now.
4003 GEPWidth = ValNumEl;
4007 SmallPtrSet<Type*, 4> Visited;
4008 if (!Indices.empty() && !Ty->isSized(&Visited))
4009 return error(ID.Loc, "base element of getelementptr must be sized");
4011 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
4012 return error(ID.Loc, "invalid getelementptr indices");
4014 if (InRangeOp) {
4015 if (*InRangeOp == 0)
4016 return error(ID.Loc,
4017 "inrange keyword may not appear on pointer operand");
4018 --*InRangeOp;
4021 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
4022 InBounds, InRangeOp);
4023 } else if (Opc == Instruction::ShuffleVector) {
4024 if (Elts.size() != 3)
4025 return error(ID.Loc, "expected three operands to shufflevector");
4026 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4027 return error(ID.Loc, "invalid operands to shufflevector");
4028 SmallVector<int, 16> Mask;
4029 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
4030 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
4031 } else if (Opc == Instruction::ExtractElement) {
4032 if (Elts.size() != 2)
4033 return error(ID.Loc, "expected two operands to extractelement");
4034 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
4035 return error(ID.Loc, "invalid extractelement operands");
4036 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
4037 } else {
4038 assert(Opc == Instruction::InsertElement && "Unknown opcode");
4039 if (Elts.size() != 3)
4040 return error(ID.Loc, "expected three operands to insertelement");
4041 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
4042 return error(ID.Loc, "invalid insertelement operands");
4043 ID.ConstantVal =
4044 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
4047 ID.Kind = ValID::t_Constant;
4048 return false;
4052 Lex.Lex();
4053 return false;
4056 /// parseGlobalValue - parse a global value with the specified type.
4057 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
4058 C = nullptr;
4059 ValID ID;
4060 Value *V = nullptr;
4061 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
4062 convertValIDToValue(Ty, ID, V, nullptr);
4063 if (V && !(C = dyn_cast<Constant>(V)))
4064 return error(ID.Loc, "global values must be constants");
4065 return Parsed;
4068 bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
4069 Type *Ty = nullptr;
4070 return parseType(Ty) || parseGlobalValue(Ty, V);
4073 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
4074 C = nullptr;
4076 LocTy KwLoc = Lex.getLoc();
4077 if (!EatIfPresent(lltok::kw_comdat))
4078 return false;
4080 if (EatIfPresent(lltok::lparen)) {
4081 if (Lex.getKind() != lltok::ComdatVar)
4082 return tokError("expected comdat variable");
4083 C = getComdat(Lex.getStrVal(), Lex.getLoc());
4084 Lex.Lex();
4085 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
4086 return true;
4087 } else {
4088 if (GlobalName.empty())
4089 return tokError("comdat cannot be unnamed");
4090 C = getComdat(std::string(GlobalName), KwLoc);
4093 return false;
4096 /// parseGlobalValueVector
4097 /// ::= /*empty*/
4098 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
4099 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
4100 std::optional<unsigned> *InRangeOp) {
4101 // Empty list.
4102 if (Lex.getKind() == lltok::rbrace ||
4103 Lex.getKind() == lltok::rsquare ||
4104 Lex.getKind() == lltok::greater ||
4105 Lex.getKind() == lltok::rparen)
4106 return false;
4108 do {
4109 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
4110 *InRangeOp = Elts.size();
4112 Constant *C;
4113 if (parseGlobalTypeAndValue(C))
4114 return true;
4115 Elts.push_back(C);
4116 } while (EatIfPresent(lltok::comma));
4118 return false;
4121 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
4122 SmallVector<Metadata *, 16> Elts;
4123 if (parseMDNodeVector(Elts))
4124 return true;
4126 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
4127 return false;
4130 /// MDNode:
4131 /// ::= !{ ... }
4132 /// ::= !7
4133 /// ::= !DILocation(...)
4134 bool LLParser::parseMDNode(MDNode *&N) {
4135 if (Lex.getKind() == lltok::MetadataVar)
4136 return parseSpecializedMDNode(N);
4138 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
4141 bool LLParser::parseMDNodeTail(MDNode *&N) {
4142 // !{ ... }
4143 if (Lex.getKind() == lltok::lbrace)
4144 return parseMDTuple(N);
4146 // !42
4147 return parseMDNodeID(N);
4150 namespace {
4152 /// Structure to represent an optional metadata field.
4153 template <class FieldTy> struct MDFieldImpl {
4154 typedef MDFieldImpl ImplTy;
4155 FieldTy Val;
4156 bool Seen;
4158 void assign(FieldTy Val) {
4159 Seen = true;
4160 this->Val = std::move(Val);
4163 explicit MDFieldImpl(FieldTy Default)
4164 : Val(std::move(Default)), Seen(false) {}
4167 /// Structure to represent an optional metadata field that
4168 /// can be of either type (A or B) and encapsulates the
4169 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
4170 /// to reimplement the specifics for representing each Field.
4171 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
4172 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
4173 FieldTypeA A;
4174 FieldTypeB B;
4175 bool Seen;
4177 enum {
4178 IsInvalid = 0,
4179 IsTypeA = 1,
4180 IsTypeB = 2
4181 } WhatIs;
4183 void assign(FieldTypeA A) {
4184 Seen = true;
4185 this->A = std::move(A);
4186 WhatIs = IsTypeA;
4189 void assign(FieldTypeB B) {
4190 Seen = true;
4191 this->B = std::move(B);
4192 WhatIs = IsTypeB;
4195 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
4196 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
4197 WhatIs(IsInvalid) {}
4200 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
4201 uint64_t Max;
4203 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
4204 : ImplTy(Default), Max(Max) {}
4207 struct LineField : public MDUnsignedField {
4208 LineField() : MDUnsignedField(0, UINT32_MAX) {}
4211 struct ColumnField : public MDUnsignedField {
4212 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
4215 struct DwarfTagField : public MDUnsignedField {
4216 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
4217 DwarfTagField(dwarf::Tag DefaultTag)
4218 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
4221 struct DwarfMacinfoTypeField : public MDUnsignedField {
4222 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
4223 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
4224 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
4227 struct DwarfAttEncodingField : public MDUnsignedField {
4228 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
4231 struct DwarfVirtualityField : public MDUnsignedField {
4232 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
4235 struct DwarfLangField : public MDUnsignedField {
4236 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
4239 struct DwarfCCField : public MDUnsignedField {
4240 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
4243 struct EmissionKindField : public MDUnsignedField {
4244 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
4247 struct NameTableKindField : public MDUnsignedField {
4248 NameTableKindField()
4249 : MDUnsignedField(
4250 0, (unsigned)
4251 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
4254 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
4255 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
4258 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
4259 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
4262 struct MDAPSIntField : public MDFieldImpl<APSInt> {
4263 MDAPSIntField() : ImplTy(APSInt()) {}
4266 struct MDSignedField : public MDFieldImpl<int64_t> {
4267 int64_t Min = INT64_MIN;
4268 int64_t Max = INT64_MAX;
4270 MDSignedField(int64_t Default = 0)
4271 : ImplTy(Default) {}
4272 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
4273 : ImplTy(Default), Min(Min), Max(Max) {}
4276 struct MDBoolField : public MDFieldImpl<bool> {
4277 MDBoolField(bool Default = false) : ImplTy(Default) {}
4280 struct MDField : public MDFieldImpl<Metadata *> {
4281 bool AllowNull;
4283 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4286 struct MDStringField : public MDFieldImpl<MDString *> {
4287 bool AllowEmpty;
4288 MDStringField(bool AllowEmpty = true)
4289 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4292 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4293 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4296 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4297 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4300 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4301 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4302 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4304 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4305 bool AllowNull = true)
4306 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4308 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4309 bool isMDField() const { return WhatIs == IsTypeB; }
4310 int64_t getMDSignedValue() const {
4311 assert(isMDSignedField() && "Wrong field type");
4312 return A.Val;
4314 Metadata *getMDFieldValue() const {
4315 assert(isMDField() && "Wrong field type");
4316 return B.Val;
4320 } // end anonymous namespace
4322 namespace llvm {
4324 template <>
4325 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4326 if (Lex.getKind() != lltok::APSInt)
4327 return tokError("expected integer");
4329 Result.assign(Lex.getAPSIntVal());
4330 Lex.Lex();
4331 return false;
4334 template <>
4335 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4336 MDUnsignedField &Result) {
4337 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4338 return tokError("expected unsigned integer");
4340 auto &U = Lex.getAPSIntVal();
4341 if (U.ugt(Result.Max))
4342 return tokError("value for '" + Name + "' too large, limit is " +
4343 Twine(Result.Max));
4344 Result.assign(U.getZExtValue());
4345 assert(Result.Val <= Result.Max && "Expected value in range");
4346 Lex.Lex();
4347 return false;
4350 template <>
4351 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4352 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4354 template <>
4355 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4356 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4359 template <>
4360 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4361 if (Lex.getKind() == lltok::APSInt)
4362 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4364 if (Lex.getKind() != lltok::DwarfTag)
4365 return tokError("expected DWARF tag");
4367 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4368 if (Tag == dwarf::DW_TAG_invalid)
4369 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4370 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4372 Result.assign(Tag);
4373 Lex.Lex();
4374 return false;
4377 template <>
4378 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4379 DwarfMacinfoTypeField &Result) {
4380 if (Lex.getKind() == lltok::APSInt)
4381 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4383 if (Lex.getKind() != lltok::DwarfMacinfo)
4384 return tokError("expected DWARF macinfo type");
4386 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4387 if (Macinfo == dwarf::DW_MACINFO_invalid)
4388 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4389 Lex.getStrVal() + "'");
4390 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4392 Result.assign(Macinfo);
4393 Lex.Lex();
4394 return false;
4397 template <>
4398 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4399 DwarfVirtualityField &Result) {
4400 if (Lex.getKind() == lltok::APSInt)
4401 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4403 if (Lex.getKind() != lltok::DwarfVirtuality)
4404 return tokError("expected DWARF virtuality code");
4406 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4407 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4408 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4409 Lex.getStrVal() + "'");
4410 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4411 Result.assign(Virtuality);
4412 Lex.Lex();
4413 return false;
4416 template <>
4417 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4418 if (Lex.getKind() == lltok::APSInt)
4419 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4421 if (Lex.getKind() != lltok::DwarfLang)
4422 return tokError("expected DWARF language");
4424 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4425 if (!Lang)
4426 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4427 "'");
4428 assert(Lang <= Result.Max && "Expected valid DWARF language");
4429 Result.assign(Lang);
4430 Lex.Lex();
4431 return false;
4434 template <>
4435 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4436 if (Lex.getKind() == lltok::APSInt)
4437 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4439 if (Lex.getKind() != lltok::DwarfCC)
4440 return tokError("expected DWARF calling convention");
4442 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4443 if (!CC)
4444 return tokError("invalid DWARF calling convention" + Twine(" '") +
4445 Lex.getStrVal() + "'");
4446 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4447 Result.assign(CC);
4448 Lex.Lex();
4449 return false;
4452 template <>
4453 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4454 EmissionKindField &Result) {
4455 if (Lex.getKind() == lltok::APSInt)
4456 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4458 if (Lex.getKind() != lltok::EmissionKind)
4459 return tokError("expected emission kind");
4461 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4462 if (!Kind)
4463 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4464 "'");
4465 assert(*Kind <= Result.Max && "Expected valid emission kind");
4466 Result.assign(*Kind);
4467 Lex.Lex();
4468 return false;
4471 template <>
4472 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4473 NameTableKindField &Result) {
4474 if (Lex.getKind() == lltok::APSInt)
4475 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4477 if (Lex.getKind() != lltok::NameTableKind)
4478 return tokError("expected nameTable kind");
4480 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4481 if (!Kind)
4482 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4483 "'");
4484 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4485 Result.assign((unsigned)*Kind);
4486 Lex.Lex();
4487 return false;
4490 template <>
4491 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4492 DwarfAttEncodingField &Result) {
4493 if (Lex.getKind() == lltok::APSInt)
4494 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4496 if (Lex.getKind() != lltok::DwarfAttEncoding)
4497 return tokError("expected DWARF type attribute encoding");
4499 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4500 if (!Encoding)
4501 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4502 Lex.getStrVal() + "'");
4503 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4504 Result.assign(Encoding);
4505 Lex.Lex();
4506 return false;
4509 /// DIFlagField
4510 /// ::= uint32
4511 /// ::= DIFlagVector
4512 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4513 template <>
4514 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4516 // parser for a single flag.
4517 auto parseFlag = [&](DINode::DIFlags &Val) {
4518 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4519 uint32_t TempVal = static_cast<uint32_t>(Val);
4520 bool Res = parseUInt32(TempVal);
4521 Val = static_cast<DINode::DIFlags>(TempVal);
4522 return Res;
4525 if (Lex.getKind() != lltok::DIFlag)
4526 return tokError("expected debug info flag");
4528 Val = DINode::getFlag(Lex.getStrVal());
4529 if (!Val)
4530 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
4531 "'");
4532 Lex.Lex();
4533 return false;
4536 // parse the flags and combine them together.
4537 DINode::DIFlags Combined = DINode::FlagZero;
4538 do {
4539 DINode::DIFlags Val;
4540 if (parseFlag(Val))
4541 return true;
4542 Combined |= Val;
4543 } while (EatIfPresent(lltok::bar));
4545 Result.assign(Combined);
4546 return false;
4549 /// DISPFlagField
4550 /// ::= uint32
4551 /// ::= DISPFlagVector
4552 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4553 template <>
4554 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4556 // parser for a single flag.
4557 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4558 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4559 uint32_t TempVal = static_cast<uint32_t>(Val);
4560 bool Res = parseUInt32(TempVal);
4561 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4562 return Res;
4565 if (Lex.getKind() != lltok::DISPFlag)
4566 return tokError("expected debug info flag");
4568 Val = DISubprogram::getFlag(Lex.getStrVal());
4569 if (!Val)
4570 return tokError(Twine("invalid subprogram debug info flag '") +
4571 Lex.getStrVal() + "'");
4572 Lex.Lex();
4573 return false;
4576 // parse the flags and combine them together.
4577 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4578 do {
4579 DISubprogram::DISPFlags Val;
4580 if (parseFlag(Val))
4581 return true;
4582 Combined |= Val;
4583 } while (EatIfPresent(lltok::bar));
4585 Result.assign(Combined);
4586 return false;
4589 template <>
4590 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4591 if (Lex.getKind() != lltok::APSInt)
4592 return tokError("expected signed integer");
4594 auto &S = Lex.getAPSIntVal();
4595 if (S < Result.Min)
4596 return tokError("value for '" + Name + "' too small, limit is " +
4597 Twine(Result.Min));
4598 if (S > Result.Max)
4599 return tokError("value for '" + Name + "' too large, limit is " +
4600 Twine(Result.Max));
4601 Result.assign(S.getExtValue());
4602 assert(Result.Val >= Result.Min && "Expected value in range");
4603 assert(Result.Val <= Result.Max && "Expected value in range");
4604 Lex.Lex();
4605 return false;
4608 template <>
4609 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4610 switch (Lex.getKind()) {
4611 default:
4612 return tokError("expected 'true' or 'false'");
4613 case lltok::kw_true:
4614 Result.assign(true);
4615 break;
4616 case lltok::kw_false:
4617 Result.assign(false);
4618 break;
4620 Lex.Lex();
4621 return false;
4624 template <>
4625 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4626 if (Lex.getKind() == lltok::kw_null) {
4627 if (!Result.AllowNull)
4628 return tokError("'" + Name + "' cannot be null");
4629 Lex.Lex();
4630 Result.assign(nullptr);
4631 return false;
4634 Metadata *MD;
4635 if (parseMetadata(MD, nullptr))
4636 return true;
4638 Result.assign(MD);
4639 return false;
4642 template <>
4643 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4644 MDSignedOrMDField &Result) {
4645 // Try to parse a signed int.
4646 if (Lex.getKind() == lltok::APSInt) {
4647 MDSignedField Res = Result.A;
4648 if (!parseMDField(Loc, Name, Res)) {
4649 Result.assign(Res);
4650 return false;
4652 return true;
4655 // Otherwise, try to parse as an MDField.
4656 MDField Res = Result.B;
4657 if (!parseMDField(Loc, Name, Res)) {
4658 Result.assign(Res);
4659 return false;
4662 return true;
4665 template <>
4666 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4667 LocTy ValueLoc = Lex.getLoc();
4668 std::string S;
4669 if (parseStringConstant(S))
4670 return true;
4672 if (!Result.AllowEmpty && S.empty())
4673 return error(ValueLoc, "'" + Name + "' cannot be empty");
4675 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4676 return false;
4679 template <>
4680 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4681 SmallVector<Metadata *, 4> MDs;
4682 if (parseMDNodeVector(MDs))
4683 return true;
4685 Result.assign(std::move(MDs));
4686 return false;
4689 template <>
4690 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4691 ChecksumKindField &Result) {
4692 std::optional<DIFile::ChecksumKind> CSKind =
4693 DIFile::getChecksumKind(Lex.getStrVal());
4695 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4696 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4697 "'");
4699 Result.assign(*CSKind);
4700 Lex.Lex();
4701 return false;
4704 } // end namespace llvm
4706 template <class ParserTy>
4707 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4708 do {
4709 if (Lex.getKind() != lltok::LabelStr)
4710 return tokError("expected field label here");
4712 if (ParseField())
4713 return true;
4714 } while (EatIfPresent(lltok::comma));
4716 return false;
4719 template <class ParserTy>
4720 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4721 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4722 Lex.Lex();
4724 if (parseToken(lltok::lparen, "expected '(' here"))
4725 return true;
4726 if (Lex.getKind() != lltok::rparen)
4727 if (parseMDFieldsImplBody(ParseField))
4728 return true;
4730 ClosingLoc = Lex.getLoc();
4731 return parseToken(lltok::rparen, "expected ')' here");
4734 template <class FieldTy>
4735 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4736 if (Result.Seen)
4737 return tokError("field '" + Name + "' cannot be specified more than once");
4739 LocTy Loc = Lex.getLoc();
4740 Lex.Lex();
4741 return parseMDField(Loc, Name, Result);
4744 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4745 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4747 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4748 if (Lex.getStrVal() == #CLASS) \
4749 return parse##CLASS(N, IsDistinct);
4750 #include "llvm/IR/Metadata.def"
4752 return tokError("expected metadata type");
4755 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4756 #define NOP_FIELD(NAME, TYPE, INIT)
4757 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4758 if (!NAME.Seen) \
4759 return error(ClosingLoc, "missing required field '" #NAME "'");
4760 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4761 if (Lex.getStrVal() == #NAME) \
4762 return parseMDField(#NAME, NAME);
4763 #define PARSE_MD_FIELDS() \
4764 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4765 do { \
4766 LocTy ClosingLoc; \
4767 if (parseMDFieldsImpl( \
4768 [&]() -> bool { \
4769 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4770 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4771 "'"); \
4772 }, \
4773 ClosingLoc)) \
4774 return true; \
4775 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4776 } while (false)
4777 #define GET_OR_DISTINCT(CLASS, ARGS) \
4778 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4780 /// parseDILocationFields:
4781 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4782 /// isImplicitCode: true)
4783 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4784 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4785 OPTIONAL(line, LineField, ); \
4786 OPTIONAL(column, ColumnField, ); \
4787 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4788 OPTIONAL(inlinedAt, MDField, ); \
4789 OPTIONAL(isImplicitCode, MDBoolField, (false));
4790 PARSE_MD_FIELDS();
4791 #undef VISIT_MD_FIELDS
4793 Result =
4794 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4795 inlinedAt.Val, isImplicitCode.Val));
4796 return false;
4799 /// parseDIAssignID:
4800 /// ::= distinct !DIAssignID()
4801 bool LLParser::parseDIAssignID(MDNode *&Result, bool IsDistinct) {
4802 if (!IsDistinct)
4803 return Lex.Error("missing 'distinct', required for !DIAssignID()");
4805 Lex.Lex();
4807 // Now eat the parens.
4808 if (parseToken(lltok::lparen, "expected '(' here"))
4809 return true;
4810 if (parseToken(lltok::rparen, "expected ')' here"))
4811 return true;
4813 Result = DIAssignID::getDistinct(Context);
4814 return false;
4817 /// parseGenericDINode:
4818 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4819 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4820 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4821 REQUIRED(tag, DwarfTagField, ); \
4822 OPTIONAL(header, MDStringField, ); \
4823 OPTIONAL(operands, MDFieldList, );
4824 PARSE_MD_FIELDS();
4825 #undef VISIT_MD_FIELDS
4827 Result = GET_OR_DISTINCT(GenericDINode,
4828 (Context, tag.Val, header.Val, operands.Val));
4829 return false;
4832 /// parseDISubrange:
4833 /// ::= !DISubrange(count: 30, lowerBound: 2)
4834 /// ::= !DISubrange(count: !node, lowerBound: 2)
4835 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4836 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4837 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4838 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4839 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4840 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4841 OPTIONAL(stride, MDSignedOrMDField, );
4842 PARSE_MD_FIELDS();
4843 #undef VISIT_MD_FIELDS
4845 Metadata *Count = nullptr;
4846 Metadata *LowerBound = nullptr;
4847 Metadata *UpperBound = nullptr;
4848 Metadata *Stride = nullptr;
4850 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4851 if (Bound.isMDSignedField())
4852 return ConstantAsMetadata::get(ConstantInt::getSigned(
4853 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4854 if (Bound.isMDField())
4855 return Bound.getMDFieldValue();
4856 return nullptr;
4859 Count = convToMetadata(count);
4860 LowerBound = convToMetadata(lowerBound);
4861 UpperBound = convToMetadata(upperBound);
4862 Stride = convToMetadata(stride);
4864 Result = GET_OR_DISTINCT(DISubrange,
4865 (Context, Count, LowerBound, UpperBound, Stride));
4867 return false;
4870 /// parseDIGenericSubrange:
4871 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4872 /// !node3)
4873 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4874 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4875 OPTIONAL(count, MDSignedOrMDField, ); \
4876 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4877 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4878 OPTIONAL(stride, MDSignedOrMDField, );
4879 PARSE_MD_FIELDS();
4880 #undef VISIT_MD_FIELDS
4882 auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4883 if (Bound.isMDSignedField())
4884 return DIExpression::get(
4885 Context, {dwarf::DW_OP_consts,
4886 static_cast<uint64_t>(Bound.getMDSignedValue())});
4887 if (Bound.isMDField())
4888 return Bound.getMDFieldValue();
4889 return nullptr;
4892 Metadata *Count = ConvToMetadata(count);
4893 Metadata *LowerBound = ConvToMetadata(lowerBound);
4894 Metadata *UpperBound = ConvToMetadata(upperBound);
4895 Metadata *Stride = ConvToMetadata(stride);
4897 Result = GET_OR_DISTINCT(DIGenericSubrange,
4898 (Context, Count, LowerBound, UpperBound, Stride));
4900 return false;
4903 /// parseDIEnumerator:
4904 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4905 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4906 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4907 REQUIRED(name, MDStringField, ); \
4908 REQUIRED(value, MDAPSIntField, ); \
4909 OPTIONAL(isUnsigned, MDBoolField, (false));
4910 PARSE_MD_FIELDS();
4911 #undef VISIT_MD_FIELDS
4913 if (isUnsigned.Val && value.Val.isNegative())
4914 return tokError("unsigned enumerator with negative value");
4916 APSInt Value(value.Val);
4917 // Add a leading zero so that unsigned values with the msb set are not
4918 // mistaken for negative values when used for signed enumerators.
4919 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
4920 Value = Value.zext(Value.getBitWidth() + 1);
4922 Result =
4923 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4925 return false;
4928 /// parseDIBasicType:
4929 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4930 /// encoding: DW_ATE_encoding, flags: 0)
4931 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
4932 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4933 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4934 OPTIONAL(name, MDStringField, ); \
4935 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4936 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4937 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4938 OPTIONAL(flags, DIFlagField, );
4939 PARSE_MD_FIELDS();
4940 #undef VISIT_MD_FIELDS
4942 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4943 align.Val, encoding.Val, flags.Val));
4944 return false;
4947 /// parseDIStringType:
4948 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
4949 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
4950 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4951 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
4952 OPTIONAL(name, MDStringField, ); \
4953 OPTIONAL(stringLength, MDField, ); \
4954 OPTIONAL(stringLengthExpression, MDField, ); \
4955 OPTIONAL(stringLocationExpression, MDField, ); \
4956 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4957 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4958 OPTIONAL(encoding, DwarfAttEncodingField, );
4959 PARSE_MD_FIELDS();
4960 #undef VISIT_MD_FIELDS
4962 Result = GET_OR_DISTINCT(
4963 DIStringType,
4964 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
4965 stringLocationExpression.Val, size.Val, align.Val, encoding.Val));
4966 return false;
4969 /// parseDIDerivedType:
4970 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4971 /// line: 7, scope: !1, baseType: !2, size: 32,
4972 /// align: 32, offset: 0, flags: 0, extraData: !3,
4973 /// dwarfAddressSpace: 3)
4974 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4975 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4976 REQUIRED(tag, DwarfTagField, ); \
4977 OPTIONAL(name, MDStringField, ); \
4978 OPTIONAL(file, MDField, ); \
4979 OPTIONAL(line, LineField, ); \
4980 OPTIONAL(scope, MDField, ); \
4981 REQUIRED(baseType, MDField, ); \
4982 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4983 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4984 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4985 OPTIONAL(flags, DIFlagField, ); \
4986 OPTIONAL(extraData, MDField, ); \
4987 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
4988 OPTIONAL(annotations, MDField, );
4989 PARSE_MD_FIELDS();
4990 #undef VISIT_MD_FIELDS
4992 std::optional<unsigned> DWARFAddressSpace;
4993 if (dwarfAddressSpace.Val != UINT32_MAX)
4994 DWARFAddressSpace = dwarfAddressSpace.Val;
4996 Result = GET_OR_DISTINCT(DIDerivedType,
4997 (Context, tag.Val, name.Val, file.Val, line.Val,
4998 scope.Val, baseType.Val, size.Val, align.Val,
4999 offset.Val, DWARFAddressSpace, flags.Val,
5000 extraData.Val, annotations.Val));
5001 return false;
5004 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
5005 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5006 REQUIRED(tag, DwarfTagField, ); \
5007 OPTIONAL(name, MDStringField, ); \
5008 OPTIONAL(file, MDField, ); \
5009 OPTIONAL(line, LineField, ); \
5010 OPTIONAL(scope, MDField, ); \
5011 OPTIONAL(baseType, MDField, ); \
5012 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5013 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5014 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5015 OPTIONAL(flags, DIFlagField, ); \
5016 OPTIONAL(elements, MDField, ); \
5017 OPTIONAL(runtimeLang, DwarfLangField, ); \
5018 OPTIONAL(vtableHolder, MDField, ); \
5019 OPTIONAL(templateParams, MDField, ); \
5020 OPTIONAL(identifier, MDStringField, ); \
5021 OPTIONAL(discriminator, MDField, ); \
5022 OPTIONAL(dataLocation, MDField, ); \
5023 OPTIONAL(associated, MDField, ); \
5024 OPTIONAL(allocated, MDField, ); \
5025 OPTIONAL(rank, MDSignedOrMDField, ); \
5026 OPTIONAL(annotations, MDField, );
5027 PARSE_MD_FIELDS();
5028 #undef VISIT_MD_FIELDS
5030 Metadata *Rank = nullptr;
5031 if (rank.isMDSignedField())
5032 Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
5033 Type::getInt64Ty(Context), rank.getMDSignedValue()));
5034 else if (rank.isMDField())
5035 Rank = rank.getMDFieldValue();
5037 // If this has an identifier try to build an ODR type.
5038 if (identifier.Val)
5039 if (auto *CT = DICompositeType::buildODRType(
5040 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
5041 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
5042 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
5043 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
5044 Rank, annotations.Val)) {
5045 Result = CT;
5046 return false;
5049 // Create a new node, and save it in the context if it belongs in the type
5050 // map.
5051 Result = GET_OR_DISTINCT(
5052 DICompositeType,
5053 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
5054 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
5055 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
5056 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
5057 annotations.Val));
5058 return false;
5061 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
5062 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5063 OPTIONAL(flags, DIFlagField, ); \
5064 OPTIONAL(cc, DwarfCCField, ); \
5065 REQUIRED(types, MDField, );
5066 PARSE_MD_FIELDS();
5067 #undef VISIT_MD_FIELDS
5069 Result = GET_OR_DISTINCT(DISubroutineType,
5070 (Context, flags.Val, cc.Val, types.Val));
5071 return false;
5074 /// parseDIFileType:
5075 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5076 /// checksumkind: CSK_MD5,
5077 /// checksum: "000102030405060708090a0b0c0d0e0f",
5078 /// source: "source file contents")
5079 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
5080 // The default constructed value for checksumkind is required, but will never
5081 // be used, as the parser checks if the field was actually Seen before using
5082 // the Val.
5083 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5084 REQUIRED(filename, MDStringField, ); \
5085 REQUIRED(directory, MDStringField, ); \
5086 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5087 OPTIONAL(checksum, MDStringField, ); \
5088 OPTIONAL(source, MDStringField, );
5089 PARSE_MD_FIELDS();
5090 #undef VISIT_MD_FIELDS
5092 std::optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
5093 if (checksumkind.Seen && checksum.Seen)
5094 OptChecksum.emplace(checksumkind.Val, checksum.Val);
5095 else if (checksumkind.Seen || checksum.Seen)
5096 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
5098 MDString *Source = nullptr;
5099 if (source.Seen)
5100 Source = source.Val;
5101 Result = GET_OR_DISTINCT(
5102 DIFile, (Context, filename.Val, directory.Val, OptChecksum, Source));
5103 return false;
5106 /// parseDICompileUnit:
5107 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5108 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5109 /// splitDebugFilename: "abc.debug",
5110 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5111 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5112 /// sysroot: "/", sdk: "MacOSX.sdk")
5113 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
5114 if (!IsDistinct)
5115 return Lex.Error("missing 'distinct', required for !DICompileUnit");
5117 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5118 REQUIRED(language, DwarfLangField, ); \
5119 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5120 OPTIONAL(producer, MDStringField, ); \
5121 OPTIONAL(isOptimized, MDBoolField, ); \
5122 OPTIONAL(flags, MDStringField, ); \
5123 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5124 OPTIONAL(splitDebugFilename, MDStringField, ); \
5125 OPTIONAL(emissionKind, EmissionKindField, ); \
5126 OPTIONAL(enums, MDField, ); \
5127 OPTIONAL(retainedTypes, MDField, ); \
5128 OPTIONAL(globals, MDField, ); \
5129 OPTIONAL(imports, MDField, ); \
5130 OPTIONAL(macros, MDField, ); \
5131 OPTIONAL(dwoId, MDUnsignedField, ); \
5132 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5133 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5134 OPTIONAL(nameTableKind, NameTableKindField, ); \
5135 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5136 OPTIONAL(sysroot, MDStringField, ); \
5137 OPTIONAL(sdk, MDStringField, );
5138 PARSE_MD_FIELDS();
5139 #undef VISIT_MD_FIELDS
5141 Result = DICompileUnit::getDistinct(
5142 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
5143 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
5144 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
5145 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
5146 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
5147 return false;
5150 /// parseDISubprogram:
5151 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5152 /// file: !1, line: 7, type: !2, isLocal: false,
5153 /// isDefinition: true, scopeLine: 8, containingType: !3,
5154 /// virtuality: DW_VIRTUALTIY_pure_virtual,
5155 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5156 /// spFlags: 10, isOptimized: false, templateParams: !4,
5157 /// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5158 /// annotations: !8)
5159 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
5160 auto Loc = Lex.getLoc();
5161 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5162 OPTIONAL(scope, MDField, ); \
5163 OPTIONAL(name, MDStringField, ); \
5164 OPTIONAL(linkageName, MDStringField, ); \
5165 OPTIONAL(file, MDField, ); \
5166 OPTIONAL(line, LineField, ); \
5167 OPTIONAL(type, MDField, ); \
5168 OPTIONAL(isLocal, MDBoolField, ); \
5169 OPTIONAL(isDefinition, MDBoolField, (true)); \
5170 OPTIONAL(scopeLine, LineField, ); \
5171 OPTIONAL(containingType, MDField, ); \
5172 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5173 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5174 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5175 OPTIONAL(flags, DIFlagField, ); \
5176 OPTIONAL(spFlags, DISPFlagField, ); \
5177 OPTIONAL(isOptimized, MDBoolField, ); \
5178 OPTIONAL(unit, MDField, ); \
5179 OPTIONAL(templateParams, MDField, ); \
5180 OPTIONAL(declaration, MDField, ); \
5181 OPTIONAL(retainedNodes, MDField, ); \
5182 OPTIONAL(thrownTypes, MDField, ); \
5183 OPTIONAL(annotations, MDField, ); \
5184 OPTIONAL(targetFuncName, MDStringField, );
5185 PARSE_MD_FIELDS();
5186 #undef VISIT_MD_FIELDS
5188 // An explicit spFlags field takes precedence over individual fields in
5189 // older IR versions.
5190 DISubprogram::DISPFlags SPFlags =
5191 spFlags.Seen ? spFlags.Val
5192 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
5193 isOptimized.Val, virtuality.Val);
5194 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
5195 return Lex.Error(
5196 Loc,
5197 "missing 'distinct', required for !DISubprogram that is a Definition");
5198 Result = GET_OR_DISTINCT(
5199 DISubprogram,
5200 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
5201 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
5202 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
5203 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
5204 targetFuncName.Val));
5205 return false;
5208 /// parseDILexicalBlock:
5209 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5210 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
5211 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5212 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5213 OPTIONAL(file, MDField, ); \
5214 OPTIONAL(line, LineField, ); \
5215 OPTIONAL(column, ColumnField, );
5216 PARSE_MD_FIELDS();
5217 #undef VISIT_MD_FIELDS
5219 Result = GET_OR_DISTINCT(
5220 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
5221 return false;
5224 /// parseDILexicalBlockFile:
5225 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5226 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
5227 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5228 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5229 OPTIONAL(file, MDField, ); \
5230 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5231 PARSE_MD_FIELDS();
5232 #undef VISIT_MD_FIELDS
5234 Result = GET_OR_DISTINCT(DILexicalBlockFile,
5235 (Context, scope.Val, file.Val, discriminator.Val));
5236 return false;
5239 /// parseDICommonBlock:
5240 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
5241 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
5242 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5243 REQUIRED(scope, MDField, ); \
5244 OPTIONAL(declaration, MDField, ); \
5245 OPTIONAL(name, MDStringField, ); \
5246 OPTIONAL(file, MDField, ); \
5247 OPTIONAL(line, LineField, );
5248 PARSE_MD_FIELDS();
5249 #undef VISIT_MD_FIELDS
5251 Result = GET_OR_DISTINCT(DICommonBlock,
5252 (Context, scope.Val, declaration.Val, name.Val,
5253 file.Val, line.Val));
5254 return false;
5257 /// parseDINamespace:
5258 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
5259 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
5260 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5261 REQUIRED(scope, MDField, ); \
5262 OPTIONAL(name, MDStringField, ); \
5263 OPTIONAL(exportSymbols, MDBoolField, );
5264 PARSE_MD_FIELDS();
5265 #undef VISIT_MD_FIELDS
5267 Result = GET_OR_DISTINCT(DINamespace,
5268 (Context, scope.Val, name.Val, exportSymbols.Val));
5269 return false;
5272 /// parseDIMacro:
5273 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5274 /// "SomeValue")
5275 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
5276 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5277 REQUIRED(type, DwarfMacinfoTypeField, ); \
5278 OPTIONAL(line, LineField, ); \
5279 REQUIRED(name, MDStringField, ); \
5280 OPTIONAL(value, MDStringField, );
5281 PARSE_MD_FIELDS();
5282 #undef VISIT_MD_FIELDS
5284 Result = GET_OR_DISTINCT(DIMacro,
5285 (Context, type.Val, line.Val, name.Val, value.Val));
5286 return false;
5289 /// parseDIMacroFile:
5290 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
5291 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
5292 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5293 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5294 OPTIONAL(line, LineField, ); \
5295 REQUIRED(file, MDField, ); \
5296 OPTIONAL(nodes, MDField, );
5297 PARSE_MD_FIELDS();
5298 #undef VISIT_MD_FIELDS
5300 Result = GET_OR_DISTINCT(DIMacroFile,
5301 (Context, type.Val, line.Val, file.Val, nodes.Val));
5302 return false;
5305 /// parseDIModule:
5306 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5307 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5308 /// file: !1, line: 4, isDecl: false)
5309 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5310 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5311 REQUIRED(scope, MDField, ); \
5312 REQUIRED(name, MDStringField, ); \
5313 OPTIONAL(configMacros, MDStringField, ); \
5314 OPTIONAL(includePath, MDStringField, ); \
5315 OPTIONAL(apinotes, MDStringField, ); \
5316 OPTIONAL(file, MDField, ); \
5317 OPTIONAL(line, LineField, ); \
5318 OPTIONAL(isDecl, MDBoolField, );
5319 PARSE_MD_FIELDS();
5320 #undef VISIT_MD_FIELDS
5322 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5323 configMacros.Val, includePath.Val,
5324 apinotes.Val, line.Val, isDecl.Val));
5325 return false;
5328 /// parseDITemplateTypeParameter:
5329 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5330 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5331 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5332 OPTIONAL(name, MDStringField, ); \
5333 REQUIRED(type, MDField, ); \
5334 OPTIONAL(defaulted, MDBoolField, );
5335 PARSE_MD_FIELDS();
5336 #undef VISIT_MD_FIELDS
5338 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
5339 (Context, name.Val, type.Val, defaulted.Val));
5340 return false;
5343 /// parseDITemplateValueParameter:
5344 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5345 /// name: "V", type: !1, defaulted: false,
5346 /// value: i32 7)
5347 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5348 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5349 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5350 OPTIONAL(name, MDStringField, ); \
5351 OPTIONAL(type, MDField, ); \
5352 OPTIONAL(defaulted, MDBoolField, ); \
5353 REQUIRED(value, MDField, );
5355 PARSE_MD_FIELDS();
5356 #undef VISIT_MD_FIELDS
5358 Result = GET_OR_DISTINCT(
5359 DITemplateValueParameter,
5360 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5361 return false;
5364 /// parseDIGlobalVariable:
5365 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5366 /// file: !1, line: 7, type: !2, isLocal: false,
5367 /// isDefinition: true, templateParams: !3,
5368 /// declaration: !4, align: 8)
5369 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5370 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5371 OPTIONAL(name, MDStringField, (/* AllowEmpty */ false)); \
5372 OPTIONAL(scope, MDField, ); \
5373 OPTIONAL(linkageName, MDStringField, ); \
5374 OPTIONAL(file, MDField, ); \
5375 OPTIONAL(line, LineField, ); \
5376 OPTIONAL(type, MDField, ); \
5377 OPTIONAL(isLocal, MDBoolField, ); \
5378 OPTIONAL(isDefinition, MDBoolField, (true)); \
5379 OPTIONAL(templateParams, MDField, ); \
5380 OPTIONAL(declaration, MDField, ); \
5381 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5382 OPTIONAL(annotations, MDField, );
5383 PARSE_MD_FIELDS();
5384 #undef VISIT_MD_FIELDS
5386 Result =
5387 GET_OR_DISTINCT(DIGlobalVariable,
5388 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5389 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5390 declaration.Val, templateParams.Val, align.Val,
5391 annotations.Val));
5392 return false;
5395 /// parseDILocalVariable:
5396 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5397 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5398 /// align: 8)
5399 /// ::= !DILocalVariable(scope: !0, name: "foo",
5400 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5401 /// align: 8)
5402 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5403 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5404 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5405 OPTIONAL(name, MDStringField, ); \
5406 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5407 OPTIONAL(file, MDField, ); \
5408 OPTIONAL(line, LineField, ); \
5409 OPTIONAL(type, MDField, ); \
5410 OPTIONAL(flags, DIFlagField, ); \
5411 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5412 OPTIONAL(annotations, MDField, );
5413 PARSE_MD_FIELDS();
5414 #undef VISIT_MD_FIELDS
5416 Result = GET_OR_DISTINCT(DILocalVariable,
5417 (Context, scope.Val, name.Val, file.Val, line.Val,
5418 type.Val, arg.Val, flags.Val, align.Val,
5419 annotations.Val));
5420 return false;
5423 /// parseDILabel:
5424 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5425 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5426 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5427 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5428 REQUIRED(name, MDStringField, ); \
5429 REQUIRED(file, MDField, ); \
5430 REQUIRED(line, LineField, );
5431 PARSE_MD_FIELDS();
5432 #undef VISIT_MD_FIELDS
5434 Result = GET_OR_DISTINCT(DILabel,
5435 (Context, scope.Val, name.Val, file.Val, line.Val));
5436 return false;
5439 /// parseDIExpression:
5440 /// ::= !DIExpression(0, 7, -1)
5441 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5442 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5443 Lex.Lex();
5445 if (parseToken(lltok::lparen, "expected '(' here"))
5446 return true;
5448 SmallVector<uint64_t, 8> Elements;
5449 if (Lex.getKind() != lltok::rparen)
5450 do {
5451 if (Lex.getKind() == lltok::DwarfOp) {
5452 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5453 Lex.Lex();
5454 Elements.push_back(Op);
5455 continue;
5457 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5460 if (Lex.getKind() == lltok::DwarfAttEncoding) {
5461 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5462 Lex.Lex();
5463 Elements.push_back(Op);
5464 continue;
5466 return tokError(Twine("invalid DWARF attribute encoding '") +
5467 Lex.getStrVal() + "'");
5470 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5471 return tokError("expected unsigned integer");
5473 auto &U = Lex.getAPSIntVal();
5474 if (U.ugt(UINT64_MAX))
5475 return tokError("element too large, limit is " + Twine(UINT64_MAX));
5476 Elements.push_back(U.getZExtValue());
5477 Lex.Lex();
5478 } while (EatIfPresent(lltok::comma));
5480 if (parseToken(lltok::rparen, "expected ')' here"))
5481 return true;
5483 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5484 return false;
5487 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) {
5488 return parseDIArgList(Result, IsDistinct, nullptr);
5490 /// ParseDIArgList:
5491 /// ::= !DIArgList(i32 7, i64 %0)
5492 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct,
5493 PerFunctionState *PFS) {
5494 assert(PFS && "Expected valid function state");
5495 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5496 Lex.Lex();
5498 if (parseToken(lltok::lparen, "expected '(' here"))
5499 return true;
5501 SmallVector<ValueAsMetadata *, 4> Args;
5502 if (Lex.getKind() != lltok::rparen)
5503 do {
5504 Metadata *MD;
5505 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5506 return true;
5507 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5508 } while (EatIfPresent(lltok::comma));
5510 if (parseToken(lltok::rparen, "expected ')' here"))
5511 return true;
5513 Result = GET_OR_DISTINCT(DIArgList, (Context, Args));
5514 return false;
5517 /// parseDIGlobalVariableExpression:
5518 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5519 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5520 bool IsDistinct) {
5521 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5522 REQUIRED(var, MDField, ); \
5523 REQUIRED(expr, MDField, );
5524 PARSE_MD_FIELDS();
5525 #undef VISIT_MD_FIELDS
5527 Result =
5528 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5529 return false;
5532 /// parseDIObjCProperty:
5533 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5534 /// getter: "getFoo", attributes: 7, type: !2)
5535 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5536 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5537 OPTIONAL(name, MDStringField, ); \
5538 OPTIONAL(file, MDField, ); \
5539 OPTIONAL(line, LineField, ); \
5540 OPTIONAL(setter, MDStringField, ); \
5541 OPTIONAL(getter, MDStringField, ); \
5542 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5543 OPTIONAL(type, MDField, );
5544 PARSE_MD_FIELDS();
5545 #undef VISIT_MD_FIELDS
5547 Result = GET_OR_DISTINCT(DIObjCProperty,
5548 (Context, name.Val, file.Val, line.Val, setter.Val,
5549 getter.Val, attributes.Val, type.Val));
5550 return false;
5553 /// parseDIImportedEntity:
5554 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5555 /// line: 7, name: "foo", elements: !2)
5556 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5557 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5558 REQUIRED(tag, DwarfTagField, ); \
5559 REQUIRED(scope, MDField, ); \
5560 OPTIONAL(entity, MDField, ); \
5561 OPTIONAL(file, MDField, ); \
5562 OPTIONAL(line, LineField, ); \
5563 OPTIONAL(name, MDStringField, ); \
5564 OPTIONAL(elements, MDField, );
5565 PARSE_MD_FIELDS();
5566 #undef VISIT_MD_FIELDS
5568 Result = GET_OR_DISTINCT(DIImportedEntity,
5569 (Context, tag.Val, scope.Val, entity.Val, file.Val,
5570 line.Val, name.Val, elements.Val));
5571 return false;
5574 #undef PARSE_MD_FIELD
5575 #undef NOP_FIELD
5576 #undef REQUIRE_FIELD
5577 #undef DECLARE_FIELD
5579 /// parseMetadataAsValue
5580 /// ::= metadata i32 %local
5581 /// ::= metadata i32 @global
5582 /// ::= metadata i32 7
5583 /// ::= metadata !0
5584 /// ::= metadata !{...}
5585 /// ::= metadata !"string"
5586 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5587 // Note: the type 'metadata' has already been parsed.
5588 Metadata *MD;
5589 if (parseMetadata(MD, &PFS))
5590 return true;
5592 V = MetadataAsValue::get(Context, MD);
5593 return false;
5596 /// parseValueAsMetadata
5597 /// ::= i32 %local
5598 /// ::= i32 @global
5599 /// ::= i32 7
5600 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5601 PerFunctionState *PFS) {
5602 Type *Ty;
5603 LocTy Loc;
5604 if (parseType(Ty, TypeMsg, Loc))
5605 return true;
5606 if (Ty->isMetadataTy())
5607 return error(Loc, "invalid metadata-value-metadata roundtrip");
5609 Value *V;
5610 if (parseValue(Ty, V, PFS))
5611 return true;
5613 MD = ValueAsMetadata::get(V);
5614 return false;
5617 /// parseMetadata
5618 /// ::= i32 %local
5619 /// ::= i32 @global
5620 /// ::= i32 7
5621 /// ::= !42
5622 /// ::= !{...}
5623 /// ::= !"string"
5624 /// ::= !DILocation(...)
5625 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5626 if (Lex.getKind() == lltok::MetadataVar) {
5627 MDNode *N;
5628 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5629 // so parsing this requires a Function State.
5630 if (Lex.getStrVal() == "DIArgList") {
5631 if (parseDIArgList(N, false, PFS))
5632 return true;
5633 } else if (parseSpecializedMDNode(N)) {
5634 return true;
5636 MD = N;
5637 return false;
5640 // ValueAsMetadata:
5641 // <type> <value>
5642 if (Lex.getKind() != lltok::exclaim)
5643 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
5645 // '!'.
5646 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5647 Lex.Lex();
5649 // MDString:
5650 // ::= '!' STRINGCONSTANT
5651 if (Lex.getKind() == lltok::StringConstant) {
5652 MDString *S;
5653 if (parseMDString(S))
5654 return true;
5655 MD = S;
5656 return false;
5659 // MDNode:
5660 // !{ ... }
5661 // !7
5662 MDNode *N;
5663 if (parseMDNodeTail(N))
5664 return true;
5665 MD = N;
5666 return false;
5669 //===----------------------------------------------------------------------===//
5670 // Function Parsing.
5671 //===----------------------------------------------------------------------===//
5673 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5674 PerFunctionState *PFS) {
5675 if (Ty->isFunctionTy())
5676 return error(ID.Loc, "functions are not values, refer to them as pointers");
5678 switch (ID.Kind) {
5679 case ValID::t_LocalID:
5680 if (!PFS)
5681 return error(ID.Loc, "invalid use of function-local name");
5682 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
5683 return V == nullptr;
5684 case ValID::t_LocalName:
5685 if (!PFS)
5686 return error(ID.Loc, "invalid use of function-local name");
5687 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
5688 return V == nullptr;
5689 case ValID::t_InlineAsm: {
5690 if (!ID.FTy)
5691 return error(ID.Loc, "invalid type for inline asm constraint string");
5692 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
5693 return error(ID.Loc, toString(std::move(Err)));
5694 V = InlineAsm::get(
5695 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
5696 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
5697 return false;
5699 case ValID::t_GlobalName:
5700 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
5701 if (V && ID.NoCFI)
5702 V = NoCFIValue::get(cast<GlobalValue>(V));
5703 return V == nullptr;
5704 case ValID::t_GlobalID:
5705 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
5706 if (V && ID.NoCFI)
5707 V = NoCFIValue::get(cast<GlobalValue>(V));
5708 return V == nullptr;
5709 case ValID::t_APSInt:
5710 if (!Ty->isIntegerTy())
5711 return error(ID.Loc, "integer constant must have integer type");
5712 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5713 V = ConstantInt::get(Context, ID.APSIntVal);
5714 return false;
5715 case ValID::t_APFloat:
5716 if (!Ty->isFloatingPointTy() ||
5717 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5718 return error(ID.Loc, "floating point constant invalid for type");
5720 // The lexer has no type info, so builds all half, bfloat, float, and double
5721 // FP constants as double. Fix this here. Long double does not need this.
5722 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5723 // Check for signaling before potentially converting and losing that info.
5724 bool IsSNAN = ID.APFloatVal.isSignaling();
5725 bool Ignored;
5726 if (Ty->isHalfTy())
5727 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5728 &Ignored);
5729 else if (Ty->isBFloatTy())
5730 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
5731 &Ignored);
5732 else if (Ty->isFloatTy())
5733 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5734 &Ignored);
5735 if (IsSNAN) {
5736 // The convert call above may quiet an SNaN, so manufacture another
5737 // SNaN. The bitcast works because the payload (significand) parameter
5738 // is truncated to fit.
5739 APInt Payload = ID.APFloatVal.bitcastToAPInt();
5740 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
5741 ID.APFloatVal.isNegative(), &Payload);
5744 V = ConstantFP::get(Context, ID.APFloatVal);
5746 if (V->getType() != Ty)
5747 return error(ID.Loc, "floating point constant does not have type '" +
5748 getTypeString(Ty) + "'");
5750 return false;
5751 case ValID::t_Null:
5752 if (!Ty->isPointerTy())
5753 return error(ID.Loc, "null must be a pointer type");
5754 V = ConstantPointerNull::get(cast<PointerType>(Ty));
5755 return false;
5756 case ValID::t_Undef:
5757 // FIXME: LabelTy should not be a first-class type.
5758 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5759 return error(ID.Loc, "invalid type for undef constant");
5760 V = UndefValue::get(Ty);
5761 return false;
5762 case ValID::t_EmptyArray:
5763 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5764 return error(ID.Loc, "invalid empty array initializer");
5765 V = UndefValue::get(Ty);
5766 return false;
5767 case ValID::t_Zero:
5768 // FIXME: LabelTy should not be a first-class type.
5769 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5770 return error(ID.Loc, "invalid type for null constant");
5771 if (auto *TETy = dyn_cast<TargetExtType>(Ty))
5772 if (!TETy->hasProperty(TargetExtType::HasZeroInit))
5773 return error(ID.Loc, "invalid type for null constant");
5774 V = Constant::getNullValue(Ty);
5775 return false;
5776 case ValID::t_None:
5777 if (!Ty->isTokenTy())
5778 return error(ID.Loc, "invalid type for none constant");
5779 V = Constant::getNullValue(Ty);
5780 return false;
5781 case ValID::t_Poison:
5782 // FIXME: LabelTy should not be a first-class type.
5783 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5784 return error(ID.Loc, "invalid type for poison constant");
5785 V = PoisonValue::get(Ty);
5786 return false;
5787 case ValID::t_Constant:
5788 if (ID.ConstantVal->getType() != Ty)
5789 return error(ID.Loc, "constant expression type mismatch: got type '" +
5790 getTypeString(ID.ConstantVal->getType()) +
5791 "' but expected '" + getTypeString(Ty) + "'");
5792 V = ID.ConstantVal;
5793 return false;
5794 case ValID::t_ConstantStruct:
5795 case ValID::t_PackedConstantStruct:
5796 if (StructType *ST = dyn_cast<StructType>(Ty)) {
5797 if (ST->getNumElements() != ID.UIntVal)
5798 return error(ID.Loc,
5799 "initializer with struct type has wrong # elements");
5800 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5801 return error(ID.Loc, "packed'ness of initializer and type don't match");
5803 // Verify that the elements are compatible with the structtype.
5804 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5805 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5806 return error(
5807 ID.Loc,
5808 "element " + Twine(i) +
5809 " of struct initializer doesn't match struct element type");
5811 V = ConstantStruct::get(
5812 ST, ArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5813 } else
5814 return error(ID.Loc, "constant expression type mismatch");
5815 return false;
5817 llvm_unreachable("Invalid ValID");
5820 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5821 C = nullptr;
5822 ValID ID;
5823 auto Loc = Lex.getLoc();
5824 if (parseValID(ID, /*PFS=*/nullptr))
5825 return true;
5826 switch (ID.Kind) {
5827 case ValID::t_APSInt:
5828 case ValID::t_APFloat:
5829 case ValID::t_Undef:
5830 case ValID::t_Constant:
5831 case ValID::t_ConstantStruct:
5832 case ValID::t_PackedConstantStruct: {
5833 Value *V;
5834 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
5835 return true;
5836 assert(isa<Constant>(V) && "Expected a constant value");
5837 C = cast<Constant>(V);
5838 return false;
5840 case ValID::t_Null:
5841 C = Constant::getNullValue(Ty);
5842 return false;
5843 default:
5844 return error(Loc, "expected a constant value");
5848 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5849 V = nullptr;
5850 ValID ID;
5851 return parseValID(ID, PFS, Ty) ||
5852 convertValIDToValue(Ty, ID, V, PFS);
5855 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5856 Type *Ty = nullptr;
5857 return parseType(Ty) || parseValue(Ty, V, PFS);
5860 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5861 PerFunctionState &PFS) {
5862 Value *V;
5863 Loc = Lex.getLoc();
5864 if (parseTypeAndValue(V, PFS))
5865 return true;
5866 if (!isa<BasicBlock>(V))
5867 return error(Loc, "expected a basic block");
5868 BB = cast<BasicBlock>(V);
5869 return false;
5872 /// FunctionHeader
5873 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5874 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5875 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5876 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5877 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) {
5878 // parse the linkage.
5879 LocTy LinkageLoc = Lex.getLoc();
5880 unsigned Linkage;
5881 unsigned Visibility;
5882 unsigned DLLStorageClass;
5883 bool DSOLocal;
5884 AttrBuilder RetAttrs(M->getContext());
5885 unsigned CC;
5886 bool HasLinkage;
5887 Type *RetType = nullptr;
5888 LocTy RetTypeLoc = Lex.getLoc();
5889 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5890 DSOLocal) ||
5891 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
5892 parseType(RetType, RetTypeLoc, true /*void allowed*/))
5893 return true;
5895 // Verify that the linkage is ok.
5896 switch ((GlobalValue::LinkageTypes)Linkage) {
5897 case GlobalValue::ExternalLinkage:
5898 break; // always ok.
5899 case GlobalValue::ExternalWeakLinkage:
5900 if (IsDefine)
5901 return error(LinkageLoc, "invalid linkage for function definition");
5902 break;
5903 case GlobalValue::PrivateLinkage:
5904 case GlobalValue::InternalLinkage:
5905 case GlobalValue::AvailableExternallyLinkage:
5906 case GlobalValue::LinkOnceAnyLinkage:
5907 case GlobalValue::LinkOnceODRLinkage:
5908 case GlobalValue::WeakAnyLinkage:
5909 case GlobalValue::WeakODRLinkage:
5910 if (!IsDefine)
5911 return error(LinkageLoc, "invalid linkage for function declaration");
5912 break;
5913 case GlobalValue::AppendingLinkage:
5914 case GlobalValue::CommonLinkage:
5915 return error(LinkageLoc, "invalid function linkage type");
5918 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5919 return error(LinkageLoc,
5920 "symbol with local linkage must have default visibility");
5922 if (!isValidDLLStorageClassForLinkage(DLLStorageClass, Linkage))
5923 return error(LinkageLoc,
5924 "symbol with local linkage cannot have a DLL storage class");
5926 if (!FunctionType::isValidReturnType(RetType))
5927 return error(RetTypeLoc, "invalid function return type");
5929 LocTy NameLoc = Lex.getLoc();
5931 std::string FunctionName;
5932 if (Lex.getKind() == lltok::GlobalVar) {
5933 FunctionName = Lex.getStrVal();
5934 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5935 unsigned NameID = Lex.getUIntVal();
5937 if (NameID != NumberedVals.size())
5938 return tokError("function expected to be numbered '%" +
5939 Twine(NumberedVals.size()) + "'");
5940 } else {
5941 return tokError("expected function name");
5944 Lex.Lex();
5946 if (Lex.getKind() != lltok::lparen)
5947 return tokError("expected '(' in function argument list");
5949 SmallVector<ArgInfo, 8> ArgList;
5950 bool IsVarArg;
5951 AttrBuilder FuncAttrs(M->getContext());
5952 std::vector<unsigned> FwdRefAttrGrps;
5953 LocTy BuiltinLoc;
5954 std::string Section;
5955 std::string Partition;
5956 MaybeAlign Alignment;
5957 std::string GC;
5958 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5959 unsigned AddrSpace = 0;
5960 Constant *Prefix = nullptr;
5961 Constant *Prologue = nullptr;
5962 Constant *PersonalityFn = nullptr;
5963 Comdat *C;
5965 if (parseArgumentList(ArgList, IsVarArg) ||
5966 parseOptionalUnnamedAddr(UnnamedAddr) ||
5967 parseOptionalProgramAddrSpace(AddrSpace) ||
5968 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5969 BuiltinLoc) ||
5970 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
5971 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
5972 parseOptionalComdat(FunctionName, C) ||
5973 parseOptionalAlignment(Alignment) ||
5974 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
5975 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
5976 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
5977 (EatIfPresent(lltok::kw_personality) &&
5978 parseGlobalTypeAndValue(PersonalityFn)))
5979 return true;
5981 if (FuncAttrs.contains(Attribute::Builtin))
5982 return error(BuiltinLoc, "'builtin' attribute not valid on function");
5984 // If the alignment was parsed as an attribute, move to the alignment field.
5985 if (MaybeAlign A = FuncAttrs.getAlignment()) {
5986 Alignment = A;
5987 FuncAttrs.removeAttribute(Attribute::Alignment);
5990 // Okay, if we got here, the function is syntactically valid. Convert types
5991 // and do semantic checks.
5992 std::vector<Type*> ParamTypeList;
5993 SmallVector<AttributeSet, 8> Attrs;
5995 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5996 ParamTypeList.push_back(ArgList[i].Ty);
5997 Attrs.push_back(ArgList[i].Attrs);
6000 AttributeList PAL =
6001 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
6002 AttributeSet::get(Context, RetAttrs), Attrs);
6004 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
6005 return error(RetTypeLoc, "functions with 'sret' argument must return void");
6007 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
6008 PointerType *PFT = PointerType::get(FT, AddrSpace);
6010 Fn = nullptr;
6011 GlobalValue *FwdFn = nullptr;
6012 if (!FunctionName.empty()) {
6013 // If this was a definition of a forward reference, remove the definition
6014 // from the forward reference table and fill in the forward ref.
6015 auto FRVI = ForwardRefVals.find(FunctionName);
6016 if (FRVI != ForwardRefVals.end()) {
6017 FwdFn = FRVI->second.first;
6018 if (FwdFn->getType() != PFT)
6019 return error(FRVI->second.second,
6020 "invalid forward reference to "
6021 "function '" +
6022 FunctionName +
6023 "' with wrong type: "
6024 "expected '" +
6025 getTypeString(PFT) + "' but was '" +
6026 getTypeString(FwdFn->getType()) + "'");
6027 ForwardRefVals.erase(FRVI);
6028 } else if ((Fn = M->getFunction(FunctionName))) {
6029 // Reject redefinitions.
6030 return error(NameLoc,
6031 "invalid redefinition of function '" + FunctionName + "'");
6032 } else if (M->getNamedValue(FunctionName)) {
6033 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
6036 } else {
6037 // If this is a definition of a forward referenced function, make sure the
6038 // types agree.
6039 auto I = ForwardRefValIDs.find(NumberedVals.size());
6040 if (I != ForwardRefValIDs.end()) {
6041 FwdFn = I->second.first;
6042 if (FwdFn->getType() != PFT)
6043 return error(NameLoc, "type of definition and forward reference of '@" +
6044 Twine(NumberedVals.size()) +
6045 "' disagree: "
6046 "expected '" +
6047 getTypeString(PFT) + "' but was '" +
6048 getTypeString(FwdFn->getType()) + "'");
6049 ForwardRefValIDs.erase(I);
6053 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
6054 FunctionName, M);
6056 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
6058 if (FunctionName.empty())
6059 NumberedVals.push_back(Fn);
6061 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
6062 maybeSetDSOLocal(DSOLocal, *Fn);
6063 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
6064 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
6065 Fn->setCallingConv(CC);
6066 Fn->setAttributes(PAL);
6067 Fn->setUnnamedAddr(UnnamedAddr);
6068 if (Alignment)
6069 Fn->setAlignment(*Alignment);
6070 Fn->setSection(Section);
6071 Fn->setPartition(Partition);
6072 Fn->setComdat(C);
6073 Fn->setPersonalityFn(PersonalityFn);
6074 if (!GC.empty()) Fn->setGC(GC);
6075 Fn->setPrefixData(Prefix);
6076 Fn->setPrologueData(Prologue);
6077 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
6079 // Add all of the arguments we parsed to the function.
6080 Function::arg_iterator ArgIt = Fn->arg_begin();
6081 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
6082 // If the argument has a name, insert it into the argument symbol table.
6083 if (ArgList[i].Name.empty()) continue;
6085 // Set the name, if it conflicted, it will be auto-renamed.
6086 ArgIt->setName(ArgList[i].Name);
6088 if (ArgIt->getName() != ArgList[i].Name)
6089 return error(ArgList[i].Loc,
6090 "redefinition of argument '%" + ArgList[i].Name + "'");
6093 if (FwdFn) {
6094 FwdFn->replaceAllUsesWith(Fn);
6095 FwdFn->eraseFromParent();
6098 if (IsDefine)
6099 return false;
6101 // Check the declaration has no block address forward references.
6102 ValID ID;
6103 if (FunctionName.empty()) {
6104 ID.Kind = ValID::t_GlobalID;
6105 ID.UIntVal = NumberedVals.size() - 1;
6106 } else {
6107 ID.Kind = ValID::t_GlobalName;
6108 ID.StrVal = FunctionName;
6110 auto Blocks = ForwardRefBlockAddresses.find(ID);
6111 if (Blocks != ForwardRefBlockAddresses.end())
6112 return error(Blocks->first.Loc,
6113 "cannot take blockaddress inside a declaration");
6114 return false;
6117 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6118 ValID ID;
6119 if (FunctionNumber == -1) {
6120 ID.Kind = ValID::t_GlobalName;
6121 ID.StrVal = std::string(F.getName());
6122 } else {
6123 ID.Kind = ValID::t_GlobalID;
6124 ID.UIntVal = FunctionNumber;
6127 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
6128 if (Blocks == P.ForwardRefBlockAddresses.end())
6129 return false;
6131 for (const auto &I : Blocks->second) {
6132 const ValID &BBID = I.first;
6133 GlobalValue *GV = I.second;
6135 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
6136 "Expected local id or name");
6137 BasicBlock *BB;
6138 if (BBID.Kind == ValID::t_LocalName)
6139 BB = getBB(BBID.StrVal, BBID.Loc);
6140 else
6141 BB = getBB(BBID.UIntVal, BBID.Loc);
6142 if (!BB)
6143 return P.error(BBID.Loc, "referenced value is not a basic block");
6145 Value *ResolvedVal = BlockAddress::get(&F, BB);
6146 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
6147 ResolvedVal);
6148 if (!ResolvedVal)
6149 return true;
6150 GV->replaceAllUsesWith(ResolvedVal);
6151 GV->eraseFromParent();
6154 P.ForwardRefBlockAddresses.erase(Blocks);
6155 return false;
6158 /// parseFunctionBody
6159 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
6160 bool LLParser::parseFunctionBody(Function &Fn) {
6161 if (Lex.getKind() != lltok::lbrace)
6162 return tokError("expected '{' in function body");
6163 Lex.Lex(); // eat the {.
6165 int FunctionNumber = -1;
6166 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
6168 PerFunctionState PFS(*this, Fn, FunctionNumber);
6170 // Resolve block addresses and allow basic blocks to be forward-declared
6171 // within this function.
6172 if (PFS.resolveForwardRefBlockAddresses())
6173 return true;
6174 SaveAndRestore ScopeExit(BlockAddressPFS, &PFS);
6176 // We need at least one basic block.
6177 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
6178 return tokError("function body requires at least one basic block");
6180 while (Lex.getKind() != lltok::rbrace &&
6181 Lex.getKind() != lltok::kw_uselistorder)
6182 if (parseBasicBlock(PFS))
6183 return true;
6185 while (Lex.getKind() != lltok::rbrace)
6186 if (parseUseListOrder(&PFS))
6187 return true;
6189 // Eat the }.
6190 Lex.Lex();
6192 // Verify function is ok.
6193 return PFS.finishFunction();
6196 /// parseBasicBlock
6197 /// ::= (LabelStr|LabelID)? Instruction*
6198 bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
6199 // If this basic block starts out with a name, remember it.
6200 std::string Name;
6201 int NameID = -1;
6202 LocTy NameLoc = Lex.getLoc();
6203 if (Lex.getKind() == lltok::LabelStr) {
6204 Name = Lex.getStrVal();
6205 Lex.Lex();
6206 } else if (Lex.getKind() == lltok::LabelID) {
6207 NameID = Lex.getUIntVal();
6208 Lex.Lex();
6211 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
6212 if (!BB)
6213 return true;
6215 std::string NameStr;
6217 // parse the instructions in this block until we get a terminator.
6218 Instruction *Inst;
6219 do {
6220 // This instruction may have three possibilities for a name: a) none
6221 // specified, b) name specified "%foo =", c) number specified: "%4 =".
6222 LocTy NameLoc = Lex.getLoc();
6223 int NameID = -1;
6224 NameStr = "";
6226 if (Lex.getKind() == lltok::LocalVarID) {
6227 NameID = Lex.getUIntVal();
6228 Lex.Lex();
6229 if (parseToken(lltok::equal, "expected '=' after instruction id"))
6230 return true;
6231 } else if (Lex.getKind() == lltok::LocalVar) {
6232 NameStr = Lex.getStrVal();
6233 Lex.Lex();
6234 if (parseToken(lltok::equal, "expected '=' after instruction name"))
6235 return true;
6238 switch (parseInstruction(Inst, BB, PFS)) {
6239 default:
6240 llvm_unreachable("Unknown parseInstruction result!");
6241 case InstError: return true;
6242 case InstNormal:
6243 Inst->insertInto(BB, BB->end());
6245 // With a normal result, we check to see if the instruction is followed by
6246 // a comma and metadata.
6247 if (EatIfPresent(lltok::comma))
6248 if (parseInstructionMetadata(*Inst))
6249 return true;
6250 break;
6251 case InstExtraComma:
6252 Inst->insertInto(BB, BB->end());
6254 // If the instruction parser ate an extra comma at the end of it, it
6255 // *must* be followed by metadata.
6256 if (parseInstructionMetadata(*Inst))
6257 return true;
6258 break;
6261 // Set the name on the instruction.
6262 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
6263 return true;
6264 } while (!Inst->isTerminator());
6266 return false;
6269 //===----------------------------------------------------------------------===//
6270 // Instruction Parsing.
6271 //===----------------------------------------------------------------------===//
6273 /// parseInstruction - parse one of the many different instructions.
6275 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
6276 PerFunctionState &PFS) {
6277 lltok::Kind Token = Lex.getKind();
6278 if (Token == lltok::Eof)
6279 return tokError("found end of file when expecting more instructions");
6280 LocTy Loc = Lex.getLoc();
6281 unsigned KeywordVal = Lex.getUIntVal();
6282 Lex.Lex(); // Eat the keyword.
6284 switch (Token) {
6285 default:
6286 return error(Loc, "expected instruction opcode");
6287 // Terminator Instructions.
6288 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
6289 case lltok::kw_ret:
6290 return parseRet(Inst, BB, PFS);
6291 case lltok::kw_br:
6292 return parseBr(Inst, PFS);
6293 case lltok::kw_switch:
6294 return parseSwitch(Inst, PFS);
6295 case lltok::kw_indirectbr:
6296 return parseIndirectBr(Inst, PFS);
6297 case lltok::kw_invoke:
6298 return parseInvoke(Inst, PFS);
6299 case lltok::kw_resume:
6300 return parseResume(Inst, PFS);
6301 case lltok::kw_cleanupret:
6302 return parseCleanupRet(Inst, PFS);
6303 case lltok::kw_catchret:
6304 return parseCatchRet(Inst, PFS);
6305 case lltok::kw_catchswitch:
6306 return parseCatchSwitch(Inst, PFS);
6307 case lltok::kw_catchpad:
6308 return parseCatchPad(Inst, PFS);
6309 case lltok::kw_cleanuppad:
6310 return parseCleanupPad(Inst, PFS);
6311 case lltok::kw_callbr:
6312 return parseCallBr(Inst, PFS);
6313 // Unary Operators.
6314 case lltok::kw_fneg: {
6315 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6316 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
6317 if (Res != 0)
6318 return Res;
6319 if (FMF.any())
6320 Inst->setFastMathFlags(FMF);
6321 return false;
6323 // Binary Operators.
6324 case lltok::kw_add:
6325 case lltok::kw_sub:
6326 case lltok::kw_mul:
6327 case lltok::kw_shl: {
6328 bool NUW = EatIfPresent(lltok::kw_nuw);
6329 bool NSW = EatIfPresent(lltok::kw_nsw);
6330 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
6332 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6333 return true;
6335 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
6336 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
6337 return false;
6339 case lltok::kw_fadd:
6340 case lltok::kw_fsub:
6341 case lltok::kw_fmul:
6342 case lltok::kw_fdiv:
6343 case lltok::kw_frem: {
6344 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6345 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
6346 if (Res != 0)
6347 return Res;
6348 if (FMF.any())
6349 Inst->setFastMathFlags(FMF);
6350 return 0;
6353 case lltok::kw_sdiv:
6354 case lltok::kw_udiv:
6355 case lltok::kw_lshr:
6356 case lltok::kw_ashr: {
6357 bool Exact = EatIfPresent(lltok::kw_exact);
6359 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6360 return true;
6361 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
6362 return false;
6365 case lltok::kw_urem:
6366 case lltok::kw_srem:
6367 return parseArithmetic(Inst, PFS, KeywordVal,
6368 /*IsFP*/ false);
6369 case lltok::kw_and:
6370 case lltok::kw_or:
6371 case lltok::kw_xor:
6372 return parseLogical(Inst, PFS, KeywordVal);
6373 case lltok::kw_icmp:
6374 return parseCompare(Inst, PFS, KeywordVal);
6375 case lltok::kw_fcmp: {
6376 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6377 int Res = parseCompare(Inst, PFS, KeywordVal);
6378 if (Res != 0)
6379 return Res;
6380 if (FMF.any())
6381 Inst->setFastMathFlags(FMF);
6382 return 0;
6385 // Casts.
6386 case lltok::kw_zext: {
6387 bool NonNeg = EatIfPresent(lltok::kw_nneg);
6388 bool Res = parseCast(Inst, PFS, KeywordVal);
6389 if (Res != 0)
6390 return Res;
6391 if (NonNeg)
6392 Inst->setNonNeg();
6393 return 0;
6395 case lltok::kw_trunc:
6396 case lltok::kw_sext:
6397 case lltok::kw_fptrunc:
6398 case lltok::kw_fpext:
6399 case lltok::kw_bitcast:
6400 case lltok::kw_addrspacecast:
6401 case lltok::kw_uitofp:
6402 case lltok::kw_sitofp:
6403 case lltok::kw_fptoui:
6404 case lltok::kw_fptosi:
6405 case lltok::kw_inttoptr:
6406 case lltok::kw_ptrtoint:
6407 return parseCast(Inst, PFS, KeywordVal);
6408 // Other.
6409 case lltok::kw_select: {
6410 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6411 int Res = parseSelect(Inst, PFS);
6412 if (Res != 0)
6413 return Res;
6414 if (FMF.any()) {
6415 if (!isa<FPMathOperator>(Inst))
6416 return error(Loc, "fast-math-flags specified for select without "
6417 "floating-point scalar or vector return type");
6418 Inst->setFastMathFlags(FMF);
6420 return 0;
6422 case lltok::kw_va_arg:
6423 return parseVAArg(Inst, PFS);
6424 case lltok::kw_extractelement:
6425 return parseExtractElement(Inst, PFS);
6426 case lltok::kw_insertelement:
6427 return parseInsertElement(Inst, PFS);
6428 case lltok::kw_shufflevector:
6429 return parseShuffleVector(Inst, PFS);
6430 case lltok::kw_phi: {
6431 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6432 int Res = parsePHI(Inst, PFS);
6433 if (Res != 0)
6434 return Res;
6435 if (FMF.any()) {
6436 if (!isa<FPMathOperator>(Inst))
6437 return error(Loc, "fast-math-flags specified for phi without "
6438 "floating-point scalar or vector return type");
6439 Inst->setFastMathFlags(FMF);
6441 return 0;
6443 case lltok::kw_landingpad:
6444 return parseLandingPad(Inst, PFS);
6445 case lltok::kw_freeze:
6446 return parseFreeze(Inst, PFS);
6447 // Call.
6448 case lltok::kw_call:
6449 return parseCall(Inst, PFS, CallInst::TCK_None);
6450 case lltok::kw_tail:
6451 return parseCall(Inst, PFS, CallInst::TCK_Tail);
6452 case lltok::kw_musttail:
6453 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
6454 case lltok::kw_notail:
6455 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
6456 // Memory.
6457 case lltok::kw_alloca:
6458 return parseAlloc(Inst, PFS);
6459 case lltok::kw_load:
6460 return parseLoad(Inst, PFS);
6461 case lltok::kw_store:
6462 return parseStore(Inst, PFS);
6463 case lltok::kw_cmpxchg:
6464 return parseCmpXchg(Inst, PFS);
6465 case lltok::kw_atomicrmw:
6466 return parseAtomicRMW(Inst, PFS);
6467 case lltok::kw_fence:
6468 return parseFence(Inst, PFS);
6469 case lltok::kw_getelementptr:
6470 return parseGetElementPtr(Inst, PFS);
6471 case lltok::kw_extractvalue:
6472 return parseExtractValue(Inst, PFS);
6473 case lltok::kw_insertvalue:
6474 return parseInsertValue(Inst, PFS);
6478 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
6479 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
6480 if (Opc == Instruction::FCmp) {
6481 switch (Lex.getKind()) {
6482 default:
6483 return tokError("expected fcmp predicate (e.g. 'oeq')");
6484 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
6485 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
6486 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
6487 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
6488 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
6489 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
6490 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
6491 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
6492 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
6493 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
6494 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
6495 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
6496 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
6497 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
6498 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
6499 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
6501 } else {
6502 switch (Lex.getKind()) {
6503 default:
6504 return tokError("expected icmp predicate (e.g. 'eq')");
6505 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
6506 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
6507 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
6508 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
6509 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
6510 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
6511 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
6512 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
6513 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
6514 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
6517 Lex.Lex();
6518 return false;
6521 //===----------------------------------------------------------------------===//
6522 // Terminator Instructions.
6523 //===----------------------------------------------------------------------===//
6525 /// parseRet - parse a return instruction.
6526 /// ::= 'ret' void (',' !dbg, !1)*
6527 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
6528 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
6529 PerFunctionState &PFS) {
6530 SMLoc TypeLoc = Lex.getLoc();
6531 Type *Ty = nullptr;
6532 if (parseType(Ty, true /*void allowed*/))
6533 return true;
6535 Type *ResType = PFS.getFunction().getReturnType();
6537 if (Ty->isVoidTy()) {
6538 if (!ResType->isVoidTy())
6539 return error(TypeLoc, "value doesn't match function result type '" +
6540 getTypeString(ResType) + "'");
6542 Inst = ReturnInst::Create(Context);
6543 return false;
6546 Value *RV;
6547 if (parseValue(Ty, RV, PFS))
6548 return true;
6550 if (ResType != RV->getType())
6551 return error(TypeLoc, "value doesn't match function result type '" +
6552 getTypeString(ResType) + "'");
6554 Inst = ReturnInst::Create(Context, RV);
6555 return false;
6558 /// parseBr
6559 /// ::= 'br' TypeAndValue
6560 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6561 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
6562 LocTy Loc, Loc2;
6563 Value *Op0;
6564 BasicBlock *Op1, *Op2;
6565 if (parseTypeAndValue(Op0, Loc, PFS))
6566 return true;
6568 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
6569 Inst = BranchInst::Create(BB);
6570 return false;
6573 if (Op0->getType() != Type::getInt1Ty(Context))
6574 return error(Loc, "branch condition must have 'i1' type");
6576 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
6577 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
6578 parseToken(lltok::comma, "expected ',' after true destination") ||
6579 parseTypeAndBasicBlock(Op2, Loc2, PFS))
6580 return true;
6582 Inst = BranchInst::Create(Op1, Op2, Op0);
6583 return false;
6586 /// parseSwitch
6587 /// Instruction
6588 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6589 /// JumpTable
6590 /// ::= (TypeAndValue ',' TypeAndValue)*
6591 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6592 LocTy CondLoc, BBLoc;
6593 Value *Cond;
6594 BasicBlock *DefaultBB;
6595 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
6596 parseToken(lltok::comma, "expected ',' after switch condition") ||
6597 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
6598 parseToken(lltok::lsquare, "expected '[' with switch table"))
6599 return true;
6601 if (!Cond->getType()->isIntegerTy())
6602 return error(CondLoc, "switch condition must have integer type");
6604 // parse the jump table pairs.
6605 SmallPtrSet<Value*, 32> SeenCases;
6606 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
6607 while (Lex.getKind() != lltok::rsquare) {
6608 Value *Constant;
6609 BasicBlock *DestBB;
6611 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
6612 parseToken(lltok::comma, "expected ',' after case value") ||
6613 parseTypeAndBasicBlock(DestBB, PFS))
6614 return true;
6616 if (!SeenCases.insert(Constant).second)
6617 return error(CondLoc, "duplicate case value in switch");
6618 if (!isa<ConstantInt>(Constant))
6619 return error(CondLoc, "case value is not a constant integer");
6621 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
6624 Lex.Lex(); // Eat the ']'.
6626 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
6627 for (unsigned i = 0, e = Table.size(); i != e; ++i)
6628 SI->addCase(Table[i].first, Table[i].second);
6629 Inst = SI;
6630 return false;
6633 /// parseIndirectBr
6634 /// Instruction
6635 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
6636 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
6637 LocTy AddrLoc;
6638 Value *Address;
6639 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
6640 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
6641 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
6642 return true;
6644 if (!Address->getType()->isPointerTy())
6645 return error(AddrLoc, "indirectbr address must have pointer type");
6647 // parse the destination list.
6648 SmallVector<BasicBlock*, 16> DestList;
6650 if (Lex.getKind() != lltok::rsquare) {
6651 BasicBlock *DestBB;
6652 if (parseTypeAndBasicBlock(DestBB, PFS))
6653 return true;
6654 DestList.push_back(DestBB);
6656 while (EatIfPresent(lltok::comma)) {
6657 if (parseTypeAndBasicBlock(DestBB, PFS))
6658 return true;
6659 DestList.push_back(DestBB);
6663 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6664 return true;
6666 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
6667 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6668 IBI->addDestination(DestList[i]);
6669 Inst = IBI;
6670 return false;
6673 // If RetType is a non-function pointer type, then this is the short syntax
6674 // for the call, which means that RetType is just the return type. Infer the
6675 // rest of the function argument types from the arguments that are present.
6676 bool LLParser::resolveFunctionType(Type *RetType,
6677 const SmallVector<ParamInfo, 16> &ArgList,
6678 FunctionType *&FuncTy) {
6679 FuncTy = dyn_cast<FunctionType>(RetType);
6680 if (!FuncTy) {
6681 // Pull out the types of all of the arguments...
6682 std::vector<Type*> ParamTypes;
6683 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6684 ParamTypes.push_back(ArgList[i].V->getType());
6686 if (!FunctionType::isValidReturnType(RetType))
6687 return true;
6689 FuncTy = FunctionType::get(RetType, ParamTypes, false);
6691 return false;
6694 /// parseInvoke
6695 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6696 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6697 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6698 LocTy CallLoc = Lex.getLoc();
6699 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
6700 std::vector<unsigned> FwdRefAttrGrps;
6701 LocTy NoBuiltinLoc;
6702 unsigned CC;
6703 unsigned InvokeAddrSpace;
6704 Type *RetType = nullptr;
6705 LocTy RetTypeLoc;
6706 ValID CalleeID;
6707 SmallVector<ParamInfo, 16> ArgList;
6708 SmallVector<OperandBundleDef, 2> BundleList;
6710 BasicBlock *NormalBB, *UnwindBB;
6711 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6712 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6713 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6714 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
6715 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6716 NoBuiltinLoc) ||
6717 parseOptionalOperandBundles(BundleList, PFS) ||
6718 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
6719 parseTypeAndBasicBlock(NormalBB, PFS) ||
6720 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6721 parseTypeAndBasicBlock(UnwindBB, PFS))
6722 return true;
6724 // If RetType is a non-function pointer type, then this is the short syntax
6725 // for the call, which means that RetType is just the return type. Infer the
6726 // rest of the function argument types from the arguments that are present.
6727 FunctionType *Ty;
6728 if (resolveFunctionType(RetType, ArgList, Ty))
6729 return error(RetTypeLoc, "Invalid result type for LLVM function");
6731 CalleeID.FTy = Ty;
6733 // Look up the callee.
6734 Value *Callee;
6735 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6736 Callee, &PFS))
6737 return true;
6739 // Set up the Attribute for the function.
6740 SmallVector<Value *, 8> Args;
6741 SmallVector<AttributeSet, 8> ArgAttrs;
6743 // Loop through FunctionType's arguments and ensure they are specified
6744 // correctly. Also, gather any parameter attributes.
6745 FunctionType::param_iterator I = Ty->param_begin();
6746 FunctionType::param_iterator E = Ty->param_end();
6747 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6748 Type *ExpectedTy = nullptr;
6749 if (I != E) {
6750 ExpectedTy = *I++;
6751 } else if (!Ty->isVarArg()) {
6752 return error(ArgList[i].Loc, "too many arguments specified");
6755 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6756 return error(ArgList[i].Loc, "argument is not of expected type '" +
6757 getTypeString(ExpectedTy) + "'");
6758 Args.push_back(ArgList[i].V);
6759 ArgAttrs.push_back(ArgList[i].Attrs);
6762 if (I != E)
6763 return error(CallLoc, "not enough parameters specified for call");
6765 // Finish off the Attribute and check them
6766 AttributeList PAL =
6767 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6768 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6770 InvokeInst *II =
6771 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6772 II->setCallingConv(CC);
6773 II->setAttributes(PAL);
6774 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6775 Inst = II;
6776 return false;
6779 /// parseResume
6780 /// ::= 'resume' TypeAndValue
6781 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
6782 Value *Exn; LocTy ExnLoc;
6783 if (parseTypeAndValue(Exn, ExnLoc, PFS))
6784 return true;
6786 ResumeInst *RI = ResumeInst::Create(Exn);
6787 Inst = RI;
6788 return false;
6791 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
6792 PerFunctionState &PFS) {
6793 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6794 return true;
6796 while (Lex.getKind() != lltok::rsquare) {
6797 // If this isn't the first argument, we need a comma.
6798 if (!Args.empty() &&
6799 parseToken(lltok::comma, "expected ',' in argument list"))
6800 return true;
6802 // parse the argument.
6803 LocTy ArgLoc;
6804 Type *ArgTy = nullptr;
6805 if (parseType(ArgTy, ArgLoc))
6806 return true;
6808 Value *V;
6809 if (ArgTy->isMetadataTy()) {
6810 if (parseMetadataAsValue(V, PFS))
6811 return true;
6812 } else {
6813 if (parseValue(ArgTy, V, PFS))
6814 return true;
6816 Args.push_back(V);
6819 Lex.Lex(); // Lex the ']'.
6820 return false;
6823 /// parseCleanupRet
6824 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6825 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6826 Value *CleanupPad = nullptr;
6828 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6829 return true;
6831 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6832 return true;
6834 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6835 return true;
6837 BasicBlock *UnwindBB = nullptr;
6838 if (Lex.getKind() == lltok::kw_to) {
6839 Lex.Lex();
6840 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6841 return true;
6842 } else {
6843 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
6844 return true;
6848 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6849 return false;
6852 /// parseCatchRet
6853 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6854 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6855 Value *CatchPad = nullptr;
6857 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
6858 return true;
6860 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
6861 return true;
6863 BasicBlock *BB;
6864 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
6865 parseTypeAndBasicBlock(BB, PFS))
6866 return true;
6868 Inst = CatchReturnInst::Create(CatchPad, BB);
6869 return false;
6872 /// parseCatchSwitch
6873 /// ::= 'catchswitch' within Parent
6874 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6875 Value *ParentPad;
6877 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6878 return true;
6880 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6881 Lex.getKind() != lltok::LocalVarID)
6882 return tokError("expected scope value for catchswitch");
6884 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6885 return true;
6887 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6888 return true;
6890 SmallVector<BasicBlock *, 32> Table;
6891 do {
6892 BasicBlock *DestBB;
6893 if (parseTypeAndBasicBlock(DestBB, PFS))
6894 return true;
6895 Table.push_back(DestBB);
6896 } while (EatIfPresent(lltok::comma));
6898 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6899 return true;
6901 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
6902 return true;
6904 BasicBlock *UnwindBB = nullptr;
6905 if (EatIfPresent(lltok::kw_to)) {
6906 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6907 return true;
6908 } else {
6909 if (parseTypeAndBasicBlock(UnwindBB, PFS))
6910 return true;
6913 auto *CatchSwitch =
6914 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6915 for (BasicBlock *DestBB : Table)
6916 CatchSwitch->addHandler(DestBB);
6917 Inst = CatchSwitch;
6918 return false;
6921 /// parseCatchPad
6922 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6923 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6924 Value *CatchSwitch = nullptr;
6926 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
6927 return true;
6929 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6930 return tokError("expected scope value for catchpad");
6932 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6933 return true;
6935 SmallVector<Value *, 8> Args;
6936 if (parseExceptionArgs(Args, PFS))
6937 return true;
6939 Inst = CatchPadInst::Create(CatchSwitch, Args);
6940 return false;
6943 /// parseCleanupPad
6944 /// ::= 'cleanuppad' within Parent ParamList
6945 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6946 Value *ParentPad = nullptr;
6948 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6949 return true;
6951 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6952 Lex.getKind() != lltok::LocalVarID)
6953 return tokError("expected scope value for cleanuppad");
6955 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6956 return true;
6958 SmallVector<Value *, 8> Args;
6959 if (parseExceptionArgs(Args, PFS))
6960 return true;
6962 Inst = CleanupPadInst::Create(ParentPad, Args);
6963 return false;
6966 //===----------------------------------------------------------------------===//
6967 // Unary Operators.
6968 //===----------------------------------------------------------------------===//
6970 /// parseUnaryOp
6971 /// ::= UnaryOp TypeAndValue ',' Value
6973 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6974 /// operand is allowed.
6975 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6976 unsigned Opc, bool IsFP) {
6977 LocTy Loc; Value *LHS;
6978 if (parseTypeAndValue(LHS, Loc, PFS))
6979 return true;
6981 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6982 : LHS->getType()->isIntOrIntVectorTy();
6984 if (!Valid)
6985 return error(Loc, "invalid operand type for instruction");
6987 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6988 return false;
6991 /// parseCallBr
6992 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6993 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6994 /// '[' LabelList ']'
6995 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6996 LocTy CallLoc = Lex.getLoc();
6997 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
6998 std::vector<unsigned> FwdRefAttrGrps;
6999 LocTy NoBuiltinLoc;
7000 unsigned CC;
7001 Type *RetType = nullptr;
7002 LocTy RetTypeLoc;
7003 ValID CalleeID;
7004 SmallVector<ParamInfo, 16> ArgList;
7005 SmallVector<OperandBundleDef, 2> BundleList;
7007 BasicBlock *DefaultDest;
7008 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7009 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7010 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
7011 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
7012 NoBuiltinLoc) ||
7013 parseOptionalOperandBundles(BundleList, PFS) ||
7014 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
7015 parseTypeAndBasicBlock(DefaultDest, PFS) ||
7016 parseToken(lltok::lsquare, "expected '[' in callbr"))
7017 return true;
7019 // parse the destination list.
7020 SmallVector<BasicBlock *, 16> IndirectDests;
7022 if (Lex.getKind() != lltok::rsquare) {
7023 BasicBlock *DestBB;
7024 if (parseTypeAndBasicBlock(DestBB, PFS))
7025 return true;
7026 IndirectDests.push_back(DestBB);
7028 while (EatIfPresent(lltok::comma)) {
7029 if (parseTypeAndBasicBlock(DestBB, PFS))
7030 return true;
7031 IndirectDests.push_back(DestBB);
7035 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
7036 return true;
7038 // If RetType is a non-function pointer type, then this is the short syntax
7039 // for the call, which means that RetType is just the return type. Infer the
7040 // rest of the function argument types from the arguments that are present.
7041 FunctionType *Ty;
7042 if (resolveFunctionType(RetType, ArgList, Ty))
7043 return error(RetTypeLoc, "Invalid result type for LLVM function");
7045 CalleeID.FTy = Ty;
7047 // Look up the callee.
7048 Value *Callee;
7049 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
7050 return true;
7052 // Set up the Attribute for the function.
7053 SmallVector<Value *, 8> Args;
7054 SmallVector<AttributeSet, 8> ArgAttrs;
7056 // Loop through FunctionType's arguments and ensure they are specified
7057 // correctly. Also, gather any parameter attributes.
7058 FunctionType::param_iterator I = Ty->param_begin();
7059 FunctionType::param_iterator E = Ty->param_end();
7060 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7061 Type *ExpectedTy = nullptr;
7062 if (I != E) {
7063 ExpectedTy = *I++;
7064 } else if (!Ty->isVarArg()) {
7065 return error(ArgList[i].Loc, "too many arguments specified");
7068 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7069 return error(ArgList[i].Loc, "argument is not of expected type '" +
7070 getTypeString(ExpectedTy) + "'");
7071 Args.push_back(ArgList[i].V);
7072 ArgAttrs.push_back(ArgList[i].Attrs);
7075 if (I != E)
7076 return error(CallLoc, "not enough parameters specified for call");
7078 // Finish off the Attribute and check them
7079 AttributeList PAL =
7080 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7081 AttributeSet::get(Context, RetAttrs), ArgAttrs);
7083 CallBrInst *CBI =
7084 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
7085 BundleList);
7086 CBI->setCallingConv(CC);
7087 CBI->setAttributes(PAL);
7088 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
7089 Inst = CBI;
7090 return false;
7093 //===----------------------------------------------------------------------===//
7094 // Binary Operators.
7095 //===----------------------------------------------------------------------===//
7097 /// parseArithmetic
7098 /// ::= ArithmeticOps TypeAndValue ',' Value
7100 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7101 /// operand is allowed.
7102 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
7103 unsigned Opc, bool IsFP) {
7104 LocTy Loc; Value *LHS, *RHS;
7105 if (parseTypeAndValue(LHS, Loc, PFS) ||
7106 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
7107 parseValue(LHS->getType(), RHS, PFS))
7108 return true;
7110 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
7111 : LHS->getType()->isIntOrIntVectorTy();
7113 if (!Valid)
7114 return error(Loc, "invalid operand type for instruction");
7116 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7117 return false;
7120 /// parseLogical
7121 /// ::= ArithmeticOps TypeAndValue ',' Value {
7122 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
7123 unsigned Opc) {
7124 LocTy Loc; Value *LHS, *RHS;
7125 if (parseTypeAndValue(LHS, Loc, PFS) ||
7126 parseToken(lltok::comma, "expected ',' in logical operation") ||
7127 parseValue(LHS->getType(), RHS, PFS))
7128 return true;
7130 if (!LHS->getType()->isIntOrIntVectorTy())
7131 return error(Loc,
7132 "instruction requires integer or integer vector operands");
7134 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7135 return false;
7138 /// parseCompare
7139 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
7140 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
7141 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
7142 unsigned Opc) {
7143 // parse the integer/fp comparison predicate.
7144 LocTy Loc;
7145 unsigned Pred;
7146 Value *LHS, *RHS;
7147 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
7148 parseToken(lltok::comma, "expected ',' after compare value") ||
7149 parseValue(LHS->getType(), RHS, PFS))
7150 return true;
7152 if (Opc == Instruction::FCmp) {
7153 if (!LHS->getType()->isFPOrFPVectorTy())
7154 return error(Loc, "fcmp requires floating point operands");
7155 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7156 } else {
7157 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
7158 if (!LHS->getType()->isIntOrIntVectorTy() &&
7159 !LHS->getType()->isPtrOrPtrVectorTy())
7160 return error(Loc, "icmp requires integer operands");
7161 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
7163 return false;
7166 //===----------------------------------------------------------------------===//
7167 // Other Instructions.
7168 //===----------------------------------------------------------------------===//
7170 /// parseCast
7171 /// ::= CastOpc TypeAndValue 'to' Type
7172 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
7173 unsigned Opc) {
7174 LocTy Loc;
7175 Value *Op;
7176 Type *DestTy = nullptr;
7177 if (parseTypeAndValue(Op, Loc, PFS) ||
7178 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
7179 parseType(DestTy))
7180 return true;
7182 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
7183 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
7184 return error(Loc, "invalid cast opcode for cast from '" +
7185 getTypeString(Op->getType()) + "' to '" +
7186 getTypeString(DestTy) + "'");
7188 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
7189 return false;
7192 /// parseSelect
7193 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7194 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
7195 LocTy Loc;
7196 Value *Op0, *Op1, *Op2;
7197 if (parseTypeAndValue(Op0, Loc, PFS) ||
7198 parseToken(lltok::comma, "expected ',' after select condition") ||
7199 parseTypeAndValue(Op1, PFS) ||
7200 parseToken(lltok::comma, "expected ',' after select value") ||
7201 parseTypeAndValue(Op2, PFS))
7202 return true;
7204 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
7205 return error(Loc, Reason);
7207 Inst = SelectInst::Create(Op0, Op1, Op2);
7208 return false;
7211 /// parseVAArg
7212 /// ::= 'va_arg' TypeAndValue ',' Type
7213 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
7214 Value *Op;
7215 Type *EltTy = nullptr;
7216 LocTy TypeLoc;
7217 if (parseTypeAndValue(Op, PFS) ||
7218 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
7219 parseType(EltTy, TypeLoc))
7220 return true;
7222 if (!EltTy->isFirstClassType())
7223 return error(TypeLoc, "va_arg requires operand with first class type");
7225 Inst = new VAArgInst(Op, EltTy);
7226 return false;
7229 /// parseExtractElement
7230 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
7231 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
7232 LocTy Loc;
7233 Value *Op0, *Op1;
7234 if (parseTypeAndValue(Op0, Loc, PFS) ||
7235 parseToken(lltok::comma, "expected ',' after extract value") ||
7236 parseTypeAndValue(Op1, PFS))
7237 return true;
7239 if (!ExtractElementInst::isValidOperands(Op0, Op1))
7240 return error(Loc, "invalid extractelement operands");
7242 Inst = ExtractElementInst::Create(Op0, Op1);
7243 return false;
7246 /// parseInsertElement
7247 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7248 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
7249 LocTy Loc;
7250 Value *Op0, *Op1, *Op2;
7251 if (parseTypeAndValue(Op0, Loc, PFS) ||
7252 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7253 parseTypeAndValue(Op1, PFS) ||
7254 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7255 parseTypeAndValue(Op2, PFS))
7256 return true;
7258 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
7259 return error(Loc, "invalid insertelement operands");
7261 Inst = InsertElementInst::Create(Op0, Op1, Op2);
7262 return false;
7265 /// parseShuffleVector
7266 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7267 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
7268 LocTy Loc;
7269 Value *Op0, *Op1, *Op2;
7270 if (parseTypeAndValue(Op0, Loc, PFS) ||
7271 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
7272 parseTypeAndValue(Op1, PFS) ||
7273 parseToken(lltok::comma, "expected ',' after shuffle value") ||
7274 parseTypeAndValue(Op2, PFS))
7275 return true;
7277 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
7278 return error(Loc, "invalid shufflevector operands");
7280 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
7281 return false;
7284 /// parsePHI
7285 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
7286 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
7287 Type *Ty = nullptr; LocTy TypeLoc;
7288 Value *Op0, *Op1;
7290 if (parseType(Ty, TypeLoc))
7291 return true;
7293 if (!Ty->isFirstClassType())
7294 return error(TypeLoc, "phi node must have first class type");
7296 bool First = true;
7297 bool AteExtraComma = false;
7298 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
7300 while (true) {
7301 if (First) {
7302 if (Lex.getKind() != lltok::lsquare)
7303 break;
7304 First = false;
7305 } else if (!EatIfPresent(lltok::comma))
7306 break;
7308 if (Lex.getKind() == lltok::MetadataVar) {
7309 AteExtraComma = true;
7310 break;
7313 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7314 parseValue(Ty, Op0, PFS) ||
7315 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7316 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7317 parseToken(lltok::rsquare, "expected ']' in phi value list"))
7318 return true;
7320 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
7323 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
7324 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
7325 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
7326 Inst = PN;
7327 return AteExtraComma ? InstExtraComma : InstNormal;
7330 /// parseLandingPad
7331 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7332 /// Clause
7333 /// ::= 'catch' TypeAndValue
7334 /// ::= 'filter'
7335 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
7336 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
7337 Type *Ty = nullptr; LocTy TyLoc;
7339 if (parseType(Ty, TyLoc))
7340 return true;
7342 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
7343 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
7345 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
7346 LandingPadInst::ClauseType CT;
7347 if (EatIfPresent(lltok::kw_catch))
7348 CT = LandingPadInst::Catch;
7349 else if (EatIfPresent(lltok::kw_filter))
7350 CT = LandingPadInst::Filter;
7351 else
7352 return tokError("expected 'catch' or 'filter' clause type");
7354 Value *V;
7355 LocTy VLoc;
7356 if (parseTypeAndValue(V, VLoc, PFS))
7357 return true;
7359 // A 'catch' type expects a non-array constant. A filter clause expects an
7360 // array constant.
7361 if (CT == LandingPadInst::Catch) {
7362 if (isa<ArrayType>(V->getType()))
7363 error(VLoc, "'catch' clause has an invalid type");
7364 } else {
7365 if (!isa<ArrayType>(V->getType()))
7366 error(VLoc, "'filter' clause has an invalid type");
7369 Constant *CV = dyn_cast<Constant>(V);
7370 if (!CV)
7371 return error(VLoc, "clause argument must be a constant");
7372 LP->addClause(CV);
7375 Inst = LP.release();
7376 return false;
7379 /// parseFreeze
7380 /// ::= 'freeze' Type Value
7381 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
7382 LocTy Loc;
7383 Value *Op;
7384 if (parseTypeAndValue(Op, Loc, PFS))
7385 return true;
7387 Inst = new FreezeInst(Op);
7388 return false;
7391 /// parseCall
7392 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
7393 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7394 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7395 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7396 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7397 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7398 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
7399 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7400 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
7401 CallInst::TailCallKind TCK) {
7402 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7403 std::vector<unsigned> FwdRefAttrGrps;
7404 LocTy BuiltinLoc;
7405 unsigned CallAddrSpace;
7406 unsigned CC;
7407 Type *RetType = nullptr;
7408 LocTy RetTypeLoc;
7409 ValID CalleeID;
7410 SmallVector<ParamInfo, 16> ArgList;
7411 SmallVector<OperandBundleDef, 2> BundleList;
7412 LocTy CallLoc = Lex.getLoc();
7414 if (TCK != CallInst::TCK_None &&
7415 parseToken(lltok::kw_call,
7416 "expected 'tail call', 'musttail call', or 'notail call'"))
7417 return true;
7419 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7421 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7422 parseOptionalProgramAddrSpace(CallAddrSpace) ||
7423 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7424 parseValID(CalleeID, &PFS) ||
7425 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
7426 PFS.getFunction().isVarArg()) ||
7427 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
7428 parseOptionalOperandBundles(BundleList, PFS))
7429 return true;
7431 // If RetType is a non-function pointer type, then this is the short syntax
7432 // for the call, which means that RetType is just the return type. Infer the
7433 // rest of the function argument types from the arguments that are present.
7434 FunctionType *Ty;
7435 if (resolveFunctionType(RetType, ArgList, Ty))
7436 return error(RetTypeLoc, "Invalid result type for LLVM function");
7438 CalleeID.FTy = Ty;
7440 // Look up the callee.
7441 Value *Callee;
7442 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7443 &PFS))
7444 return true;
7446 // Set up the Attribute for the function.
7447 SmallVector<AttributeSet, 8> Attrs;
7449 SmallVector<Value*, 8> Args;
7451 // Loop through FunctionType's arguments and ensure they are specified
7452 // correctly. Also, gather any parameter attributes.
7453 FunctionType::param_iterator I = Ty->param_begin();
7454 FunctionType::param_iterator E = Ty->param_end();
7455 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7456 Type *ExpectedTy = nullptr;
7457 if (I != E) {
7458 ExpectedTy = *I++;
7459 } else if (!Ty->isVarArg()) {
7460 return error(ArgList[i].Loc, "too many arguments specified");
7463 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7464 return error(ArgList[i].Loc, "argument is not of expected type '" +
7465 getTypeString(ExpectedTy) + "'");
7466 Args.push_back(ArgList[i].V);
7467 Attrs.push_back(ArgList[i].Attrs);
7470 if (I != E)
7471 return error(CallLoc, "not enough parameters specified for call");
7473 // Finish off the Attribute and check them
7474 AttributeList PAL =
7475 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7476 AttributeSet::get(Context, RetAttrs), Attrs);
7478 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
7479 CI->setTailCallKind(TCK);
7480 CI->setCallingConv(CC);
7481 if (FMF.any()) {
7482 if (!isa<FPMathOperator>(CI)) {
7483 CI->deleteValue();
7484 return error(CallLoc, "fast-math-flags specified for call without "
7485 "floating-point scalar or vector return type");
7487 CI->setFastMathFlags(FMF);
7489 CI->setAttributes(PAL);
7490 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7491 Inst = CI;
7492 return false;
7495 //===----------------------------------------------------------------------===//
7496 // Memory Instructions.
7497 //===----------------------------------------------------------------------===//
7499 /// parseAlloc
7500 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7501 /// (',' 'align' i32)? (',', 'addrspace(n))?
7502 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
7503 Value *Size = nullptr;
7504 LocTy SizeLoc, TyLoc, ASLoc;
7505 MaybeAlign Alignment;
7506 unsigned AddrSpace = 0;
7507 Type *Ty = nullptr;
7509 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7510 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7512 if (parseType(Ty, TyLoc))
7513 return true;
7515 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
7516 return error(TyLoc, "invalid type for alloca");
7518 bool AteExtraComma = false;
7519 if (EatIfPresent(lltok::comma)) {
7520 if (Lex.getKind() == lltok::kw_align) {
7521 if (parseOptionalAlignment(Alignment))
7522 return true;
7523 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7524 return true;
7525 } else if (Lex.getKind() == lltok::kw_addrspace) {
7526 ASLoc = Lex.getLoc();
7527 if (parseOptionalAddrSpace(AddrSpace))
7528 return true;
7529 } else if (Lex.getKind() == lltok::MetadataVar) {
7530 AteExtraComma = true;
7531 } else {
7532 if (parseTypeAndValue(Size, SizeLoc, PFS))
7533 return true;
7534 if (EatIfPresent(lltok::comma)) {
7535 if (Lex.getKind() == lltok::kw_align) {
7536 if (parseOptionalAlignment(Alignment))
7537 return true;
7538 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7539 return true;
7540 } else if (Lex.getKind() == lltok::kw_addrspace) {
7541 ASLoc = Lex.getLoc();
7542 if (parseOptionalAddrSpace(AddrSpace))
7543 return true;
7544 } else if (Lex.getKind() == lltok::MetadataVar) {
7545 AteExtraComma = true;
7551 if (Size && !Size->getType()->isIntegerTy())
7552 return error(SizeLoc, "element count must have integer type");
7554 SmallPtrSet<Type *, 4> Visited;
7555 if (!Alignment && !Ty->isSized(&Visited))
7556 return error(TyLoc, "Cannot allocate unsized type");
7557 if (!Alignment)
7558 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
7559 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
7560 AI->setUsedWithInAlloca(IsInAlloca);
7561 AI->setSwiftError(IsSwiftError);
7562 Inst = AI;
7563 return AteExtraComma ? InstExtraComma : InstNormal;
7566 /// parseLoad
7567 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7568 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
7569 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7570 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
7571 Value *Val; LocTy Loc;
7572 MaybeAlign Alignment;
7573 bool AteExtraComma = false;
7574 bool isAtomic = false;
7575 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7576 SyncScope::ID SSID = SyncScope::System;
7578 if (Lex.getKind() == lltok::kw_atomic) {
7579 isAtomic = true;
7580 Lex.Lex();
7583 bool isVolatile = false;
7584 if (Lex.getKind() == lltok::kw_volatile) {
7585 isVolatile = true;
7586 Lex.Lex();
7589 Type *Ty;
7590 LocTy ExplicitTypeLoc = Lex.getLoc();
7591 if (parseType(Ty) ||
7592 parseToken(lltok::comma, "expected comma after load's type") ||
7593 parseTypeAndValue(Val, Loc, PFS) ||
7594 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7595 parseOptionalCommaAlign(Alignment, AteExtraComma))
7596 return true;
7598 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
7599 return error(Loc, "load operand must be a pointer to a first class type");
7600 if (isAtomic && !Alignment)
7601 return error(Loc, "atomic load must have explicit non-zero alignment");
7602 if (Ordering == AtomicOrdering::Release ||
7603 Ordering == AtomicOrdering::AcquireRelease)
7604 return error(Loc, "atomic load cannot use Release ordering");
7606 SmallPtrSet<Type *, 4> Visited;
7607 if (!Alignment && !Ty->isSized(&Visited))
7608 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
7609 if (!Alignment)
7610 Alignment = M->getDataLayout().getABITypeAlign(Ty);
7611 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
7612 return AteExtraComma ? InstExtraComma : InstNormal;
7615 /// parseStore
7617 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7618 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7619 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7620 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
7621 Value *Val, *Ptr; LocTy Loc, PtrLoc;
7622 MaybeAlign Alignment;
7623 bool AteExtraComma = false;
7624 bool isAtomic = false;
7625 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7626 SyncScope::ID SSID = SyncScope::System;
7628 if (Lex.getKind() == lltok::kw_atomic) {
7629 isAtomic = true;
7630 Lex.Lex();
7633 bool isVolatile = false;
7634 if (Lex.getKind() == lltok::kw_volatile) {
7635 isVolatile = true;
7636 Lex.Lex();
7639 if (parseTypeAndValue(Val, Loc, PFS) ||
7640 parseToken(lltok::comma, "expected ',' after store operand") ||
7641 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7642 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7643 parseOptionalCommaAlign(Alignment, AteExtraComma))
7644 return true;
7646 if (!Ptr->getType()->isPointerTy())
7647 return error(PtrLoc, "store operand must be a pointer");
7648 if (!Val->getType()->isFirstClassType())
7649 return error(Loc, "store operand must be a first class value");
7650 if (isAtomic && !Alignment)
7651 return error(Loc, "atomic store must have explicit non-zero alignment");
7652 if (Ordering == AtomicOrdering::Acquire ||
7653 Ordering == AtomicOrdering::AcquireRelease)
7654 return error(Loc, "atomic store cannot use Acquire ordering");
7655 SmallPtrSet<Type *, 4> Visited;
7656 if (!Alignment && !Val->getType()->isSized(&Visited))
7657 return error(Loc, "storing unsized types is not allowed");
7658 if (!Alignment)
7659 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
7661 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
7662 return AteExtraComma ? InstExtraComma : InstNormal;
7665 /// parseCmpXchg
7666 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7667 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
7668 /// 'Align'?
7669 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
7670 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7671 bool AteExtraComma = false;
7672 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7673 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
7674 SyncScope::ID SSID = SyncScope::System;
7675 bool isVolatile = false;
7676 bool isWeak = false;
7677 MaybeAlign Alignment;
7679 if (EatIfPresent(lltok::kw_weak))
7680 isWeak = true;
7682 if (EatIfPresent(lltok::kw_volatile))
7683 isVolatile = true;
7685 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7686 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7687 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
7688 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7689 parseTypeAndValue(New, NewLoc, PFS) ||
7690 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7691 parseOrdering(FailureOrdering) ||
7692 parseOptionalCommaAlign(Alignment, AteExtraComma))
7693 return true;
7695 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
7696 return tokError("invalid cmpxchg success ordering");
7697 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
7698 return tokError("invalid cmpxchg failure ordering");
7699 if (!Ptr->getType()->isPointerTy())
7700 return error(PtrLoc, "cmpxchg operand must be a pointer");
7701 if (Cmp->getType() != New->getType())
7702 return error(NewLoc, "compare value and new value type do not match");
7703 if (!New->getType()->isFirstClassType())
7704 return error(NewLoc, "cmpxchg operand must be a first class value");
7706 const Align DefaultAlignment(
7707 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7708 Cmp->getType()));
7710 AtomicCmpXchgInst *CXI =
7711 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
7712 SuccessOrdering, FailureOrdering, SSID);
7713 CXI->setVolatile(isVolatile);
7714 CXI->setWeak(isWeak);
7716 Inst = CXI;
7717 return AteExtraComma ? InstExtraComma : InstNormal;
7720 /// parseAtomicRMW
7721 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7722 /// 'singlethread'? AtomicOrdering
7723 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7724 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7725 bool AteExtraComma = false;
7726 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7727 SyncScope::ID SSID = SyncScope::System;
7728 bool isVolatile = false;
7729 bool IsFP = false;
7730 AtomicRMWInst::BinOp Operation;
7731 MaybeAlign Alignment;
7733 if (EatIfPresent(lltok::kw_volatile))
7734 isVolatile = true;
7736 switch (Lex.getKind()) {
7737 default:
7738 return tokError("expected binary operation in atomicrmw");
7739 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7740 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7741 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7742 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7743 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7744 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7745 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7746 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7747 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7748 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7749 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7750 case lltok::kw_uinc_wrap:
7751 Operation = AtomicRMWInst::UIncWrap;
7752 break;
7753 case lltok::kw_udec_wrap:
7754 Operation = AtomicRMWInst::UDecWrap;
7755 break;
7756 case lltok::kw_fadd:
7757 Operation = AtomicRMWInst::FAdd;
7758 IsFP = true;
7759 break;
7760 case lltok::kw_fsub:
7761 Operation = AtomicRMWInst::FSub;
7762 IsFP = true;
7763 break;
7764 case lltok::kw_fmax:
7765 Operation = AtomicRMWInst::FMax;
7766 IsFP = true;
7767 break;
7768 case lltok::kw_fmin:
7769 Operation = AtomicRMWInst::FMin;
7770 IsFP = true;
7771 break;
7773 Lex.Lex(); // Eat the operation.
7775 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7776 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7777 parseTypeAndValue(Val, ValLoc, PFS) ||
7778 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
7779 parseOptionalCommaAlign(Alignment, AteExtraComma))
7780 return true;
7782 if (Ordering == AtomicOrdering::Unordered)
7783 return tokError("atomicrmw cannot be unordered");
7784 if (!Ptr->getType()->isPointerTy())
7785 return error(PtrLoc, "atomicrmw operand must be a pointer");
7787 if (Operation == AtomicRMWInst::Xchg) {
7788 if (!Val->getType()->isIntegerTy() &&
7789 !Val->getType()->isFloatingPointTy() &&
7790 !Val->getType()->isPointerTy()) {
7791 return error(
7792 ValLoc,
7793 "atomicrmw " + AtomicRMWInst::getOperationName(Operation) +
7794 " operand must be an integer, floating point, or pointer type");
7796 } else if (IsFP) {
7797 if (!Val->getType()->isFloatingPointTy()) {
7798 return error(ValLoc, "atomicrmw " +
7799 AtomicRMWInst::getOperationName(Operation) +
7800 " operand must be a floating point type");
7802 } else {
7803 if (!Val->getType()->isIntegerTy()) {
7804 return error(ValLoc, "atomicrmw " +
7805 AtomicRMWInst::getOperationName(Operation) +
7806 " operand must be an integer");
7810 unsigned Size =
7811 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
7812 Val->getType());
7813 if (Size < 8 || (Size & (Size - 1)))
7814 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7815 " integer");
7816 const Align DefaultAlignment(
7817 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7818 Val->getType()));
7819 AtomicRMWInst *RMWI =
7820 new AtomicRMWInst(Operation, Ptr, Val,
7821 Alignment.value_or(DefaultAlignment), Ordering, SSID);
7822 RMWI->setVolatile(isVolatile);
7823 Inst = RMWI;
7824 return AteExtraComma ? InstExtraComma : InstNormal;
7827 /// parseFence
7828 /// ::= 'fence' 'singlethread'? AtomicOrdering
7829 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
7830 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7831 SyncScope::ID SSID = SyncScope::System;
7832 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7833 return true;
7835 if (Ordering == AtomicOrdering::Unordered)
7836 return tokError("fence cannot be unordered");
7837 if (Ordering == AtomicOrdering::Monotonic)
7838 return tokError("fence cannot be monotonic");
7840 Inst = new FenceInst(Context, Ordering, SSID);
7841 return InstNormal;
7844 /// parseGetElementPtr
7845 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7846 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7847 Value *Ptr = nullptr;
7848 Value *Val = nullptr;
7849 LocTy Loc, EltLoc;
7851 bool InBounds = EatIfPresent(lltok::kw_inbounds);
7853 Type *Ty = nullptr;
7854 if (parseType(Ty) ||
7855 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
7856 parseTypeAndValue(Ptr, Loc, PFS))
7857 return true;
7859 Type *BaseType = Ptr->getType();
7860 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7861 if (!BasePointerType)
7862 return error(Loc, "base of getelementptr must be a pointer");
7864 SmallVector<Value*, 16> Indices;
7865 bool AteExtraComma = false;
7866 // GEP returns a vector of pointers if at least one of parameters is a vector.
7867 // All vector parameters should have the same vector width.
7868 ElementCount GEPWidth = BaseType->isVectorTy()
7869 ? cast<VectorType>(BaseType)->getElementCount()
7870 : ElementCount::getFixed(0);
7872 while (EatIfPresent(lltok::comma)) {
7873 if (Lex.getKind() == lltok::MetadataVar) {
7874 AteExtraComma = true;
7875 break;
7877 if (parseTypeAndValue(Val, EltLoc, PFS))
7878 return true;
7879 if (!Val->getType()->isIntOrIntVectorTy())
7880 return error(EltLoc, "getelementptr index must be an integer");
7882 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
7883 ElementCount ValNumEl = ValVTy->getElementCount();
7884 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
7885 return error(
7886 EltLoc,
7887 "getelementptr vector index has a wrong number of elements");
7888 GEPWidth = ValNumEl;
7890 Indices.push_back(Val);
7893 SmallPtrSet<Type*, 4> Visited;
7894 if (!Indices.empty() && !Ty->isSized(&Visited))
7895 return error(Loc, "base element of getelementptr must be sized");
7897 auto *STy = dyn_cast<StructType>(Ty);
7898 if (STy && STy->containsScalableVectorType())
7899 return error(Loc, "getelementptr cannot target structure that contains "
7900 "scalable vector type");
7902 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7903 return error(Loc, "invalid getelementptr indices");
7904 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7905 if (InBounds)
7906 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7907 return AteExtraComma ? InstExtraComma : InstNormal;
7910 /// parseExtractValue
7911 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
7912 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7913 Value *Val; LocTy Loc;
7914 SmallVector<unsigned, 4> Indices;
7915 bool AteExtraComma;
7916 if (parseTypeAndValue(Val, Loc, PFS) ||
7917 parseIndexList(Indices, AteExtraComma))
7918 return true;
7920 if (!Val->getType()->isAggregateType())
7921 return error(Loc, "extractvalue operand must be aggregate type");
7923 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7924 return error(Loc, "invalid indices for extractvalue");
7925 Inst = ExtractValueInst::Create(Val, Indices);
7926 return AteExtraComma ? InstExtraComma : InstNormal;
7929 /// parseInsertValue
7930 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7931 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7932 Value *Val0, *Val1; LocTy Loc0, Loc1;
7933 SmallVector<unsigned, 4> Indices;
7934 bool AteExtraComma;
7935 if (parseTypeAndValue(Val0, Loc0, PFS) ||
7936 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
7937 parseTypeAndValue(Val1, Loc1, PFS) ||
7938 parseIndexList(Indices, AteExtraComma))
7939 return true;
7941 if (!Val0->getType()->isAggregateType())
7942 return error(Loc0, "insertvalue operand must be aggregate type");
7944 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7945 if (!IndexedType)
7946 return error(Loc0, "invalid indices for insertvalue");
7947 if (IndexedType != Val1->getType())
7948 return error(Loc1, "insertvalue operand and field disagree in type: '" +
7949 getTypeString(Val1->getType()) + "' instead of '" +
7950 getTypeString(IndexedType) + "'");
7951 Inst = InsertValueInst::Create(Val0, Val1, Indices);
7952 return AteExtraComma ? InstExtraComma : InstNormal;
7955 //===----------------------------------------------------------------------===//
7956 // Embedded metadata.
7957 //===----------------------------------------------------------------------===//
7959 /// parseMDNodeVector
7960 /// ::= { Element (',' Element)* }
7961 /// Element
7962 /// ::= 'null' | TypeAndValue
7963 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7964 if (parseToken(lltok::lbrace, "expected '{' here"))
7965 return true;
7967 // Check for an empty list.
7968 if (EatIfPresent(lltok::rbrace))
7969 return false;
7971 do {
7972 // Null is a special case since it is typeless.
7973 if (EatIfPresent(lltok::kw_null)) {
7974 Elts.push_back(nullptr);
7975 continue;
7978 Metadata *MD;
7979 if (parseMetadata(MD, nullptr))
7980 return true;
7981 Elts.push_back(MD);
7982 } while (EatIfPresent(lltok::comma));
7984 return parseToken(lltok::rbrace, "expected end of metadata node");
7987 //===----------------------------------------------------------------------===//
7988 // Use-list order directives.
7989 //===----------------------------------------------------------------------===//
7990 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7991 SMLoc Loc) {
7992 if (V->use_empty())
7993 return error(Loc, "value has no uses");
7995 unsigned NumUses = 0;
7996 SmallDenseMap<const Use *, unsigned, 16> Order;
7997 for (const Use &U : V->uses()) {
7998 if (++NumUses > Indexes.size())
7999 break;
8000 Order[&U] = Indexes[NumUses - 1];
8002 if (NumUses < 2)
8003 return error(Loc, "value only has one use");
8004 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
8005 return error(Loc,
8006 "wrong number of indexes, expected " + Twine(V->getNumUses()));
8008 V->sortUseList([&](const Use &L, const Use &R) {
8009 return Order.lookup(&L) < Order.lookup(&R);
8011 return false;
8014 /// parseUseListOrderIndexes
8015 /// ::= '{' uint32 (',' uint32)+ '}'
8016 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
8017 SMLoc Loc = Lex.getLoc();
8018 if (parseToken(lltok::lbrace, "expected '{' here"))
8019 return true;
8020 if (Lex.getKind() == lltok::rbrace)
8021 return Lex.Error("expected non-empty list of uselistorder indexes");
8023 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
8024 // indexes should be distinct numbers in the range [0, size-1], and should
8025 // not be in order.
8026 unsigned Offset = 0;
8027 unsigned Max = 0;
8028 bool IsOrdered = true;
8029 assert(Indexes.empty() && "Expected empty order vector");
8030 do {
8031 unsigned Index;
8032 if (parseUInt32(Index))
8033 return true;
8035 // Update consistency checks.
8036 Offset += Index - Indexes.size();
8037 Max = std::max(Max, Index);
8038 IsOrdered &= Index == Indexes.size();
8040 Indexes.push_back(Index);
8041 } while (EatIfPresent(lltok::comma));
8043 if (parseToken(lltok::rbrace, "expected '}' here"))
8044 return true;
8046 if (Indexes.size() < 2)
8047 return error(Loc, "expected >= 2 uselistorder indexes");
8048 if (Offset != 0 || Max >= Indexes.size())
8049 return error(Loc,
8050 "expected distinct uselistorder indexes in range [0, size)");
8051 if (IsOrdered)
8052 return error(Loc, "expected uselistorder indexes to change the order");
8054 return false;
8057 /// parseUseListOrder
8058 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
8059 bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
8060 SMLoc Loc = Lex.getLoc();
8061 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
8062 return true;
8064 Value *V;
8065 SmallVector<unsigned, 16> Indexes;
8066 if (parseTypeAndValue(V, PFS) ||
8067 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
8068 parseUseListOrderIndexes(Indexes))
8069 return true;
8071 return sortUseListOrder(V, Indexes, Loc);
8074 /// parseUseListOrderBB
8075 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
8076 bool LLParser::parseUseListOrderBB() {
8077 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
8078 SMLoc Loc = Lex.getLoc();
8079 Lex.Lex();
8081 ValID Fn, Label;
8082 SmallVector<unsigned, 16> Indexes;
8083 if (parseValID(Fn, /*PFS=*/nullptr) ||
8084 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
8085 parseValID(Label, /*PFS=*/nullptr) ||
8086 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
8087 parseUseListOrderIndexes(Indexes))
8088 return true;
8090 // Check the function.
8091 GlobalValue *GV;
8092 if (Fn.Kind == ValID::t_GlobalName)
8093 GV = M->getNamedValue(Fn.StrVal);
8094 else if (Fn.Kind == ValID::t_GlobalID)
8095 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
8096 else
8097 return error(Fn.Loc, "expected function name in uselistorder_bb");
8098 if (!GV)
8099 return error(Fn.Loc,
8100 "invalid function forward reference in uselistorder_bb");
8101 auto *F = dyn_cast<Function>(GV);
8102 if (!F)
8103 return error(Fn.Loc, "expected function name in uselistorder_bb");
8104 if (F->isDeclaration())
8105 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
8107 // Check the basic block.
8108 if (Label.Kind == ValID::t_LocalID)
8109 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
8110 if (Label.Kind != ValID::t_LocalName)
8111 return error(Label.Loc, "expected basic block name in uselistorder_bb");
8112 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
8113 if (!V)
8114 return error(Label.Loc, "invalid basic block in uselistorder_bb");
8115 if (!isa<BasicBlock>(V))
8116 return error(Label.Loc, "expected basic block in uselistorder_bb");
8118 return sortUseListOrder(V, Indexes, Loc);
8121 /// ModuleEntry
8122 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
8123 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
8124 bool LLParser::parseModuleEntry(unsigned ID) {
8125 assert(Lex.getKind() == lltok::kw_module);
8126 Lex.Lex();
8128 std::string Path;
8129 if (parseToken(lltok::colon, "expected ':' here") ||
8130 parseToken(lltok::lparen, "expected '(' here") ||
8131 parseToken(lltok::kw_path, "expected 'path' here") ||
8132 parseToken(lltok::colon, "expected ':' here") ||
8133 parseStringConstant(Path) ||
8134 parseToken(lltok::comma, "expected ',' here") ||
8135 parseToken(lltok::kw_hash, "expected 'hash' here") ||
8136 parseToken(lltok::colon, "expected ':' here") ||
8137 parseToken(lltok::lparen, "expected '(' here"))
8138 return true;
8140 ModuleHash Hash;
8141 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
8142 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
8143 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
8144 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
8145 parseUInt32(Hash[4]))
8146 return true;
8148 if (parseToken(lltok::rparen, "expected ')' here") ||
8149 parseToken(lltok::rparen, "expected ')' here"))
8150 return true;
8152 auto ModuleEntry = Index->addModule(Path, Hash);
8153 ModuleIdMap[ID] = ModuleEntry->first();
8155 return false;
8158 /// TypeIdEntry
8159 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
8160 bool LLParser::parseTypeIdEntry(unsigned ID) {
8161 assert(Lex.getKind() == lltok::kw_typeid);
8162 Lex.Lex();
8164 std::string Name;
8165 if (parseToken(lltok::colon, "expected ':' here") ||
8166 parseToken(lltok::lparen, "expected '(' here") ||
8167 parseToken(lltok::kw_name, "expected 'name' here") ||
8168 parseToken(lltok::colon, "expected ':' here") ||
8169 parseStringConstant(Name))
8170 return true;
8172 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
8173 if (parseToken(lltok::comma, "expected ',' here") ||
8174 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
8175 return true;
8177 // Check if this ID was forward referenced, and if so, update the
8178 // corresponding GUIDs.
8179 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8180 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8181 for (auto TIDRef : FwdRefTIDs->second) {
8182 assert(!*TIDRef.first &&
8183 "Forward referenced type id GUID expected to be 0");
8184 *TIDRef.first = GlobalValue::getGUID(Name);
8186 ForwardRefTypeIds.erase(FwdRefTIDs);
8189 return false;
8192 /// TypeIdSummary
8193 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
8194 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
8195 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
8196 parseToken(lltok::colon, "expected ':' here") ||
8197 parseToken(lltok::lparen, "expected '(' here") ||
8198 parseTypeTestResolution(TIS.TTRes))
8199 return true;
8201 if (EatIfPresent(lltok::comma)) {
8202 // Expect optional wpdResolutions field
8203 if (parseOptionalWpdResolutions(TIS.WPDRes))
8204 return true;
8207 if (parseToken(lltok::rparen, "expected ')' here"))
8208 return true;
8210 return false;
8213 static ValueInfo EmptyVI =
8214 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
8216 /// TypeIdCompatibleVtableEntry
8217 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
8218 /// TypeIdCompatibleVtableInfo
8219 /// ')'
8220 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
8221 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
8222 Lex.Lex();
8224 std::string Name;
8225 if (parseToken(lltok::colon, "expected ':' here") ||
8226 parseToken(lltok::lparen, "expected '(' here") ||
8227 parseToken(lltok::kw_name, "expected 'name' here") ||
8228 parseToken(lltok::colon, "expected ':' here") ||
8229 parseStringConstant(Name))
8230 return true;
8232 TypeIdCompatibleVtableInfo &TI =
8233 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
8234 if (parseToken(lltok::comma, "expected ',' here") ||
8235 parseToken(lltok::kw_summary, "expected 'summary' here") ||
8236 parseToken(lltok::colon, "expected ':' here") ||
8237 parseToken(lltok::lparen, "expected '(' here"))
8238 return true;
8240 IdToIndexMapType IdToIndexMap;
8241 // parse each call edge
8242 do {
8243 uint64_t Offset;
8244 if (parseToken(lltok::lparen, "expected '(' here") ||
8245 parseToken(lltok::kw_offset, "expected 'offset' here") ||
8246 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8247 parseToken(lltok::comma, "expected ',' here"))
8248 return true;
8250 LocTy Loc = Lex.getLoc();
8251 unsigned GVId;
8252 ValueInfo VI;
8253 if (parseGVReference(VI, GVId))
8254 return true;
8256 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
8257 // forward reference. We will save the location of the ValueInfo needing an
8258 // update, but can only do so once the std::vector is finalized.
8259 if (VI == EmptyVI)
8260 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
8261 TI.push_back({Offset, VI});
8263 if (parseToken(lltok::rparen, "expected ')' in call"))
8264 return true;
8265 } while (EatIfPresent(lltok::comma));
8267 // Now that the TI vector is finalized, it is safe to save the locations
8268 // of any forward GV references that need updating later.
8269 for (auto I : IdToIndexMap) {
8270 auto &Infos = ForwardRefValueInfos[I.first];
8271 for (auto P : I.second) {
8272 assert(TI[P.first].VTableVI == EmptyVI &&
8273 "Forward referenced ValueInfo expected to be empty");
8274 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
8278 if (parseToken(lltok::rparen, "expected ')' here") ||
8279 parseToken(lltok::rparen, "expected ')' here"))
8280 return true;
8282 // Check if this ID was forward referenced, and if so, update the
8283 // corresponding GUIDs.
8284 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8285 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8286 for (auto TIDRef : FwdRefTIDs->second) {
8287 assert(!*TIDRef.first &&
8288 "Forward referenced type id GUID expected to be 0");
8289 *TIDRef.first = GlobalValue::getGUID(Name);
8291 ForwardRefTypeIds.erase(FwdRefTIDs);
8294 return false;
8297 /// TypeTestResolution
8298 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
8299 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8300 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8301 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8302 /// [',' 'inlinesBits' ':' UInt64]? ')'
8303 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
8304 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
8305 parseToken(lltok::colon, "expected ':' here") ||
8306 parseToken(lltok::lparen, "expected '(' here") ||
8307 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8308 parseToken(lltok::colon, "expected ':' here"))
8309 return true;
8311 switch (Lex.getKind()) {
8312 case lltok::kw_unknown:
8313 TTRes.TheKind = TypeTestResolution::Unknown;
8314 break;
8315 case lltok::kw_unsat:
8316 TTRes.TheKind = TypeTestResolution::Unsat;
8317 break;
8318 case lltok::kw_byteArray:
8319 TTRes.TheKind = TypeTestResolution::ByteArray;
8320 break;
8321 case lltok::kw_inline:
8322 TTRes.TheKind = TypeTestResolution::Inline;
8323 break;
8324 case lltok::kw_single:
8325 TTRes.TheKind = TypeTestResolution::Single;
8326 break;
8327 case lltok::kw_allOnes:
8328 TTRes.TheKind = TypeTestResolution::AllOnes;
8329 break;
8330 default:
8331 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
8333 Lex.Lex();
8335 if (parseToken(lltok::comma, "expected ',' here") ||
8336 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
8337 parseToken(lltok::colon, "expected ':' here") ||
8338 parseUInt32(TTRes.SizeM1BitWidth))
8339 return true;
8341 // parse optional fields
8342 while (EatIfPresent(lltok::comma)) {
8343 switch (Lex.getKind()) {
8344 case lltok::kw_alignLog2:
8345 Lex.Lex();
8346 if (parseToken(lltok::colon, "expected ':'") ||
8347 parseUInt64(TTRes.AlignLog2))
8348 return true;
8349 break;
8350 case lltok::kw_sizeM1:
8351 Lex.Lex();
8352 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
8353 return true;
8354 break;
8355 case lltok::kw_bitMask: {
8356 unsigned Val;
8357 Lex.Lex();
8358 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
8359 return true;
8360 assert(Val <= 0xff);
8361 TTRes.BitMask = (uint8_t)Val;
8362 break;
8364 case lltok::kw_inlineBits:
8365 Lex.Lex();
8366 if (parseToken(lltok::colon, "expected ':'") ||
8367 parseUInt64(TTRes.InlineBits))
8368 return true;
8369 break;
8370 default:
8371 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
8375 if (parseToken(lltok::rparen, "expected ')' here"))
8376 return true;
8378 return false;
8381 /// OptionalWpdResolutions
8382 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
8383 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
8384 bool LLParser::parseOptionalWpdResolutions(
8385 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8386 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
8387 parseToken(lltok::colon, "expected ':' here") ||
8388 parseToken(lltok::lparen, "expected '(' here"))
8389 return true;
8391 do {
8392 uint64_t Offset;
8393 WholeProgramDevirtResolution WPDRes;
8394 if (parseToken(lltok::lparen, "expected '(' here") ||
8395 parseToken(lltok::kw_offset, "expected 'offset' here") ||
8396 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8397 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
8398 parseToken(lltok::rparen, "expected ')' here"))
8399 return true;
8400 WPDResMap[Offset] = WPDRes;
8401 } while (EatIfPresent(lltok::comma));
8403 if (parseToken(lltok::rparen, "expected ')' here"))
8404 return true;
8406 return false;
8409 /// WpdRes
8410 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
8411 /// [',' OptionalResByArg]? ')'
8412 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
8413 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
8414 /// [',' OptionalResByArg]? ')'
8415 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
8416 /// [',' OptionalResByArg]? ')'
8417 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
8418 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
8419 parseToken(lltok::colon, "expected ':' here") ||
8420 parseToken(lltok::lparen, "expected '(' here") ||
8421 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8422 parseToken(lltok::colon, "expected ':' here"))
8423 return true;
8425 switch (Lex.getKind()) {
8426 case lltok::kw_indir:
8427 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
8428 break;
8429 case lltok::kw_singleImpl:
8430 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
8431 break;
8432 case lltok::kw_branchFunnel:
8433 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
8434 break;
8435 default:
8436 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8438 Lex.Lex();
8440 // parse optional fields
8441 while (EatIfPresent(lltok::comma)) {
8442 switch (Lex.getKind()) {
8443 case lltok::kw_singleImplName:
8444 Lex.Lex();
8445 if (parseToken(lltok::colon, "expected ':' here") ||
8446 parseStringConstant(WPDRes.SingleImplName))
8447 return true;
8448 break;
8449 case lltok::kw_resByArg:
8450 if (parseOptionalResByArg(WPDRes.ResByArg))
8451 return true;
8452 break;
8453 default:
8454 return error(Lex.getLoc(),
8455 "expected optional WholeProgramDevirtResolution field");
8459 if (parseToken(lltok::rparen, "expected ')' here"))
8460 return true;
8462 return false;
8465 /// OptionalResByArg
8466 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8467 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8468 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8469 /// 'virtualConstProp' )
8470 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8471 /// [',' 'bit' ':' UInt32]? ')'
8472 bool LLParser::parseOptionalResByArg(
8473 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
8474 &ResByArg) {
8475 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
8476 parseToken(lltok::colon, "expected ':' here") ||
8477 parseToken(lltok::lparen, "expected '(' here"))
8478 return true;
8480 do {
8481 std::vector<uint64_t> Args;
8482 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
8483 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
8484 parseToken(lltok::colon, "expected ':' here") ||
8485 parseToken(lltok::lparen, "expected '(' here") ||
8486 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8487 parseToken(lltok::colon, "expected ':' here"))
8488 return true;
8490 WholeProgramDevirtResolution::ByArg ByArg;
8491 switch (Lex.getKind()) {
8492 case lltok::kw_indir:
8493 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
8494 break;
8495 case lltok::kw_uniformRetVal:
8496 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
8497 break;
8498 case lltok::kw_uniqueRetVal:
8499 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
8500 break;
8501 case lltok::kw_virtualConstProp:
8502 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
8503 break;
8504 default:
8505 return error(Lex.getLoc(),
8506 "unexpected WholeProgramDevirtResolution::ByArg kind");
8508 Lex.Lex();
8510 // parse optional fields
8511 while (EatIfPresent(lltok::comma)) {
8512 switch (Lex.getKind()) {
8513 case lltok::kw_info:
8514 Lex.Lex();
8515 if (parseToken(lltok::colon, "expected ':' here") ||
8516 parseUInt64(ByArg.Info))
8517 return true;
8518 break;
8519 case lltok::kw_byte:
8520 Lex.Lex();
8521 if (parseToken(lltok::colon, "expected ':' here") ||
8522 parseUInt32(ByArg.Byte))
8523 return true;
8524 break;
8525 case lltok::kw_bit:
8526 Lex.Lex();
8527 if (parseToken(lltok::colon, "expected ':' here") ||
8528 parseUInt32(ByArg.Bit))
8529 return true;
8530 break;
8531 default:
8532 return error(Lex.getLoc(),
8533 "expected optional whole program devirt field");
8537 if (parseToken(lltok::rparen, "expected ')' here"))
8538 return true;
8540 ResByArg[Args] = ByArg;
8541 } while (EatIfPresent(lltok::comma));
8543 if (parseToken(lltok::rparen, "expected ')' here"))
8544 return true;
8546 return false;
8549 /// OptionalResByArg
8550 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
8551 bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
8552 if (parseToken(lltok::kw_args, "expected 'args' here") ||
8553 parseToken(lltok::colon, "expected ':' here") ||
8554 parseToken(lltok::lparen, "expected '(' here"))
8555 return true;
8557 do {
8558 uint64_t Val;
8559 if (parseUInt64(Val))
8560 return true;
8561 Args.push_back(Val);
8562 } while (EatIfPresent(lltok::comma));
8564 if (parseToken(lltok::rparen, "expected ')' here"))
8565 return true;
8567 return false;
8570 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
8572 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
8573 bool ReadOnly = Fwd->isReadOnly();
8574 bool WriteOnly = Fwd->isWriteOnly();
8575 assert(!(ReadOnly && WriteOnly));
8576 *Fwd = Resolved;
8577 if (ReadOnly)
8578 Fwd->setReadOnly();
8579 if (WriteOnly)
8580 Fwd->setWriteOnly();
8583 /// Stores the given Name/GUID and associated summary into the Index.
8584 /// Also updates any forward references to the associated entry ID.
8585 void LLParser::addGlobalValueToIndex(
8586 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
8587 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
8588 // First create the ValueInfo utilizing the Name or GUID.
8589 ValueInfo VI;
8590 if (GUID != 0) {
8591 assert(Name.empty());
8592 VI = Index->getOrInsertValueInfo(GUID);
8593 } else {
8594 assert(!Name.empty());
8595 if (M) {
8596 auto *GV = M->getNamedValue(Name);
8597 assert(GV);
8598 VI = Index->getOrInsertValueInfo(GV);
8599 } else {
8600 assert(
8601 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
8602 "Need a source_filename to compute GUID for local");
8603 GUID = GlobalValue::getGUID(
8604 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
8605 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
8609 // Resolve forward references from calls/refs
8610 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
8611 if (FwdRefVIs != ForwardRefValueInfos.end()) {
8612 for (auto VIRef : FwdRefVIs->second) {
8613 assert(VIRef.first->getRef() == FwdVIRef &&
8614 "Forward referenced ValueInfo expected to be empty");
8615 resolveFwdRef(VIRef.first, VI);
8617 ForwardRefValueInfos.erase(FwdRefVIs);
8620 // Resolve forward references from aliases
8621 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
8622 if (FwdRefAliasees != ForwardRefAliasees.end()) {
8623 for (auto AliaseeRef : FwdRefAliasees->second) {
8624 assert(!AliaseeRef.first->hasAliasee() &&
8625 "Forward referencing alias already has aliasee");
8626 assert(Summary && "Aliasee must be a definition");
8627 AliaseeRef.first->setAliasee(VI, Summary.get());
8629 ForwardRefAliasees.erase(FwdRefAliasees);
8632 // Add the summary if one was provided.
8633 if (Summary)
8634 Index->addGlobalValueSummary(VI, std::move(Summary));
8636 // Save the associated ValueInfo for use in later references by ID.
8637 if (ID == NumberedValueInfos.size())
8638 NumberedValueInfos.push_back(VI);
8639 else {
8640 // Handle non-continuous numbers (to make test simplification easier).
8641 if (ID > NumberedValueInfos.size())
8642 NumberedValueInfos.resize(ID + 1);
8643 NumberedValueInfos[ID] = VI;
8647 /// parseSummaryIndexFlags
8648 /// ::= 'flags' ':' UInt64
8649 bool LLParser::parseSummaryIndexFlags() {
8650 assert(Lex.getKind() == lltok::kw_flags);
8651 Lex.Lex();
8653 if (parseToken(lltok::colon, "expected ':' here"))
8654 return true;
8655 uint64_t Flags;
8656 if (parseUInt64(Flags))
8657 return true;
8658 if (Index)
8659 Index->setFlags(Flags);
8660 return false;
8663 /// parseBlockCount
8664 /// ::= 'blockcount' ':' UInt64
8665 bool LLParser::parseBlockCount() {
8666 assert(Lex.getKind() == lltok::kw_blockcount);
8667 Lex.Lex();
8669 if (parseToken(lltok::colon, "expected ':' here"))
8670 return true;
8671 uint64_t BlockCount;
8672 if (parseUInt64(BlockCount))
8673 return true;
8674 if (Index)
8675 Index->setBlockCount(BlockCount);
8676 return false;
8679 /// parseGVEntry
8680 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8681 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8682 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
8683 bool LLParser::parseGVEntry(unsigned ID) {
8684 assert(Lex.getKind() == lltok::kw_gv);
8685 Lex.Lex();
8687 if (parseToken(lltok::colon, "expected ':' here") ||
8688 parseToken(lltok::lparen, "expected '(' here"))
8689 return true;
8691 std::string Name;
8692 GlobalValue::GUID GUID = 0;
8693 switch (Lex.getKind()) {
8694 case lltok::kw_name:
8695 Lex.Lex();
8696 if (parseToken(lltok::colon, "expected ':' here") ||
8697 parseStringConstant(Name))
8698 return true;
8699 // Can't create GUID/ValueInfo until we have the linkage.
8700 break;
8701 case lltok::kw_guid:
8702 Lex.Lex();
8703 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
8704 return true;
8705 break;
8706 default:
8707 return error(Lex.getLoc(), "expected name or guid tag");
8710 if (!EatIfPresent(lltok::comma)) {
8711 // No summaries. Wrap up.
8712 if (parseToken(lltok::rparen, "expected ')' here"))
8713 return true;
8714 // This was created for a call to an external or indirect target.
8715 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8716 // created for indirect calls with VP. A Name with no GUID came from
8717 // an external definition. We pass ExternalLinkage since that is only
8718 // used when the GUID must be computed from Name, and in that case
8719 // the symbol must have external linkage.
8720 addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8721 nullptr);
8722 return false;
8725 // Have a list of summaries
8726 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8727 parseToken(lltok::colon, "expected ':' here") ||
8728 parseToken(lltok::lparen, "expected '(' here"))
8729 return true;
8730 do {
8731 switch (Lex.getKind()) {
8732 case lltok::kw_function:
8733 if (parseFunctionSummary(Name, GUID, ID))
8734 return true;
8735 break;
8736 case lltok::kw_variable:
8737 if (parseVariableSummary(Name, GUID, ID))
8738 return true;
8739 break;
8740 case lltok::kw_alias:
8741 if (parseAliasSummary(Name, GUID, ID))
8742 return true;
8743 break;
8744 default:
8745 return error(Lex.getLoc(), "expected summary type");
8747 } while (EatIfPresent(lltok::comma));
8749 if (parseToken(lltok::rparen, "expected ')' here") ||
8750 parseToken(lltok::rparen, "expected ')' here"))
8751 return true;
8753 return false;
8756 /// FunctionSummary
8757 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8758 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8759 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8760 /// [',' OptionalRefs]? ')'
8761 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8762 unsigned ID) {
8763 assert(Lex.getKind() == lltok::kw_function);
8764 Lex.Lex();
8766 StringRef ModulePath;
8767 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8768 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8769 /*NotEligibleToImport=*/false,
8770 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8771 unsigned InstCount;
8772 std::vector<FunctionSummary::EdgeTy> Calls;
8773 FunctionSummary::TypeIdInfo TypeIdInfo;
8774 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
8775 std::vector<ValueInfo> Refs;
8776 std::vector<CallsiteInfo> Callsites;
8777 std::vector<AllocInfo> Allocs;
8778 // Default is all-zeros (conservative values).
8779 FunctionSummary::FFlags FFlags = {};
8780 if (parseToken(lltok::colon, "expected ':' here") ||
8781 parseToken(lltok::lparen, "expected '(' here") ||
8782 parseModuleReference(ModulePath) ||
8783 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8784 parseToken(lltok::comma, "expected ',' here") ||
8785 parseToken(lltok::kw_insts, "expected 'insts' here") ||
8786 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
8787 return true;
8789 // parse optional fields
8790 while (EatIfPresent(lltok::comma)) {
8791 switch (Lex.getKind()) {
8792 case lltok::kw_funcFlags:
8793 if (parseOptionalFFlags(FFlags))
8794 return true;
8795 break;
8796 case lltok::kw_calls:
8797 if (parseOptionalCalls(Calls))
8798 return true;
8799 break;
8800 case lltok::kw_typeIdInfo:
8801 if (parseOptionalTypeIdInfo(TypeIdInfo))
8802 return true;
8803 break;
8804 case lltok::kw_refs:
8805 if (parseOptionalRefs(Refs))
8806 return true;
8807 break;
8808 case lltok::kw_params:
8809 if (parseOptionalParamAccesses(ParamAccesses))
8810 return true;
8811 break;
8812 case lltok::kw_allocs:
8813 if (parseOptionalAllocs(Allocs))
8814 return true;
8815 break;
8816 case lltok::kw_callsites:
8817 if (parseOptionalCallsites(Callsites))
8818 return true;
8819 break;
8820 default:
8821 return error(Lex.getLoc(), "expected optional function summary field");
8825 if (parseToken(lltok::rparen, "expected ')' here"))
8826 return true;
8828 auto FS = std::make_unique<FunctionSummary>(
8829 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8830 std::move(Calls), std::move(TypeIdInfo.TypeTests),
8831 std::move(TypeIdInfo.TypeTestAssumeVCalls),
8832 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8833 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8834 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
8835 std::move(ParamAccesses), std::move(Callsites), std::move(Allocs));
8837 FS->setModulePath(ModulePath);
8839 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8840 ID, std::move(FS));
8842 return false;
8845 /// VariableSummary
8846 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8847 /// [',' OptionalRefs]? ')'
8848 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8849 unsigned ID) {
8850 assert(Lex.getKind() == lltok::kw_variable);
8851 Lex.Lex();
8853 StringRef ModulePath;
8854 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8855 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8856 /*NotEligibleToImport=*/false,
8857 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8858 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8859 /* WriteOnly */ false,
8860 /* Constant */ false,
8861 GlobalObject::VCallVisibilityPublic);
8862 std::vector<ValueInfo> Refs;
8863 VTableFuncList VTableFuncs;
8864 if (parseToken(lltok::colon, "expected ':' here") ||
8865 parseToken(lltok::lparen, "expected '(' here") ||
8866 parseModuleReference(ModulePath) ||
8867 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8868 parseToken(lltok::comma, "expected ',' here") ||
8869 parseGVarFlags(GVarFlags))
8870 return true;
8872 // parse optional fields
8873 while (EatIfPresent(lltok::comma)) {
8874 switch (Lex.getKind()) {
8875 case lltok::kw_vTableFuncs:
8876 if (parseOptionalVTableFuncs(VTableFuncs))
8877 return true;
8878 break;
8879 case lltok::kw_refs:
8880 if (parseOptionalRefs(Refs))
8881 return true;
8882 break;
8883 default:
8884 return error(Lex.getLoc(), "expected optional variable summary field");
8888 if (parseToken(lltok::rparen, "expected ')' here"))
8889 return true;
8891 auto GS =
8892 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8894 GS->setModulePath(ModulePath);
8895 GS->setVTableFuncs(std::move(VTableFuncs));
8897 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8898 ID, std::move(GS));
8900 return false;
8903 /// AliasSummary
8904 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8905 /// 'aliasee' ':' GVReference ')'
8906 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8907 unsigned ID) {
8908 assert(Lex.getKind() == lltok::kw_alias);
8909 LocTy Loc = Lex.getLoc();
8910 Lex.Lex();
8912 StringRef ModulePath;
8913 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8914 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8915 /*NotEligibleToImport=*/false,
8916 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8917 if (parseToken(lltok::colon, "expected ':' here") ||
8918 parseToken(lltok::lparen, "expected '(' here") ||
8919 parseModuleReference(ModulePath) ||
8920 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8921 parseToken(lltok::comma, "expected ',' here") ||
8922 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8923 parseToken(lltok::colon, "expected ':' here"))
8924 return true;
8926 ValueInfo AliaseeVI;
8927 unsigned GVId;
8928 if (parseGVReference(AliaseeVI, GVId))
8929 return true;
8931 if (parseToken(lltok::rparen, "expected ')' here"))
8932 return true;
8934 auto AS = std::make_unique<AliasSummary>(GVFlags);
8936 AS->setModulePath(ModulePath);
8938 // Record forward reference if the aliasee is not parsed yet.
8939 if (AliaseeVI.getRef() == FwdVIRef) {
8940 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
8941 } else {
8942 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8943 assert(Summary && "Aliasee must be a definition");
8944 AS->setAliasee(AliaseeVI, Summary);
8947 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8948 ID, std::move(AS));
8950 return false;
8953 /// Flag
8954 /// ::= [0|1]
8955 bool LLParser::parseFlag(unsigned &Val) {
8956 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8957 return tokError("expected integer");
8958 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8959 Lex.Lex();
8960 return false;
8963 /// OptionalFFlags
8964 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8965 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8966 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
8967 /// [',' 'noInline' ':' Flag]? ')'
8968 /// [',' 'alwaysInline' ':' Flag]? ')'
8969 /// [',' 'noUnwind' ':' Flag]? ')'
8970 /// [',' 'mayThrow' ':' Flag]? ')'
8971 /// [',' 'hasUnknownCall' ':' Flag]? ')'
8972 /// [',' 'mustBeUnreachable' ':' Flag]? ')'
8974 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8975 assert(Lex.getKind() == lltok::kw_funcFlags);
8976 Lex.Lex();
8978 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
8979 parseToken(lltok::lparen, "expected '(' in funcFlags"))
8980 return true;
8982 do {
8983 unsigned Val = 0;
8984 switch (Lex.getKind()) {
8985 case lltok::kw_readNone:
8986 Lex.Lex();
8987 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8988 return true;
8989 FFlags.ReadNone = Val;
8990 break;
8991 case lltok::kw_readOnly:
8992 Lex.Lex();
8993 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8994 return true;
8995 FFlags.ReadOnly = Val;
8996 break;
8997 case lltok::kw_noRecurse:
8998 Lex.Lex();
8999 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9000 return true;
9001 FFlags.NoRecurse = Val;
9002 break;
9003 case lltok::kw_returnDoesNotAlias:
9004 Lex.Lex();
9005 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9006 return true;
9007 FFlags.ReturnDoesNotAlias = Val;
9008 break;
9009 case lltok::kw_noInline:
9010 Lex.Lex();
9011 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9012 return true;
9013 FFlags.NoInline = Val;
9014 break;
9015 case lltok::kw_alwaysInline:
9016 Lex.Lex();
9017 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9018 return true;
9019 FFlags.AlwaysInline = Val;
9020 break;
9021 case lltok::kw_noUnwind:
9022 Lex.Lex();
9023 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9024 return true;
9025 FFlags.NoUnwind = Val;
9026 break;
9027 case lltok::kw_mayThrow:
9028 Lex.Lex();
9029 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9030 return true;
9031 FFlags.MayThrow = Val;
9032 break;
9033 case lltok::kw_hasUnknownCall:
9034 Lex.Lex();
9035 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9036 return true;
9037 FFlags.HasUnknownCall = Val;
9038 break;
9039 case lltok::kw_mustBeUnreachable:
9040 Lex.Lex();
9041 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
9042 return true;
9043 FFlags.MustBeUnreachable = Val;
9044 break;
9045 default:
9046 return error(Lex.getLoc(), "expected function flag type");
9048 } while (EatIfPresent(lltok::comma));
9050 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
9051 return true;
9053 return false;
9056 /// OptionalCalls
9057 /// := 'calls' ':' '(' Call [',' Call]* ')'
9058 /// Call ::= '(' 'callee' ':' GVReference
9059 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
9060 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
9061 assert(Lex.getKind() == lltok::kw_calls);
9062 Lex.Lex();
9064 if (parseToken(lltok::colon, "expected ':' in calls") ||
9065 parseToken(lltok::lparen, "expected '(' in calls"))
9066 return true;
9068 IdToIndexMapType IdToIndexMap;
9069 // parse each call edge
9070 do {
9071 ValueInfo VI;
9072 if (parseToken(lltok::lparen, "expected '(' in call") ||
9073 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
9074 parseToken(lltok::colon, "expected ':'"))
9075 return true;
9077 LocTy Loc = Lex.getLoc();
9078 unsigned GVId;
9079 if (parseGVReference(VI, GVId))
9080 return true;
9082 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
9083 unsigned RelBF = 0;
9084 if (EatIfPresent(lltok::comma)) {
9085 // Expect either hotness or relbf
9086 if (EatIfPresent(lltok::kw_hotness)) {
9087 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
9088 return true;
9089 } else {
9090 if (parseToken(lltok::kw_relbf, "expected relbf") ||
9091 parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
9092 return true;
9095 // Keep track of the Call array index needing a forward reference.
9096 // We will save the location of the ValueInfo needing an update, but
9097 // can only do so once the std::vector is finalized.
9098 if (VI.getRef() == FwdVIRef)
9099 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
9100 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
9102 if (parseToken(lltok::rparen, "expected ')' in call"))
9103 return true;
9104 } while (EatIfPresent(lltok::comma));
9106 // Now that the Calls vector is finalized, it is safe to save the locations
9107 // of any forward GV references that need updating later.
9108 for (auto I : IdToIndexMap) {
9109 auto &Infos = ForwardRefValueInfos[I.first];
9110 for (auto P : I.second) {
9111 assert(Calls[P.first].first.getRef() == FwdVIRef &&
9112 "Forward referenced ValueInfo expected to be empty");
9113 Infos.emplace_back(&Calls[P.first].first, P.second);
9117 if (parseToken(lltok::rparen, "expected ')' in calls"))
9118 return true;
9120 return false;
9123 /// Hotness
9124 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
9125 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
9126 switch (Lex.getKind()) {
9127 case lltok::kw_unknown:
9128 Hotness = CalleeInfo::HotnessType::Unknown;
9129 break;
9130 case lltok::kw_cold:
9131 Hotness = CalleeInfo::HotnessType::Cold;
9132 break;
9133 case lltok::kw_none:
9134 Hotness = CalleeInfo::HotnessType::None;
9135 break;
9136 case lltok::kw_hot:
9137 Hotness = CalleeInfo::HotnessType::Hot;
9138 break;
9139 case lltok::kw_critical:
9140 Hotness = CalleeInfo::HotnessType::Critical;
9141 break;
9142 default:
9143 return error(Lex.getLoc(), "invalid call edge hotness");
9145 Lex.Lex();
9146 return false;
9149 /// OptionalVTableFuncs
9150 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
9151 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
9152 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
9153 assert(Lex.getKind() == lltok::kw_vTableFuncs);
9154 Lex.Lex();
9156 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
9157 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
9158 return true;
9160 IdToIndexMapType IdToIndexMap;
9161 // parse each virtual function pair
9162 do {
9163 ValueInfo VI;
9164 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
9165 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
9166 parseToken(lltok::colon, "expected ':'"))
9167 return true;
9169 LocTy Loc = Lex.getLoc();
9170 unsigned GVId;
9171 if (parseGVReference(VI, GVId))
9172 return true;
9174 uint64_t Offset;
9175 if (parseToken(lltok::comma, "expected comma") ||
9176 parseToken(lltok::kw_offset, "expected offset") ||
9177 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
9178 return true;
9180 // Keep track of the VTableFuncs array index needing a forward reference.
9181 // We will save the location of the ValueInfo needing an update, but
9182 // can only do so once the std::vector is finalized.
9183 if (VI == EmptyVI)
9184 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
9185 VTableFuncs.push_back({VI, Offset});
9187 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
9188 return true;
9189 } while (EatIfPresent(lltok::comma));
9191 // Now that the VTableFuncs vector is finalized, it is safe to save the
9192 // locations of any forward GV references that need updating later.
9193 for (auto I : IdToIndexMap) {
9194 auto &Infos = ForwardRefValueInfos[I.first];
9195 for (auto P : I.second) {
9196 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
9197 "Forward referenced ValueInfo expected to be empty");
9198 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
9202 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
9203 return true;
9205 return false;
9208 /// ParamNo := 'param' ':' UInt64
9209 bool LLParser::parseParamNo(uint64_t &ParamNo) {
9210 if (parseToken(lltok::kw_param, "expected 'param' here") ||
9211 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
9212 return true;
9213 return false;
9216 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
9217 bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
9218 APSInt Lower;
9219 APSInt Upper;
9220 auto ParseAPSInt = [&](APSInt &Val) {
9221 if (Lex.getKind() != lltok::APSInt)
9222 return tokError("expected integer");
9223 Val = Lex.getAPSIntVal();
9224 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
9225 Val.setIsSigned(true);
9226 Lex.Lex();
9227 return false;
9229 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
9230 parseToken(lltok::colon, "expected ':' here") ||
9231 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
9232 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
9233 parseToken(lltok::rsquare, "expected ']' here"))
9234 return true;
9236 ++Upper;
9237 Range =
9238 (Lower == Upper && !Lower.isMaxValue())
9239 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
9240 : ConstantRange(Lower, Upper);
9242 return false;
9245 /// ParamAccessCall
9246 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
9247 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
9248 IdLocListType &IdLocList) {
9249 if (parseToken(lltok::lparen, "expected '(' here") ||
9250 parseToken(lltok::kw_callee, "expected 'callee' here") ||
9251 parseToken(lltok::colon, "expected ':' here"))
9252 return true;
9254 unsigned GVId;
9255 ValueInfo VI;
9256 LocTy Loc = Lex.getLoc();
9257 if (parseGVReference(VI, GVId))
9258 return true;
9260 Call.Callee = VI;
9261 IdLocList.emplace_back(GVId, Loc);
9263 if (parseToken(lltok::comma, "expected ',' here") ||
9264 parseParamNo(Call.ParamNo) ||
9265 parseToken(lltok::comma, "expected ',' here") ||
9266 parseParamAccessOffset(Call.Offsets))
9267 return true;
9269 if (parseToken(lltok::rparen, "expected ')' here"))
9270 return true;
9272 return false;
9275 /// ParamAccess
9276 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
9277 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
9278 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
9279 IdLocListType &IdLocList) {
9280 if (parseToken(lltok::lparen, "expected '(' here") ||
9281 parseParamNo(Param.ParamNo) ||
9282 parseToken(lltok::comma, "expected ',' here") ||
9283 parseParamAccessOffset(Param.Use))
9284 return true;
9286 if (EatIfPresent(lltok::comma)) {
9287 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
9288 parseToken(lltok::colon, "expected ':' here") ||
9289 parseToken(lltok::lparen, "expected '(' here"))
9290 return true;
9291 do {
9292 FunctionSummary::ParamAccess::Call Call;
9293 if (parseParamAccessCall(Call, IdLocList))
9294 return true;
9295 Param.Calls.push_back(Call);
9296 } while (EatIfPresent(lltok::comma));
9298 if (parseToken(lltok::rparen, "expected ')' here"))
9299 return true;
9302 if (parseToken(lltok::rparen, "expected ')' here"))
9303 return true;
9305 return false;
9308 /// OptionalParamAccesses
9309 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
9310 bool LLParser::parseOptionalParamAccesses(
9311 std::vector<FunctionSummary::ParamAccess> &Params) {
9312 assert(Lex.getKind() == lltok::kw_params);
9313 Lex.Lex();
9315 if (parseToken(lltok::colon, "expected ':' here") ||
9316 parseToken(lltok::lparen, "expected '(' here"))
9317 return true;
9319 IdLocListType VContexts;
9320 size_t CallsNum = 0;
9321 do {
9322 FunctionSummary::ParamAccess ParamAccess;
9323 if (parseParamAccess(ParamAccess, VContexts))
9324 return true;
9325 CallsNum += ParamAccess.Calls.size();
9326 assert(VContexts.size() == CallsNum);
9327 (void)CallsNum;
9328 Params.emplace_back(std::move(ParamAccess));
9329 } while (EatIfPresent(lltok::comma));
9331 if (parseToken(lltok::rparen, "expected ')' here"))
9332 return true;
9334 // Now that the Params is finalized, it is safe to save the locations
9335 // of any forward GV references that need updating later.
9336 IdLocListType::const_iterator ItContext = VContexts.begin();
9337 for (auto &PA : Params) {
9338 for (auto &C : PA.Calls) {
9339 if (C.Callee.getRef() == FwdVIRef)
9340 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
9341 ItContext->second);
9342 ++ItContext;
9345 assert(ItContext == VContexts.end());
9347 return false;
9350 /// OptionalRefs
9351 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
9352 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9353 assert(Lex.getKind() == lltok::kw_refs);
9354 Lex.Lex();
9356 if (parseToken(lltok::colon, "expected ':' in refs") ||
9357 parseToken(lltok::lparen, "expected '(' in refs"))
9358 return true;
9360 struct ValueContext {
9361 ValueInfo VI;
9362 unsigned GVId;
9363 LocTy Loc;
9365 std::vector<ValueContext> VContexts;
9366 // parse each ref edge
9367 do {
9368 ValueContext VC;
9369 VC.Loc = Lex.getLoc();
9370 if (parseGVReference(VC.VI, VC.GVId))
9371 return true;
9372 VContexts.push_back(VC);
9373 } while (EatIfPresent(lltok::comma));
9375 // Sort value contexts so that ones with writeonly
9376 // and readonly ValueInfo are at the end of VContexts vector.
9377 // See FunctionSummary::specialRefCounts()
9378 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
9379 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9382 IdToIndexMapType IdToIndexMap;
9383 for (auto &VC : VContexts) {
9384 // Keep track of the Refs array index needing a forward reference.
9385 // We will save the location of the ValueInfo needing an update, but
9386 // can only do so once the std::vector is finalized.
9387 if (VC.VI.getRef() == FwdVIRef)
9388 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
9389 Refs.push_back(VC.VI);
9392 // Now that the Refs vector is finalized, it is safe to save the locations
9393 // of any forward GV references that need updating later.
9394 for (auto I : IdToIndexMap) {
9395 auto &Infos = ForwardRefValueInfos[I.first];
9396 for (auto P : I.second) {
9397 assert(Refs[P.first].getRef() == FwdVIRef &&
9398 "Forward referenced ValueInfo expected to be empty");
9399 Infos.emplace_back(&Refs[P.first], P.second);
9403 if (parseToken(lltok::rparen, "expected ')' in refs"))
9404 return true;
9406 return false;
9409 /// OptionalTypeIdInfo
9410 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
9411 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
9412 /// [',' TypeCheckedLoadConstVCalls]? ')'
9413 bool LLParser::parseOptionalTypeIdInfo(
9414 FunctionSummary::TypeIdInfo &TypeIdInfo) {
9415 assert(Lex.getKind() == lltok::kw_typeIdInfo);
9416 Lex.Lex();
9418 if (parseToken(lltok::colon, "expected ':' here") ||
9419 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9420 return true;
9422 do {
9423 switch (Lex.getKind()) {
9424 case lltok::kw_typeTests:
9425 if (parseTypeTests(TypeIdInfo.TypeTests))
9426 return true;
9427 break;
9428 case lltok::kw_typeTestAssumeVCalls:
9429 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
9430 TypeIdInfo.TypeTestAssumeVCalls))
9431 return true;
9432 break;
9433 case lltok::kw_typeCheckedLoadVCalls:
9434 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
9435 TypeIdInfo.TypeCheckedLoadVCalls))
9436 return true;
9437 break;
9438 case lltok::kw_typeTestAssumeConstVCalls:
9439 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
9440 TypeIdInfo.TypeTestAssumeConstVCalls))
9441 return true;
9442 break;
9443 case lltok::kw_typeCheckedLoadConstVCalls:
9444 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
9445 TypeIdInfo.TypeCheckedLoadConstVCalls))
9446 return true;
9447 break;
9448 default:
9449 return error(Lex.getLoc(), "invalid typeIdInfo list type");
9451 } while (EatIfPresent(lltok::comma));
9453 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9454 return true;
9456 return false;
9459 /// TypeTests
9460 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9461 /// [',' (SummaryID | UInt64)]* ')'
9462 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9463 assert(Lex.getKind() == lltok::kw_typeTests);
9464 Lex.Lex();
9466 if (parseToken(lltok::colon, "expected ':' here") ||
9467 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9468 return true;
9470 IdToIndexMapType IdToIndexMap;
9471 do {
9472 GlobalValue::GUID GUID = 0;
9473 if (Lex.getKind() == lltok::SummaryID) {
9474 unsigned ID = Lex.getUIntVal();
9475 LocTy Loc = Lex.getLoc();
9476 // Keep track of the TypeTests array index needing a forward reference.
9477 // We will save the location of the GUID needing an update, but
9478 // can only do so once the std::vector is finalized.
9479 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
9480 Lex.Lex();
9481 } else if (parseUInt64(GUID))
9482 return true;
9483 TypeTests.push_back(GUID);
9484 } while (EatIfPresent(lltok::comma));
9486 // Now that the TypeTests vector is finalized, it is safe to save the
9487 // locations of any forward GV references that need updating later.
9488 for (auto I : IdToIndexMap) {
9489 auto &Ids = ForwardRefTypeIds[I.first];
9490 for (auto P : I.second) {
9491 assert(TypeTests[P.first] == 0 &&
9492 "Forward referenced type id GUID expected to be 0");
9493 Ids.emplace_back(&TypeTests[P.first], P.second);
9497 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9498 return true;
9500 return false;
9503 /// VFuncIdList
9504 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
9505 bool LLParser::parseVFuncIdList(
9506 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
9507 assert(Lex.getKind() == Kind);
9508 Lex.Lex();
9510 if (parseToken(lltok::colon, "expected ':' here") ||
9511 parseToken(lltok::lparen, "expected '(' here"))
9512 return true;
9514 IdToIndexMapType IdToIndexMap;
9515 do {
9516 FunctionSummary::VFuncId VFuncId;
9517 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
9518 return true;
9519 VFuncIdList.push_back(VFuncId);
9520 } while (EatIfPresent(lltok::comma));
9522 if (parseToken(lltok::rparen, "expected ')' here"))
9523 return true;
9525 // Now that the VFuncIdList vector is finalized, it is safe to save the
9526 // locations of any forward GV references that need updating later.
9527 for (auto I : IdToIndexMap) {
9528 auto &Ids = ForwardRefTypeIds[I.first];
9529 for (auto P : I.second) {
9530 assert(VFuncIdList[P.first].GUID == 0 &&
9531 "Forward referenced type id GUID expected to be 0");
9532 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
9536 return false;
9539 /// ConstVCallList
9540 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
9541 bool LLParser::parseConstVCallList(
9542 lltok::Kind Kind,
9543 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
9544 assert(Lex.getKind() == Kind);
9545 Lex.Lex();
9547 if (parseToken(lltok::colon, "expected ':' here") ||
9548 parseToken(lltok::lparen, "expected '(' here"))
9549 return true;
9551 IdToIndexMapType IdToIndexMap;
9552 do {
9553 FunctionSummary::ConstVCall ConstVCall;
9554 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
9555 return true;
9556 ConstVCallList.push_back(ConstVCall);
9557 } while (EatIfPresent(lltok::comma));
9559 if (parseToken(lltok::rparen, "expected ')' here"))
9560 return true;
9562 // Now that the ConstVCallList vector is finalized, it is safe to save the
9563 // locations of any forward GV references that need updating later.
9564 for (auto I : IdToIndexMap) {
9565 auto &Ids = ForwardRefTypeIds[I.first];
9566 for (auto P : I.second) {
9567 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
9568 "Forward referenced type id GUID expected to be 0");
9569 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
9573 return false;
9576 /// ConstVCall
9577 /// ::= '(' VFuncId ',' Args ')'
9578 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
9579 IdToIndexMapType &IdToIndexMap, unsigned Index) {
9580 if (parseToken(lltok::lparen, "expected '(' here") ||
9581 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
9582 return true;
9584 if (EatIfPresent(lltok::comma))
9585 if (parseArgs(ConstVCall.Args))
9586 return true;
9588 if (parseToken(lltok::rparen, "expected ')' here"))
9589 return true;
9591 return false;
9594 /// VFuncId
9595 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9596 /// 'offset' ':' UInt64 ')'
9597 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
9598 IdToIndexMapType &IdToIndexMap, unsigned Index) {
9599 assert(Lex.getKind() == lltok::kw_vFuncId);
9600 Lex.Lex();
9602 if (parseToken(lltok::colon, "expected ':' here") ||
9603 parseToken(lltok::lparen, "expected '(' here"))
9604 return true;
9606 if (Lex.getKind() == lltok::SummaryID) {
9607 VFuncId.GUID = 0;
9608 unsigned ID = Lex.getUIntVal();
9609 LocTy Loc = Lex.getLoc();
9610 // Keep track of the array index needing a forward reference.
9611 // We will save the location of the GUID needing an update, but
9612 // can only do so once the caller's std::vector is finalized.
9613 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
9614 Lex.Lex();
9615 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
9616 parseToken(lltok::colon, "expected ':' here") ||
9617 parseUInt64(VFuncId.GUID))
9618 return true;
9620 if (parseToken(lltok::comma, "expected ',' here") ||
9621 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9622 parseToken(lltok::colon, "expected ':' here") ||
9623 parseUInt64(VFuncId.Offset) ||
9624 parseToken(lltok::rparen, "expected ')' here"))
9625 return true;
9627 return false;
9630 /// GVFlags
9631 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9632 /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
9633 /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
9634 /// 'canAutoHide' ':' Flag ',' ')'
9635 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
9636 assert(Lex.getKind() == lltok::kw_flags);
9637 Lex.Lex();
9639 if (parseToken(lltok::colon, "expected ':' here") ||
9640 parseToken(lltok::lparen, "expected '(' here"))
9641 return true;
9643 do {
9644 unsigned Flag = 0;
9645 switch (Lex.getKind()) {
9646 case lltok::kw_linkage:
9647 Lex.Lex();
9648 if (parseToken(lltok::colon, "expected ':'"))
9649 return true;
9650 bool HasLinkage;
9651 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
9652 assert(HasLinkage && "Linkage not optional in summary entry");
9653 Lex.Lex();
9654 break;
9655 case lltok::kw_visibility:
9656 Lex.Lex();
9657 if (parseToken(lltok::colon, "expected ':'"))
9658 return true;
9659 parseOptionalVisibility(Flag);
9660 GVFlags.Visibility = Flag;
9661 break;
9662 case lltok::kw_notEligibleToImport:
9663 Lex.Lex();
9664 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9665 return true;
9666 GVFlags.NotEligibleToImport = Flag;
9667 break;
9668 case lltok::kw_live:
9669 Lex.Lex();
9670 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9671 return true;
9672 GVFlags.Live = Flag;
9673 break;
9674 case lltok::kw_dsoLocal:
9675 Lex.Lex();
9676 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9677 return true;
9678 GVFlags.DSOLocal = Flag;
9679 break;
9680 case lltok::kw_canAutoHide:
9681 Lex.Lex();
9682 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9683 return true;
9684 GVFlags.CanAutoHide = Flag;
9685 break;
9686 default:
9687 return error(Lex.getLoc(), "expected gv flag type");
9689 } while (EatIfPresent(lltok::comma));
9691 if (parseToken(lltok::rparen, "expected ')' here"))
9692 return true;
9694 return false;
9697 /// GVarFlags
9698 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9699 /// ',' 'writeonly' ':' Flag
9700 /// ',' 'constant' ':' Flag ')'
9701 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
9702 assert(Lex.getKind() == lltok::kw_varFlags);
9703 Lex.Lex();
9705 if (parseToken(lltok::colon, "expected ':' here") ||
9706 parseToken(lltok::lparen, "expected '(' here"))
9707 return true;
9709 auto ParseRest = [this](unsigned int &Val) {
9710 Lex.Lex();
9711 if (parseToken(lltok::colon, "expected ':'"))
9712 return true;
9713 return parseFlag(Val);
9716 do {
9717 unsigned Flag = 0;
9718 switch (Lex.getKind()) {
9719 case lltok::kw_readonly:
9720 if (ParseRest(Flag))
9721 return true;
9722 GVarFlags.MaybeReadOnly = Flag;
9723 break;
9724 case lltok::kw_writeonly:
9725 if (ParseRest(Flag))
9726 return true;
9727 GVarFlags.MaybeWriteOnly = Flag;
9728 break;
9729 case lltok::kw_constant:
9730 if (ParseRest(Flag))
9731 return true;
9732 GVarFlags.Constant = Flag;
9733 break;
9734 case lltok::kw_vcall_visibility:
9735 if (ParseRest(Flag))
9736 return true;
9737 GVarFlags.VCallVisibility = Flag;
9738 break;
9739 default:
9740 return error(Lex.getLoc(), "expected gvar flag type");
9742 } while (EatIfPresent(lltok::comma));
9743 return parseToken(lltok::rparen, "expected ')' here");
9746 /// ModuleReference
9747 /// ::= 'module' ':' UInt
9748 bool LLParser::parseModuleReference(StringRef &ModulePath) {
9749 // parse module id.
9750 if (parseToken(lltok::kw_module, "expected 'module' here") ||
9751 parseToken(lltok::colon, "expected ':' here") ||
9752 parseToken(lltok::SummaryID, "expected module ID"))
9753 return true;
9755 unsigned ModuleID = Lex.getUIntVal();
9756 auto I = ModuleIdMap.find(ModuleID);
9757 // We should have already parsed all module IDs
9758 assert(I != ModuleIdMap.end());
9759 ModulePath = I->second;
9760 return false;
9763 /// GVReference
9764 /// ::= SummaryID
9765 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
9766 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
9767 if (!ReadOnly)
9768 WriteOnly = EatIfPresent(lltok::kw_writeonly);
9769 if (parseToken(lltok::SummaryID, "expected GV ID"))
9770 return true;
9772 GVId = Lex.getUIntVal();
9773 // Check if we already have a VI for this GV
9774 if (GVId < NumberedValueInfos.size()) {
9775 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
9776 VI = NumberedValueInfos[GVId];
9777 } else
9778 // We will create a forward reference to the stored location.
9779 VI = ValueInfo(false, FwdVIRef);
9781 if (ReadOnly)
9782 VI.setReadOnly();
9783 if (WriteOnly)
9784 VI.setWriteOnly();
9785 return false;
9788 /// OptionalAllocs
9789 /// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
9790 /// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
9791 /// ',' MemProfs ')'
9792 /// Version ::= UInt32
9793 bool LLParser::parseOptionalAllocs(std::vector<AllocInfo> &Allocs) {
9794 assert(Lex.getKind() == lltok::kw_allocs);
9795 Lex.Lex();
9797 if (parseToken(lltok::colon, "expected ':' in allocs") ||
9798 parseToken(lltok::lparen, "expected '(' in allocs"))
9799 return true;
9801 // parse each alloc
9802 do {
9803 if (parseToken(lltok::lparen, "expected '(' in alloc") ||
9804 parseToken(lltok::kw_versions, "expected 'versions' in alloc") ||
9805 parseToken(lltok::colon, "expected ':'") ||
9806 parseToken(lltok::lparen, "expected '(' in versions"))
9807 return true;
9809 SmallVector<uint8_t> Versions;
9810 do {
9811 uint8_t V = 0;
9812 if (parseAllocType(V))
9813 return true;
9814 Versions.push_back(V);
9815 } while (EatIfPresent(lltok::comma));
9817 if (parseToken(lltok::rparen, "expected ')' in versions") ||
9818 parseToken(lltok::comma, "expected ',' in alloc"))
9819 return true;
9821 std::vector<MIBInfo> MIBs;
9822 if (parseMemProfs(MIBs))
9823 return true;
9825 Allocs.push_back({Versions, MIBs});
9827 if (parseToken(lltok::rparen, "expected ')' in alloc"))
9828 return true;
9829 } while (EatIfPresent(lltok::comma));
9831 if (parseToken(lltok::rparen, "expected ')' in allocs"))
9832 return true;
9834 return false;
9837 /// MemProfs
9838 /// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
9839 /// MemProf ::= '(' 'type' ':' AllocType
9840 /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
9841 /// StackId ::= UInt64
9842 bool LLParser::parseMemProfs(std::vector<MIBInfo> &MIBs) {
9843 assert(Lex.getKind() == lltok::kw_memProf);
9844 Lex.Lex();
9846 if (parseToken(lltok::colon, "expected ':' in memprof") ||
9847 parseToken(lltok::lparen, "expected '(' in memprof"))
9848 return true;
9850 // parse each MIB
9851 do {
9852 if (parseToken(lltok::lparen, "expected '(' in memprof") ||
9853 parseToken(lltok::kw_type, "expected 'type' in memprof") ||
9854 parseToken(lltok::colon, "expected ':'"))
9855 return true;
9857 uint8_t AllocType;
9858 if (parseAllocType(AllocType))
9859 return true;
9861 if (parseToken(lltok::comma, "expected ',' in memprof") ||
9862 parseToken(lltok::kw_stackIds, "expected 'stackIds' in memprof") ||
9863 parseToken(lltok::colon, "expected ':'") ||
9864 parseToken(lltok::lparen, "expected '(' in stackIds"))
9865 return true;
9867 SmallVector<unsigned> StackIdIndices;
9868 do {
9869 uint64_t StackId = 0;
9870 if (parseUInt64(StackId))
9871 return true;
9872 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
9873 } while (EatIfPresent(lltok::comma));
9875 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
9876 return true;
9878 MIBs.push_back({(AllocationType)AllocType, StackIdIndices});
9880 if (parseToken(lltok::rparen, "expected ')' in memprof"))
9881 return true;
9882 } while (EatIfPresent(lltok::comma));
9884 if (parseToken(lltok::rparen, "expected ')' in memprof"))
9885 return true;
9887 return false;
9890 /// AllocType
9891 /// := ('none'|'notcold'|'cold'|'hot')
9892 bool LLParser::parseAllocType(uint8_t &AllocType) {
9893 switch (Lex.getKind()) {
9894 case lltok::kw_none:
9895 AllocType = (uint8_t)AllocationType::None;
9896 break;
9897 case lltok::kw_notcold:
9898 AllocType = (uint8_t)AllocationType::NotCold;
9899 break;
9900 case lltok::kw_cold:
9901 AllocType = (uint8_t)AllocationType::Cold;
9902 break;
9903 case lltok::kw_hot:
9904 AllocType = (uint8_t)AllocationType::Hot;
9905 break;
9906 default:
9907 return error(Lex.getLoc(), "invalid alloc type");
9909 Lex.Lex();
9910 return false;
9913 /// OptionalCallsites
9914 /// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
9915 /// Callsite ::= '(' 'callee' ':' GVReference
9916 /// ',' 'clones' ':' '(' Version [',' Version]* ')'
9917 /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
9918 /// Version ::= UInt32
9919 /// StackId ::= UInt64
9920 bool LLParser::parseOptionalCallsites(std::vector<CallsiteInfo> &Callsites) {
9921 assert(Lex.getKind() == lltok::kw_callsites);
9922 Lex.Lex();
9924 if (parseToken(lltok::colon, "expected ':' in callsites") ||
9925 parseToken(lltok::lparen, "expected '(' in callsites"))
9926 return true;
9928 IdToIndexMapType IdToIndexMap;
9929 // parse each callsite
9930 do {
9931 if (parseToken(lltok::lparen, "expected '(' in callsite") ||
9932 parseToken(lltok::kw_callee, "expected 'callee' in callsite") ||
9933 parseToken(lltok::colon, "expected ':'"))
9934 return true;
9936 ValueInfo VI;
9937 unsigned GVId = 0;
9938 LocTy Loc = Lex.getLoc();
9939 if (!EatIfPresent(lltok::kw_null)) {
9940 if (parseGVReference(VI, GVId))
9941 return true;
9944 if (parseToken(lltok::comma, "expected ',' in callsite") ||
9945 parseToken(lltok::kw_clones, "expected 'clones' in callsite") ||
9946 parseToken(lltok::colon, "expected ':'") ||
9947 parseToken(lltok::lparen, "expected '(' in clones"))
9948 return true;
9950 SmallVector<unsigned> Clones;
9951 do {
9952 unsigned V = 0;
9953 if (parseUInt32(V))
9954 return true;
9955 Clones.push_back(V);
9956 } while (EatIfPresent(lltok::comma));
9958 if (parseToken(lltok::rparen, "expected ')' in clones") ||
9959 parseToken(lltok::comma, "expected ',' in callsite") ||
9960 parseToken(lltok::kw_stackIds, "expected 'stackIds' in callsite") ||
9961 parseToken(lltok::colon, "expected ':'") ||
9962 parseToken(lltok::lparen, "expected '(' in stackIds"))
9963 return true;
9965 SmallVector<unsigned> StackIdIndices;
9966 do {
9967 uint64_t StackId = 0;
9968 if (parseUInt64(StackId))
9969 return true;
9970 StackIdIndices.push_back(Index->addOrGetStackIdIndex(StackId));
9971 } while (EatIfPresent(lltok::comma));
9973 if (parseToken(lltok::rparen, "expected ')' in stackIds"))
9974 return true;
9976 // Keep track of the Callsites array index needing a forward reference.
9977 // We will save the location of the ValueInfo needing an update, but
9978 // can only do so once the SmallVector is finalized.
9979 if (VI.getRef() == FwdVIRef)
9980 IdToIndexMap[GVId].push_back(std::make_pair(Callsites.size(), Loc));
9981 Callsites.push_back({VI, Clones, StackIdIndices});
9983 if (parseToken(lltok::rparen, "expected ')' in callsite"))
9984 return true;
9985 } while (EatIfPresent(lltok::comma));
9987 // Now that the Callsites vector is finalized, it is safe to save the
9988 // locations of any forward GV references that need updating later.
9989 for (auto I : IdToIndexMap) {
9990 auto &Infos = ForwardRefValueInfos[I.first];
9991 for (auto P : I.second) {
9992 assert(Callsites[P.first].Callee.getRef() == FwdVIRef &&
9993 "Forward referenced ValueInfo expected to be empty");
9994 Infos.emplace_back(&Callsites[P.first].Callee, P.second);
9998 if (parseToken(lltok::rparen, "expected ')' in callsites"))
9999 return true;
10001 return false;