1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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/STLExtras.h"
17 #include "llvm/ADT/ScopeExit.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/InstIterator.h"
36 #include "llvm/IR/Instructions.h"
37 #include "llvm/IR/IntrinsicInst.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/LLVMContext.h"
40 #include "llvm/IR/Metadata.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/Operator.h"
43 #include "llvm/IR/Value.h"
44 #include "llvm/IR/ValueSymbolTable.h"
45 #include "llvm/Support/Casting.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/ModRef.h"
49 #include "llvm/Support/SaveAndRestore.h"
50 #include "llvm/Support/raw_ostream.h"
59 static cl::opt
<bool> AllowIncompleteIR(
60 "allow-incomplete-ir", cl::init(false), cl::Hidden
,
62 "Allow incomplete IR on a best effort basis (references to unknown "
63 "metadata will be dropped)"));
65 static std::string
getTypeString(Type
*T
) {
67 raw_string_ostream
Tmp(Result
);
72 /// Run: module ::= toplevelentity*
73 bool LLParser::Run(bool UpgradeDebugInfo
,
74 DataLayoutCallbackTy DataLayoutCallback
) {
78 if (Context
.shouldDiscardValueNames())
81 "Can't read textual IR with a Context that discards named Values");
84 if (parseTargetDefinitions(DataLayoutCallback
))
88 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo
) ||
92 bool LLParser::parseStandaloneConstantValue(Constant
*&C
,
93 const SlotMapping
*Slots
) {
94 restoreParsingState(Slots
);
98 if (parseType(Ty
) || parseConstantValue(Ty
, C
))
100 if (Lex
.getKind() != lltok::Eof
)
101 return error(Lex
.getLoc(), "expected end of string");
105 bool LLParser::parseTypeAtBeginning(Type
*&Ty
, unsigned &Read
,
106 const SlotMapping
*Slots
) {
107 restoreParsingState(Slots
);
111 SMLoc Start
= Lex
.getLoc();
115 SMLoc End
= Lex
.getLoc();
116 Read
= End
.getPointer() - Start
.getPointer();
121 void LLParser::restoreParsingState(const SlotMapping
*Slots
) {
124 NumberedVals
= Slots
->GlobalValues
;
125 NumberedMetadata
= Slots
->MetadataNodes
;
126 for (const auto &I
: Slots
->NamedTypes
)
128 std::make_pair(I
.getKey(), std::make_pair(I
.second
, LocTy())));
129 for (const auto &I
: Slots
->Types
)
130 NumberedTypes
.insert(
131 std::make_pair(I
.first
, std::make_pair(I
.second
, LocTy())));
134 static void dropIntrinsicWithUnknownMetadataArgument(IntrinsicInst
*II
) {
135 // White-list intrinsics that are safe to drop.
136 if (!isa
<DbgInfoIntrinsic
>(II
) &&
137 II
->getIntrinsicID() != Intrinsic::experimental_noalias_scope_decl
)
140 SmallVector
<MetadataAsValue
*> MVs
;
141 for (Value
*V
: II
->args())
142 if (auto *MV
= dyn_cast
<MetadataAsValue
>(V
))
143 if (auto *MD
= dyn_cast
<MDNode
>(MV
->getMetadata()))
144 if (MD
->isTemporary())
148 assert(II
->use_empty() && "Cannot have uses");
149 II
->eraseFromParent();
151 // Also remove no longer used MetadataAsValue wrappers.
152 for (MetadataAsValue
*MV
: MVs
)
158 void LLParser::dropUnknownMetadataReferences() {
159 auto Pred
= [](unsigned MDKind
, MDNode
*Node
) { return Node
->isTemporary(); };
160 for (Function
&F
: *M
) {
161 F
.eraseMetadataIf(Pred
);
162 for (Instruction
&I
: make_early_inc_range(instructions(F
))) {
163 I
.eraseMetadataIf(Pred
);
165 if (auto *II
= dyn_cast
<IntrinsicInst
>(&I
))
166 dropIntrinsicWithUnknownMetadataArgument(II
);
170 for (GlobalVariable
&GV
: M
->globals())
171 GV
.eraseMetadataIf(Pred
);
173 for (const auto &[ID
, Info
] : make_early_inc_range(ForwardRefMDNodes
)) {
174 // Check whether there is only a single use left, which would be in our
175 // own NumberedMetadata.
176 if (Info
.first
->getNumTemporaryUses() == 1) {
177 NumberedMetadata
.erase(ID
);
178 ForwardRefMDNodes
.erase(ID
);
183 /// validateEndOfModule - Do final validity and basic correctness checks at the
184 /// end of the module.
185 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo
) {
188 // Handle any function attribute group forward references.
189 for (const auto &RAG
: ForwardRefAttrGroups
) {
190 Value
*V
= RAG
.first
;
191 const std::vector
<unsigned> &Attrs
= RAG
.second
;
192 AttrBuilder
B(Context
);
194 for (const auto &Attr
: Attrs
) {
195 auto R
= NumberedAttrBuilders
.find(Attr
);
196 if (R
!= NumberedAttrBuilders
.end())
200 if (Function
*Fn
= dyn_cast
<Function
>(V
)) {
201 AttributeList AS
= Fn
->getAttributes();
202 AttrBuilder
FnAttrs(M
->getContext(), AS
.getFnAttrs());
203 AS
= AS
.removeFnAttributes(Context
);
207 // If the alignment was parsed as an attribute, move to the alignment
209 if (MaybeAlign A
= FnAttrs
.getAlignment()) {
210 Fn
->setAlignment(*A
);
211 FnAttrs
.removeAttribute(Attribute::Alignment
);
214 AS
= AS
.addFnAttributes(Context
, FnAttrs
);
215 Fn
->setAttributes(AS
);
216 } else if (CallInst
*CI
= dyn_cast
<CallInst
>(V
)) {
217 AttributeList AS
= CI
->getAttributes();
218 AttrBuilder
FnAttrs(M
->getContext(), AS
.getFnAttrs());
219 AS
= AS
.removeFnAttributes(Context
);
221 AS
= AS
.addFnAttributes(Context
, FnAttrs
);
222 CI
->setAttributes(AS
);
223 } else if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(V
)) {
224 AttributeList AS
= II
->getAttributes();
225 AttrBuilder
FnAttrs(M
->getContext(), AS
.getFnAttrs());
226 AS
= AS
.removeFnAttributes(Context
);
228 AS
= AS
.addFnAttributes(Context
, FnAttrs
);
229 II
->setAttributes(AS
);
230 } else if (CallBrInst
*CBI
= dyn_cast
<CallBrInst
>(V
)) {
231 AttributeList AS
= CBI
->getAttributes();
232 AttrBuilder
FnAttrs(M
->getContext(), AS
.getFnAttrs());
233 AS
= AS
.removeFnAttributes(Context
);
235 AS
= AS
.addFnAttributes(Context
, FnAttrs
);
236 CBI
->setAttributes(AS
);
237 } else if (auto *GV
= dyn_cast
<GlobalVariable
>(V
)) {
238 AttrBuilder
Attrs(M
->getContext(), GV
->getAttributes());
240 GV
->setAttributes(AttributeSet::get(Context
,Attrs
));
242 llvm_unreachable("invalid object with forward attribute group reference");
246 // If there are entries in ForwardRefBlockAddresses at this point, the
247 // function was never defined.
248 if (!ForwardRefBlockAddresses
.empty())
249 return error(ForwardRefBlockAddresses
.begin()->first
.Loc
,
250 "expected function name in blockaddress");
252 auto ResolveForwardRefDSOLocalEquivalents
= [&](const ValID
&GVRef
,
253 GlobalValue
*FwdRef
) {
254 GlobalValue
*GV
= nullptr;
255 if (GVRef
.Kind
== ValID::t_GlobalName
) {
256 GV
= M
->getNamedValue(GVRef
.StrVal
);
257 } else if (GVRef
.UIntVal
< NumberedVals
.size()) {
258 GV
= dyn_cast
<GlobalValue
>(NumberedVals
[GVRef
.UIntVal
]);
262 return error(GVRef
.Loc
, "unknown function '" + GVRef
.StrVal
+
263 "' referenced by dso_local_equivalent");
265 if (!GV
->getValueType()->isFunctionTy())
266 return error(GVRef
.Loc
,
267 "expected a function, alias to function, or ifunc "
268 "in dso_local_equivalent");
270 auto *Equiv
= DSOLocalEquivalent::get(GV
);
271 FwdRef
->replaceAllUsesWith(Equiv
);
272 FwdRef
->eraseFromParent();
276 // If there are entries in ForwardRefDSOLocalEquivalentIDs/Names at this
277 // point, they are references after the function was defined. Resolve those
279 for (auto &Iter
: ForwardRefDSOLocalEquivalentIDs
) {
280 if (ResolveForwardRefDSOLocalEquivalents(Iter
.first
, Iter
.second
))
283 for (auto &Iter
: ForwardRefDSOLocalEquivalentNames
) {
284 if (ResolveForwardRefDSOLocalEquivalents(Iter
.first
, Iter
.second
))
287 ForwardRefDSOLocalEquivalentIDs
.clear();
288 ForwardRefDSOLocalEquivalentNames
.clear();
290 for (const auto &NT
: NumberedTypes
)
291 if (NT
.second
.second
.isValid())
292 return error(NT
.second
.second
,
293 "use of undefined type '%" + Twine(NT
.first
) + "'");
295 for (StringMap
<std::pair
<Type
*, LocTy
> >::iterator I
=
296 NamedTypes
.begin(), E
= NamedTypes
.end(); I
!= E
; ++I
)
297 if (I
->second
.second
.isValid())
298 return error(I
->second
.second
,
299 "use of undefined type named '" + I
->getKey() + "'");
301 if (!ForwardRefComdats
.empty())
302 return error(ForwardRefComdats
.begin()->second
,
303 "use of undefined comdat '$" +
304 ForwardRefComdats
.begin()->first
+ "'");
306 // Automatically create declarations for intrinsics. Intrinsics can only be
307 // called directly, so the call function type directly determines the
308 // declaration function type.
309 for (const auto &[Name
, Info
] : make_early_inc_range(ForwardRefVals
)) {
310 if (!StringRef(Name
).starts_with("llvm."))
313 // Don't do anything if the intrinsic is called with different function
314 // types. This would result in a verifier error anyway.
315 auto GetCommonFunctionType
= [](Value
*V
) -> FunctionType
* {
316 FunctionType
*FTy
= nullptr;
317 for (User
*U
: V
->users()) {
318 auto *CB
= dyn_cast
<CallBase
>(U
);
319 if (!CB
|| (FTy
&& FTy
!= CB
->getFunctionType()))
321 FTy
= CB
->getFunctionType();
325 if (FunctionType
*FTy
= GetCommonFunctionType(Info
.first
)) {
327 Function::Create(FTy
, GlobalValue::ExternalLinkage
, Name
, M
);
328 Info
.first
->replaceAllUsesWith(Fn
);
329 Info
.first
->eraseFromParent();
330 ForwardRefVals
.erase(Name
);
334 if (!ForwardRefVals
.empty())
335 return error(ForwardRefVals
.begin()->second
.second
,
336 "use of undefined value '@" + ForwardRefVals
.begin()->first
+
339 if (!ForwardRefValIDs
.empty())
340 return error(ForwardRefValIDs
.begin()->second
.second
,
341 "use of undefined value '@" +
342 Twine(ForwardRefValIDs
.begin()->first
) + "'");
344 if (AllowIncompleteIR
&& !ForwardRefMDNodes
.empty())
345 dropUnknownMetadataReferences();
347 if (!ForwardRefMDNodes
.empty())
348 return error(ForwardRefMDNodes
.begin()->second
.second
,
349 "use of undefined metadata '!" +
350 Twine(ForwardRefMDNodes
.begin()->first
) + "'");
352 // Resolve metadata cycles.
353 for (auto &N
: NumberedMetadata
) {
354 if (N
.second
&& !N
.second
->isResolved())
355 N
.second
->resolveCycles();
358 for (auto *Inst
: InstsWithTBAATag
) {
359 MDNode
*MD
= Inst
->getMetadata(LLVMContext::MD_tbaa
);
360 // With incomplete IR, the tbaa metadata may have been dropped.
361 if (!AllowIncompleteIR
)
362 assert(MD
&& "UpgradeInstWithTBAATag should have a TBAA tag");
364 auto *UpgradedMD
= UpgradeTBAANode(*MD
);
365 if (MD
!= UpgradedMD
)
366 Inst
->setMetadata(LLVMContext::MD_tbaa
, UpgradedMD
);
370 // Look for intrinsic functions and CallInst that need to be upgraded. We use
371 // make_early_inc_range here because we may remove some functions.
372 for (Function
&F
: llvm::make_early_inc_range(*M
))
373 UpgradeCallsToIntrinsic(&F
);
375 if (UpgradeDebugInfo
)
376 llvm::UpgradeDebugInfo(*M
);
378 UpgradeModuleFlags(*M
);
379 UpgradeSectionAttributes(*M
);
383 // Initialize the slot mapping.
384 // Because by this point we've parsed and validated everything, we can "steal"
385 // the mapping from LLParser as it doesn't need it anymore.
386 Slots
->GlobalValues
= std::move(NumberedVals
);
387 Slots
->MetadataNodes
= std::move(NumberedMetadata
);
388 for (const auto &I
: NamedTypes
)
389 Slots
->NamedTypes
.insert(std::make_pair(I
.getKey(), I
.second
.first
));
390 for (const auto &I
: NumberedTypes
)
391 Slots
->Types
.insert(std::make_pair(I
.first
, I
.second
.first
));
396 /// Do final validity and basic correctness checks at the end of the index.
397 bool LLParser::validateEndOfIndex() {
401 if (!ForwardRefValueInfos
.empty())
402 return error(ForwardRefValueInfos
.begin()->second
.front().second
,
403 "use of undefined summary '^" +
404 Twine(ForwardRefValueInfos
.begin()->first
) + "'");
406 if (!ForwardRefAliasees
.empty())
407 return error(ForwardRefAliasees
.begin()->second
.front().second
,
408 "use of undefined summary '^" +
409 Twine(ForwardRefAliasees
.begin()->first
) + "'");
411 if (!ForwardRefTypeIds
.empty())
412 return error(ForwardRefTypeIds
.begin()->second
.front().second
,
413 "use of undefined type id summary '^" +
414 Twine(ForwardRefTypeIds
.begin()->first
) + "'");
419 //===----------------------------------------------------------------------===//
420 // Top-Level Entities
421 //===----------------------------------------------------------------------===//
423 bool LLParser::parseTargetDefinitions(DataLayoutCallbackTy DataLayoutCallback
) {
424 // Delay parsing of the data layout string until the target triple is known.
425 // Then, pass both the the target triple and the tentative data layout string
426 // to DataLayoutCallback, allowing to override the DL string.
427 // This enables importing modules with invalid DL strings.
428 std::string TentativeDLStr
= M
->getDataLayoutStr();
433 switch (Lex
.getKind()) {
434 case lltok::kw_target
:
435 if (parseTargetDefinition(TentativeDLStr
, DLStrLoc
))
438 case lltok::kw_source_filename
:
439 if (parseSourceFileName())
446 // Run the override callback to potentially change the data layout string, and
447 // parse the data layout string.
448 if (auto LayoutOverride
=
449 DataLayoutCallback(M
->getTargetTriple(), TentativeDLStr
)) {
450 TentativeDLStr
= *LayoutOverride
;
453 Expected
<DataLayout
> MaybeDL
= DataLayout::parse(TentativeDLStr
);
455 return error(DLStrLoc
, toString(MaybeDL
.takeError()));
456 M
->setDataLayout(MaybeDL
.get());
460 bool LLParser::parseTopLevelEntities() {
461 // If there is no Module, then parse just the summary index entries.
464 switch (Lex
.getKind()) {
467 case lltok::SummaryID
:
468 if (parseSummaryEntry())
471 case lltok::kw_source_filename
:
472 if (parseSourceFileName())
476 // Skip everything else
482 switch (Lex
.getKind()) {
484 return tokError("expected top-level entity");
485 case lltok::Eof
: return false;
486 case lltok::kw_declare
:
490 case lltok::kw_define
:
494 case lltok::kw_module
:
495 if (parseModuleAsm())
498 case lltok::LocalVarID
:
499 if (parseUnnamedType())
502 case lltok::LocalVar
:
503 if (parseNamedType())
506 case lltok::GlobalID
:
507 if (parseUnnamedGlobal())
510 case lltok::GlobalVar
:
511 if (parseNamedGlobal())
514 case lltok::ComdatVar
: if (parseComdat()) return true; break;
516 if (parseStandaloneMetadata())
519 case lltok::SummaryID
:
520 if (parseSummaryEntry())
523 case lltok::MetadataVar
:
524 if (parseNamedMetadata())
527 case lltok::kw_attributes
:
528 if (parseUnnamedAttrGrp())
531 case lltok::kw_uselistorder
:
532 if (parseUseListOrder())
535 case lltok::kw_uselistorder_bb
:
536 if (parseUseListOrderBB())
544 /// ::= 'module' 'asm' STRINGCONSTANT
545 bool LLParser::parseModuleAsm() {
546 assert(Lex
.getKind() == lltok::kw_module
);
550 if (parseToken(lltok::kw_asm
, "expected 'module asm'") ||
551 parseStringConstant(AsmStr
))
554 M
->appendModuleInlineAsm(AsmStr
);
559 /// ::= 'target' 'triple' '=' STRINGCONSTANT
560 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
561 bool LLParser::parseTargetDefinition(std::string
&TentativeDLStr
,
563 assert(Lex
.getKind() == lltok::kw_target
);
567 return tokError("unknown target property");
568 case lltok::kw_triple
:
570 if (parseToken(lltok::equal
, "expected '=' after target triple") ||
571 parseStringConstant(Str
))
573 M
->setTargetTriple(Str
);
575 case lltok::kw_datalayout
:
577 if (parseToken(lltok::equal
, "expected '=' after target datalayout"))
579 DLStrLoc
= Lex
.getLoc();
580 if (parseStringConstant(TentativeDLStr
))
587 /// ::= 'source_filename' '=' STRINGCONSTANT
588 bool LLParser::parseSourceFileName() {
589 assert(Lex
.getKind() == lltok::kw_source_filename
);
591 if (parseToken(lltok::equal
, "expected '=' after source_filename") ||
592 parseStringConstant(SourceFileName
))
595 M
->setSourceFileName(SourceFileName
);
599 /// parseUnnamedType:
600 /// ::= LocalVarID '=' 'type' type
601 bool LLParser::parseUnnamedType() {
602 LocTy TypeLoc
= Lex
.getLoc();
603 unsigned TypeID
= Lex
.getUIntVal();
604 Lex
.Lex(); // eat LocalVarID;
606 if (parseToken(lltok::equal
, "expected '=' after name") ||
607 parseToken(lltok::kw_type
, "expected 'type' after '='"))
610 Type
*Result
= nullptr;
611 if (parseStructDefinition(TypeLoc
, "", NumberedTypes
[TypeID
], Result
))
614 if (!isa
<StructType
>(Result
)) {
615 std::pair
<Type
*, LocTy
> &Entry
= NumberedTypes
[TypeID
];
617 return error(TypeLoc
, "non-struct types may not be recursive");
618 Entry
.first
= Result
;
619 Entry
.second
= SMLoc();
626 /// ::= LocalVar '=' 'type' type
627 bool LLParser::parseNamedType() {
628 std::string Name
= Lex
.getStrVal();
629 LocTy NameLoc
= Lex
.getLoc();
630 Lex
.Lex(); // eat LocalVar.
632 if (parseToken(lltok::equal
, "expected '=' after name") ||
633 parseToken(lltok::kw_type
, "expected 'type' after name"))
636 Type
*Result
= nullptr;
637 if (parseStructDefinition(NameLoc
, Name
, NamedTypes
[Name
], Result
))
640 if (!isa
<StructType
>(Result
)) {
641 std::pair
<Type
*, LocTy
> &Entry
= NamedTypes
[Name
];
643 return error(NameLoc
, "non-struct types may not be recursive");
644 Entry
.first
= Result
;
645 Entry
.second
= SMLoc();
652 /// ::= 'declare' FunctionHeader
653 bool LLParser::parseDeclare() {
654 assert(Lex
.getKind() == lltok::kw_declare
);
657 std::vector
<std::pair
<unsigned, MDNode
*>> MDs
;
658 while (Lex
.getKind() == lltok::MetadataVar
) {
661 if (parseMetadataAttachment(MDK
, N
))
663 MDs
.push_back({MDK
, N
});
667 SmallVector
<unsigned> UnnamedArgNums
;
668 if (parseFunctionHeader(F
, false, UnnamedArgNums
))
671 F
->addMetadata(MD
.first
, *MD
.second
);
676 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
677 bool LLParser::parseDefine() {
678 assert(Lex
.getKind() == lltok::kw_define
);
682 SmallVector
<unsigned> UnnamedArgNums
;
683 return parseFunctionHeader(F
, true, UnnamedArgNums
) ||
684 parseOptionalFunctionMetadata(*F
) ||
685 parseFunctionBody(*F
, UnnamedArgNums
);
691 bool LLParser::parseGlobalType(bool &IsConstant
) {
692 if (Lex
.getKind() == lltok::kw_constant
)
694 else if (Lex
.getKind() == lltok::kw_global
)
698 return tokError("expected 'global' or 'constant'");
704 bool LLParser::parseOptionalUnnamedAddr(
705 GlobalVariable::UnnamedAddr
&UnnamedAddr
) {
706 if (EatIfPresent(lltok::kw_unnamed_addr
))
707 UnnamedAddr
= GlobalValue::UnnamedAddr::Global
;
708 else if (EatIfPresent(lltok::kw_local_unnamed_addr
))
709 UnnamedAddr
= GlobalValue::UnnamedAddr::Local
;
711 UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
715 /// parseUnnamedGlobal:
716 /// OptionalVisibility (ALIAS | IFUNC) ...
717 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
718 /// OptionalDLLStorageClass
719 /// ... -> global variable
720 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
721 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
722 /// OptionalVisibility
723 /// OptionalDLLStorageClass
724 /// ... -> global variable
725 bool LLParser::parseUnnamedGlobal() {
726 unsigned VarID
= NumberedVals
.size();
728 LocTy NameLoc
= Lex
.getLoc();
730 // Handle the GlobalID form.
731 if (Lex
.getKind() == lltok::GlobalID
) {
732 if (Lex
.getUIntVal() != VarID
)
733 return error(Lex
.getLoc(),
734 "variable expected to be numbered '%" + Twine(VarID
) + "'");
735 Lex
.Lex(); // eat GlobalID;
737 if (parseToken(lltok::equal
, "expected '=' after name"))
742 unsigned Linkage
, Visibility
, DLLStorageClass
;
744 GlobalVariable::ThreadLocalMode TLM
;
745 GlobalVariable::UnnamedAddr UnnamedAddr
;
746 if (parseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
748 parseOptionalThreadLocal(TLM
) || parseOptionalUnnamedAddr(UnnamedAddr
))
751 switch (Lex
.getKind()) {
753 return parseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
,
754 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
755 case lltok::kw_alias
:
756 case lltok::kw_ifunc
:
757 return parseAliasOrIFunc(Name
, NameLoc
, Linkage
, Visibility
,
758 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
762 /// parseNamedGlobal:
763 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
764 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
765 /// OptionalVisibility OptionalDLLStorageClass
766 /// ... -> global variable
767 bool LLParser::parseNamedGlobal() {
768 assert(Lex
.getKind() == lltok::GlobalVar
);
769 LocTy NameLoc
= Lex
.getLoc();
770 std::string Name
= Lex
.getStrVal();
774 unsigned Linkage
, Visibility
, DLLStorageClass
;
776 GlobalVariable::ThreadLocalMode TLM
;
777 GlobalVariable::UnnamedAddr UnnamedAddr
;
778 if (parseToken(lltok::equal
, "expected '=' in global variable") ||
779 parseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
781 parseOptionalThreadLocal(TLM
) || parseOptionalUnnamedAddr(UnnamedAddr
))
784 switch (Lex
.getKind()) {
786 return parseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
,
787 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
788 case lltok::kw_alias
:
789 case lltok::kw_ifunc
:
790 return parseAliasOrIFunc(Name
, NameLoc
, Linkage
, Visibility
,
791 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
795 bool LLParser::parseComdat() {
796 assert(Lex
.getKind() == lltok::ComdatVar
);
797 std::string Name
= Lex
.getStrVal();
798 LocTy NameLoc
= Lex
.getLoc();
801 if (parseToken(lltok::equal
, "expected '=' here"))
804 if (parseToken(lltok::kw_comdat
, "expected comdat keyword"))
805 return tokError("expected comdat type");
807 Comdat::SelectionKind SK
;
808 switch (Lex
.getKind()) {
810 return tokError("unknown selection kind");
814 case lltok::kw_exactmatch
:
815 SK
= Comdat::ExactMatch
;
817 case lltok::kw_largest
:
818 SK
= Comdat::Largest
;
820 case lltok::kw_nodeduplicate
:
821 SK
= Comdat::NoDeduplicate
;
823 case lltok::kw_samesize
:
824 SK
= Comdat::SameSize
;
829 // See if the comdat was forward referenced, if so, use the comdat.
830 Module::ComdatSymTabType
&ComdatSymTab
= M
->getComdatSymbolTable();
831 Module::ComdatSymTabType::iterator I
= ComdatSymTab
.find(Name
);
832 if (I
!= ComdatSymTab
.end() && !ForwardRefComdats
.erase(Name
))
833 return error(NameLoc
, "redefinition of comdat '$" + Name
+ "'");
836 if (I
!= ComdatSymTab
.end())
839 C
= M
->getOrInsertComdat(Name
);
840 C
->setSelectionKind(SK
);
846 // ::= '!' STRINGCONSTANT
847 bool LLParser::parseMDString(MDString
*&Result
) {
849 if (parseStringConstant(Str
))
851 Result
= MDString::get(Context
, Str
);
856 // ::= '!' MDNodeNumber
857 bool LLParser::parseMDNodeID(MDNode
*&Result
) {
858 // !{ ..., !42, ... }
859 LocTy IDLoc
= Lex
.getLoc();
861 if (parseUInt32(MID
))
864 // If not a forward reference, just return it now.
865 if (NumberedMetadata
.count(MID
)) {
866 Result
= NumberedMetadata
[MID
];
870 // Otherwise, create MDNode forward reference.
871 auto &FwdRef
= ForwardRefMDNodes
[MID
];
872 FwdRef
= std::make_pair(MDTuple::getTemporary(Context
, std::nullopt
), IDLoc
);
874 Result
= FwdRef
.first
.get();
875 NumberedMetadata
[MID
].reset(Result
);
879 /// parseNamedMetadata:
880 /// !foo = !{ !1, !2 }
881 bool LLParser::parseNamedMetadata() {
882 assert(Lex
.getKind() == lltok::MetadataVar
);
883 std::string Name
= Lex
.getStrVal();
886 if (parseToken(lltok::equal
, "expected '=' here") ||
887 parseToken(lltok::exclaim
, "Expected '!' here") ||
888 parseToken(lltok::lbrace
, "Expected '{' here"))
891 NamedMDNode
*NMD
= M
->getOrInsertNamedMetadata(Name
);
892 if (Lex
.getKind() != lltok::rbrace
)
895 // parse DIExpressions inline as a special case. They are still MDNodes,
896 // so they can still appear in named metadata. Remove this logic if they
897 // become plain Metadata.
898 if (Lex
.getKind() == lltok::MetadataVar
&&
899 Lex
.getStrVal() == "DIExpression") {
900 if (parseDIExpression(N
, /*IsDistinct=*/false))
902 // DIArgLists should only appear inline in a function, as they may
903 // contain LocalAsMetadata arguments which require a function context.
904 } else if (Lex
.getKind() == lltok::MetadataVar
&&
905 Lex
.getStrVal() == "DIArgList") {
906 return tokError("found DIArgList outside of function");
907 } else if (parseToken(lltok::exclaim
, "Expected '!' here") ||
912 } while (EatIfPresent(lltok::comma
));
914 return parseToken(lltok::rbrace
, "expected end of metadata node");
917 /// parseStandaloneMetadata:
919 bool LLParser::parseStandaloneMetadata() {
920 assert(Lex
.getKind() == lltok::exclaim
);
922 unsigned MetadataID
= 0;
925 if (parseUInt32(MetadataID
) || parseToken(lltok::equal
, "expected '=' here"))
928 // Detect common error, from old metadata syntax.
929 if (Lex
.getKind() == lltok::Type
)
930 return tokError("unexpected type in metadata definition");
932 bool IsDistinct
= EatIfPresent(lltok::kw_distinct
);
933 if (Lex
.getKind() == lltok::MetadataVar
) {
934 if (parseSpecializedMDNode(Init
, IsDistinct
))
936 } else if (parseToken(lltok::exclaim
, "Expected '!' here") ||
937 parseMDTuple(Init
, IsDistinct
))
940 // See if this was forward referenced, if so, handle it.
941 auto FI
= ForwardRefMDNodes
.find(MetadataID
);
942 if (FI
!= ForwardRefMDNodes
.end()) {
943 auto *ToReplace
= FI
->second
.first
.get();
944 // DIAssignID has its own special forward-reference "replacement" for
945 // attachments (the temporary attachments are never actually attached).
946 if (isa
<DIAssignID
>(Init
)) {
947 for (auto *Inst
: TempDIAssignIDAttachments
[ToReplace
]) {
948 assert(!Inst
->getMetadata(LLVMContext::MD_DIAssignID
) &&
949 "Inst unexpectedly already has DIAssignID attachment");
950 Inst
->setMetadata(LLVMContext::MD_DIAssignID
, Init
);
954 ToReplace
->replaceAllUsesWith(Init
);
955 ForwardRefMDNodes
.erase(FI
);
957 assert(NumberedMetadata
[MetadataID
] == Init
&& "Tracking VH didn't work");
959 if (NumberedMetadata
.count(MetadataID
))
960 return tokError("Metadata id is already used");
961 NumberedMetadata
[MetadataID
].reset(Init
);
967 // Skips a single module summary entry.
968 bool LLParser::skipModuleSummaryEntry() {
969 // Each module summary entry consists of a tag for the entry
970 // type, followed by a colon, then the fields which may be surrounded by
971 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
972 // support is in place we will look for the tokens corresponding to the
974 if (Lex
.getKind() != lltok::kw_gv
&& Lex
.getKind() != lltok::kw_module
&&
975 Lex
.getKind() != lltok::kw_typeid
&& Lex
.getKind() != lltok::kw_flags
&&
976 Lex
.getKind() != lltok::kw_blockcount
)
978 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
979 "start of summary entry");
980 if (Lex
.getKind() == lltok::kw_flags
)
981 return parseSummaryIndexFlags();
982 if (Lex
.getKind() == lltok::kw_blockcount
)
983 return parseBlockCount();
985 if (parseToken(lltok::colon
, "expected ':' at start of summary entry") ||
986 parseToken(lltok::lparen
, "expected '(' at start of summary entry"))
988 // Now walk through the parenthesized entry, until the number of open
989 // parentheses goes back down to 0 (the first '(' was parsed above).
990 unsigned NumOpenParen
= 1;
992 switch (Lex
.getKind()) {
1000 return tokError("found end of file while parsing summary entry");
1002 // Skip everything in between parentheses.
1006 } while (NumOpenParen
> 0);
1011 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
1012 bool LLParser::parseSummaryEntry() {
1013 assert(Lex
.getKind() == lltok::SummaryID
);
1014 unsigned SummaryID
= Lex
.getUIntVal();
1016 // For summary entries, colons should be treated as distinct tokens,
1017 // not an indication of the end of a label token.
1018 Lex
.setIgnoreColonInIdentifiers(true);
1021 if (parseToken(lltok::equal
, "expected '=' here"))
1024 // If we don't have an index object, skip the summary entry.
1026 return skipModuleSummaryEntry();
1028 bool result
= false;
1029 switch (Lex
.getKind()) {
1031 result
= parseGVEntry(SummaryID
);
1033 case lltok::kw_module
:
1034 result
= parseModuleEntry(SummaryID
);
1036 case lltok::kw_typeid
:
1037 result
= parseTypeIdEntry(SummaryID
);
1039 case lltok::kw_typeidCompatibleVTable
:
1040 result
= parseTypeIdCompatibleVtableEntry(SummaryID
);
1042 case lltok::kw_flags
:
1043 result
= parseSummaryIndexFlags();
1045 case lltok::kw_blockcount
:
1046 result
= parseBlockCount();
1049 result
= error(Lex
.getLoc(), "unexpected summary kind");
1052 Lex
.setIgnoreColonInIdentifiers(false);
1056 static bool isValidVisibilityForLinkage(unsigned V
, unsigned L
) {
1057 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes
)L
) ||
1058 (GlobalValue::VisibilityTypes
)V
== GlobalValue::DefaultVisibility
;
1060 static bool isValidDLLStorageClassForLinkage(unsigned S
, unsigned L
) {
1061 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes
)L
) ||
1062 (GlobalValue::DLLStorageClassTypes
)S
== GlobalValue::DefaultStorageClass
;
1065 // If there was an explicit dso_local, update GV. In the absence of an explicit
1066 // dso_local we keep the default value.
1067 static void maybeSetDSOLocal(bool DSOLocal
, GlobalValue
&GV
) {
1069 GV
.setDSOLocal(true);
1072 /// parseAliasOrIFunc:
1073 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1074 /// OptionalVisibility OptionalDLLStorageClass
1075 /// OptionalThreadLocal OptionalUnnamedAddr
1076 /// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
1078 /// AliaseeOrResolver
1079 /// ::= TypeAndValue
1082 /// ::= ',' 'partition' StringConstant
1084 /// Everything through OptionalUnnamedAddr has already been parsed.
1086 bool LLParser::parseAliasOrIFunc(const std::string
&Name
, LocTy NameLoc
,
1087 unsigned L
, unsigned Visibility
,
1088 unsigned DLLStorageClass
, bool DSOLocal
,
1089 GlobalVariable::ThreadLocalMode TLM
,
1090 GlobalVariable::UnnamedAddr UnnamedAddr
) {
1092 if (Lex
.getKind() == lltok::kw_alias
)
1094 else if (Lex
.getKind() == lltok::kw_ifunc
)
1097 llvm_unreachable("Not an alias or ifunc!");
1100 GlobalValue::LinkageTypes Linkage
= (GlobalValue::LinkageTypes
) L
;
1102 if(IsAlias
&& !GlobalAlias::isValidLinkage(Linkage
))
1103 return error(NameLoc
, "invalid linkage type for alias");
1105 if (!isValidVisibilityForLinkage(Visibility
, L
))
1106 return error(NameLoc
,
1107 "symbol with local linkage must have default visibility");
1109 if (!isValidDLLStorageClassForLinkage(DLLStorageClass
, L
))
1110 return error(NameLoc
,
1111 "symbol with local linkage cannot have a DLL storage class");
1114 LocTy ExplicitTypeLoc
= Lex
.getLoc();
1115 if (parseType(Ty
) ||
1116 parseToken(lltok::comma
, "expected comma after alias or ifunc's type"))
1120 LocTy AliaseeLoc
= Lex
.getLoc();
1121 if (Lex
.getKind() != lltok::kw_bitcast
&&
1122 Lex
.getKind() != lltok::kw_getelementptr
&&
1123 Lex
.getKind() != lltok::kw_addrspacecast
&&
1124 Lex
.getKind() != lltok::kw_inttoptr
) {
1125 if (parseGlobalTypeAndValue(Aliasee
))
1128 // The bitcast dest type is not present, it is implied by the dest type.
1130 if (parseValID(ID
, /*PFS=*/nullptr))
1132 if (ID
.Kind
!= ValID::t_Constant
)
1133 return error(AliaseeLoc
, "invalid aliasee");
1134 Aliasee
= ID
.ConstantVal
;
1137 Type
*AliaseeType
= Aliasee
->getType();
1138 auto *PTy
= dyn_cast
<PointerType
>(AliaseeType
);
1140 return error(AliaseeLoc
, "An alias or ifunc must have pointer type");
1141 unsigned AddrSpace
= PTy
->getAddressSpace();
1143 GlobalValue
*GVal
= nullptr;
1145 // See if the alias was forward referenced, if so, prepare to replace the
1146 // forward reference.
1147 if (!Name
.empty()) {
1148 auto I
= ForwardRefVals
.find(Name
);
1149 if (I
!= ForwardRefVals
.end()) {
1150 GVal
= I
->second
.first
;
1151 ForwardRefVals
.erase(Name
);
1152 } else if (M
->getNamedValue(Name
)) {
1153 return error(NameLoc
, "redefinition of global '@" + Name
+ "'");
1156 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
1157 if (I
!= ForwardRefValIDs
.end()) {
1158 GVal
= I
->second
.first
;
1159 ForwardRefValIDs
.erase(I
);
1163 // Okay, create the alias/ifunc but do not insert it into the module yet.
1164 std::unique_ptr
<GlobalAlias
> GA
;
1165 std::unique_ptr
<GlobalIFunc
> GI
;
1168 GA
.reset(GlobalAlias::create(Ty
, AddrSpace
,
1169 (GlobalValue::LinkageTypes
)Linkage
, Name
,
1170 Aliasee
, /*Parent*/ nullptr));
1173 GI
.reset(GlobalIFunc::create(Ty
, AddrSpace
,
1174 (GlobalValue::LinkageTypes
)Linkage
, Name
,
1175 Aliasee
, /*Parent*/ nullptr));
1178 GV
->setThreadLocalMode(TLM
);
1179 GV
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
1180 GV
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
1181 GV
->setUnnamedAddr(UnnamedAddr
);
1182 maybeSetDSOLocal(DSOLocal
, *GV
);
1184 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1185 // Now parse them if there are any.
1186 while (Lex
.getKind() == lltok::comma
) {
1189 if (Lex
.getKind() == lltok::kw_partition
) {
1191 GV
->setPartition(Lex
.getStrVal());
1192 if (parseToken(lltok::StringConstant
, "expected partition string"))
1195 return tokError("unknown alias or ifunc property!");
1200 NumberedVals
.push_back(GV
);
1203 // Verify that types agree.
1204 if (GVal
->getType() != GV
->getType())
1207 "forward reference and definition of alias have different types");
1209 // If they agree, just RAUW the old value with the alias and remove the
1210 // forward ref info.
1211 GVal
->replaceAllUsesWith(GV
);
1212 GVal
->eraseFromParent();
1215 // Insert into the module, we know its name won't collide now.
1217 M
->insertAlias(GA
.release());
1219 M
->insertIFunc(GI
.release());
1220 assert(GV
->getName() == Name
&& "Should not be a name conflict!");
1225 static bool isSanitizer(lltok::Kind Kind
) {
1227 case lltok::kw_no_sanitize_address
:
1228 case lltok::kw_no_sanitize_hwaddress
:
1229 case lltok::kw_sanitize_memtag
:
1230 case lltok::kw_sanitize_address_dyninit
:
1237 bool LLParser::parseSanitizer(GlobalVariable
*GV
) {
1238 using SanitizerMetadata
= GlobalValue::SanitizerMetadata
;
1239 SanitizerMetadata Meta
;
1240 if (GV
->hasSanitizerMetadata())
1241 Meta
= GV
->getSanitizerMetadata();
1243 switch (Lex
.getKind()) {
1244 case lltok::kw_no_sanitize_address
:
1245 Meta
.NoAddress
= true;
1247 case lltok::kw_no_sanitize_hwaddress
:
1248 Meta
.NoHWAddress
= true;
1250 case lltok::kw_sanitize_memtag
:
1253 case lltok::kw_sanitize_address_dyninit
:
1254 Meta
.IsDynInit
= true;
1257 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1259 GV
->setSanitizerMetadata(Meta
);
1265 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1266 /// OptionalVisibility OptionalDLLStorageClass
1267 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1268 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1269 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1270 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1271 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1272 /// Const OptionalAttrs
1274 /// Everything up to and including OptionalUnnamedAddr has been parsed
1277 bool LLParser::parseGlobal(const std::string
&Name
, LocTy NameLoc
,
1278 unsigned Linkage
, bool HasLinkage
,
1279 unsigned Visibility
, unsigned DLLStorageClass
,
1280 bool DSOLocal
, GlobalVariable::ThreadLocalMode TLM
,
1281 GlobalVariable::UnnamedAddr UnnamedAddr
) {
1282 if (!isValidVisibilityForLinkage(Visibility
, Linkage
))
1283 return error(NameLoc
,
1284 "symbol with local linkage must have default visibility");
1286 if (!isValidDLLStorageClassForLinkage(DLLStorageClass
, Linkage
))
1287 return error(NameLoc
,
1288 "symbol with local linkage cannot have a DLL storage class");
1291 bool IsConstant
, IsExternallyInitialized
;
1292 LocTy IsExternallyInitializedLoc
;
1296 if (parseOptionalAddrSpace(AddrSpace
) ||
1297 parseOptionalToken(lltok::kw_externally_initialized
,
1298 IsExternallyInitialized
,
1299 &IsExternallyInitializedLoc
) ||
1300 parseGlobalType(IsConstant
) || parseType(Ty
, TyLoc
))
1303 // If the linkage is specified and is external, then no initializer is
1305 Constant
*Init
= nullptr;
1307 !GlobalValue::isValidDeclarationLinkage(
1308 (GlobalValue::LinkageTypes
)Linkage
)) {
1309 if (parseGlobalValue(Ty
, Init
))
1313 if (Ty
->isFunctionTy() || !PointerType::isValidElementType(Ty
))
1314 return error(TyLoc
, "invalid type for global variable");
1316 GlobalValue
*GVal
= nullptr;
1318 // See if the global was forward referenced, if so, use the global.
1319 if (!Name
.empty()) {
1320 auto I
= ForwardRefVals
.find(Name
);
1321 if (I
!= ForwardRefVals
.end()) {
1322 GVal
= I
->second
.first
;
1323 ForwardRefVals
.erase(I
);
1324 } else if (M
->getNamedValue(Name
)) {
1325 return error(NameLoc
, "redefinition of global '@" + Name
+ "'");
1328 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
1329 if (I
!= ForwardRefValIDs
.end()) {
1330 GVal
= I
->second
.first
;
1331 ForwardRefValIDs
.erase(I
);
1335 GlobalVariable
*GV
= new GlobalVariable(
1336 *M
, Ty
, false, GlobalValue::ExternalLinkage
, nullptr, Name
, nullptr,
1337 GlobalVariable::NotThreadLocal
, AddrSpace
);
1340 NumberedVals
.push_back(GV
);
1342 // Set the parsed properties on the global.
1344 GV
->setInitializer(Init
);
1345 GV
->setConstant(IsConstant
);
1346 GV
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
1347 maybeSetDSOLocal(DSOLocal
, *GV
);
1348 GV
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
1349 GV
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
1350 GV
->setExternallyInitialized(IsExternallyInitialized
);
1351 GV
->setThreadLocalMode(TLM
);
1352 GV
->setUnnamedAddr(UnnamedAddr
);
1355 if (GVal
->getAddressSpace() != AddrSpace
)
1358 "forward reference and definition of global have different types");
1360 GVal
->replaceAllUsesWith(GV
);
1361 GVal
->eraseFromParent();
1364 // parse attributes on the global.
1365 while (Lex
.getKind() == lltok::comma
) {
1368 if (Lex
.getKind() == lltok::kw_section
) {
1370 GV
->setSection(Lex
.getStrVal());
1371 if (parseToken(lltok::StringConstant
, "expected global section string"))
1373 } else if (Lex
.getKind() == lltok::kw_partition
) {
1375 GV
->setPartition(Lex
.getStrVal());
1376 if (parseToken(lltok::StringConstant
, "expected partition string"))
1378 } else if (Lex
.getKind() == lltok::kw_align
) {
1379 MaybeAlign Alignment
;
1380 if (parseOptionalAlignment(Alignment
))
1383 GV
->setAlignment(*Alignment
);
1384 } else if (Lex
.getKind() == lltok::kw_code_model
) {
1385 CodeModel::Model CodeModel
;
1386 if (parseOptionalCodeModel(CodeModel
))
1388 GV
->setCodeModel(CodeModel
);
1389 } else if (Lex
.getKind() == lltok::MetadataVar
) {
1390 if (parseGlobalObjectMetadataAttachment(*GV
))
1392 } else if (isSanitizer(Lex
.getKind())) {
1393 if (parseSanitizer(GV
))
1397 if (parseOptionalComdat(Name
, C
))
1402 return tokError("unknown global variable property!");
1406 AttrBuilder
Attrs(M
->getContext());
1408 std::vector
<unsigned> FwdRefAttrGrps
;
1409 if (parseFnAttributeValuePairs(Attrs
, FwdRefAttrGrps
, false, BuiltinLoc
))
1411 if (Attrs
.hasAttributes() || !FwdRefAttrGrps
.empty()) {
1412 GV
->setAttributes(AttributeSet::get(Context
, Attrs
));
1413 ForwardRefAttrGroups
[GV
] = FwdRefAttrGrps
;
1419 /// parseUnnamedAttrGrp
1420 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1421 bool LLParser::parseUnnamedAttrGrp() {
1422 assert(Lex
.getKind() == lltok::kw_attributes
);
1423 LocTy AttrGrpLoc
= Lex
.getLoc();
1426 if (Lex
.getKind() != lltok::AttrGrpID
)
1427 return tokError("expected attribute group id");
1429 unsigned VarID
= Lex
.getUIntVal();
1430 std::vector
<unsigned> unused
;
1434 if (parseToken(lltok::equal
, "expected '=' here") ||
1435 parseToken(lltok::lbrace
, "expected '{' here"))
1438 auto R
= NumberedAttrBuilders
.find(VarID
);
1439 if (R
== NumberedAttrBuilders
.end())
1440 R
= NumberedAttrBuilders
.emplace(VarID
, AttrBuilder(M
->getContext())).first
;
1442 if (parseFnAttributeValuePairs(R
->second
, unused
, true, BuiltinLoc
) ||
1443 parseToken(lltok::rbrace
, "expected end of attribute group"))
1446 if (!R
->second
.hasAttributes())
1447 return error(AttrGrpLoc
, "attribute group has no attributes");
1452 static Attribute::AttrKind
tokenToAttribute(lltok::Kind Kind
) {
1454 #define GET_ATTR_NAMES
1455 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1456 case lltok::kw_##DISPLAY_NAME: \
1457 return Attribute::ENUM_NAME;
1458 #include "llvm/IR/Attributes.inc"
1460 return Attribute::None
;
1464 bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr
, AttrBuilder
&B
,
1466 if (Attribute::isTypeAttrKind(Attr
))
1467 return parseRequiredTypeAttr(B
, Lex
.getKind(), Attr
);
1470 case Attribute::Alignment
: {
1471 MaybeAlign Alignment
;
1475 if (parseToken(lltok::equal
, "expected '=' here") || parseUInt32(Value
))
1477 Alignment
= Align(Value
);
1479 if (parseOptionalAlignment(Alignment
, true))
1482 B
.addAlignmentAttr(Alignment
);
1485 case Attribute::StackAlignment
: {
1489 if (parseToken(lltok::equal
, "expected '=' here") ||
1490 parseUInt32(Alignment
))
1493 if (parseOptionalStackAlignment(Alignment
))
1496 B
.addStackAlignmentAttr(Alignment
);
1499 case Attribute::AllocSize
: {
1500 unsigned ElemSizeArg
;
1501 std::optional
<unsigned> NumElemsArg
;
1502 if (parseAllocSizeArguments(ElemSizeArg
, NumElemsArg
))
1504 B
.addAllocSizeAttr(ElemSizeArg
, NumElemsArg
);
1507 case Attribute::VScaleRange
: {
1508 unsigned MinValue
, MaxValue
;
1509 if (parseVScaleRangeArguments(MinValue
, MaxValue
))
1511 B
.addVScaleRangeAttr(MinValue
,
1512 MaxValue
> 0 ? MaxValue
: std::optional
<unsigned>());
1515 case Attribute::Dereferenceable
: {
1517 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable
, Bytes
))
1519 B
.addDereferenceableAttr(Bytes
);
1522 case Attribute::DereferenceableOrNull
: {
1524 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null
, Bytes
))
1526 B
.addDereferenceableOrNullAttr(Bytes
);
1529 case Attribute::UWTable
: {
1531 if (parseOptionalUWTableKind(Kind
))
1533 B
.addUWTableAttr(Kind
);
1536 case Attribute::AllocKind
: {
1537 AllocFnKind Kind
= AllocFnKind::Unknown
;
1538 if (parseAllocKind(Kind
))
1540 B
.addAllocKindAttr(Kind
);
1543 case Attribute::Memory
: {
1544 std::optional
<MemoryEffects
> ME
= parseMemoryAttr();
1547 B
.addMemoryAttr(*ME
);
1550 case Attribute::NoFPClass
: {
1551 if (FPClassTest NoFPClass
=
1552 static_cast<FPClassTest
>(parseNoFPClassAttr())) {
1553 B
.addNoFPClassAttr(NoFPClass
);
1560 B
.addAttribute(Attr
);
1566 static bool upgradeMemoryAttr(MemoryEffects
&ME
, lltok::Kind Kind
) {
1568 case lltok::kw_readnone
:
1569 ME
&= MemoryEffects::none();
1571 case lltok::kw_readonly
:
1572 ME
&= MemoryEffects::readOnly();
1574 case lltok::kw_writeonly
:
1575 ME
&= MemoryEffects::writeOnly();
1577 case lltok::kw_argmemonly
:
1578 ME
&= MemoryEffects::argMemOnly();
1580 case lltok::kw_inaccessiblememonly
:
1581 ME
&= MemoryEffects::inaccessibleMemOnly();
1583 case lltok::kw_inaccessiblemem_or_argmemonly
:
1584 ME
&= MemoryEffects::inaccessibleOrArgMemOnly();
1591 /// parseFnAttributeValuePairs
1592 /// ::= <attr> | <attr> '=' <value>
1593 bool LLParser::parseFnAttributeValuePairs(AttrBuilder
&B
,
1594 std::vector
<unsigned> &FwdRefAttrGrps
,
1595 bool InAttrGrp
, LocTy
&BuiltinLoc
) {
1596 bool HaveError
= false;
1600 MemoryEffects ME
= MemoryEffects::unknown();
1602 lltok::Kind Token
= Lex
.getKind();
1603 if (Token
== lltok::rbrace
)
1606 if (Token
== lltok::StringConstant
) {
1607 if (parseStringAttribute(B
))
1612 if (Token
== lltok::AttrGrpID
) {
1613 // Allow a function to reference an attribute group:
1615 // define void @foo() #1 { ... }
1619 "cannot have an attribute group reference in an attribute group");
1621 // Save the reference to the attribute group. We'll fill it in later.
1622 FwdRefAttrGrps
.push_back(Lex
.getUIntVal());
1628 SMLoc Loc
= Lex
.getLoc();
1629 if (Token
== lltok::kw_builtin
)
1632 if (upgradeMemoryAttr(ME
, Token
)) {
1637 Attribute::AttrKind Attr
= tokenToAttribute(Token
);
1638 if (Attr
== Attribute::None
) {
1641 return error(Lex
.getLoc(), "unterminated attribute group");
1644 if (parseEnumAttribute(Attr
, B
, InAttrGrp
))
1647 // As a hack, we allow function alignment to be initially parsed as an
1648 // attribute on a function declaration/definition or added to an attribute
1649 // group and later moved to the alignment field.
1650 if (!Attribute::canUseAsFnAttr(Attr
) && Attr
!= Attribute::Alignment
)
1651 HaveError
|= error(Loc
, "this attribute does not apply to functions");
1654 if (ME
!= MemoryEffects::unknown())
1655 B
.addMemoryAttr(ME
);
1659 //===----------------------------------------------------------------------===//
1660 // GlobalValue Reference/Resolution Routines.
1661 //===----------------------------------------------------------------------===//
1663 static inline GlobalValue
*createGlobalFwdRef(Module
*M
, PointerType
*PTy
) {
1664 // The used global type does not matter. We will later RAUW it with a
1665 // global/function of the correct type.
1666 return new GlobalVariable(*M
, Type::getInt8Ty(M
->getContext()), false,
1667 GlobalValue::ExternalWeakLinkage
, nullptr, "",
1668 nullptr, GlobalVariable::NotThreadLocal
,
1669 PTy
->getAddressSpace());
1672 Value
*LLParser::checkValidVariableType(LocTy Loc
, const Twine
&Name
, Type
*Ty
,
1674 Type
*ValTy
= Val
->getType();
1677 if (Ty
->isLabelTy())
1678 error(Loc
, "'" + Name
+ "' is not a basic block");
1680 error(Loc
, "'" + Name
+ "' defined with type '" +
1681 getTypeString(Val
->getType()) + "' but expected '" +
1682 getTypeString(Ty
) + "'");
1686 /// getGlobalVal - Get a value with the specified name or ID, creating a
1687 /// forward reference record if needed. This can return null if the value
1688 /// exists but does not have the right type.
1689 GlobalValue
*LLParser::getGlobalVal(const std::string
&Name
, Type
*Ty
,
1691 PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
1693 error(Loc
, "global variable reference must have pointer type");
1697 // Look this name up in the normal function symbol table.
1699 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
));
1701 // If this is a forward reference for the value, see if we already created a
1702 // forward ref record.
1704 auto I
= ForwardRefVals
.find(Name
);
1705 if (I
!= ForwardRefVals
.end())
1706 Val
= I
->second
.first
;
1709 // If we have the value in the symbol table or fwd-ref table, return it.
1711 return cast_or_null
<GlobalValue
>(
1712 checkValidVariableType(Loc
, "@" + Name
, Ty
, Val
));
1714 // Otherwise, create a new forward reference for this value and remember it.
1715 GlobalValue
*FwdVal
= createGlobalFwdRef(M
, PTy
);
1716 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
1720 GlobalValue
*LLParser::getGlobalVal(unsigned ID
, Type
*Ty
, LocTy Loc
) {
1721 PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
1723 error(Loc
, "global variable reference must have pointer type");
1727 GlobalValue
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : nullptr;
1729 // If this is a forward reference for the value, see if we already created a
1730 // forward ref record.
1732 auto I
= ForwardRefValIDs
.find(ID
);
1733 if (I
!= ForwardRefValIDs
.end())
1734 Val
= I
->second
.first
;
1737 // If we have the value in the symbol table or fwd-ref table, return it.
1739 return cast_or_null
<GlobalValue
>(
1740 checkValidVariableType(Loc
, "@" + Twine(ID
), Ty
, Val
));
1742 // Otherwise, create a new forward reference for this value and remember it.
1743 GlobalValue
*FwdVal
= createGlobalFwdRef(M
, PTy
);
1744 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
1748 //===----------------------------------------------------------------------===//
1749 // Comdat Reference/Resolution Routines.
1750 //===----------------------------------------------------------------------===//
1752 Comdat
*LLParser::getComdat(const std::string
&Name
, LocTy Loc
) {
1753 // Look this name up in the comdat symbol table.
1754 Module::ComdatSymTabType
&ComdatSymTab
= M
->getComdatSymbolTable();
1755 Module::ComdatSymTabType::iterator I
= ComdatSymTab
.find(Name
);
1756 if (I
!= ComdatSymTab
.end())
1759 // Otherwise, create a new forward reference for this value and remember it.
1760 Comdat
*C
= M
->getOrInsertComdat(Name
);
1761 ForwardRefComdats
[Name
] = Loc
;
1765 //===----------------------------------------------------------------------===//
1767 //===----------------------------------------------------------------------===//
1769 /// parseToken - If the current token has the specified kind, eat it and return
1770 /// success. Otherwise, emit the specified error and return failure.
1771 bool LLParser::parseToken(lltok::Kind T
, const char *ErrMsg
) {
1772 if (Lex
.getKind() != T
)
1773 return tokError(ErrMsg
);
1778 /// parseStringConstant
1779 /// ::= StringConstant
1780 bool LLParser::parseStringConstant(std::string
&Result
) {
1781 if (Lex
.getKind() != lltok::StringConstant
)
1782 return tokError("expected string constant");
1783 Result
= Lex
.getStrVal();
1790 bool LLParser::parseUInt32(uint32_t &Val
) {
1791 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
1792 return tokError("expected integer");
1793 uint64_t Val64
= Lex
.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL
+1);
1794 if (Val64
!= unsigned(Val64
))
1795 return tokError("expected 32-bit integer (too large)");
1803 bool LLParser::parseUInt64(uint64_t &Val
) {
1804 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
1805 return tokError("expected integer");
1806 Val
= Lex
.getAPSIntVal().getLimitedValue();
1812 /// := 'localdynamic'
1813 /// := 'initialexec'
1815 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode
&TLM
) {
1816 switch (Lex
.getKind()) {
1818 return tokError("expected localdynamic, initialexec or localexec");
1819 case lltok::kw_localdynamic
:
1820 TLM
= GlobalVariable::LocalDynamicTLSModel
;
1822 case lltok::kw_initialexec
:
1823 TLM
= GlobalVariable::InitialExecTLSModel
;
1825 case lltok::kw_localexec
:
1826 TLM
= GlobalVariable::LocalExecTLSModel
;
1834 /// parseOptionalThreadLocal
1836 /// := 'thread_local'
1837 /// := 'thread_local' '(' tlsmodel ')'
1838 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode
&TLM
) {
1839 TLM
= GlobalVariable::NotThreadLocal
;
1840 if (!EatIfPresent(lltok::kw_thread_local
))
1843 TLM
= GlobalVariable::GeneralDynamicTLSModel
;
1844 if (Lex
.getKind() == lltok::lparen
) {
1846 return parseTLSModel(TLM
) ||
1847 parseToken(lltok::rparen
, "expected ')' after thread local model");
1852 /// parseOptionalAddrSpace
1854 /// := 'addrspace' '(' uint32 ')'
1855 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace
, unsigned DefaultAS
) {
1856 AddrSpace
= DefaultAS
;
1857 if (!EatIfPresent(lltok::kw_addrspace
))
1860 auto ParseAddrspaceValue
= [&](unsigned &AddrSpace
) -> bool {
1861 if (Lex
.getKind() == lltok::StringConstant
) {
1862 auto AddrSpaceStr
= Lex
.getStrVal();
1863 if (AddrSpaceStr
== "A") {
1864 AddrSpace
= M
->getDataLayout().getAllocaAddrSpace();
1865 } else if (AddrSpaceStr
== "G") {
1866 AddrSpace
= M
->getDataLayout().getDefaultGlobalsAddressSpace();
1867 } else if (AddrSpaceStr
== "P") {
1868 AddrSpace
= M
->getDataLayout().getProgramAddressSpace();
1870 return tokError("invalid symbolic addrspace '" + AddrSpaceStr
+ "'");
1875 if (Lex
.getKind() != lltok::APSInt
)
1876 return tokError("expected integer or string constant");
1877 SMLoc Loc
= Lex
.getLoc();
1878 if (parseUInt32(AddrSpace
))
1880 if (!isUInt
<24>(AddrSpace
))
1881 return error(Loc
, "invalid address space, must be a 24-bit integer");
1885 return parseToken(lltok::lparen
, "expected '(' in address space") ||
1886 ParseAddrspaceValue(AddrSpace
) ||
1887 parseToken(lltok::rparen
, "expected ')' in address space");
1890 /// parseStringAttribute
1891 /// := StringConstant
1892 /// := StringConstant '=' StringConstant
1893 bool LLParser::parseStringAttribute(AttrBuilder
&B
) {
1894 std::string Attr
= Lex
.getStrVal();
1897 if (EatIfPresent(lltok::equal
) && parseStringConstant(Val
))
1899 B
.addAttribute(Attr
, Val
);
1903 /// Parse a potentially empty list of parameter or return attributes.
1904 bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder
&B
, bool IsParam
) {
1905 bool HaveError
= false;
1910 lltok::Kind Token
= Lex
.getKind();
1911 if (Token
== lltok::StringConstant
) {
1912 if (parseStringAttribute(B
))
1917 SMLoc Loc
= Lex
.getLoc();
1918 Attribute::AttrKind Attr
= tokenToAttribute(Token
);
1919 if (Attr
== Attribute::None
)
1922 if (parseEnumAttribute(Attr
, B
, /* InAttrGroup */ false))
1925 if (IsParam
&& !Attribute::canUseAsParamAttr(Attr
))
1926 HaveError
|= error(Loc
, "this attribute does not apply to parameters");
1927 if (!IsParam
&& !Attribute::canUseAsRetAttr(Attr
))
1928 HaveError
|= error(Loc
, "this attribute does not apply to return values");
1932 static unsigned parseOptionalLinkageAux(lltok::Kind Kind
, bool &HasLinkage
) {
1937 return GlobalValue::ExternalLinkage
;
1938 case lltok::kw_private
:
1939 return GlobalValue::PrivateLinkage
;
1940 case lltok::kw_internal
:
1941 return GlobalValue::InternalLinkage
;
1942 case lltok::kw_weak
:
1943 return GlobalValue::WeakAnyLinkage
;
1944 case lltok::kw_weak_odr
:
1945 return GlobalValue::WeakODRLinkage
;
1946 case lltok::kw_linkonce
:
1947 return GlobalValue::LinkOnceAnyLinkage
;
1948 case lltok::kw_linkonce_odr
:
1949 return GlobalValue::LinkOnceODRLinkage
;
1950 case lltok::kw_available_externally
:
1951 return GlobalValue::AvailableExternallyLinkage
;
1952 case lltok::kw_appending
:
1953 return GlobalValue::AppendingLinkage
;
1954 case lltok::kw_common
:
1955 return GlobalValue::CommonLinkage
;
1956 case lltok::kw_extern_weak
:
1957 return GlobalValue::ExternalWeakLinkage
;
1958 case lltok::kw_external
:
1959 return GlobalValue::ExternalLinkage
;
1963 /// parseOptionalLinkage
1970 /// ::= 'linkonce_odr'
1971 /// ::= 'available_externally'
1974 /// ::= 'extern_weak'
1976 bool LLParser::parseOptionalLinkage(unsigned &Res
, bool &HasLinkage
,
1977 unsigned &Visibility
,
1978 unsigned &DLLStorageClass
, bool &DSOLocal
) {
1979 Res
= parseOptionalLinkageAux(Lex
.getKind(), HasLinkage
);
1982 parseOptionalDSOLocal(DSOLocal
);
1983 parseOptionalVisibility(Visibility
);
1984 parseOptionalDLLStorageClass(DLLStorageClass
);
1986 if (DSOLocal
&& DLLStorageClass
== GlobalValue::DLLImportStorageClass
) {
1987 return error(Lex
.getLoc(), "dso_location and DLL-StorageClass mismatch");
1993 void LLParser::parseOptionalDSOLocal(bool &DSOLocal
) {
1994 switch (Lex
.getKind()) {
1998 case lltok::kw_dso_local
:
2002 case lltok::kw_dso_preemptable
:
2009 /// parseOptionalVisibility
2015 void LLParser::parseOptionalVisibility(unsigned &Res
) {
2016 switch (Lex
.getKind()) {
2018 Res
= GlobalValue::DefaultVisibility
;
2020 case lltok::kw_default
:
2021 Res
= GlobalValue::DefaultVisibility
;
2023 case lltok::kw_hidden
:
2024 Res
= GlobalValue::HiddenVisibility
;
2026 case lltok::kw_protected
:
2027 Res
= GlobalValue::ProtectedVisibility
;
2033 /// parseOptionalDLLStorageClass
2038 void LLParser::parseOptionalDLLStorageClass(unsigned &Res
) {
2039 switch (Lex
.getKind()) {
2041 Res
= GlobalValue::DefaultStorageClass
;
2043 case lltok::kw_dllimport
:
2044 Res
= GlobalValue::DLLImportStorageClass
;
2046 case lltok::kw_dllexport
:
2047 Res
= GlobalValue::DLLExportStorageClass
;
2053 /// parseOptionalCallingConv
2057 /// ::= 'intel_ocl_bicc'
2059 /// ::= 'cfguard_checkcc'
2060 /// ::= 'x86_stdcallcc'
2061 /// ::= 'x86_fastcallcc'
2062 /// ::= 'x86_thiscallcc'
2063 /// ::= 'x86_vectorcallcc'
2064 /// ::= 'arm_apcscc'
2065 /// ::= 'arm_aapcscc'
2066 /// ::= 'arm_aapcs_vfpcc'
2067 /// ::= 'aarch64_vector_pcs'
2068 /// ::= 'aarch64_sve_vector_pcs'
2069 /// ::= 'aarch64_sme_preservemost_from_x0'
2070 /// ::= 'aarch64_sme_preservemost_from_x2'
2071 /// ::= 'msp430_intrcc'
2072 /// ::= 'avr_intrcc'
2073 /// ::= 'avr_signalcc'
2074 /// ::= 'ptx_kernel'
2075 /// ::= 'ptx_device'
2077 /// ::= 'spir_kernel'
2078 /// ::= 'x86_64_sysvcc'
2081 /// ::= 'preserve_mostcc'
2082 /// ::= 'preserve_allcc'
2085 /// ::= 'swifttailcc'
2086 /// ::= 'x86_intrcc'
2089 /// ::= 'cxx_fast_tlscc'
2097 /// ::= 'amdgpu_cs_chain'
2098 /// ::= 'amdgpu_cs_chain_preserve'
2099 /// ::= 'amdgpu_kernel'
2101 /// ::= 'm68k_rtdcc'
2105 bool LLParser::parseOptionalCallingConv(unsigned &CC
) {
2106 switch (Lex
.getKind()) {
2107 default: CC
= CallingConv::C
; return false;
2108 case lltok::kw_ccc
: CC
= CallingConv::C
; break;
2109 case lltok::kw_fastcc
: CC
= CallingConv::Fast
; break;
2110 case lltok::kw_coldcc
: CC
= CallingConv::Cold
; break;
2111 case lltok::kw_cfguard_checkcc
: CC
= CallingConv::CFGuard_Check
; break;
2112 case lltok::kw_x86_stdcallcc
: CC
= CallingConv::X86_StdCall
; break;
2113 case lltok::kw_x86_fastcallcc
: CC
= CallingConv::X86_FastCall
; break;
2114 case lltok::kw_x86_regcallcc
: CC
= CallingConv::X86_RegCall
; break;
2115 case lltok::kw_x86_thiscallcc
: CC
= CallingConv::X86_ThisCall
; break;
2116 case lltok::kw_x86_vectorcallcc
:CC
= CallingConv::X86_VectorCall
; break;
2117 case lltok::kw_arm_apcscc
: CC
= CallingConv::ARM_APCS
; break;
2118 case lltok::kw_arm_aapcscc
: CC
= CallingConv::ARM_AAPCS
; break;
2119 case lltok::kw_arm_aapcs_vfpcc
:CC
= CallingConv::ARM_AAPCS_VFP
; break;
2120 case lltok::kw_aarch64_vector_pcs
:CC
= CallingConv::AArch64_VectorCall
; break;
2121 case lltok::kw_aarch64_sve_vector_pcs
:
2122 CC
= CallingConv::AArch64_SVE_VectorCall
;
2124 case lltok::kw_aarch64_sme_preservemost_from_x0
:
2125 CC
= CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X0
;
2127 case lltok::kw_aarch64_sme_preservemost_from_x2
:
2128 CC
= CallingConv::AArch64_SME_ABI_Support_Routines_PreserveMost_From_X2
;
2130 case lltok::kw_msp430_intrcc
: CC
= CallingConv::MSP430_INTR
; break;
2131 case lltok::kw_avr_intrcc
: CC
= CallingConv::AVR_INTR
; break;
2132 case lltok::kw_avr_signalcc
: CC
= CallingConv::AVR_SIGNAL
; break;
2133 case lltok::kw_ptx_kernel
: CC
= CallingConv::PTX_Kernel
; break;
2134 case lltok::kw_ptx_device
: CC
= CallingConv::PTX_Device
; break;
2135 case lltok::kw_spir_kernel
: CC
= CallingConv::SPIR_KERNEL
; break;
2136 case lltok::kw_spir_func
: CC
= CallingConv::SPIR_FUNC
; break;
2137 case lltok::kw_intel_ocl_bicc
: CC
= CallingConv::Intel_OCL_BI
; break;
2138 case lltok::kw_x86_64_sysvcc
: CC
= CallingConv::X86_64_SysV
; break;
2139 case lltok::kw_win64cc
: CC
= CallingConv::Win64
; break;
2140 case lltok::kw_anyregcc
: CC
= CallingConv::AnyReg
; break;
2141 case lltok::kw_preserve_mostcc
:CC
= CallingConv::PreserveMost
; break;
2142 case lltok::kw_preserve_allcc
: CC
= CallingConv::PreserveAll
; break;
2143 case lltok::kw_ghccc
: CC
= CallingConv::GHC
; break;
2144 case lltok::kw_swiftcc
: CC
= CallingConv::Swift
; break;
2145 case lltok::kw_swifttailcc
: CC
= CallingConv::SwiftTail
; break;
2146 case lltok::kw_x86_intrcc
: CC
= CallingConv::X86_INTR
; break;
2147 case lltok::kw_hhvmcc
:
2148 CC
= CallingConv::DUMMY_HHVM
;
2150 case lltok::kw_hhvm_ccc
:
2151 CC
= CallingConv::DUMMY_HHVM_C
;
2153 case lltok::kw_cxx_fast_tlscc
: CC
= CallingConv::CXX_FAST_TLS
; break;
2154 case lltok::kw_amdgpu_vs
: CC
= CallingConv::AMDGPU_VS
; break;
2155 case lltok::kw_amdgpu_gfx
: CC
= CallingConv::AMDGPU_Gfx
; break;
2156 case lltok::kw_amdgpu_ls
: CC
= CallingConv::AMDGPU_LS
; break;
2157 case lltok::kw_amdgpu_hs
: CC
= CallingConv::AMDGPU_HS
; break;
2158 case lltok::kw_amdgpu_es
: CC
= CallingConv::AMDGPU_ES
; break;
2159 case lltok::kw_amdgpu_gs
: CC
= CallingConv::AMDGPU_GS
; break;
2160 case lltok::kw_amdgpu_ps
: CC
= CallingConv::AMDGPU_PS
; break;
2161 case lltok::kw_amdgpu_cs
: CC
= CallingConv::AMDGPU_CS
; break;
2162 case lltok::kw_amdgpu_cs_chain
:
2163 CC
= CallingConv::AMDGPU_CS_Chain
;
2165 case lltok::kw_amdgpu_cs_chain_preserve
:
2166 CC
= CallingConv::AMDGPU_CS_ChainPreserve
;
2168 case lltok::kw_amdgpu_kernel
: CC
= CallingConv::AMDGPU_KERNEL
; break;
2169 case lltok::kw_tailcc
: CC
= CallingConv::Tail
; break;
2170 case lltok::kw_m68k_rtdcc
: CC
= CallingConv::M68k_RTD
; break;
2171 case lltok::kw_graalcc
: CC
= CallingConv::GRAAL
; break;
2172 case lltok::kw_cc
: {
2174 return parseUInt32(CC
);
2182 /// parseMetadataAttachment
2184 bool LLParser::parseMetadataAttachment(unsigned &Kind
, MDNode
*&MD
) {
2185 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata attachment");
2187 std::string Name
= Lex
.getStrVal();
2188 Kind
= M
->getMDKindID(Name
);
2191 return parseMDNode(MD
);
2194 /// parseInstructionMetadata
2195 /// ::= !dbg !42 (',' !dbg !57)*
2196 bool LLParser::parseInstructionMetadata(Instruction
&Inst
) {
2198 if (Lex
.getKind() != lltok::MetadataVar
)
2199 return tokError("expected metadata after comma");
2203 if (parseMetadataAttachment(MDK
, N
))
2206 if (MDK
== LLVMContext::MD_DIAssignID
)
2207 TempDIAssignIDAttachments
[N
].push_back(&Inst
);
2209 Inst
.setMetadata(MDK
, N
);
2211 if (MDK
== LLVMContext::MD_tbaa
)
2212 InstsWithTBAATag
.push_back(&Inst
);
2214 // If this is the end of the list, we're done.
2215 } while (EatIfPresent(lltok::comma
));
2219 /// parseGlobalObjectMetadataAttachment
2221 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject
&GO
) {
2224 if (parseMetadataAttachment(MDK
, N
))
2227 GO
.addMetadata(MDK
, *N
);
2231 /// parseOptionalFunctionMetadata
2233 bool LLParser::parseOptionalFunctionMetadata(Function
&F
) {
2234 while (Lex
.getKind() == lltok::MetadataVar
)
2235 if (parseGlobalObjectMetadataAttachment(F
))
2240 /// parseOptionalAlignment
2243 bool LLParser::parseOptionalAlignment(MaybeAlign
&Alignment
, bool AllowParens
) {
2244 Alignment
= std::nullopt
;
2245 if (!EatIfPresent(lltok::kw_align
))
2247 LocTy AlignLoc
= Lex
.getLoc();
2250 LocTy ParenLoc
= Lex
.getLoc();
2251 bool HaveParens
= false;
2253 if (EatIfPresent(lltok::lparen
))
2257 if (parseUInt64(Value
))
2260 if (HaveParens
&& !EatIfPresent(lltok::rparen
))
2261 return error(ParenLoc
, "expected ')'");
2263 if (!isPowerOf2_64(Value
))
2264 return error(AlignLoc
, "alignment is not a power of two");
2265 if (Value
> Value::MaximumAlignment
)
2266 return error(AlignLoc
, "huge alignments are not supported yet");
2267 Alignment
= Align(Value
);
2271 /// parseOptionalCodeModel
2273 /// ::= 'code_model' "large"
2274 bool LLParser::parseOptionalCodeModel(CodeModel::Model
&model
) {
2276 auto StrVal
= Lex
.getStrVal();
2277 auto ErrMsg
= "expected global code model string";
2278 if (StrVal
== "tiny")
2279 model
= CodeModel::Tiny
;
2280 else if (StrVal
== "small")
2281 model
= CodeModel::Small
;
2282 else if (StrVal
== "kernel")
2283 model
= CodeModel::Kernel
;
2284 else if (StrVal
== "medium")
2285 model
= CodeModel::Medium
;
2286 else if (StrVal
== "large")
2287 model
= CodeModel::Large
;
2289 return tokError(ErrMsg
);
2290 if (parseToken(lltok::StringConstant
, ErrMsg
))
2295 /// parseOptionalDerefAttrBytes
2297 /// ::= AttrKind '(' 4 ')'
2299 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2300 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind
,
2302 assert((AttrKind
== lltok::kw_dereferenceable
||
2303 AttrKind
== lltok::kw_dereferenceable_or_null
) &&
2307 if (!EatIfPresent(AttrKind
))
2309 LocTy ParenLoc
= Lex
.getLoc();
2310 if (!EatIfPresent(lltok::lparen
))
2311 return error(ParenLoc
, "expected '('");
2312 LocTy DerefLoc
= Lex
.getLoc();
2313 if (parseUInt64(Bytes
))
2315 ParenLoc
= Lex
.getLoc();
2316 if (!EatIfPresent(lltok::rparen
))
2317 return error(ParenLoc
, "expected ')'");
2319 return error(DerefLoc
, "dereferenceable bytes must be non-zero");
2323 bool LLParser::parseOptionalUWTableKind(UWTableKind
&Kind
) {
2325 Kind
= UWTableKind::Default
;
2326 if (!EatIfPresent(lltok::lparen
))
2328 LocTy KindLoc
= Lex
.getLoc();
2329 if (Lex
.getKind() == lltok::kw_sync
)
2330 Kind
= UWTableKind::Sync
;
2331 else if (Lex
.getKind() == lltok::kw_async
)
2332 Kind
= UWTableKind::Async
;
2334 return error(KindLoc
, "expected unwind table kind");
2336 return parseToken(lltok::rparen
, "expected ')'");
2339 bool LLParser::parseAllocKind(AllocFnKind
&Kind
) {
2341 LocTy ParenLoc
= Lex
.getLoc();
2342 if (!EatIfPresent(lltok::lparen
))
2343 return error(ParenLoc
, "expected '('");
2344 LocTy KindLoc
= Lex
.getLoc();
2346 if (parseStringConstant(Arg
))
2347 return error(KindLoc
, "expected allockind value");
2348 for (StringRef A
: llvm::split(Arg
, ",")) {
2350 Kind
|= AllocFnKind::Alloc
;
2351 } else if (A
== "realloc") {
2352 Kind
|= AllocFnKind::Realloc
;
2353 } else if (A
== "free") {
2354 Kind
|= AllocFnKind::Free
;
2355 } else if (A
== "uninitialized") {
2356 Kind
|= AllocFnKind::Uninitialized
;
2357 } else if (A
== "zeroed") {
2358 Kind
|= AllocFnKind::Zeroed
;
2359 } else if (A
== "aligned") {
2360 Kind
|= AllocFnKind::Aligned
;
2362 return error(KindLoc
, Twine("unknown allockind ") + A
);
2365 ParenLoc
= Lex
.getLoc();
2366 if (!EatIfPresent(lltok::rparen
))
2367 return error(ParenLoc
, "expected ')'");
2368 if (Kind
== AllocFnKind::Unknown
)
2369 return error(KindLoc
, "expected allockind value");
2373 static std::optional
<MemoryEffects::Location
> keywordToLoc(lltok::Kind Tok
) {
2375 case lltok::kw_argmem
:
2376 return IRMemLocation::ArgMem
;
2377 case lltok::kw_inaccessiblemem
:
2378 return IRMemLocation::InaccessibleMem
;
2380 return std::nullopt
;
2384 static std::optional
<ModRefInfo
> keywordToModRef(lltok::Kind Tok
) {
2386 case lltok::kw_none
:
2387 return ModRefInfo::NoModRef
;
2388 case lltok::kw_read
:
2389 return ModRefInfo::Ref
;
2390 case lltok::kw_write
:
2391 return ModRefInfo::Mod
;
2392 case lltok::kw_readwrite
:
2393 return ModRefInfo::ModRef
;
2395 return std::nullopt
;
2399 std::optional
<MemoryEffects
> LLParser::parseMemoryAttr() {
2400 MemoryEffects ME
= MemoryEffects::none();
2402 // We use syntax like memory(argmem: read), so the colon should not be
2403 // interpreted as a label terminator.
2404 Lex
.setIgnoreColonInIdentifiers(true);
2405 auto _
= make_scope_exit([&] { Lex
.setIgnoreColonInIdentifiers(false); });
2408 if (!EatIfPresent(lltok::lparen
)) {
2409 tokError("expected '('");
2410 return std::nullopt
;
2413 bool SeenLoc
= false;
2415 std::optional
<IRMemLocation
> Loc
= keywordToLoc(Lex
.getKind());
2418 if (!EatIfPresent(lltok::colon
)) {
2419 tokError("expected ':' after location");
2420 return std::nullopt
;
2424 std::optional
<ModRefInfo
> MR
= keywordToModRef(Lex
.getKind());
2427 tokError("expected memory location (argmem, inaccessiblemem) "
2428 "or access kind (none, read, write, readwrite)");
2430 tokError("expected access kind (none, read, write, readwrite)");
2431 return std::nullopt
;
2437 ME
= ME
.getWithModRef(*Loc
, *MR
);
2440 tokError("default access kind must be specified first");
2441 return std::nullopt
;
2443 ME
= MemoryEffects(*MR
);
2446 if (EatIfPresent(lltok::rparen
))
2448 } while (EatIfPresent(lltok::comma
));
2450 tokError("unterminated memory attribute");
2451 return std::nullopt
;
2454 static unsigned keywordToFPClassTest(lltok::Kind Tok
) {
2460 case lltok::kw_snan
:
2462 case lltok::kw_qnan
:
2466 case lltok::kw_ninf
:
2468 case lltok::kw_pinf
:
2470 case lltok::kw_norm
:
2472 case lltok::kw_nnorm
:
2474 case lltok::kw_pnorm
:
2478 case lltok::kw_nsub
:
2479 return fcNegSubnormal
;
2480 case lltok::kw_psub
:
2481 return fcPosSubnormal
;
2482 case lltok::kw_zero
:
2484 case lltok::kw_nzero
:
2486 case lltok::kw_pzero
:
2493 unsigned LLParser::parseNoFPClassAttr() {
2494 unsigned Mask
= fcNone
;
2497 if (!EatIfPresent(lltok::lparen
)) {
2498 tokError("expected '('");
2504 unsigned TestMask
= keywordToFPClassTest(Lex
.getKind());
2505 if (TestMask
!= 0) {
2507 // TODO: Disallow overlapping masks to avoid copy paste errors
2508 } else if (Mask
== 0 && Lex
.getKind() == lltok::APSInt
&&
2509 !parseUInt64(Value
)) {
2510 if (Value
== 0 || (Value
& ~static_cast<unsigned>(fcAllFlags
)) != 0) {
2511 error(Lex
.getLoc(), "invalid mask value for 'nofpclass'");
2515 if (!EatIfPresent(lltok::rparen
)) {
2516 error(Lex
.getLoc(), "expected ')'");
2522 error(Lex
.getLoc(), "expected nofpclass test mask");
2527 if (EatIfPresent(lltok::rparen
))
2531 llvm_unreachable("unterminated nofpclass attribute");
2534 /// parseOptionalCommaAlign
2538 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2540 bool LLParser::parseOptionalCommaAlign(MaybeAlign
&Alignment
,
2541 bool &AteExtraComma
) {
2542 AteExtraComma
= false;
2543 while (EatIfPresent(lltok::comma
)) {
2544 // Metadata at the end is an early exit.
2545 if (Lex
.getKind() == lltok::MetadataVar
) {
2546 AteExtraComma
= true;
2550 if (Lex
.getKind() != lltok::kw_align
)
2551 return error(Lex
.getLoc(), "expected metadata or 'align'");
2553 if (parseOptionalAlignment(Alignment
))
2560 /// parseOptionalCommaAddrSpace
2562 /// ::= ',' addrspace(1)
2564 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2566 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace
, LocTy
&Loc
,
2567 bool &AteExtraComma
) {
2568 AteExtraComma
= false;
2569 while (EatIfPresent(lltok::comma
)) {
2570 // Metadata at the end is an early exit.
2571 if (Lex
.getKind() == lltok::MetadataVar
) {
2572 AteExtraComma
= true;
2577 if (Lex
.getKind() != lltok::kw_addrspace
)
2578 return error(Lex
.getLoc(), "expected metadata or 'addrspace'");
2580 if (parseOptionalAddrSpace(AddrSpace
))
2587 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg
,
2588 std::optional
<unsigned> &HowManyArg
) {
2591 auto StartParen
= Lex
.getLoc();
2592 if (!EatIfPresent(lltok::lparen
))
2593 return error(StartParen
, "expected '('");
2595 if (parseUInt32(BaseSizeArg
))
2598 if (EatIfPresent(lltok::comma
)) {
2599 auto HowManyAt
= Lex
.getLoc();
2601 if (parseUInt32(HowMany
))
2603 if (HowMany
== BaseSizeArg
)
2604 return error(HowManyAt
,
2605 "'allocsize' indices can't refer to the same parameter");
2606 HowManyArg
= HowMany
;
2608 HowManyArg
= std::nullopt
;
2610 auto EndParen
= Lex
.getLoc();
2611 if (!EatIfPresent(lltok::rparen
))
2612 return error(EndParen
, "expected ')'");
2616 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue
,
2617 unsigned &MaxValue
) {
2620 auto StartParen
= Lex
.getLoc();
2621 if (!EatIfPresent(lltok::lparen
))
2622 return error(StartParen
, "expected '('");
2624 if (parseUInt32(MinValue
))
2627 if (EatIfPresent(lltok::comma
)) {
2628 if (parseUInt32(MaxValue
))
2631 MaxValue
= MinValue
;
2633 auto EndParen
= Lex
.getLoc();
2634 if (!EatIfPresent(lltok::rparen
))
2635 return error(EndParen
, "expected ')'");
2639 /// parseScopeAndOrdering
2640 /// if isAtomic: ::= SyncScope? AtomicOrdering
2643 /// This sets Scope and Ordering to the parsed values.
2644 bool LLParser::parseScopeAndOrdering(bool IsAtomic
, SyncScope::ID
&SSID
,
2645 AtomicOrdering
&Ordering
) {
2649 return parseScope(SSID
) || parseOrdering(Ordering
);
2653 /// ::= syncscope("singlethread" | "<target scope>")?
2655 /// This sets synchronization scope ID to the ID of the parsed value.
2656 bool LLParser::parseScope(SyncScope::ID
&SSID
) {
2657 SSID
= SyncScope::System
;
2658 if (EatIfPresent(lltok::kw_syncscope
)) {
2659 auto StartParenAt
= Lex
.getLoc();
2660 if (!EatIfPresent(lltok::lparen
))
2661 return error(StartParenAt
, "Expected '(' in syncscope");
2664 auto SSNAt
= Lex
.getLoc();
2665 if (parseStringConstant(SSN
))
2666 return error(SSNAt
, "Expected synchronization scope name");
2668 auto EndParenAt
= Lex
.getLoc();
2669 if (!EatIfPresent(lltok::rparen
))
2670 return error(EndParenAt
, "Expected ')' in syncscope");
2672 SSID
= Context
.getOrInsertSyncScopeID(SSN
);
2679 /// ::= AtomicOrdering
2681 /// This sets Ordering to the parsed value.
2682 bool LLParser::parseOrdering(AtomicOrdering
&Ordering
) {
2683 switch (Lex
.getKind()) {
2685 return tokError("Expected ordering on atomic instruction");
2686 case lltok::kw_unordered
: Ordering
= AtomicOrdering::Unordered
; break;
2687 case lltok::kw_monotonic
: Ordering
= AtomicOrdering::Monotonic
; break;
2688 // Not specified yet:
2689 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2690 case lltok::kw_acquire
: Ordering
= AtomicOrdering::Acquire
; break;
2691 case lltok::kw_release
: Ordering
= AtomicOrdering::Release
; break;
2692 case lltok::kw_acq_rel
: Ordering
= AtomicOrdering::AcquireRelease
; break;
2693 case lltok::kw_seq_cst
:
2694 Ordering
= AtomicOrdering::SequentiallyConsistent
;
2701 /// parseOptionalStackAlignment
2703 /// ::= 'alignstack' '(' 4 ')'
2704 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment
) {
2706 if (!EatIfPresent(lltok::kw_alignstack
))
2708 LocTy ParenLoc
= Lex
.getLoc();
2709 if (!EatIfPresent(lltok::lparen
))
2710 return error(ParenLoc
, "expected '('");
2711 LocTy AlignLoc
= Lex
.getLoc();
2712 if (parseUInt32(Alignment
))
2714 ParenLoc
= Lex
.getLoc();
2715 if (!EatIfPresent(lltok::rparen
))
2716 return error(ParenLoc
, "expected ')'");
2717 if (!isPowerOf2_32(Alignment
))
2718 return error(AlignLoc
, "stack alignment is not a power of two");
2722 /// parseIndexList - This parses the index list for an insert/extractvalue
2723 /// instruction. This sets AteExtraComma in the case where we eat an extra
2724 /// comma at the end of the line and find that it is followed by metadata.
2725 /// Clients that don't allow metadata can call the version of this function that
2726 /// only takes one argument.
2729 /// ::= (',' uint32)+
2731 bool LLParser::parseIndexList(SmallVectorImpl
<unsigned> &Indices
,
2732 bool &AteExtraComma
) {
2733 AteExtraComma
= false;
2735 if (Lex
.getKind() != lltok::comma
)
2736 return tokError("expected ',' as start of index list");
2738 while (EatIfPresent(lltok::comma
)) {
2739 if (Lex
.getKind() == lltok::MetadataVar
) {
2740 if (Indices
.empty())
2741 return tokError("expected index");
2742 AteExtraComma
= true;
2746 if (parseUInt32(Idx
))
2748 Indices
.push_back(Idx
);
2754 //===----------------------------------------------------------------------===//
2756 //===----------------------------------------------------------------------===//
2758 /// parseType - parse a type.
2759 bool LLParser::parseType(Type
*&Result
, const Twine
&Msg
, bool AllowVoid
) {
2760 SMLoc TypeLoc
= Lex
.getLoc();
2761 switch (Lex
.getKind()) {
2763 return tokError(Msg
);
2765 // Type ::= 'float' | 'void' (etc)
2766 Result
= Lex
.getTyVal();
2769 // Handle "ptr" opaque pointer type.
2771 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2772 if (Result
->isPointerTy()) {
2774 if (parseOptionalAddrSpace(AddrSpace
))
2776 Result
= PointerType::get(getContext(), AddrSpace
);
2778 // Give a nice error for 'ptr*'.
2779 if (Lex
.getKind() == lltok::star
)
2780 return tokError("ptr* is invalid - use ptr instead");
2782 // Fall through to parsing the type suffixes only if this 'ptr' is a
2783 // function return. Otherwise, return success, implicitly rejecting other
2785 if (Lex
.getKind() != lltok::lparen
)
2789 case lltok::kw_target
: {
2790 // Type ::= TargetExtType
2791 if (parseTargetExtType(Result
))
2796 // Type ::= StructType
2797 if (parseAnonStructType(Result
, false))
2800 case lltok::lsquare
:
2801 // Type ::= '[' ... ']'
2802 Lex
.Lex(); // eat the lsquare.
2803 if (parseArrayVectorType(Result
, false))
2806 case lltok::less
: // Either vector or packed struct.
2807 // Type ::= '<' ... '>'
2809 if (Lex
.getKind() == lltok::lbrace
) {
2810 if (parseAnonStructType(Result
, true) ||
2811 parseToken(lltok::greater
, "expected '>' at end of packed struct"))
2813 } else if (parseArrayVectorType(Result
, true))
2816 case lltok::LocalVar
: {
2818 std::pair
<Type
*, LocTy
> &Entry
= NamedTypes
[Lex
.getStrVal()];
2820 // If the type hasn't been defined yet, create a forward definition and
2821 // remember where that forward def'n was seen (in case it never is defined).
2823 Entry
.first
= StructType::create(Context
, Lex
.getStrVal());
2824 Entry
.second
= Lex
.getLoc();
2826 Result
= Entry
.first
;
2831 case lltok::LocalVarID
: {
2833 std::pair
<Type
*, LocTy
> &Entry
= NumberedTypes
[Lex
.getUIntVal()];
2835 // If the type hasn't been defined yet, create a forward definition and
2836 // remember where that forward def'n was seen (in case it never is defined).
2838 Entry
.first
= StructType::create(Context
);
2839 Entry
.second
= Lex
.getLoc();
2841 Result
= Entry
.first
;
2847 // parse the type suffixes.
2849 switch (Lex
.getKind()) {
2852 if (!AllowVoid
&& Result
->isVoidTy())
2853 return error(TypeLoc
, "void type only allowed for function results");
2856 // Type ::= Type '*'
2858 if (Result
->isLabelTy())
2859 return tokError("basic block pointers are invalid");
2860 if (Result
->isVoidTy())
2861 return tokError("pointers to void are invalid - use i8* instead");
2862 if (!PointerType::isValidElementType(Result
))
2863 return tokError("pointer to this type is invalid");
2864 Result
= PointerType::getUnqual(Result
);
2868 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2869 case lltok::kw_addrspace
: {
2870 if (Result
->isLabelTy())
2871 return tokError("basic block pointers are invalid");
2872 if (Result
->isVoidTy())
2873 return tokError("pointers to void are invalid; use i8* instead");
2874 if (!PointerType::isValidElementType(Result
))
2875 return tokError("pointer to this type is invalid");
2877 if (parseOptionalAddrSpace(AddrSpace
) ||
2878 parseToken(lltok::star
, "expected '*' in address space"))
2881 Result
= PointerType::get(Result
, AddrSpace
);
2885 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2887 if (parseFunctionType(Result
))
2894 /// parseParameterList
2896 /// ::= '(' Arg (',' Arg)* ')'
2898 /// ::= Type OptionalAttributes Value OptionalAttributes
2899 bool LLParser::parseParameterList(SmallVectorImpl
<ParamInfo
> &ArgList
,
2900 PerFunctionState
&PFS
, bool IsMustTailCall
,
2901 bool InVarArgsFunc
) {
2902 if (parseToken(lltok::lparen
, "expected '(' in call"))
2905 while (Lex
.getKind() != lltok::rparen
) {
2906 // If this isn't the first argument, we need a comma.
2907 if (!ArgList
.empty() &&
2908 parseToken(lltok::comma
, "expected ',' in argument list"))
2911 // parse an ellipsis if this is a musttail call in a variadic function.
2912 if (Lex
.getKind() == lltok::dotdotdot
) {
2913 const char *Msg
= "unexpected ellipsis in argument list for ";
2914 if (!IsMustTailCall
)
2915 return tokError(Twine(Msg
) + "non-musttail call");
2917 return tokError(Twine(Msg
) + "musttail call in non-varargs function");
2918 Lex
.Lex(); // Lex the '...', it is purely for readability.
2919 return parseToken(lltok::rparen
, "expected ')' at end of argument list");
2922 // parse the argument.
2924 Type
*ArgTy
= nullptr;
2926 if (parseType(ArgTy
, ArgLoc
))
2929 AttrBuilder
ArgAttrs(M
->getContext());
2931 if (ArgTy
->isMetadataTy()) {
2932 if (parseMetadataAsValue(V
, PFS
))
2935 // Otherwise, handle normal operands.
2936 if (parseOptionalParamAttrs(ArgAttrs
) || parseValue(ArgTy
, V
, PFS
))
2939 ArgList
.push_back(ParamInfo(
2940 ArgLoc
, V
, AttributeSet::get(V
->getContext(), ArgAttrs
)));
2943 if (IsMustTailCall
&& InVarArgsFunc
)
2944 return tokError("expected '...' at end of argument list for musttail call "
2945 "in varargs function");
2947 Lex
.Lex(); // Lex the ')'.
2951 /// parseRequiredTypeAttr
2952 /// ::= attrname(<ty>)
2953 bool LLParser::parseRequiredTypeAttr(AttrBuilder
&B
, lltok::Kind AttrToken
,
2954 Attribute::AttrKind AttrKind
) {
2956 if (!EatIfPresent(AttrToken
))
2958 if (!EatIfPresent(lltok::lparen
))
2959 return error(Lex
.getLoc(), "expected '('");
2962 if (!EatIfPresent(lltok::rparen
))
2963 return error(Lex
.getLoc(), "expected ')'");
2965 B
.addTypeAttr(AttrKind
, Ty
);
2969 /// parseOptionalOperandBundles
2971 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2974 /// ::= bundle-tag '(' ')'
2975 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2977 /// bundle-tag ::= String Constant
2978 bool LLParser::parseOptionalOperandBundles(
2979 SmallVectorImpl
<OperandBundleDef
> &BundleList
, PerFunctionState
&PFS
) {
2980 LocTy BeginLoc
= Lex
.getLoc();
2981 if (!EatIfPresent(lltok::lsquare
))
2984 while (Lex
.getKind() != lltok::rsquare
) {
2985 // If this isn't the first operand bundle, we need a comma.
2986 if (!BundleList
.empty() &&
2987 parseToken(lltok::comma
, "expected ',' in input list"))
2991 if (parseStringConstant(Tag
))
2994 if (parseToken(lltok::lparen
, "expected '(' in operand bundle"))
2997 std::vector
<Value
*> Inputs
;
2998 while (Lex
.getKind() != lltok::rparen
) {
2999 // If this isn't the first input, we need a comma.
3000 if (!Inputs
.empty() &&
3001 parseToken(lltok::comma
, "expected ',' in input list"))
3005 Value
*Input
= nullptr;
3006 if (parseType(Ty
) || parseValue(Ty
, Input
, PFS
))
3008 Inputs
.push_back(Input
);
3011 BundleList
.emplace_back(std::move(Tag
), std::move(Inputs
));
3013 Lex
.Lex(); // Lex the ')'.
3016 if (BundleList
.empty())
3017 return error(BeginLoc
, "operand bundle set must not be empty");
3019 Lex
.Lex(); // Lex the ']'.
3023 bool LLParser::checkValueID(LocTy Loc
, StringRef Kind
, StringRef Prefix
,
3024 unsigned NextID
, unsigned ID
) const {
3026 return error(Loc
, Kind
+ " expected to be numbered '" + Prefix
+
3027 Twine(NextID
) + "' or greater");
3032 /// parseArgumentList - parse the argument list for a function type or function
3034 /// ::= '(' ArgTypeListI ')'
3038 /// ::= ArgTypeList ',' '...'
3039 /// ::= ArgType (',' ArgType)*
3041 bool LLParser::parseArgumentList(SmallVectorImpl
<ArgInfo
> &ArgList
,
3042 SmallVectorImpl
<unsigned> &UnnamedArgNums
,
3044 unsigned CurValID
= 0;
3046 assert(Lex
.getKind() == lltok::lparen
);
3047 Lex
.Lex(); // eat the (.
3049 if (Lex
.getKind() != lltok::rparen
) {
3051 // Handle ... at end of arg list.
3052 if (EatIfPresent(lltok::dotdotdot
)) {
3057 // Otherwise must be an argument type.
3058 LocTy TypeLoc
= Lex
.getLoc();
3059 Type
*ArgTy
= nullptr;
3060 AttrBuilder
Attrs(M
->getContext());
3061 if (parseType(ArgTy
) || parseOptionalParamAttrs(Attrs
))
3064 if (ArgTy
->isVoidTy())
3065 return error(TypeLoc
, "argument can not have void type");
3068 if (Lex
.getKind() == lltok::LocalVar
) {
3069 Name
= Lex
.getStrVal();
3073 if (Lex
.getKind() == lltok::LocalVarID
) {
3074 ArgID
= Lex
.getUIntVal();
3075 if (checkValueID(TypeLoc
, "argument", "%", CurValID
, ArgID
))
3081 UnnamedArgNums
.push_back(ArgID
);
3082 CurValID
= ArgID
+ 1;
3085 if (!ArgTy
->isFirstClassType())
3086 return error(TypeLoc
, "invalid type for function argument");
3088 ArgList
.emplace_back(TypeLoc
, ArgTy
,
3089 AttributeSet::get(ArgTy
->getContext(), Attrs
),
3091 } while (EatIfPresent(lltok::comma
));
3094 return parseToken(lltok::rparen
, "expected ')' at end of argument list");
3097 /// parseFunctionType
3098 /// ::= Type ArgumentList OptionalAttrs
3099 bool LLParser::parseFunctionType(Type
*&Result
) {
3100 assert(Lex
.getKind() == lltok::lparen
);
3102 if (!FunctionType::isValidReturnType(Result
))
3103 return tokError("invalid function return type");
3105 SmallVector
<ArgInfo
, 8> ArgList
;
3107 SmallVector
<unsigned> UnnamedArgNums
;
3108 if (parseArgumentList(ArgList
, UnnamedArgNums
, IsVarArg
))
3111 // Reject names on the arguments lists.
3112 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
3113 if (!ArgList
[i
].Name
.empty())
3114 return error(ArgList
[i
].Loc
, "argument name invalid in function type");
3115 if (ArgList
[i
].Attrs
.hasAttributes())
3116 return error(ArgList
[i
].Loc
,
3117 "argument attributes invalid in function type");
3120 SmallVector
<Type
*, 16> ArgListTy
;
3121 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
3122 ArgListTy
.push_back(ArgList
[i
].Ty
);
3124 Result
= FunctionType::get(Result
, ArgListTy
, IsVarArg
);
3128 /// parseAnonStructType - parse an anonymous struct type, which is inlined into
3130 bool LLParser::parseAnonStructType(Type
*&Result
, bool Packed
) {
3131 SmallVector
<Type
*, 8> Elts
;
3132 if (parseStructBody(Elts
))
3135 Result
= StructType::get(Context
, Elts
, Packed
);
3139 /// parseStructDefinition - parse a struct in a 'type' definition.
3140 bool LLParser::parseStructDefinition(SMLoc TypeLoc
, StringRef Name
,
3141 std::pair
<Type
*, LocTy
> &Entry
,
3143 // If the type was already defined, diagnose the redefinition.
3144 if (Entry
.first
&& !Entry
.second
.isValid())
3145 return error(TypeLoc
, "redefinition of type");
3147 // If we have opaque, just return without filling in the definition for the
3148 // struct. This counts as a definition as far as the .ll file goes.
3149 if (EatIfPresent(lltok::kw_opaque
)) {
3150 // This type is being defined, so clear the location to indicate this.
3151 Entry
.second
= SMLoc();
3153 // If this type number has never been uttered, create it.
3155 Entry
.first
= StructType::create(Context
, Name
);
3156 ResultTy
= Entry
.first
;
3160 // If the type starts with '<', then it is either a packed struct or a vector.
3161 bool isPacked
= EatIfPresent(lltok::less
);
3163 // If we don't have a struct, then we have a random type alias, which we
3164 // accept for compatibility with old files. These types are not allowed to be
3165 // forward referenced and not allowed to be recursive.
3166 if (Lex
.getKind() != lltok::lbrace
) {
3168 return error(TypeLoc
, "forward references to non-struct type");
3172 return parseArrayVectorType(ResultTy
, true);
3173 return parseType(ResultTy
);
3176 // This type is being defined, so clear the location to indicate this.
3177 Entry
.second
= SMLoc();
3179 // If this type number has never been uttered, create it.
3181 Entry
.first
= StructType::create(Context
, Name
);
3183 StructType
*STy
= cast
<StructType
>(Entry
.first
);
3185 SmallVector
<Type
*, 8> Body
;
3186 if (parseStructBody(Body
) ||
3187 (isPacked
&& parseToken(lltok::greater
, "expected '>' in packed struct")))
3190 STy
->setBody(Body
, isPacked
);
3195 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
3198 /// ::= '{' Type (',' Type)* '}'
3199 /// ::= '<' '{' '}' '>'
3200 /// ::= '<' '{' Type (',' Type)* '}' '>'
3201 bool LLParser::parseStructBody(SmallVectorImpl
<Type
*> &Body
) {
3202 assert(Lex
.getKind() == lltok::lbrace
);
3203 Lex
.Lex(); // Consume the '{'
3205 // Handle the empty struct.
3206 if (EatIfPresent(lltok::rbrace
))
3209 LocTy EltTyLoc
= Lex
.getLoc();
3215 if (!StructType::isValidElementType(Ty
))
3216 return error(EltTyLoc
, "invalid element type for struct");
3218 while (EatIfPresent(lltok::comma
)) {
3219 EltTyLoc
= Lex
.getLoc();
3223 if (!StructType::isValidElementType(Ty
))
3224 return error(EltTyLoc
, "invalid element type for struct");
3229 return parseToken(lltok::rbrace
, "expected '}' at end of struct");
3232 /// parseArrayVectorType - parse an array or vector type, assuming the first
3233 /// token has already been consumed.
3235 /// ::= '[' APSINTVAL 'x' Types ']'
3236 /// ::= '<' APSINTVAL 'x' Types '>'
3237 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
3238 bool LLParser::parseArrayVectorType(Type
*&Result
, bool IsVector
) {
3239 bool Scalable
= false;
3241 if (IsVector
&& Lex
.getKind() == lltok::kw_vscale
) {
3242 Lex
.Lex(); // consume the 'vscale'
3243 if (parseToken(lltok::kw_x
, "expected 'x' after vscale"))
3249 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned() ||
3250 Lex
.getAPSIntVal().getBitWidth() > 64)
3251 return tokError("expected number in address space");
3253 LocTy SizeLoc
= Lex
.getLoc();
3254 uint64_t Size
= Lex
.getAPSIntVal().getZExtValue();
3257 if (parseToken(lltok::kw_x
, "expected 'x' after element count"))
3260 LocTy TypeLoc
= Lex
.getLoc();
3261 Type
*EltTy
= nullptr;
3262 if (parseType(EltTy
))
3265 if (parseToken(IsVector
? lltok::greater
: lltok::rsquare
,
3266 "expected end of sequential type"))
3271 return error(SizeLoc
, "zero element vector is illegal");
3272 if ((unsigned)Size
!= Size
)
3273 return error(SizeLoc
, "size too large for vector");
3274 if (!VectorType::isValidElementType(EltTy
))
3275 return error(TypeLoc
, "invalid vector element type");
3276 Result
= VectorType::get(EltTy
, unsigned(Size
), Scalable
);
3278 if (!ArrayType::isValidElementType(EltTy
))
3279 return error(TypeLoc
, "invalid array element type");
3280 Result
= ArrayType::get(EltTy
, Size
);
3285 /// parseTargetExtType - handle target extension type syntax
3287 /// ::= 'target' '(' STRINGCONSTANT TargetExtTypeParams TargetExtIntParams ')'
3289 /// TargetExtTypeParams
3291 /// ::= ',' Type TargetExtTypeParams
3293 /// TargetExtIntParams
3295 /// ::= ',' uint32 TargetExtIntParams
3296 bool LLParser::parseTargetExtType(Type
*&Result
) {
3297 Lex
.Lex(); // Eat the 'target' keyword.
3299 // Get the mandatory type name.
3300 std::string TypeName
;
3301 if (parseToken(lltok::lparen
, "expected '(' in target extension type") ||
3302 parseStringConstant(TypeName
))
3305 // Parse all of the integer and type parameters at the same time; the use of
3306 // SeenInt will allow us to catch cases where type parameters follow integer
3308 SmallVector
<Type
*> TypeParams
;
3309 SmallVector
<unsigned> IntParams
;
3310 bool SeenInt
= false;
3311 while (Lex
.getKind() == lltok::comma
) {
3312 Lex
.Lex(); // Eat the comma.
3314 if (Lex
.getKind() == lltok::APSInt
) {
3317 if (parseUInt32(IntVal
))
3319 IntParams
.push_back(IntVal
);
3320 } else if (SeenInt
) {
3321 // The only other kind of parameter we support is type parameters, which
3322 // must precede the integer parameters. This is therefore an error.
3323 return tokError("expected uint32 param");
3326 if (parseType(TypeParam
, /*AllowVoid=*/true))
3328 TypeParams
.push_back(TypeParam
);
3332 if (parseToken(lltok::rparen
, "expected ')' in target extension type"))
3335 Result
= TargetExtType::get(Context
, TypeName
, TypeParams
, IntParams
);
3339 //===----------------------------------------------------------------------===//
3340 // Function Semantic Analysis.
3341 //===----------------------------------------------------------------------===//
3343 LLParser::PerFunctionState::PerFunctionState(LLParser
&p
, Function
&f
,
3345 ArrayRef
<unsigned> UnnamedArgNums
)
3346 : P(p
), F(f
), FunctionNumber(functionNumber
) {
3348 // Insert unnamed arguments into the NumberedVals list.
3349 auto It
= UnnamedArgNums
.begin();
3350 for (Argument
&A
: F
.args()) {
3352 unsigned ArgNum
= *It
++;
3353 NumberedVals
.add(ArgNum
, &A
);
3358 LLParser::PerFunctionState::~PerFunctionState() {
3359 // If there were any forward referenced non-basicblock values, delete them.
3361 for (const auto &P
: ForwardRefVals
) {
3362 if (isa
<BasicBlock
>(P
.second
.first
))
3364 P
.second
.first
->replaceAllUsesWith(
3365 UndefValue::get(P
.second
.first
->getType()));
3366 P
.second
.first
->deleteValue();
3369 for (const auto &P
: ForwardRefValIDs
) {
3370 if (isa
<BasicBlock
>(P
.second
.first
))
3372 P
.second
.first
->replaceAllUsesWith(
3373 UndefValue::get(P
.second
.first
->getType()));
3374 P
.second
.first
->deleteValue();
3378 bool LLParser::PerFunctionState::finishFunction() {
3379 if (!ForwardRefVals
.empty())
3380 return P
.error(ForwardRefVals
.begin()->second
.second
,
3381 "use of undefined value '%" + ForwardRefVals
.begin()->first
+
3383 if (!ForwardRefValIDs
.empty())
3384 return P
.error(ForwardRefValIDs
.begin()->second
.second
,
3385 "use of undefined value '%" +
3386 Twine(ForwardRefValIDs
.begin()->first
) + "'");
3390 /// getVal - Get a value with the specified name or ID, creating a
3391 /// forward reference record if needed. This can return null if the value
3392 /// exists but does not have the right type.
3393 Value
*LLParser::PerFunctionState::getVal(const std::string
&Name
, Type
*Ty
,
3395 // Look this name up in the normal function symbol table.
3396 Value
*Val
= F
.getValueSymbolTable()->lookup(Name
);
3398 // If this is a forward reference for the value, see if we already created a
3399 // forward ref record.
3401 auto I
= ForwardRefVals
.find(Name
);
3402 if (I
!= ForwardRefVals
.end())
3403 Val
= I
->second
.first
;
3406 // If we have the value in the symbol table or fwd-ref table, return it.
3408 return P
.checkValidVariableType(Loc
, "%" + Name
, Ty
, Val
);
3410 // Don't make placeholders with invalid type.
3411 if (!Ty
->isFirstClassType()) {
3412 P
.error(Loc
, "invalid use of a non-first-class type");
3416 // Otherwise, create a new forward reference for this value and remember it.
3418 if (Ty
->isLabelTy()) {
3419 FwdVal
= BasicBlock::Create(F
.getContext(), Name
, &F
);
3421 FwdVal
= new Argument(Ty
, Name
);
3423 if (FwdVal
->getName() != Name
) {
3424 P
.error(Loc
, "name is too long which can result in name collisions, "
3425 "consider making the name shorter or "
3426 "increasing -non-global-value-max-name-size");
3430 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
3434 Value
*LLParser::PerFunctionState::getVal(unsigned ID
, Type
*Ty
, LocTy Loc
) {
3435 // Look this name up in the normal function symbol table.
3436 Value
*Val
= NumberedVals
.get(ID
);
3438 // If this is a forward reference for the value, see if we already created a
3439 // forward ref record.
3441 auto I
= ForwardRefValIDs
.find(ID
);
3442 if (I
!= ForwardRefValIDs
.end())
3443 Val
= I
->second
.first
;
3446 // If we have the value in the symbol table or fwd-ref table, return it.
3448 return P
.checkValidVariableType(Loc
, "%" + Twine(ID
), Ty
, Val
);
3450 if (!Ty
->isFirstClassType()) {
3451 P
.error(Loc
, "invalid use of a non-first-class type");
3455 // Otherwise, create a new forward reference for this value and remember it.
3457 if (Ty
->isLabelTy()) {
3458 FwdVal
= BasicBlock::Create(F
.getContext(), "", &F
);
3460 FwdVal
= new Argument(Ty
);
3463 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
3467 /// setInstName - After an instruction is parsed and inserted into its
3468 /// basic block, this installs its name.
3469 bool LLParser::PerFunctionState::setInstName(int NameID
,
3470 const std::string
&NameStr
,
3471 LocTy NameLoc
, Instruction
*Inst
) {
3472 // If this instruction has void type, it cannot have a name or ID specified.
3473 if (Inst
->getType()->isVoidTy()) {
3474 if (NameID
!= -1 || !NameStr
.empty())
3475 return P
.error(NameLoc
, "instructions returning void cannot have a name");
3479 // If this was a numbered instruction, verify that the instruction is the
3480 // expected value and resolve any forward references.
3481 if (NameStr
.empty()) {
3482 // If neither a name nor an ID was specified, just use the next ID.
3484 NameID
= NumberedVals
.getNext();
3486 if (P
.checkValueID(NameLoc
, "instruction", "%", NumberedVals
.getNext(),
3490 auto FI
= ForwardRefValIDs
.find(NameID
);
3491 if (FI
!= ForwardRefValIDs
.end()) {
3492 Value
*Sentinel
= FI
->second
.first
;
3493 if (Sentinel
->getType() != Inst
->getType())
3494 return P
.error(NameLoc
, "instruction forward referenced with type '" +
3495 getTypeString(FI
->second
.first
->getType()) +
3498 Sentinel
->replaceAllUsesWith(Inst
);
3499 Sentinel
->deleteValue();
3500 ForwardRefValIDs
.erase(FI
);
3503 NumberedVals
.add(NameID
, Inst
);
3507 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3508 auto FI
= ForwardRefVals
.find(NameStr
);
3509 if (FI
!= ForwardRefVals
.end()) {
3510 Value
*Sentinel
= FI
->second
.first
;
3511 if (Sentinel
->getType() != Inst
->getType())
3512 return P
.error(NameLoc
, "instruction forward referenced with type '" +
3513 getTypeString(FI
->second
.first
->getType()) +
3516 Sentinel
->replaceAllUsesWith(Inst
);
3517 Sentinel
->deleteValue();
3518 ForwardRefVals
.erase(FI
);
3521 // Set the name on the instruction.
3522 Inst
->setName(NameStr
);
3524 if (Inst
->getName() != NameStr
)
3525 return P
.error(NameLoc
, "multiple definition of local value named '" +
3530 /// getBB - Get a basic block with the specified name or ID, creating a
3531 /// forward reference record if needed.
3532 BasicBlock
*LLParser::PerFunctionState::getBB(const std::string
&Name
,
3534 return dyn_cast_or_null
<BasicBlock
>(
3535 getVal(Name
, Type::getLabelTy(F
.getContext()), Loc
));
3538 BasicBlock
*LLParser::PerFunctionState::getBB(unsigned ID
, LocTy Loc
) {
3539 return dyn_cast_or_null
<BasicBlock
>(
3540 getVal(ID
, Type::getLabelTy(F
.getContext()), Loc
));
3543 /// defineBB - Define the specified basic block, which is either named or
3544 /// unnamed. If there is an error, this returns null otherwise it returns
3545 /// the block being defined.
3546 BasicBlock
*LLParser::PerFunctionState::defineBB(const std::string
&Name
,
3547 int NameID
, LocTy Loc
) {
3551 if (P
.checkValueID(Loc
, "label", "", NumberedVals
.getNext(), NameID
))
3554 NameID
= NumberedVals
.getNext();
3556 BB
= getBB(NameID
, Loc
);
3558 P
.error(Loc
, "unable to create block numbered '" + Twine(NameID
) + "'");
3562 BB
= getBB(Name
, Loc
);
3564 P
.error(Loc
, "unable to create block named '" + Name
+ "'");
3569 // Move the block to the end of the function. Forward ref'd blocks are
3570 // inserted wherever they happen to be referenced.
3571 F
.splice(F
.end(), &F
, BB
->getIterator());
3573 // Remove the block from forward ref sets.
3575 ForwardRefValIDs
.erase(NameID
);
3576 NumberedVals
.add(NameID
, BB
);
3578 // BB forward references are already in the function symbol table.
3579 ForwardRefVals
.erase(Name
);
3585 //===----------------------------------------------------------------------===//
3587 //===----------------------------------------------------------------------===//
3589 /// parseValID - parse an abstract value that doesn't necessarily have a
3590 /// type implied. For example, if we parse "4" we don't know what integer type
3591 /// it has. The value will later be combined with its type and checked for
3592 /// basic correctness. PFS is used to convert function-local operands of
3593 /// metadata (since metadata operands are not just parsed here but also
3594 /// converted to values). PFS can be null when we are not parsing metadata
3595 /// values inside a function.
3596 bool LLParser::parseValID(ValID
&ID
, PerFunctionState
*PFS
, Type
*ExpectedTy
) {
3597 ID
.Loc
= Lex
.getLoc();
3598 switch (Lex
.getKind()) {
3600 return tokError("expected value token");
3601 case lltok::GlobalID
: // @42
3602 ID
.UIntVal
= Lex
.getUIntVal();
3603 ID
.Kind
= ValID::t_GlobalID
;
3605 case lltok::GlobalVar
: // @foo
3606 ID
.StrVal
= Lex
.getStrVal();
3607 ID
.Kind
= ValID::t_GlobalName
;
3609 case lltok::LocalVarID
: // %42
3610 ID
.UIntVal
= Lex
.getUIntVal();
3611 ID
.Kind
= ValID::t_LocalID
;
3613 case lltok::LocalVar
: // %foo
3614 ID
.StrVal
= Lex
.getStrVal();
3615 ID
.Kind
= ValID::t_LocalName
;
3618 ID
.APSIntVal
= Lex
.getAPSIntVal();
3619 ID
.Kind
= ValID::t_APSInt
;
3621 case lltok::APFloat
:
3622 ID
.APFloatVal
= Lex
.getAPFloatVal();
3623 ID
.Kind
= ValID::t_APFloat
;
3625 case lltok::kw_true
:
3626 ID
.ConstantVal
= ConstantInt::getTrue(Context
);
3627 ID
.Kind
= ValID::t_Constant
;
3629 case lltok::kw_false
:
3630 ID
.ConstantVal
= ConstantInt::getFalse(Context
);
3631 ID
.Kind
= ValID::t_Constant
;
3633 case lltok::kw_null
: ID
.Kind
= ValID::t_Null
; break;
3634 case lltok::kw_undef
: ID
.Kind
= ValID::t_Undef
; break;
3635 case lltok::kw_poison
: ID
.Kind
= ValID::t_Poison
; break;
3636 case lltok::kw_zeroinitializer
: ID
.Kind
= ValID::t_Zero
; break;
3637 case lltok::kw_none
: ID
.Kind
= ValID::t_None
; break;
3639 case lltok::lbrace
: {
3640 // ValID ::= '{' ConstVector '}'
3642 SmallVector
<Constant
*, 16> Elts
;
3643 if (parseGlobalValueVector(Elts
) ||
3644 parseToken(lltok::rbrace
, "expected end of struct constant"))
3647 ID
.ConstantStructElts
= std::make_unique
<Constant
*[]>(Elts
.size());
3648 ID
.UIntVal
= Elts
.size();
3649 memcpy(ID
.ConstantStructElts
.get(), Elts
.data(),
3650 Elts
.size() * sizeof(Elts
[0]));
3651 ID
.Kind
= ValID::t_ConstantStruct
;
3655 // ValID ::= '<' ConstVector '>' --> Vector.
3656 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3658 bool isPackedStruct
= EatIfPresent(lltok::lbrace
);
3660 SmallVector
<Constant
*, 16> Elts
;
3661 LocTy FirstEltLoc
= Lex
.getLoc();
3662 if (parseGlobalValueVector(Elts
) ||
3664 parseToken(lltok::rbrace
, "expected end of packed struct")) ||
3665 parseToken(lltok::greater
, "expected end of constant"))
3668 if (isPackedStruct
) {
3669 ID
.ConstantStructElts
= std::make_unique
<Constant
*[]>(Elts
.size());
3670 memcpy(ID
.ConstantStructElts
.get(), Elts
.data(),
3671 Elts
.size() * sizeof(Elts
[0]));
3672 ID
.UIntVal
= Elts
.size();
3673 ID
.Kind
= ValID::t_PackedConstantStruct
;
3678 return error(ID
.Loc
, "constant vector must not be empty");
3680 if (!Elts
[0]->getType()->isIntegerTy() &&
3681 !Elts
[0]->getType()->isFloatingPointTy() &&
3682 !Elts
[0]->getType()->isPointerTy())
3685 "vector elements must have integer, pointer or floating point type");
3687 // Verify that all the vector elements have the same type.
3688 for (unsigned i
= 1, e
= Elts
.size(); i
!= e
; ++i
)
3689 if (Elts
[i
]->getType() != Elts
[0]->getType())
3690 return error(FirstEltLoc
, "vector element #" + Twine(i
) +
3691 " is not of type '" +
3692 getTypeString(Elts
[0]->getType()));
3694 ID
.ConstantVal
= ConstantVector::get(Elts
);
3695 ID
.Kind
= ValID::t_Constant
;
3698 case lltok::lsquare
: { // Array Constant
3700 SmallVector
<Constant
*, 16> Elts
;
3701 LocTy FirstEltLoc
= Lex
.getLoc();
3702 if (parseGlobalValueVector(Elts
) ||
3703 parseToken(lltok::rsquare
, "expected end of array constant"))
3706 // Handle empty element.
3708 // Use undef instead of an array because it's inconvenient to determine
3709 // the element type at this point, there being no elements to examine.
3710 ID
.Kind
= ValID::t_EmptyArray
;
3714 if (!Elts
[0]->getType()->isFirstClassType())
3715 return error(FirstEltLoc
, "invalid array element type: " +
3716 getTypeString(Elts
[0]->getType()));
3718 ArrayType
*ATy
= ArrayType::get(Elts
[0]->getType(), Elts
.size());
3720 // Verify all elements are correct type!
3721 for (unsigned i
= 0, e
= Elts
.size(); i
!= e
; ++i
) {
3722 if (Elts
[i
]->getType() != Elts
[0]->getType())
3723 return error(FirstEltLoc
, "array element #" + Twine(i
) +
3724 " is not of type '" +
3725 getTypeString(Elts
[0]->getType()));
3728 ID
.ConstantVal
= ConstantArray::get(ATy
, Elts
);
3729 ID
.Kind
= ValID::t_Constant
;
3732 case lltok::kw_c
: // c "foo"
3734 ID
.ConstantVal
= ConstantDataArray::getString(Context
, Lex
.getStrVal(),
3736 if (parseToken(lltok::StringConstant
, "expected string"))
3738 ID
.Kind
= ValID::t_Constant
;
3741 case lltok::kw_asm
: {
3742 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3744 bool HasSideEffect
, AlignStack
, AsmDialect
, CanThrow
;
3746 if (parseOptionalToken(lltok::kw_sideeffect
, HasSideEffect
) ||
3747 parseOptionalToken(lltok::kw_alignstack
, AlignStack
) ||
3748 parseOptionalToken(lltok::kw_inteldialect
, AsmDialect
) ||
3749 parseOptionalToken(lltok::kw_unwind
, CanThrow
) ||
3750 parseStringConstant(ID
.StrVal
) ||
3751 parseToken(lltok::comma
, "expected comma in inline asm expression") ||
3752 parseToken(lltok::StringConstant
, "expected constraint string"))
3754 ID
.StrVal2
= Lex
.getStrVal();
3755 ID
.UIntVal
= unsigned(HasSideEffect
) | (unsigned(AlignStack
) << 1) |
3756 (unsigned(AsmDialect
) << 2) | (unsigned(CanThrow
) << 3);
3757 ID
.Kind
= ValID::t_InlineAsm
;
3761 case lltok::kw_blockaddress
: {
3762 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3767 if (parseToken(lltok::lparen
, "expected '(' in block address expression") ||
3768 parseValID(Fn
, PFS
) ||
3769 parseToken(lltok::comma
,
3770 "expected comma in block address expression") ||
3771 parseValID(Label
, PFS
) ||
3772 parseToken(lltok::rparen
, "expected ')' in block address expression"))
3775 if (Fn
.Kind
!= ValID::t_GlobalID
&& Fn
.Kind
!= ValID::t_GlobalName
)
3776 return error(Fn
.Loc
, "expected function name in blockaddress");
3777 if (Label
.Kind
!= ValID::t_LocalID
&& Label
.Kind
!= ValID::t_LocalName
)
3778 return error(Label
.Loc
, "expected basic block name in blockaddress");
3780 // Try to find the function (but skip it if it's forward-referenced).
3781 GlobalValue
*GV
= nullptr;
3782 if (Fn
.Kind
== ValID::t_GlobalID
) {
3783 if (Fn
.UIntVal
< NumberedVals
.size())
3784 GV
= NumberedVals
[Fn
.UIntVal
];
3785 } else if (!ForwardRefVals
.count(Fn
.StrVal
)) {
3786 GV
= M
->getNamedValue(Fn
.StrVal
);
3788 Function
*F
= nullptr;
3790 // Confirm that it's actually a function with a definition.
3791 if (!isa
<Function
>(GV
))
3792 return error(Fn
.Loc
, "expected function name in blockaddress");
3793 F
= cast
<Function
>(GV
);
3794 if (F
->isDeclaration())
3795 return error(Fn
.Loc
, "cannot take blockaddress inside a declaration");
3799 // Make a global variable as a placeholder for this reference.
3800 GlobalValue
*&FwdRef
=
3801 ForwardRefBlockAddresses
.insert(std::make_pair(
3803 std::map
<ValID
, GlobalValue
*>()))
3804 .first
->second
.insert(std::make_pair(std::move(Label
), nullptr))
3809 // If we know the type that the blockaddress is being assigned to,
3810 // we can use the address space of that type.
3811 if (!ExpectedTy
->isPointerTy())
3812 return error(ID
.Loc
,
3813 "type of blockaddress must be a pointer and not '" +
3814 getTypeString(ExpectedTy
) + "'");
3815 FwdDeclAS
= ExpectedTy
->getPointerAddressSpace();
3817 // Otherwise, we default the address space of the current function.
3818 FwdDeclAS
= PFS
->getFunction().getAddressSpace();
3820 llvm_unreachable("Unknown address space for blockaddress");
3822 FwdRef
= new GlobalVariable(
3823 *M
, Type::getInt8Ty(Context
), false, GlobalValue::InternalLinkage
,
3824 nullptr, "", nullptr, GlobalValue::NotThreadLocal
, FwdDeclAS
);
3827 ID
.ConstantVal
= FwdRef
;
3828 ID
.Kind
= ValID::t_Constant
;
3832 // We found the function; now find the basic block. Don't use PFS, since we
3833 // might be inside a constant expression.
3835 if (BlockAddressPFS
&& F
== &BlockAddressPFS
->getFunction()) {
3836 if (Label
.Kind
== ValID::t_LocalID
)
3837 BB
= BlockAddressPFS
->getBB(Label
.UIntVal
, Label
.Loc
);
3839 BB
= BlockAddressPFS
->getBB(Label
.StrVal
, Label
.Loc
);
3841 return error(Label
.Loc
, "referenced value is not a basic block");
3843 if (Label
.Kind
== ValID::t_LocalID
)
3844 return error(Label
.Loc
, "cannot take address of numeric label after "
3845 "the function is defined");
3846 BB
= dyn_cast_or_null
<BasicBlock
>(
3847 F
->getValueSymbolTable()->lookup(Label
.StrVal
));
3849 return error(Label
.Loc
, "referenced value is not a basic block");
3852 ID
.ConstantVal
= BlockAddress::get(F
, BB
);
3853 ID
.Kind
= ValID::t_Constant
;
3857 case lltok::kw_dso_local_equivalent
: {
3858 // ValID ::= 'dso_local_equivalent' @foo
3863 if (parseValID(Fn
, PFS
))
3866 if (Fn
.Kind
!= ValID::t_GlobalID
&& Fn
.Kind
!= ValID::t_GlobalName
)
3867 return error(Fn
.Loc
,
3868 "expected global value name in dso_local_equivalent");
3870 // Try to find the function (but skip it if it's forward-referenced).
3871 GlobalValue
*GV
= nullptr;
3872 if (Fn
.Kind
== ValID::t_GlobalID
) {
3873 if (Fn
.UIntVal
< NumberedVals
.size())
3874 GV
= NumberedVals
[Fn
.UIntVal
];
3875 } else if (!ForwardRefVals
.count(Fn
.StrVal
)) {
3876 GV
= M
->getNamedValue(Fn
.StrVal
);
3880 // Make a placeholder global variable as a placeholder for this reference.
3881 auto &FwdRefMap
= (Fn
.Kind
== ValID::t_GlobalID
)
3882 ? ForwardRefDSOLocalEquivalentIDs
3883 : ForwardRefDSOLocalEquivalentNames
;
3884 GlobalValue
*&FwdRef
= FwdRefMap
.try_emplace(Fn
, nullptr).first
->second
;
3886 FwdRef
= new GlobalVariable(*M
, Type::getInt8Ty(Context
), false,
3887 GlobalValue::InternalLinkage
, nullptr, "",
3888 nullptr, GlobalValue::NotThreadLocal
);
3891 ID
.ConstantVal
= FwdRef
;
3892 ID
.Kind
= ValID::t_Constant
;
3896 if (!GV
->getValueType()->isFunctionTy())
3897 return error(Fn
.Loc
, "expected a function, alias to function, or ifunc "
3898 "in dso_local_equivalent");
3900 ID
.ConstantVal
= DSOLocalEquivalent::get(GV
);
3901 ID
.Kind
= ValID::t_Constant
;
3905 case lltok::kw_no_cfi
: {
3906 // ValID ::= 'no_cfi' @foo
3909 if (parseValID(ID
, PFS
))
3912 if (ID
.Kind
!= ValID::t_GlobalID
&& ID
.Kind
!= ValID::t_GlobalName
)
3913 return error(ID
.Loc
, "expected global value name in no_cfi");
3919 case lltok::kw_trunc
:
3920 case lltok::kw_bitcast
:
3921 case lltok::kw_addrspacecast
:
3922 case lltok::kw_inttoptr
:
3923 case lltok::kw_ptrtoint
: {
3924 unsigned Opc
= Lex
.getUIntVal();
3925 Type
*DestTy
= nullptr;
3928 if (parseToken(lltok::lparen
, "expected '(' after constantexpr cast") ||
3929 parseGlobalTypeAndValue(SrcVal
) ||
3930 parseToken(lltok::kw_to
, "expected 'to' in constantexpr cast") ||
3931 parseType(DestTy
) ||
3932 parseToken(lltok::rparen
, "expected ')' at end of constantexpr cast"))
3934 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, SrcVal
, DestTy
))
3935 return error(ID
.Loc
, "invalid cast opcode for cast from '" +
3936 getTypeString(SrcVal
->getType()) + "' to '" +
3937 getTypeString(DestTy
) + "'");
3938 ID
.ConstantVal
= ConstantExpr::getCast((Instruction::CastOps
)Opc
,
3940 ID
.Kind
= ValID::t_Constant
;
3943 case lltok::kw_extractvalue
:
3944 return error(ID
.Loc
, "extractvalue constexprs are no longer supported");
3945 case lltok::kw_insertvalue
:
3946 return error(ID
.Loc
, "insertvalue constexprs are no longer supported");
3947 case lltok::kw_udiv
:
3948 return error(ID
.Loc
, "udiv constexprs are no longer supported");
3949 case lltok::kw_sdiv
:
3950 return error(ID
.Loc
, "sdiv constexprs are no longer supported");
3951 case lltok::kw_urem
:
3952 return error(ID
.Loc
, "urem constexprs are no longer supported");
3953 case lltok::kw_srem
:
3954 return error(ID
.Loc
, "srem constexprs are no longer supported");
3955 case lltok::kw_fadd
:
3956 return error(ID
.Loc
, "fadd constexprs are no longer supported");
3957 case lltok::kw_fsub
:
3958 return error(ID
.Loc
, "fsub constexprs are no longer supported");
3959 case lltok::kw_fmul
:
3960 return error(ID
.Loc
, "fmul constexprs are no longer supported");
3961 case lltok::kw_fdiv
:
3962 return error(ID
.Loc
, "fdiv constexprs are no longer supported");
3963 case lltok::kw_frem
:
3964 return error(ID
.Loc
, "frem constexprs are no longer supported");
3966 return error(ID
.Loc
, "and constexprs are no longer supported");
3968 return error(ID
.Loc
, "or constexprs are no longer supported");
3969 case lltok::kw_lshr
:
3970 return error(ID
.Loc
, "lshr constexprs are no longer supported");
3971 case lltok::kw_ashr
:
3972 return error(ID
.Loc
, "ashr constexprs are no longer supported");
3973 case lltok::kw_fneg
:
3974 return error(ID
.Loc
, "fneg constexprs are no longer supported");
3975 case lltok::kw_select
:
3976 return error(ID
.Loc
, "select constexprs are no longer supported");
3977 case lltok::kw_zext
:
3978 return error(ID
.Loc
, "zext constexprs are no longer supported");
3979 case lltok::kw_sext
:
3980 return error(ID
.Loc
, "sext constexprs are no longer supported");
3981 case lltok::kw_fptrunc
:
3982 return error(ID
.Loc
, "fptrunc constexprs are no longer supported");
3983 case lltok::kw_fpext
:
3984 return error(ID
.Loc
, "fpext constexprs are no longer supported");
3985 case lltok::kw_uitofp
:
3986 return error(ID
.Loc
, "uitofp constexprs are no longer supported");
3987 case lltok::kw_sitofp
:
3988 return error(ID
.Loc
, "sitofp constexprs are no longer supported");
3989 case lltok::kw_fptoui
:
3990 return error(ID
.Loc
, "fptoui constexprs are no longer supported");
3991 case lltok::kw_fptosi
:
3992 return error(ID
.Loc
, "fptosi constexprs are no longer supported");
3993 case lltok::kw_icmp
:
3994 case lltok::kw_fcmp
: {
3995 unsigned PredVal
, Opc
= Lex
.getUIntVal();
3996 Constant
*Val0
, *Val1
;
3998 if (parseCmpPredicate(PredVal
, Opc
) ||
3999 parseToken(lltok::lparen
, "expected '(' in compare constantexpr") ||
4000 parseGlobalTypeAndValue(Val0
) ||
4001 parseToken(lltok::comma
, "expected comma in compare constantexpr") ||
4002 parseGlobalTypeAndValue(Val1
) ||
4003 parseToken(lltok::rparen
, "expected ')' in compare constantexpr"))
4006 if (Val0
->getType() != Val1
->getType())
4007 return error(ID
.Loc
, "compare operands must have the same type");
4009 CmpInst::Predicate Pred
= (CmpInst::Predicate
)PredVal
;
4011 if (Opc
== Instruction::FCmp
) {
4012 if (!Val0
->getType()->isFPOrFPVectorTy())
4013 return error(ID
.Loc
, "fcmp requires floating point operands");
4014 ID
.ConstantVal
= ConstantExpr::getFCmp(Pred
, Val0
, Val1
);
4016 assert(Opc
== Instruction::ICmp
&& "Unexpected opcode for CmpInst!");
4017 if (!Val0
->getType()->isIntOrIntVectorTy() &&
4018 !Val0
->getType()->isPtrOrPtrVectorTy())
4019 return error(ID
.Loc
, "icmp requires pointer or integer operands");
4020 ID
.ConstantVal
= ConstantExpr::getICmp(Pred
, Val0
, Val1
);
4022 ID
.Kind
= ValID::t_Constant
;
4026 // Binary Operators.
4031 case lltok::kw_xor
: {
4034 unsigned Opc
= Lex
.getUIntVal();
4035 Constant
*Val0
, *Val1
;
4037 if (Opc
== Instruction::Add
|| Opc
== Instruction::Sub
||
4038 Opc
== Instruction::Mul
|| Opc
== Instruction::Shl
) {
4039 if (EatIfPresent(lltok::kw_nuw
))
4041 if (EatIfPresent(lltok::kw_nsw
)) {
4043 if (EatIfPresent(lltok::kw_nuw
))
4047 if (parseToken(lltok::lparen
, "expected '(' in binary constantexpr") ||
4048 parseGlobalTypeAndValue(Val0
) ||
4049 parseToken(lltok::comma
, "expected comma in binary constantexpr") ||
4050 parseGlobalTypeAndValue(Val1
) ||
4051 parseToken(lltok::rparen
, "expected ')' in binary constantexpr"))
4053 if (Val0
->getType() != Val1
->getType())
4054 return error(ID
.Loc
, "operands of constexpr must have same type");
4055 // Check that the type is valid for the operator.
4056 if (!Val0
->getType()->isIntOrIntVectorTy())
4057 return error(ID
.Loc
,
4058 "constexpr requires integer or integer vector operands");
4060 if (NUW
) Flags
|= OverflowingBinaryOperator::NoUnsignedWrap
;
4061 if (NSW
) Flags
|= OverflowingBinaryOperator::NoSignedWrap
;
4062 ID
.ConstantVal
= ConstantExpr::get(Opc
, Val0
, Val1
, Flags
);
4063 ID
.Kind
= ValID::t_Constant
;
4067 case lltok::kw_splat
: {
4069 if (parseToken(lltok::lparen
, "expected '(' after vector splat"))
4072 if (parseGlobalTypeAndValue(C
))
4074 if (parseToken(lltok::rparen
, "expected ')' at end of vector splat"))
4078 ID
.Kind
= ValID::t_ConstantSplat
;
4082 case lltok::kw_getelementptr
:
4083 case lltok::kw_shufflevector
:
4084 case lltok::kw_insertelement
:
4085 case lltok::kw_extractelement
: {
4086 unsigned Opc
= Lex
.getUIntVal();
4087 SmallVector
<Constant
*, 16> Elts
;
4088 bool InBounds
= false;
4092 if (Opc
== Instruction::GetElementPtr
)
4093 InBounds
= EatIfPresent(lltok::kw_inbounds
);
4095 if (parseToken(lltok::lparen
, "expected '(' in constantexpr"))
4098 if (Opc
== Instruction::GetElementPtr
) {
4099 if (parseType(Ty
) ||
4100 parseToken(lltok::comma
, "expected comma after getelementptr's type"))
4104 std::optional
<unsigned> InRangeOp
;
4105 if (parseGlobalValueVector(
4106 Elts
, Opc
== Instruction::GetElementPtr
? &InRangeOp
: nullptr) ||
4107 parseToken(lltok::rparen
, "expected ')' in constantexpr"))
4110 if (Opc
== Instruction::GetElementPtr
) {
4111 if (Elts
.size() == 0 ||
4112 !Elts
[0]->getType()->isPtrOrPtrVectorTy())
4113 return error(ID
.Loc
, "base of getelementptr must be a pointer");
4115 Type
*BaseType
= Elts
[0]->getType();
4117 BaseType
->isVectorTy()
4118 ? cast
<FixedVectorType
>(BaseType
)->getNumElements()
4121 ArrayRef
<Constant
*> Indices(Elts
.begin() + 1, Elts
.end());
4122 for (Constant
*Val
: Indices
) {
4123 Type
*ValTy
= Val
->getType();
4124 if (!ValTy
->isIntOrIntVectorTy())
4125 return error(ID
.Loc
, "getelementptr index must be an integer");
4126 if (auto *ValVTy
= dyn_cast
<VectorType
>(ValTy
)) {
4127 unsigned ValNumEl
= cast
<FixedVectorType
>(ValVTy
)->getNumElements();
4128 if (GEPWidth
&& (ValNumEl
!= GEPWidth
))
4131 "getelementptr vector index has a wrong number of elements");
4132 // GEPWidth may have been unknown because the base is a scalar,
4133 // but it is known now.
4134 GEPWidth
= ValNumEl
;
4138 SmallPtrSet
<Type
*, 4> Visited
;
4139 if (!Indices
.empty() && !Ty
->isSized(&Visited
))
4140 return error(ID
.Loc
, "base element of getelementptr must be sized");
4142 if (!GetElementPtrInst::getIndexedType(Ty
, Indices
))
4143 return error(ID
.Loc
, "invalid getelementptr indices");
4146 if (*InRangeOp
== 0)
4147 return error(ID
.Loc
,
4148 "inrange keyword may not appear on pointer operand");
4152 ID
.ConstantVal
= ConstantExpr::getGetElementPtr(Ty
, Elts
[0], Indices
,
4153 InBounds
, InRangeOp
);
4154 } else if (Opc
== Instruction::ShuffleVector
) {
4155 if (Elts
.size() != 3)
4156 return error(ID
.Loc
, "expected three operands to shufflevector");
4157 if (!ShuffleVectorInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
4158 return error(ID
.Loc
, "invalid operands to shufflevector");
4159 SmallVector
<int, 16> Mask
;
4160 ShuffleVectorInst::getShuffleMask(cast
<Constant
>(Elts
[2]), Mask
);
4161 ID
.ConstantVal
= ConstantExpr::getShuffleVector(Elts
[0], Elts
[1], Mask
);
4162 } else if (Opc
== Instruction::ExtractElement
) {
4163 if (Elts
.size() != 2)
4164 return error(ID
.Loc
, "expected two operands to extractelement");
4165 if (!ExtractElementInst::isValidOperands(Elts
[0], Elts
[1]))
4166 return error(ID
.Loc
, "invalid extractelement operands");
4167 ID
.ConstantVal
= ConstantExpr::getExtractElement(Elts
[0], Elts
[1]);
4169 assert(Opc
== Instruction::InsertElement
&& "Unknown opcode");
4170 if (Elts
.size() != 3)
4171 return error(ID
.Loc
, "expected three operands to insertelement");
4172 if (!InsertElementInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
4173 return error(ID
.Loc
, "invalid insertelement operands");
4175 ConstantExpr::getInsertElement(Elts
[0], Elts
[1],Elts
[2]);
4178 ID
.Kind
= ValID::t_Constant
;
4187 /// parseGlobalValue - parse a global value with the specified type.
4188 bool LLParser::parseGlobalValue(Type
*Ty
, Constant
*&C
) {
4192 bool Parsed
= parseValID(ID
, /*PFS=*/nullptr, Ty
) ||
4193 convertValIDToValue(Ty
, ID
, V
, nullptr);
4194 if (V
&& !(C
= dyn_cast
<Constant
>(V
)))
4195 return error(ID
.Loc
, "global values must be constants");
4199 bool LLParser::parseGlobalTypeAndValue(Constant
*&V
) {
4201 return parseType(Ty
) || parseGlobalValue(Ty
, V
);
4204 bool LLParser::parseOptionalComdat(StringRef GlobalName
, Comdat
*&C
) {
4207 LocTy KwLoc
= Lex
.getLoc();
4208 if (!EatIfPresent(lltok::kw_comdat
))
4211 if (EatIfPresent(lltok::lparen
)) {
4212 if (Lex
.getKind() != lltok::ComdatVar
)
4213 return tokError("expected comdat variable");
4214 C
= getComdat(Lex
.getStrVal(), Lex
.getLoc());
4216 if (parseToken(lltok::rparen
, "expected ')' after comdat var"))
4219 if (GlobalName
.empty())
4220 return tokError("comdat cannot be unnamed");
4221 C
= getComdat(std::string(GlobalName
), KwLoc
);
4227 /// parseGlobalValueVector
4229 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
4230 bool LLParser::parseGlobalValueVector(SmallVectorImpl
<Constant
*> &Elts
,
4231 std::optional
<unsigned> *InRangeOp
) {
4233 if (Lex
.getKind() == lltok::rbrace
||
4234 Lex
.getKind() == lltok::rsquare
||
4235 Lex
.getKind() == lltok::greater
||
4236 Lex
.getKind() == lltok::rparen
)
4240 if (InRangeOp
&& !*InRangeOp
&& EatIfPresent(lltok::kw_inrange
))
4241 *InRangeOp
= Elts
.size();
4244 if (parseGlobalTypeAndValue(C
))
4247 } while (EatIfPresent(lltok::comma
));
4252 bool LLParser::parseMDTuple(MDNode
*&MD
, bool IsDistinct
) {
4253 SmallVector
<Metadata
*, 16> Elts
;
4254 if (parseMDNodeVector(Elts
))
4257 MD
= (IsDistinct
? MDTuple::getDistinct
: MDTuple::get
)(Context
, Elts
);
4264 /// ::= !DILocation(...)
4265 bool LLParser::parseMDNode(MDNode
*&N
) {
4266 if (Lex
.getKind() == lltok::MetadataVar
)
4267 return parseSpecializedMDNode(N
);
4269 return parseToken(lltok::exclaim
, "expected '!' here") || parseMDNodeTail(N
);
4272 bool LLParser::parseMDNodeTail(MDNode
*&N
) {
4274 if (Lex
.getKind() == lltok::lbrace
)
4275 return parseMDTuple(N
);
4278 return parseMDNodeID(N
);
4283 /// Structure to represent an optional metadata field.
4284 template <class FieldTy
> struct MDFieldImpl
{
4285 typedef MDFieldImpl ImplTy
;
4289 void assign(FieldTy Val
) {
4291 this->Val
= std::move(Val
);
4294 explicit MDFieldImpl(FieldTy Default
)
4295 : Val(std::move(Default
)), Seen(false) {}
4298 /// Structure to represent an optional metadata field that
4299 /// can be of either type (A or B) and encapsulates the
4300 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
4301 /// to reimplement the specifics for representing each Field.
4302 template <class FieldTypeA
, class FieldTypeB
> struct MDEitherFieldImpl
{
4303 typedef MDEitherFieldImpl
<FieldTypeA
, FieldTypeB
> ImplTy
;
4314 void assign(FieldTypeA A
) {
4316 this->A
= std::move(A
);
4320 void assign(FieldTypeB B
) {
4322 this->B
= std::move(B
);
4326 explicit MDEitherFieldImpl(FieldTypeA DefaultA
, FieldTypeB DefaultB
)
4327 : A(std::move(DefaultA
)), B(std::move(DefaultB
)), Seen(false),
4328 WhatIs(IsInvalid
) {}
4331 struct MDUnsignedField
: public MDFieldImpl
<uint64_t> {
4334 MDUnsignedField(uint64_t Default
= 0, uint64_t Max
= UINT64_MAX
)
4335 : ImplTy(Default
), Max(Max
) {}
4338 struct LineField
: public MDUnsignedField
{
4339 LineField() : MDUnsignedField(0, UINT32_MAX
) {}
4342 struct ColumnField
: public MDUnsignedField
{
4343 ColumnField() : MDUnsignedField(0, UINT16_MAX
) {}
4346 struct DwarfTagField
: public MDUnsignedField
{
4347 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user
) {}
4348 DwarfTagField(dwarf::Tag DefaultTag
)
4349 : MDUnsignedField(DefaultTag
, dwarf::DW_TAG_hi_user
) {}
4352 struct DwarfMacinfoTypeField
: public MDUnsignedField
{
4353 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext
) {}
4354 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType
)
4355 : MDUnsignedField(DefaultType
, dwarf::DW_MACINFO_vendor_ext
) {}
4358 struct DwarfAttEncodingField
: public MDUnsignedField
{
4359 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user
) {}
4362 struct DwarfVirtualityField
: public MDUnsignedField
{
4363 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max
) {}
4366 struct DwarfLangField
: public MDUnsignedField
{
4367 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user
) {}
4370 struct DwarfCCField
: public MDUnsignedField
{
4371 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user
) {}
4374 struct EmissionKindField
: public MDUnsignedField
{
4375 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind
) {}
4378 struct NameTableKindField
: public MDUnsignedField
{
4379 NameTableKindField()
4382 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind
) {}
4385 struct DIFlagField
: public MDFieldImpl
<DINode::DIFlags
> {
4386 DIFlagField() : MDFieldImpl(DINode::FlagZero
) {}
4389 struct DISPFlagField
: public MDFieldImpl
<DISubprogram::DISPFlags
> {
4390 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero
) {}
4393 struct MDAPSIntField
: public MDFieldImpl
<APSInt
> {
4394 MDAPSIntField() : ImplTy(APSInt()) {}
4397 struct MDSignedField
: public MDFieldImpl
<int64_t> {
4398 int64_t Min
= INT64_MIN
;
4399 int64_t Max
= INT64_MAX
;
4401 MDSignedField(int64_t Default
= 0)
4402 : ImplTy(Default
) {}
4403 MDSignedField(int64_t Default
, int64_t Min
, int64_t Max
)
4404 : ImplTy(Default
), Min(Min
), Max(Max
) {}
4407 struct MDBoolField
: public MDFieldImpl
<bool> {
4408 MDBoolField(bool Default
= false) : ImplTy(Default
) {}
4411 struct MDField
: public MDFieldImpl
<Metadata
*> {
4414 MDField(bool AllowNull
= true) : ImplTy(nullptr), AllowNull(AllowNull
) {}
4417 struct MDStringField
: public MDFieldImpl
<MDString
*> {
4419 MDStringField(bool AllowEmpty
= true)
4420 : ImplTy(nullptr), AllowEmpty(AllowEmpty
) {}
4423 struct MDFieldList
: public MDFieldImpl
<SmallVector
<Metadata
*, 4>> {
4424 MDFieldList() : ImplTy(SmallVector
<Metadata
*, 4>()) {}
4427 struct ChecksumKindField
: public MDFieldImpl
<DIFile::ChecksumKind
> {
4428 ChecksumKindField(DIFile::ChecksumKind CSKind
) : ImplTy(CSKind
) {}
4431 struct MDSignedOrMDField
: MDEitherFieldImpl
<MDSignedField
, MDField
> {
4432 MDSignedOrMDField(int64_t Default
= 0, bool AllowNull
= true)
4433 : ImplTy(MDSignedField(Default
), MDField(AllowNull
)) {}
4435 MDSignedOrMDField(int64_t Default
, int64_t Min
, int64_t Max
,
4436 bool AllowNull
= true)
4437 : ImplTy(MDSignedField(Default
, Min
, Max
), MDField(AllowNull
)) {}
4439 bool isMDSignedField() const { return WhatIs
== IsTypeA
; }
4440 bool isMDField() const { return WhatIs
== IsTypeB
; }
4441 int64_t getMDSignedValue() const {
4442 assert(isMDSignedField() && "Wrong field type");
4445 Metadata
*getMDFieldValue() const {
4446 assert(isMDField() && "Wrong field type");
4451 } // end anonymous namespace
4456 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDAPSIntField
&Result
) {
4457 if (Lex
.getKind() != lltok::APSInt
)
4458 return tokError("expected integer");
4460 Result
.assign(Lex
.getAPSIntVal());
4466 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4467 MDUnsignedField
&Result
) {
4468 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
4469 return tokError("expected unsigned integer");
4471 auto &U
= Lex
.getAPSIntVal();
4472 if (U
.ugt(Result
.Max
))
4473 return tokError("value for '" + Name
+ "' too large, limit is " +
4475 Result
.assign(U
.getZExtValue());
4476 assert(Result
.Val
<= Result
.Max
&& "Expected value in range");
4482 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, LineField
&Result
) {
4483 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4486 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, ColumnField
&Result
) {
4487 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4491 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DwarfTagField
&Result
) {
4492 if (Lex
.getKind() == lltok::APSInt
)
4493 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4495 if (Lex
.getKind() != lltok::DwarfTag
)
4496 return tokError("expected DWARF tag");
4498 unsigned Tag
= dwarf::getTag(Lex
.getStrVal());
4499 if (Tag
== dwarf::DW_TAG_invalid
)
4500 return tokError("invalid DWARF tag" + Twine(" '") + Lex
.getStrVal() + "'");
4501 assert(Tag
<= Result
.Max
&& "Expected valid DWARF tag");
4509 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4510 DwarfMacinfoTypeField
&Result
) {
4511 if (Lex
.getKind() == lltok::APSInt
)
4512 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4514 if (Lex
.getKind() != lltok::DwarfMacinfo
)
4515 return tokError("expected DWARF macinfo type");
4517 unsigned Macinfo
= dwarf::getMacinfo(Lex
.getStrVal());
4518 if (Macinfo
== dwarf::DW_MACINFO_invalid
)
4519 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4520 Lex
.getStrVal() + "'");
4521 assert(Macinfo
<= Result
.Max
&& "Expected valid DWARF macinfo type");
4523 Result
.assign(Macinfo
);
4529 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4530 DwarfVirtualityField
&Result
) {
4531 if (Lex
.getKind() == lltok::APSInt
)
4532 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4534 if (Lex
.getKind() != lltok::DwarfVirtuality
)
4535 return tokError("expected DWARF virtuality code");
4537 unsigned Virtuality
= dwarf::getVirtuality(Lex
.getStrVal());
4538 if (Virtuality
== dwarf::DW_VIRTUALITY_invalid
)
4539 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4540 Lex
.getStrVal() + "'");
4541 assert(Virtuality
<= Result
.Max
&& "Expected valid DWARF virtuality code");
4542 Result
.assign(Virtuality
);
4548 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DwarfLangField
&Result
) {
4549 if (Lex
.getKind() == lltok::APSInt
)
4550 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4552 if (Lex
.getKind() != lltok::DwarfLang
)
4553 return tokError("expected DWARF language");
4555 unsigned Lang
= dwarf::getLanguage(Lex
.getStrVal());
4557 return tokError("invalid DWARF language" + Twine(" '") + Lex
.getStrVal() +
4559 assert(Lang
<= Result
.Max
&& "Expected valid DWARF language");
4560 Result
.assign(Lang
);
4566 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DwarfCCField
&Result
) {
4567 if (Lex
.getKind() == lltok::APSInt
)
4568 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4570 if (Lex
.getKind() != lltok::DwarfCC
)
4571 return tokError("expected DWARF calling convention");
4573 unsigned CC
= dwarf::getCallingConvention(Lex
.getStrVal());
4575 return tokError("invalid DWARF calling convention" + Twine(" '") +
4576 Lex
.getStrVal() + "'");
4577 assert(CC
<= Result
.Max
&& "Expected valid DWARF calling convention");
4584 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4585 EmissionKindField
&Result
) {
4586 if (Lex
.getKind() == lltok::APSInt
)
4587 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4589 if (Lex
.getKind() != lltok::EmissionKind
)
4590 return tokError("expected emission kind");
4592 auto Kind
= DICompileUnit::getEmissionKind(Lex
.getStrVal());
4594 return tokError("invalid emission kind" + Twine(" '") + Lex
.getStrVal() +
4596 assert(*Kind
<= Result
.Max
&& "Expected valid emission kind");
4597 Result
.assign(*Kind
);
4603 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4604 NameTableKindField
&Result
) {
4605 if (Lex
.getKind() == lltok::APSInt
)
4606 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4608 if (Lex
.getKind() != lltok::NameTableKind
)
4609 return tokError("expected nameTable kind");
4611 auto Kind
= DICompileUnit::getNameTableKind(Lex
.getStrVal());
4613 return tokError("invalid nameTable kind" + Twine(" '") + Lex
.getStrVal() +
4615 assert(((unsigned)*Kind
) <= Result
.Max
&& "Expected valid nameTable kind");
4616 Result
.assign((unsigned)*Kind
);
4622 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4623 DwarfAttEncodingField
&Result
) {
4624 if (Lex
.getKind() == lltok::APSInt
)
4625 return parseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4627 if (Lex
.getKind() != lltok::DwarfAttEncoding
)
4628 return tokError("expected DWARF type attribute encoding");
4630 unsigned Encoding
= dwarf::getAttributeEncoding(Lex
.getStrVal());
4632 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4633 Lex
.getStrVal() + "'");
4634 assert(Encoding
<= Result
.Max
&& "Expected valid DWARF language");
4635 Result
.assign(Encoding
);
4642 /// ::= DIFlagVector
4643 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4645 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DIFlagField
&Result
) {
4647 // parser for a single flag.
4648 auto parseFlag
= [&](DINode::DIFlags
&Val
) {
4649 if (Lex
.getKind() == lltok::APSInt
&& !Lex
.getAPSIntVal().isSigned()) {
4650 uint32_t TempVal
= static_cast<uint32_t>(Val
);
4651 bool Res
= parseUInt32(TempVal
);
4652 Val
= static_cast<DINode::DIFlags
>(TempVal
);
4656 if (Lex
.getKind() != lltok::DIFlag
)
4657 return tokError("expected debug info flag");
4659 Val
= DINode::getFlag(Lex
.getStrVal());
4661 return tokError(Twine("invalid debug info flag '") + Lex
.getStrVal() +
4667 // parse the flags and combine them together.
4668 DINode::DIFlags Combined
= DINode::FlagZero
;
4670 DINode::DIFlags Val
;
4674 } while (EatIfPresent(lltok::bar
));
4676 Result
.assign(Combined
);
4682 /// ::= DISPFlagVector
4683 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4685 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, DISPFlagField
&Result
) {
4687 // parser for a single flag.
4688 auto parseFlag
= [&](DISubprogram::DISPFlags
&Val
) {
4689 if (Lex
.getKind() == lltok::APSInt
&& !Lex
.getAPSIntVal().isSigned()) {
4690 uint32_t TempVal
= static_cast<uint32_t>(Val
);
4691 bool Res
= parseUInt32(TempVal
);
4692 Val
= static_cast<DISubprogram::DISPFlags
>(TempVal
);
4696 if (Lex
.getKind() != lltok::DISPFlag
)
4697 return tokError("expected debug info flag");
4699 Val
= DISubprogram::getFlag(Lex
.getStrVal());
4701 return tokError(Twine("invalid subprogram debug info flag '") +
4702 Lex
.getStrVal() + "'");
4707 // parse the flags and combine them together.
4708 DISubprogram::DISPFlags Combined
= DISubprogram::SPFlagZero
;
4710 DISubprogram::DISPFlags Val
;
4714 } while (EatIfPresent(lltok::bar
));
4716 Result
.assign(Combined
);
4721 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDSignedField
&Result
) {
4722 if (Lex
.getKind() != lltok::APSInt
)
4723 return tokError("expected signed integer");
4725 auto &S
= Lex
.getAPSIntVal();
4727 return tokError("value for '" + Name
+ "' too small, limit is " +
4730 return tokError("value for '" + Name
+ "' too large, limit is " +
4732 Result
.assign(S
.getExtValue());
4733 assert(Result
.Val
>= Result
.Min
&& "Expected value in range");
4734 assert(Result
.Val
<= Result
.Max
&& "Expected value in range");
4740 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDBoolField
&Result
) {
4741 switch (Lex
.getKind()) {
4743 return tokError("expected 'true' or 'false'");
4744 case lltok::kw_true
:
4745 Result
.assign(true);
4747 case lltok::kw_false
:
4748 Result
.assign(false);
4756 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDField
&Result
) {
4757 if (Lex
.getKind() == lltok::kw_null
) {
4758 if (!Result
.AllowNull
)
4759 return tokError("'" + Name
+ "' cannot be null");
4761 Result
.assign(nullptr);
4766 if (parseMetadata(MD
, nullptr))
4774 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4775 MDSignedOrMDField
&Result
) {
4776 // Try to parse a signed int.
4777 if (Lex
.getKind() == lltok::APSInt
) {
4778 MDSignedField Res
= Result
.A
;
4779 if (!parseMDField(Loc
, Name
, Res
)) {
4786 // Otherwise, try to parse as an MDField.
4787 MDField Res
= Result
.B
;
4788 if (!parseMDField(Loc
, Name
, Res
)) {
4797 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDStringField
&Result
) {
4798 LocTy ValueLoc
= Lex
.getLoc();
4800 if (parseStringConstant(S
))
4803 if (!Result
.AllowEmpty
&& S
.empty())
4804 return error(ValueLoc
, "'" + Name
+ "' cannot be empty");
4806 Result
.assign(S
.empty() ? nullptr : MDString::get(Context
, S
));
4811 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
, MDFieldList
&Result
) {
4812 SmallVector
<Metadata
*, 4> MDs
;
4813 if (parseMDNodeVector(MDs
))
4816 Result
.assign(std::move(MDs
));
4821 bool LLParser::parseMDField(LocTy Loc
, StringRef Name
,
4822 ChecksumKindField
&Result
) {
4823 std::optional
<DIFile::ChecksumKind
> CSKind
=
4824 DIFile::getChecksumKind(Lex
.getStrVal());
4826 if (Lex
.getKind() != lltok::ChecksumKind
|| !CSKind
)
4827 return tokError("invalid checksum kind" + Twine(" '") + Lex
.getStrVal() +
4830 Result
.assign(*CSKind
);
4835 } // end namespace llvm
4837 template <class ParserTy
>
4838 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField
) {
4840 if (Lex
.getKind() != lltok::LabelStr
)
4841 return tokError("expected field label here");
4845 } while (EatIfPresent(lltok::comma
));
4850 template <class ParserTy
>
4851 bool LLParser::parseMDFieldsImpl(ParserTy ParseField
, LocTy
&ClosingLoc
) {
4852 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4855 if (parseToken(lltok::lparen
, "expected '(' here"))
4857 if (Lex
.getKind() != lltok::rparen
)
4858 if (parseMDFieldsImplBody(ParseField
))
4861 ClosingLoc
= Lex
.getLoc();
4862 return parseToken(lltok::rparen
, "expected ')' here");
4865 template <class FieldTy
>
4866 bool LLParser::parseMDField(StringRef Name
, FieldTy
&Result
) {
4868 return tokError("field '" + Name
+ "' cannot be specified more than once");
4870 LocTy Loc
= Lex
.getLoc();
4872 return parseMDField(Loc
, Name
, Result
);
4875 bool LLParser::parseSpecializedMDNode(MDNode
*&N
, bool IsDistinct
) {
4876 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4878 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4879 if (Lex.getStrVal() == #CLASS) \
4880 return parse##CLASS(N, IsDistinct);
4881 #include "llvm/IR/Metadata.def"
4883 return tokError("expected metadata type");
4886 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4887 #define NOP_FIELD(NAME, TYPE, INIT)
4888 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4890 return error(ClosingLoc, "missing required field '" #NAME "'");
4891 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4892 if (Lex.getStrVal() == #NAME) \
4893 return parseMDField(#NAME, NAME);
4894 #define PARSE_MD_FIELDS() \
4895 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4898 if (parseMDFieldsImpl( \
4900 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4901 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4906 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4908 #define GET_OR_DISTINCT(CLASS, ARGS) \
4909 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4911 /// parseDILocationFields:
4912 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4913 /// isImplicitCode: true)
4914 bool LLParser::parseDILocation(MDNode
*&Result
, bool IsDistinct
) {
4915 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4916 OPTIONAL(line, LineField, ); \
4917 OPTIONAL(column, ColumnField, ); \
4918 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4919 OPTIONAL(inlinedAt, MDField, ); \
4920 OPTIONAL(isImplicitCode, MDBoolField, (false));
4922 #undef VISIT_MD_FIELDS
4925 GET_OR_DISTINCT(DILocation
, (Context
, line
.Val
, column
.Val
, scope
.Val
,
4926 inlinedAt
.Val
, isImplicitCode
.Val
));
4930 /// parseDIAssignID:
4931 /// ::= distinct !DIAssignID()
4932 bool LLParser::parseDIAssignID(MDNode
*&Result
, bool IsDistinct
) {
4934 return Lex
.Error("missing 'distinct', required for !DIAssignID()");
4938 // Now eat the parens.
4939 if (parseToken(lltok::lparen
, "expected '(' here"))
4941 if (parseToken(lltok::rparen
, "expected ')' here"))
4944 Result
= DIAssignID::getDistinct(Context
);
4948 /// parseGenericDINode:
4949 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4950 bool LLParser::parseGenericDINode(MDNode
*&Result
, bool IsDistinct
) {
4951 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4952 REQUIRED(tag, DwarfTagField, ); \
4953 OPTIONAL(header, MDStringField, ); \
4954 OPTIONAL(operands, MDFieldList, );
4956 #undef VISIT_MD_FIELDS
4958 Result
= GET_OR_DISTINCT(GenericDINode
,
4959 (Context
, tag
.Val
, header
.Val
, operands
.Val
));
4963 /// parseDISubrange:
4964 /// ::= !DISubrange(count: 30, lowerBound: 2)
4965 /// ::= !DISubrange(count: !node, lowerBound: 2)
4966 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4967 bool LLParser::parseDISubrange(MDNode
*&Result
, bool IsDistinct
) {
4968 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4969 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4970 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4971 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4972 OPTIONAL(stride, MDSignedOrMDField, );
4974 #undef VISIT_MD_FIELDS
4976 Metadata
*Count
= nullptr;
4977 Metadata
*LowerBound
= nullptr;
4978 Metadata
*UpperBound
= nullptr;
4979 Metadata
*Stride
= nullptr;
4981 auto convToMetadata
= [&](MDSignedOrMDField Bound
) -> Metadata
* {
4982 if (Bound
.isMDSignedField())
4983 return ConstantAsMetadata::get(ConstantInt::getSigned(
4984 Type::getInt64Ty(Context
), Bound
.getMDSignedValue()));
4985 if (Bound
.isMDField())
4986 return Bound
.getMDFieldValue();
4990 Count
= convToMetadata(count
);
4991 LowerBound
= convToMetadata(lowerBound
);
4992 UpperBound
= convToMetadata(upperBound
);
4993 Stride
= convToMetadata(stride
);
4995 Result
= GET_OR_DISTINCT(DISubrange
,
4996 (Context
, Count
, LowerBound
, UpperBound
, Stride
));
5001 /// parseDIGenericSubrange:
5002 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
5004 bool LLParser::parseDIGenericSubrange(MDNode
*&Result
, bool IsDistinct
) {
5005 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5006 OPTIONAL(count, MDSignedOrMDField, ); \
5007 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
5008 OPTIONAL(upperBound, MDSignedOrMDField, ); \
5009 OPTIONAL(stride, MDSignedOrMDField, );
5011 #undef VISIT_MD_FIELDS
5013 auto ConvToMetadata
= [&](MDSignedOrMDField Bound
) -> Metadata
* {
5014 if (Bound
.isMDSignedField())
5015 return DIExpression::get(
5016 Context
, {dwarf::DW_OP_consts
,
5017 static_cast<uint64_t>(Bound
.getMDSignedValue())});
5018 if (Bound
.isMDField())
5019 return Bound
.getMDFieldValue();
5023 Metadata
*Count
= ConvToMetadata(count
);
5024 Metadata
*LowerBound
= ConvToMetadata(lowerBound
);
5025 Metadata
*UpperBound
= ConvToMetadata(upperBound
);
5026 Metadata
*Stride
= ConvToMetadata(stride
);
5028 Result
= GET_OR_DISTINCT(DIGenericSubrange
,
5029 (Context
, Count
, LowerBound
, UpperBound
, Stride
));
5034 /// parseDIEnumerator:
5035 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
5036 bool LLParser::parseDIEnumerator(MDNode
*&Result
, bool IsDistinct
) {
5037 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5038 REQUIRED(name, MDStringField, ); \
5039 REQUIRED(value, MDAPSIntField, ); \
5040 OPTIONAL(isUnsigned, MDBoolField, (false));
5042 #undef VISIT_MD_FIELDS
5044 if (isUnsigned
.Val
&& value
.Val
.isNegative())
5045 return tokError("unsigned enumerator with negative value");
5047 APSInt
Value(value
.Val
);
5048 // Add a leading zero so that unsigned values with the msb set are not
5049 // mistaken for negative values when used for signed enumerators.
5050 if (!isUnsigned
.Val
&& value
.Val
.isUnsigned() && value
.Val
.isSignBitSet())
5051 Value
= Value
.zext(Value
.getBitWidth() + 1);
5054 GET_OR_DISTINCT(DIEnumerator
, (Context
, Value
, isUnsigned
.Val
, name
.Val
));
5059 /// parseDIBasicType:
5060 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
5061 /// encoding: DW_ATE_encoding, flags: 0)
5062 bool LLParser::parseDIBasicType(MDNode
*&Result
, bool IsDistinct
) {
5063 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5064 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
5065 OPTIONAL(name, MDStringField, ); \
5066 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5067 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5068 OPTIONAL(encoding, DwarfAttEncodingField, ); \
5069 OPTIONAL(flags, DIFlagField, );
5071 #undef VISIT_MD_FIELDS
5073 Result
= GET_OR_DISTINCT(DIBasicType
, (Context
, tag
.Val
, name
.Val
, size
.Val
,
5074 align
.Val
, encoding
.Val
, flags
.Val
));
5078 /// parseDIStringType:
5079 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
5080 bool LLParser::parseDIStringType(MDNode
*&Result
, bool IsDistinct
) {
5081 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5082 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
5083 OPTIONAL(name, MDStringField, ); \
5084 OPTIONAL(stringLength, MDField, ); \
5085 OPTIONAL(stringLengthExpression, MDField, ); \
5086 OPTIONAL(stringLocationExpression, MDField, ); \
5087 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5088 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5089 OPTIONAL(encoding, DwarfAttEncodingField, );
5091 #undef VISIT_MD_FIELDS
5093 Result
= GET_OR_DISTINCT(
5095 (Context
, tag
.Val
, name
.Val
, stringLength
.Val
, stringLengthExpression
.Val
,
5096 stringLocationExpression
.Val
, size
.Val
, align
.Val
, encoding
.Val
));
5100 /// parseDIDerivedType:
5101 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
5102 /// line: 7, scope: !1, baseType: !2, size: 32,
5103 /// align: 32, offset: 0, flags: 0, extraData: !3,
5104 /// dwarfAddressSpace: 3)
5105 bool LLParser::parseDIDerivedType(MDNode
*&Result
, bool IsDistinct
) {
5106 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5107 REQUIRED(tag, DwarfTagField, ); \
5108 OPTIONAL(name, MDStringField, ); \
5109 OPTIONAL(file, MDField, ); \
5110 OPTIONAL(line, LineField, ); \
5111 OPTIONAL(scope, MDField, ); \
5112 REQUIRED(baseType, MDField, ); \
5113 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5114 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5115 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5116 OPTIONAL(flags, DIFlagField, ); \
5117 OPTIONAL(extraData, MDField, ); \
5118 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
5119 OPTIONAL(annotations, MDField, );
5121 #undef VISIT_MD_FIELDS
5123 std::optional
<unsigned> DWARFAddressSpace
;
5124 if (dwarfAddressSpace
.Val
!= UINT32_MAX
)
5125 DWARFAddressSpace
= dwarfAddressSpace
.Val
;
5127 Result
= GET_OR_DISTINCT(DIDerivedType
,
5128 (Context
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
,
5129 scope
.Val
, baseType
.Val
, size
.Val
, align
.Val
,
5130 offset
.Val
, DWARFAddressSpace
, flags
.Val
,
5131 extraData
.Val
, annotations
.Val
));
5135 bool LLParser::parseDICompositeType(MDNode
*&Result
, bool IsDistinct
) {
5136 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5137 REQUIRED(tag, DwarfTagField, ); \
5138 OPTIONAL(name, MDStringField, ); \
5139 OPTIONAL(file, MDField, ); \
5140 OPTIONAL(line, LineField, ); \
5141 OPTIONAL(scope, MDField, ); \
5142 OPTIONAL(baseType, MDField, ); \
5143 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
5144 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5145 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
5146 OPTIONAL(flags, DIFlagField, ); \
5147 OPTIONAL(elements, MDField, ); \
5148 OPTIONAL(runtimeLang, DwarfLangField, ); \
5149 OPTIONAL(vtableHolder, MDField, ); \
5150 OPTIONAL(templateParams, MDField, ); \
5151 OPTIONAL(identifier, MDStringField, ); \
5152 OPTIONAL(discriminator, MDField, ); \
5153 OPTIONAL(dataLocation, MDField, ); \
5154 OPTIONAL(associated, MDField, ); \
5155 OPTIONAL(allocated, MDField, ); \
5156 OPTIONAL(rank, MDSignedOrMDField, ); \
5157 OPTIONAL(annotations, MDField, );
5159 #undef VISIT_MD_FIELDS
5161 Metadata
*Rank
= nullptr;
5162 if (rank
.isMDSignedField())
5163 Rank
= ConstantAsMetadata::get(ConstantInt::getSigned(
5164 Type::getInt64Ty(Context
), rank
.getMDSignedValue()));
5165 else if (rank
.isMDField())
5166 Rank
= rank
.getMDFieldValue();
5168 // If this has an identifier try to build an ODR type.
5170 if (auto *CT
= DICompositeType::buildODRType(
5171 Context
, *identifier
.Val
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
,
5172 scope
.Val
, baseType
.Val
, size
.Val
, align
.Val
, offset
.Val
, flags
.Val
,
5173 elements
.Val
, runtimeLang
.Val
, vtableHolder
.Val
, templateParams
.Val
,
5174 discriminator
.Val
, dataLocation
.Val
, associated
.Val
, allocated
.Val
,
5175 Rank
, annotations
.Val
)) {
5180 // Create a new node, and save it in the context if it belongs in the type
5182 Result
= GET_OR_DISTINCT(
5184 (Context
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
, scope
.Val
, baseType
.Val
,
5185 size
.Val
, align
.Val
, offset
.Val
, flags
.Val
, elements
.Val
,
5186 runtimeLang
.Val
, vtableHolder
.Val
, templateParams
.Val
, identifier
.Val
,
5187 discriminator
.Val
, dataLocation
.Val
, associated
.Val
, allocated
.Val
, Rank
,
5192 bool LLParser::parseDISubroutineType(MDNode
*&Result
, bool IsDistinct
) {
5193 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5194 OPTIONAL(flags, DIFlagField, ); \
5195 OPTIONAL(cc, DwarfCCField, ); \
5196 REQUIRED(types, MDField, );
5198 #undef VISIT_MD_FIELDS
5200 Result
= GET_OR_DISTINCT(DISubroutineType
,
5201 (Context
, flags
.Val
, cc
.Val
, types
.Val
));
5205 /// parseDIFileType:
5206 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
5207 /// checksumkind: CSK_MD5,
5208 /// checksum: "000102030405060708090a0b0c0d0e0f",
5209 /// source: "source file contents")
5210 bool LLParser::parseDIFile(MDNode
*&Result
, bool IsDistinct
) {
5211 // The default constructed value for checksumkind is required, but will never
5212 // be used, as the parser checks if the field was actually Seen before using
5214 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5215 REQUIRED(filename, MDStringField, ); \
5216 REQUIRED(directory, MDStringField, ); \
5217 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
5218 OPTIONAL(checksum, MDStringField, ); \
5219 OPTIONAL(source, MDStringField, );
5221 #undef VISIT_MD_FIELDS
5223 std::optional
<DIFile::ChecksumInfo
<MDString
*>> OptChecksum
;
5224 if (checksumkind
.Seen
&& checksum
.Seen
)
5225 OptChecksum
.emplace(checksumkind
.Val
, checksum
.Val
);
5226 else if (checksumkind
.Seen
|| checksum
.Seen
)
5227 return Lex
.Error("'checksumkind' and 'checksum' must be provided together");
5229 MDString
*Source
= nullptr;
5231 Source
= source
.Val
;
5232 Result
= GET_OR_DISTINCT(
5233 DIFile
, (Context
, filename
.Val
, directory
.Val
, OptChecksum
, Source
));
5237 /// parseDICompileUnit:
5238 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
5239 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
5240 /// splitDebugFilename: "abc.debug",
5241 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
5242 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
5243 /// sysroot: "/", sdk: "MacOSX.sdk")
5244 bool LLParser::parseDICompileUnit(MDNode
*&Result
, bool IsDistinct
) {
5246 return Lex
.Error("missing 'distinct', required for !DICompileUnit");
5248 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5249 REQUIRED(language, DwarfLangField, ); \
5250 REQUIRED(file, MDField, (/* AllowNull */ false)); \
5251 OPTIONAL(producer, MDStringField, ); \
5252 OPTIONAL(isOptimized, MDBoolField, ); \
5253 OPTIONAL(flags, MDStringField, ); \
5254 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
5255 OPTIONAL(splitDebugFilename, MDStringField, ); \
5256 OPTIONAL(emissionKind, EmissionKindField, ); \
5257 OPTIONAL(enums, MDField, ); \
5258 OPTIONAL(retainedTypes, MDField, ); \
5259 OPTIONAL(globals, MDField, ); \
5260 OPTIONAL(imports, MDField, ); \
5261 OPTIONAL(macros, MDField, ); \
5262 OPTIONAL(dwoId, MDUnsignedField, ); \
5263 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
5264 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
5265 OPTIONAL(nameTableKind, NameTableKindField, ); \
5266 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
5267 OPTIONAL(sysroot, MDStringField, ); \
5268 OPTIONAL(sdk, MDStringField, );
5270 #undef VISIT_MD_FIELDS
5272 Result
= DICompileUnit::getDistinct(
5273 Context
, language
.Val
, file
.Val
, producer
.Val
, isOptimized
.Val
, flags
.Val
,
5274 runtimeVersion
.Val
, splitDebugFilename
.Val
, emissionKind
.Val
, enums
.Val
,
5275 retainedTypes
.Val
, globals
.Val
, imports
.Val
, macros
.Val
, dwoId
.Val
,
5276 splitDebugInlining
.Val
, debugInfoForProfiling
.Val
, nameTableKind
.Val
,
5277 rangesBaseAddress
.Val
, sysroot
.Val
, sdk
.Val
);
5281 /// parseDISubprogram:
5282 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
5283 /// file: !1, line: 7, type: !2, isLocal: false,
5284 /// isDefinition: true, scopeLine: 8, containingType: !3,
5285 /// virtuality: DW_VIRTUALTIY_pure_virtual,
5286 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
5287 /// spFlags: 10, isOptimized: false, templateParams: !4,
5288 /// declaration: !5, retainedNodes: !6, thrownTypes: !7,
5289 /// annotations: !8)
5290 bool LLParser::parseDISubprogram(MDNode
*&Result
, bool IsDistinct
) {
5291 auto Loc
= Lex
.getLoc();
5292 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5293 OPTIONAL(scope, MDField, ); \
5294 OPTIONAL(name, MDStringField, ); \
5295 OPTIONAL(linkageName, MDStringField, ); \
5296 OPTIONAL(file, MDField, ); \
5297 OPTIONAL(line, LineField, ); \
5298 OPTIONAL(type, MDField, ); \
5299 OPTIONAL(isLocal, MDBoolField, ); \
5300 OPTIONAL(isDefinition, MDBoolField, (true)); \
5301 OPTIONAL(scopeLine, LineField, ); \
5302 OPTIONAL(containingType, MDField, ); \
5303 OPTIONAL(virtuality, DwarfVirtualityField, ); \
5304 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
5305 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
5306 OPTIONAL(flags, DIFlagField, ); \
5307 OPTIONAL(spFlags, DISPFlagField, ); \
5308 OPTIONAL(isOptimized, MDBoolField, ); \
5309 OPTIONAL(unit, MDField, ); \
5310 OPTIONAL(templateParams, MDField, ); \
5311 OPTIONAL(declaration, MDField, ); \
5312 OPTIONAL(retainedNodes, MDField, ); \
5313 OPTIONAL(thrownTypes, MDField, ); \
5314 OPTIONAL(annotations, MDField, ); \
5315 OPTIONAL(targetFuncName, MDStringField, );
5317 #undef VISIT_MD_FIELDS
5319 // An explicit spFlags field takes precedence over individual fields in
5320 // older IR versions.
5321 DISubprogram::DISPFlags SPFlags
=
5322 spFlags
.Seen
? spFlags
.Val
5323 : DISubprogram::toSPFlags(isLocal
.Val
, isDefinition
.Val
,
5324 isOptimized
.Val
, virtuality
.Val
);
5325 if ((SPFlags
& DISubprogram::SPFlagDefinition
) && !IsDistinct
)
5328 "missing 'distinct', required for !DISubprogram that is a Definition");
5329 Result
= GET_OR_DISTINCT(
5331 (Context
, scope
.Val
, name
.Val
, linkageName
.Val
, file
.Val
, line
.Val
,
5332 type
.Val
, scopeLine
.Val
, containingType
.Val
, virtualIndex
.Val
,
5333 thisAdjustment
.Val
, flags
.Val
, SPFlags
, unit
.Val
, templateParams
.Val
,
5334 declaration
.Val
, retainedNodes
.Val
, thrownTypes
.Val
, annotations
.Val
,
5335 targetFuncName
.Val
));
5339 /// parseDILexicalBlock:
5340 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
5341 bool LLParser::parseDILexicalBlock(MDNode
*&Result
, bool IsDistinct
) {
5342 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5343 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5344 OPTIONAL(file, MDField, ); \
5345 OPTIONAL(line, LineField, ); \
5346 OPTIONAL(column, ColumnField, );
5348 #undef VISIT_MD_FIELDS
5350 Result
= GET_OR_DISTINCT(
5351 DILexicalBlock
, (Context
, scope
.Val
, file
.Val
, line
.Val
, column
.Val
));
5355 /// parseDILexicalBlockFile:
5356 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
5357 bool LLParser::parseDILexicalBlockFile(MDNode
*&Result
, bool IsDistinct
) {
5358 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5359 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5360 OPTIONAL(file, MDField, ); \
5361 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
5363 #undef VISIT_MD_FIELDS
5365 Result
= GET_OR_DISTINCT(DILexicalBlockFile
,
5366 (Context
, scope
.Val
, file
.Val
, discriminator
.Val
));
5370 /// parseDICommonBlock:
5371 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
5372 bool LLParser::parseDICommonBlock(MDNode
*&Result
, bool IsDistinct
) {
5373 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5374 REQUIRED(scope, MDField, ); \
5375 OPTIONAL(declaration, MDField, ); \
5376 OPTIONAL(name, MDStringField, ); \
5377 OPTIONAL(file, MDField, ); \
5378 OPTIONAL(line, LineField, );
5380 #undef VISIT_MD_FIELDS
5382 Result
= GET_OR_DISTINCT(DICommonBlock
,
5383 (Context
, scope
.Val
, declaration
.Val
, name
.Val
,
5384 file
.Val
, line
.Val
));
5388 /// parseDINamespace:
5389 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
5390 bool LLParser::parseDINamespace(MDNode
*&Result
, bool IsDistinct
) {
5391 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5392 REQUIRED(scope, MDField, ); \
5393 OPTIONAL(name, MDStringField, ); \
5394 OPTIONAL(exportSymbols, MDBoolField, );
5396 #undef VISIT_MD_FIELDS
5398 Result
= GET_OR_DISTINCT(DINamespace
,
5399 (Context
, scope
.Val
, name
.Val
, exportSymbols
.Val
));
5404 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
5406 bool LLParser::parseDIMacro(MDNode
*&Result
, bool IsDistinct
) {
5407 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5408 REQUIRED(type, DwarfMacinfoTypeField, ); \
5409 OPTIONAL(line, LineField, ); \
5410 REQUIRED(name, MDStringField, ); \
5411 OPTIONAL(value, MDStringField, );
5413 #undef VISIT_MD_FIELDS
5415 Result
= GET_OR_DISTINCT(DIMacro
,
5416 (Context
, type
.Val
, line
.Val
, name
.Val
, value
.Val
));
5420 /// parseDIMacroFile:
5421 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
5422 bool LLParser::parseDIMacroFile(MDNode
*&Result
, bool IsDistinct
) {
5423 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5424 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
5425 OPTIONAL(line, LineField, ); \
5426 REQUIRED(file, MDField, ); \
5427 OPTIONAL(nodes, MDField, );
5429 #undef VISIT_MD_FIELDS
5431 Result
= GET_OR_DISTINCT(DIMacroFile
,
5432 (Context
, type
.Val
, line
.Val
, file
.Val
, nodes
.Val
));
5437 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5438 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5439 /// file: !1, line: 4, isDecl: false)
5440 bool LLParser::parseDIModule(MDNode
*&Result
, bool IsDistinct
) {
5441 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5442 REQUIRED(scope, MDField, ); \
5443 REQUIRED(name, MDStringField, ); \
5444 OPTIONAL(configMacros, MDStringField, ); \
5445 OPTIONAL(includePath, MDStringField, ); \
5446 OPTIONAL(apinotes, MDStringField, ); \
5447 OPTIONAL(file, MDField, ); \
5448 OPTIONAL(line, LineField, ); \
5449 OPTIONAL(isDecl, MDBoolField, );
5451 #undef VISIT_MD_FIELDS
5453 Result
= GET_OR_DISTINCT(DIModule
, (Context
, file
.Val
, scope
.Val
, name
.Val
,
5454 configMacros
.Val
, includePath
.Val
,
5455 apinotes
.Val
, line
.Val
, isDecl
.Val
));
5459 /// parseDITemplateTypeParameter:
5460 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5461 bool LLParser::parseDITemplateTypeParameter(MDNode
*&Result
, bool IsDistinct
) {
5462 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5463 OPTIONAL(name, MDStringField, ); \
5464 REQUIRED(type, MDField, ); \
5465 OPTIONAL(defaulted, MDBoolField, );
5467 #undef VISIT_MD_FIELDS
5469 Result
= GET_OR_DISTINCT(DITemplateTypeParameter
,
5470 (Context
, name
.Val
, type
.Val
, defaulted
.Val
));
5474 /// parseDITemplateValueParameter:
5475 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5476 /// name: "V", type: !1, defaulted: false,
5478 bool LLParser::parseDITemplateValueParameter(MDNode
*&Result
, bool IsDistinct
) {
5479 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5480 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5481 OPTIONAL(name, MDStringField, ); \
5482 OPTIONAL(type, MDField, ); \
5483 OPTIONAL(defaulted, MDBoolField, ); \
5484 REQUIRED(value, MDField, );
5487 #undef VISIT_MD_FIELDS
5489 Result
= GET_OR_DISTINCT(
5490 DITemplateValueParameter
,
5491 (Context
, tag
.Val
, name
.Val
, type
.Val
, defaulted
.Val
, value
.Val
));
5495 /// parseDIGlobalVariable:
5496 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5497 /// file: !1, line: 7, type: !2, isLocal: false,
5498 /// isDefinition: true, templateParams: !3,
5499 /// declaration: !4, align: 8)
5500 bool LLParser::parseDIGlobalVariable(MDNode
*&Result
, bool IsDistinct
) {
5501 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5502 OPTIONAL(name, MDStringField, (/* AllowEmpty */ false)); \
5503 OPTIONAL(scope, MDField, ); \
5504 OPTIONAL(linkageName, MDStringField, ); \
5505 OPTIONAL(file, MDField, ); \
5506 OPTIONAL(line, LineField, ); \
5507 OPTIONAL(type, MDField, ); \
5508 OPTIONAL(isLocal, MDBoolField, ); \
5509 OPTIONAL(isDefinition, MDBoolField, (true)); \
5510 OPTIONAL(templateParams, MDField, ); \
5511 OPTIONAL(declaration, MDField, ); \
5512 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5513 OPTIONAL(annotations, MDField, );
5515 #undef VISIT_MD_FIELDS
5518 GET_OR_DISTINCT(DIGlobalVariable
,
5519 (Context
, scope
.Val
, name
.Val
, linkageName
.Val
, file
.Val
,
5520 line
.Val
, type
.Val
, isLocal
.Val
, isDefinition
.Val
,
5521 declaration
.Val
, templateParams
.Val
, align
.Val
,
5526 /// parseDILocalVariable:
5527 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5528 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5530 /// ::= !DILocalVariable(scope: !0, name: "foo",
5531 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5533 bool LLParser::parseDILocalVariable(MDNode
*&Result
, bool IsDistinct
) {
5534 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5535 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5536 OPTIONAL(name, MDStringField, ); \
5537 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5538 OPTIONAL(file, MDField, ); \
5539 OPTIONAL(line, LineField, ); \
5540 OPTIONAL(type, MDField, ); \
5541 OPTIONAL(flags, DIFlagField, ); \
5542 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5543 OPTIONAL(annotations, MDField, );
5545 #undef VISIT_MD_FIELDS
5547 Result
= GET_OR_DISTINCT(DILocalVariable
,
5548 (Context
, scope
.Val
, name
.Val
, file
.Val
, line
.Val
,
5549 type
.Val
, arg
.Val
, flags
.Val
, align
.Val
,
5555 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5556 bool LLParser::parseDILabel(MDNode
*&Result
, bool IsDistinct
) {
5557 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5558 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5559 REQUIRED(name, MDStringField, ); \
5560 REQUIRED(file, MDField, ); \
5561 REQUIRED(line, LineField, );
5563 #undef VISIT_MD_FIELDS
5565 Result
= GET_OR_DISTINCT(DILabel
,
5566 (Context
, scope
.Val
, name
.Val
, file
.Val
, line
.Val
));
5570 /// parseDIExpression:
5571 /// ::= !DIExpression(0, 7, -1)
5572 bool LLParser::parseDIExpression(MDNode
*&Result
, bool IsDistinct
) {
5573 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
5576 if (parseToken(lltok::lparen
, "expected '(' here"))
5579 SmallVector
<uint64_t, 8> Elements
;
5580 if (Lex
.getKind() != lltok::rparen
)
5582 if (Lex
.getKind() == lltok::DwarfOp
) {
5583 if (unsigned Op
= dwarf::getOperationEncoding(Lex
.getStrVal())) {
5585 Elements
.push_back(Op
);
5588 return tokError(Twine("invalid DWARF op '") + Lex
.getStrVal() + "'");
5591 if (Lex
.getKind() == lltok::DwarfAttEncoding
) {
5592 if (unsigned Op
= dwarf::getAttributeEncoding(Lex
.getStrVal())) {
5594 Elements
.push_back(Op
);
5597 return tokError(Twine("invalid DWARF attribute encoding '") +
5598 Lex
.getStrVal() + "'");
5601 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
5602 return tokError("expected unsigned integer");
5604 auto &U
= Lex
.getAPSIntVal();
5605 if (U
.ugt(UINT64_MAX
))
5606 return tokError("element too large, limit is " + Twine(UINT64_MAX
));
5607 Elements
.push_back(U
.getZExtValue());
5609 } while (EatIfPresent(lltok::comma
));
5611 if (parseToken(lltok::rparen
, "expected ')' here"))
5614 Result
= GET_OR_DISTINCT(DIExpression
, (Context
, Elements
));
5619 /// ::= !DIArgList(i32 7, i64 %0)
5620 bool LLParser::parseDIArgList(Metadata
*&MD
, PerFunctionState
*PFS
) {
5621 assert(PFS
&& "Expected valid function state");
5622 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
5625 if (parseToken(lltok::lparen
, "expected '(' here"))
5628 SmallVector
<ValueAsMetadata
*, 4> Args
;
5629 if (Lex
.getKind() != lltok::rparen
)
5632 if (parseValueAsMetadata(MD
, "expected value-as-metadata operand", PFS
))
5634 Args
.push_back(dyn_cast
<ValueAsMetadata
>(MD
));
5635 } while (EatIfPresent(lltok::comma
));
5637 if (parseToken(lltok::rparen
, "expected ')' here"))
5640 MD
= DIArgList::get(Context
, Args
);
5644 /// parseDIGlobalVariableExpression:
5645 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5646 bool LLParser::parseDIGlobalVariableExpression(MDNode
*&Result
,
5648 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5649 REQUIRED(var, MDField, ); \
5650 REQUIRED(expr, MDField, );
5652 #undef VISIT_MD_FIELDS
5655 GET_OR_DISTINCT(DIGlobalVariableExpression
, (Context
, var
.Val
, expr
.Val
));
5659 /// parseDIObjCProperty:
5660 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5661 /// getter: "getFoo", attributes: 7, type: !2)
5662 bool LLParser::parseDIObjCProperty(MDNode
*&Result
, bool IsDistinct
) {
5663 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5664 OPTIONAL(name, MDStringField, ); \
5665 OPTIONAL(file, MDField, ); \
5666 OPTIONAL(line, LineField, ); \
5667 OPTIONAL(setter, MDStringField, ); \
5668 OPTIONAL(getter, MDStringField, ); \
5669 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5670 OPTIONAL(type, MDField, );
5672 #undef VISIT_MD_FIELDS
5674 Result
= GET_OR_DISTINCT(DIObjCProperty
,
5675 (Context
, name
.Val
, file
.Val
, line
.Val
, setter
.Val
,
5676 getter
.Val
, attributes
.Val
, type
.Val
));
5680 /// parseDIImportedEntity:
5681 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5682 /// line: 7, name: "foo", elements: !2)
5683 bool LLParser::parseDIImportedEntity(MDNode
*&Result
, bool IsDistinct
) {
5684 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5685 REQUIRED(tag, DwarfTagField, ); \
5686 REQUIRED(scope, MDField, ); \
5687 OPTIONAL(entity, MDField, ); \
5688 OPTIONAL(file, MDField, ); \
5689 OPTIONAL(line, LineField, ); \
5690 OPTIONAL(name, MDStringField, ); \
5691 OPTIONAL(elements, MDField, );
5693 #undef VISIT_MD_FIELDS
5695 Result
= GET_OR_DISTINCT(DIImportedEntity
,
5696 (Context
, tag
.Val
, scope
.Val
, entity
.Val
, file
.Val
,
5697 line
.Val
, name
.Val
, elements
.Val
));
5701 #undef PARSE_MD_FIELD
5703 #undef REQUIRE_FIELD
5704 #undef DECLARE_FIELD
5706 /// parseMetadataAsValue
5707 /// ::= metadata i32 %local
5708 /// ::= metadata i32 @global
5709 /// ::= metadata i32 7
5711 /// ::= metadata !{...}
5712 /// ::= metadata !"string"
5713 bool LLParser::parseMetadataAsValue(Value
*&V
, PerFunctionState
&PFS
) {
5714 // Note: the type 'metadata' has already been parsed.
5716 if (parseMetadata(MD
, &PFS
))
5719 V
= MetadataAsValue::get(Context
, MD
);
5723 /// parseValueAsMetadata
5727 bool LLParser::parseValueAsMetadata(Metadata
*&MD
, const Twine
&TypeMsg
,
5728 PerFunctionState
*PFS
) {
5731 if (parseType(Ty
, TypeMsg
, Loc
))
5733 if (Ty
->isMetadataTy())
5734 return error(Loc
, "invalid metadata-value-metadata roundtrip");
5737 if (parseValue(Ty
, V
, PFS
))
5740 MD
= ValueAsMetadata::get(V
);
5751 /// ::= !DILocation(...)
5752 bool LLParser::parseMetadata(Metadata
*&MD
, PerFunctionState
*PFS
) {
5753 if (Lex
.getKind() == lltok::MetadataVar
) {
5754 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5755 // so parsing this requires a Function State.
5756 if (Lex
.getStrVal() == "DIArgList") {
5758 if (parseDIArgList(AL
, PFS
))
5764 if (parseSpecializedMDNode(N
)) {
5773 if (Lex
.getKind() != lltok::exclaim
)
5774 return parseValueAsMetadata(MD
, "expected metadata operand", PFS
);
5777 assert(Lex
.getKind() == lltok::exclaim
&& "Expected '!' here");
5781 // ::= '!' STRINGCONSTANT
5782 if (Lex
.getKind() == lltok::StringConstant
) {
5784 if (parseMDString(S
))
5794 if (parseMDNodeTail(N
))
5800 //===----------------------------------------------------------------------===//
5801 // Function Parsing.
5802 //===----------------------------------------------------------------------===//
5804 bool LLParser::convertValIDToValue(Type
*Ty
, ValID
&ID
, Value
*&V
,
5805 PerFunctionState
*PFS
) {
5806 if (Ty
->isFunctionTy())
5807 return error(ID
.Loc
, "functions are not values, refer to them as pointers");
5810 case ValID::t_LocalID
:
5812 return error(ID
.Loc
, "invalid use of function-local name");
5813 V
= PFS
->getVal(ID
.UIntVal
, Ty
, ID
.Loc
);
5814 return V
== nullptr;
5815 case ValID::t_LocalName
:
5817 return error(ID
.Loc
, "invalid use of function-local name");
5818 V
= PFS
->getVal(ID
.StrVal
, Ty
, ID
.Loc
);
5819 return V
== nullptr;
5820 case ValID::t_InlineAsm
: {
5822 return error(ID
.Loc
, "invalid type for inline asm constraint string");
5823 if (Error Err
= InlineAsm::verify(ID
.FTy
, ID
.StrVal2
))
5824 return error(ID
.Loc
, toString(std::move(Err
)));
5826 ID
.FTy
, ID
.StrVal
, ID
.StrVal2
, ID
.UIntVal
& 1, (ID
.UIntVal
>> 1) & 1,
5827 InlineAsm::AsmDialect((ID
.UIntVal
>> 2) & 1), (ID
.UIntVal
>> 3) & 1);
5830 case ValID::t_GlobalName
:
5831 V
= getGlobalVal(ID
.StrVal
, Ty
, ID
.Loc
);
5833 V
= NoCFIValue::get(cast
<GlobalValue
>(V
));
5834 return V
== nullptr;
5835 case ValID::t_GlobalID
:
5836 V
= getGlobalVal(ID
.UIntVal
, Ty
, ID
.Loc
);
5838 V
= NoCFIValue::get(cast
<GlobalValue
>(V
));
5839 return V
== nullptr;
5840 case ValID::t_APSInt
:
5841 if (!Ty
->isIntegerTy())
5842 return error(ID
.Loc
, "integer constant must have integer type");
5843 ID
.APSIntVal
= ID
.APSIntVal
.extOrTrunc(Ty
->getPrimitiveSizeInBits());
5844 V
= ConstantInt::get(Context
, ID
.APSIntVal
);
5846 case ValID::t_APFloat
:
5847 if (!Ty
->isFloatingPointTy() ||
5848 !ConstantFP::isValueValidForType(Ty
, ID
.APFloatVal
))
5849 return error(ID
.Loc
, "floating point constant invalid for type");
5851 // The lexer has no type info, so builds all half, bfloat, float, and double
5852 // FP constants as double. Fix this here. Long double does not need this.
5853 if (&ID
.APFloatVal
.getSemantics() == &APFloat::IEEEdouble()) {
5854 // Check for signaling before potentially converting and losing that info.
5855 bool IsSNAN
= ID
.APFloatVal
.isSignaling();
5858 ID
.APFloatVal
.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven
,
5860 else if (Ty
->isBFloatTy())
5861 ID
.APFloatVal
.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven
,
5863 else if (Ty
->isFloatTy())
5864 ID
.APFloatVal
.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven
,
5867 // The convert call above may quiet an SNaN, so manufacture another
5868 // SNaN. The bitcast works because the payload (significand) parameter
5869 // is truncated to fit.
5870 APInt Payload
= ID
.APFloatVal
.bitcastToAPInt();
5871 ID
.APFloatVal
= APFloat::getSNaN(ID
.APFloatVal
.getSemantics(),
5872 ID
.APFloatVal
.isNegative(), &Payload
);
5875 V
= ConstantFP::get(Context
, ID
.APFloatVal
);
5877 if (V
->getType() != Ty
)
5878 return error(ID
.Loc
, "floating point constant does not have type '" +
5879 getTypeString(Ty
) + "'");
5883 if (!Ty
->isPointerTy())
5884 return error(ID
.Loc
, "null must be a pointer type");
5885 V
= ConstantPointerNull::get(cast
<PointerType
>(Ty
));
5887 case ValID::t_Undef
:
5888 // FIXME: LabelTy should not be a first-class type.
5889 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5890 return error(ID
.Loc
, "invalid type for undef constant");
5891 V
= UndefValue::get(Ty
);
5893 case ValID::t_EmptyArray
:
5894 if (!Ty
->isArrayTy() || cast
<ArrayType
>(Ty
)->getNumElements() != 0)
5895 return error(ID
.Loc
, "invalid empty array initializer");
5896 V
= UndefValue::get(Ty
);
5899 // FIXME: LabelTy should not be a first-class type.
5900 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5901 return error(ID
.Loc
, "invalid type for null constant");
5902 if (auto *TETy
= dyn_cast
<TargetExtType
>(Ty
))
5903 if (!TETy
->hasProperty(TargetExtType::HasZeroInit
))
5904 return error(ID
.Loc
, "invalid type for null constant");
5905 V
= Constant::getNullValue(Ty
);
5908 if (!Ty
->isTokenTy())
5909 return error(ID
.Loc
, "invalid type for none constant");
5910 V
= Constant::getNullValue(Ty
);
5912 case ValID::t_Poison
:
5913 // FIXME: LabelTy should not be a first-class type.
5914 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5915 return error(ID
.Loc
, "invalid type for poison constant");
5916 V
= PoisonValue::get(Ty
);
5918 case ValID::t_Constant
:
5919 if (ID
.ConstantVal
->getType() != Ty
)
5920 return error(ID
.Loc
, "constant expression type mismatch: got type '" +
5921 getTypeString(ID
.ConstantVal
->getType()) +
5922 "' but expected '" + getTypeString(Ty
) + "'");
5925 case ValID::t_ConstantSplat
:
5926 if (!Ty
->isVectorTy())
5927 return error(ID
.Loc
, "vector constant must have vector type");
5928 if (ID
.ConstantVal
->getType() != Ty
->getScalarType())
5929 return error(ID
.Loc
, "constant expression type mismatch: got type '" +
5930 getTypeString(ID
.ConstantVal
->getType()) +
5931 "' but expected '" +
5932 getTypeString(Ty
->getScalarType()) + "'");
5933 V
= ConstantVector::getSplat(cast
<VectorType
>(Ty
)->getElementCount(),
5936 case ValID::t_ConstantStruct
:
5937 case ValID::t_PackedConstantStruct
:
5938 if (StructType
*ST
= dyn_cast
<StructType
>(Ty
)) {
5939 if (ST
->getNumElements() != ID
.UIntVal
)
5940 return error(ID
.Loc
,
5941 "initializer with struct type has wrong # elements");
5942 if (ST
->isPacked() != (ID
.Kind
== ValID::t_PackedConstantStruct
))
5943 return error(ID
.Loc
, "packed'ness of initializer and type don't match");
5945 // Verify that the elements are compatible with the structtype.
5946 for (unsigned i
= 0, e
= ID
.UIntVal
; i
!= e
; ++i
)
5947 if (ID
.ConstantStructElts
[i
]->getType() != ST
->getElementType(i
))
5950 "element " + Twine(i
) +
5951 " of struct initializer doesn't match struct element type");
5953 V
= ConstantStruct::get(
5954 ST
, ArrayRef(ID
.ConstantStructElts
.get(), ID
.UIntVal
));
5956 return error(ID
.Loc
, "constant expression type mismatch");
5959 llvm_unreachable("Invalid ValID");
5962 bool LLParser::parseConstantValue(Type
*Ty
, Constant
*&C
) {
5965 auto Loc
= Lex
.getLoc();
5966 if (parseValID(ID
, /*PFS=*/nullptr))
5969 case ValID::t_APSInt
:
5970 case ValID::t_APFloat
:
5971 case ValID::t_Undef
:
5972 case ValID::t_Constant
:
5973 case ValID::t_ConstantSplat
:
5974 case ValID::t_ConstantStruct
:
5975 case ValID::t_PackedConstantStruct
: {
5977 if (convertValIDToValue(Ty
, ID
, V
, /*PFS=*/nullptr))
5979 assert(isa
<Constant
>(V
) && "Expected a constant value");
5980 C
= cast
<Constant
>(V
);
5984 C
= Constant::getNullValue(Ty
);
5987 return error(Loc
, "expected a constant value");
5991 bool LLParser::parseValue(Type
*Ty
, Value
*&V
, PerFunctionState
*PFS
) {
5994 return parseValID(ID
, PFS
, Ty
) ||
5995 convertValIDToValue(Ty
, ID
, V
, PFS
);
5998 bool LLParser::parseTypeAndValue(Value
*&V
, PerFunctionState
*PFS
) {
6000 return parseType(Ty
) || parseValue(Ty
, V
, PFS
);
6003 bool LLParser::parseTypeAndBasicBlock(BasicBlock
*&BB
, LocTy
&Loc
,
6004 PerFunctionState
&PFS
) {
6007 if (parseTypeAndValue(V
, PFS
))
6009 if (!isa
<BasicBlock
>(V
))
6010 return error(Loc
, "expected a basic block");
6011 BB
= cast
<BasicBlock
>(V
);
6016 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
6017 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
6018 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
6019 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
6020 bool LLParser::parseFunctionHeader(Function
*&Fn
, bool IsDefine
,
6021 SmallVectorImpl
<unsigned> &UnnamedArgNums
) {
6022 // parse the linkage.
6023 LocTy LinkageLoc
= Lex
.getLoc();
6025 unsigned Visibility
;
6026 unsigned DLLStorageClass
;
6028 AttrBuilder
RetAttrs(M
->getContext());
6031 Type
*RetType
= nullptr;
6032 LocTy RetTypeLoc
= Lex
.getLoc();
6033 if (parseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
6035 parseOptionalCallingConv(CC
) || parseOptionalReturnAttrs(RetAttrs
) ||
6036 parseType(RetType
, RetTypeLoc
, true /*void allowed*/))
6039 // Verify that the linkage is ok.
6040 switch ((GlobalValue::LinkageTypes
)Linkage
) {
6041 case GlobalValue::ExternalLinkage
:
6042 break; // always ok.
6043 case GlobalValue::ExternalWeakLinkage
:
6045 return error(LinkageLoc
, "invalid linkage for function definition");
6047 case GlobalValue::PrivateLinkage
:
6048 case GlobalValue::InternalLinkage
:
6049 case GlobalValue::AvailableExternallyLinkage
:
6050 case GlobalValue::LinkOnceAnyLinkage
:
6051 case GlobalValue::LinkOnceODRLinkage
:
6052 case GlobalValue::WeakAnyLinkage
:
6053 case GlobalValue::WeakODRLinkage
:
6055 return error(LinkageLoc
, "invalid linkage for function declaration");
6057 case GlobalValue::AppendingLinkage
:
6058 case GlobalValue::CommonLinkage
:
6059 return error(LinkageLoc
, "invalid function linkage type");
6062 if (!isValidVisibilityForLinkage(Visibility
, Linkage
))
6063 return error(LinkageLoc
,
6064 "symbol with local linkage must have default visibility");
6066 if (!isValidDLLStorageClassForLinkage(DLLStorageClass
, Linkage
))
6067 return error(LinkageLoc
,
6068 "symbol with local linkage cannot have a DLL storage class");
6070 if (!FunctionType::isValidReturnType(RetType
))
6071 return error(RetTypeLoc
, "invalid function return type");
6073 LocTy NameLoc
= Lex
.getLoc();
6075 std::string FunctionName
;
6076 if (Lex
.getKind() == lltok::GlobalVar
) {
6077 FunctionName
= Lex
.getStrVal();
6078 } else if (Lex
.getKind() == lltok::GlobalID
) { // @42 is ok.
6079 unsigned NameID
= Lex
.getUIntVal();
6081 if (NameID
!= NumberedVals
.size())
6082 return tokError("function expected to be numbered '%" +
6083 Twine(NumberedVals
.size()) + "'");
6085 return tokError("expected function name");
6090 if (Lex
.getKind() != lltok::lparen
)
6091 return tokError("expected '(' in function argument list");
6093 SmallVector
<ArgInfo
, 8> ArgList
;
6095 AttrBuilder
FuncAttrs(M
->getContext());
6096 std::vector
<unsigned> FwdRefAttrGrps
;
6098 std::string Section
;
6099 std::string Partition
;
6100 MaybeAlign Alignment
;
6102 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
6103 unsigned AddrSpace
= 0;
6104 Constant
*Prefix
= nullptr;
6105 Constant
*Prologue
= nullptr;
6106 Constant
*PersonalityFn
= nullptr;
6109 if (parseArgumentList(ArgList
, UnnamedArgNums
, IsVarArg
) ||
6110 parseOptionalUnnamedAddr(UnnamedAddr
) ||
6111 parseOptionalProgramAddrSpace(AddrSpace
) ||
6112 parseFnAttributeValuePairs(FuncAttrs
, FwdRefAttrGrps
, false,
6114 (EatIfPresent(lltok::kw_section
) && parseStringConstant(Section
)) ||
6115 (EatIfPresent(lltok::kw_partition
) && parseStringConstant(Partition
)) ||
6116 parseOptionalComdat(FunctionName
, C
) ||
6117 parseOptionalAlignment(Alignment
) ||
6118 (EatIfPresent(lltok::kw_gc
) && parseStringConstant(GC
)) ||
6119 (EatIfPresent(lltok::kw_prefix
) && parseGlobalTypeAndValue(Prefix
)) ||
6120 (EatIfPresent(lltok::kw_prologue
) && parseGlobalTypeAndValue(Prologue
)) ||
6121 (EatIfPresent(lltok::kw_personality
) &&
6122 parseGlobalTypeAndValue(PersonalityFn
)))
6125 if (FuncAttrs
.contains(Attribute::Builtin
))
6126 return error(BuiltinLoc
, "'builtin' attribute not valid on function");
6128 // If the alignment was parsed as an attribute, move to the alignment field.
6129 if (MaybeAlign A
= FuncAttrs
.getAlignment()) {
6131 FuncAttrs
.removeAttribute(Attribute::Alignment
);
6134 // Okay, if we got here, the function is syntactically valid. Convert types
6135 // and do semantic checks.
6136 std::vector
<Type
*> ParamTypeList
;
6137 SmallVector
<AttributeSet
, 8> Attrs
;
6139 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
6140 ParamTypeList
.push_back(ArgList
[i
].Ty
);
6141 Attrs
.push_back(ArgList
[i
].Attrs
);
6145 AttributeList::get(Context
, AttributeSet::get(Context
, FuncAttrs
),
6146 AttributeSet::get(Context
, RetAttrs
), Attrs
);
6148 if (PAL
.hasParamAttr(0, Attribute::StructRet
) && !RetType
->isVoidTy())
6149 return error(RetTypeLoc
, "functions with 'sret' argument must return void");
6151 FunctionType
*FT
= FunctionType::get(RetType
, ParamTypeList
, IsVarArg
);
6152 PointerType
*PFT
= PointerType::get(FT
, AddrSpace
);
6155 GlobalValue
*FwdFn
= nullptr;
6156 if (!FunctionName
.empty()) {
6157 // If this was a definition of a forward reference, remove the definition
6158 // from the forward reference table and fill in the forward ref.
6159 auto FRVI
= ForwardRefVals
.find(FunctionName
);
6160 if (FRVI
!= ForwardRefVals
.end()) {
6161 FwdFn
= FRVI
->second
.first
;
6162 if (FwdFn
->getType() != PFT
)
6163 return error(FRVI
->second
.second
,
6164 "invalid forward reference to "
6167 "' with wrong type: "
6169 getTypeString(PFT
) + "' but was '" +
6170 getTypeString(FwdFn
->getType()) + "'");
6171 ForwardRefVals
.erase(FRVI
);
6172 } else if ((Fn
= M
->getFunction(FunctionName
))) {
6173 // Reject redefinitions.
6174 return error(NameLoc
,
6175 "invalid redefinition of function '" + FunctionName
+ "'");
6176 } else if (M
->getNamedValue(FunctionName
)) {
6177 return error(NameLoc
, "redefinition of function '@" + FunctionName
+ "'");
6181 // If this is a definition of a forward referenced function, make sure the
6183 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
6184 if (I
!= ForwardRefValIDs
.end()) {
6185 FwdFn
= I
->second
.first
;
6186 if (FwdFn
->getType() != PFT
)
6187 return error(NameLoc
, "type of definition and forward reference of '@" +
6188 Twine(NumberedVals
.size()) +
6191 getTypeString(PFT
) + "' but was '" +
6192 getTypeString(FwdFn
->getType()) + "'");
6193 ForwardRefValIDs
.erase(I
);
6197 Fn
= Function::Create(FT
, GlobalValue::ExternalLinkage
, AddrSpace
,
6200 assert(Fn
->getAddressSpace() == AddrSpace
&& "Created function in wrong AS");
6202 if (FunctionName
.empty())
6203 NumberedVals
.push_back(Fn
);
6205 Fn
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
6206 maybeSetDSOLocal(DSOLocal
, *Fn
);
6207 Fn
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
6208 Fn
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
6209 Fn
->setCallingConv(CC
);
6210 Fn
->setAttributes(PAL
);
6211 Fn
->setUnnamedAddr(UnnamedAddr
);
6213 Fn
->setAlignment(*Alignment
);
6214 Fn
->setSection(Section
);
6215 Fn
->setPartition(Partition
);
6217 Fn
->setPersonalityFn(PersonalityFn
);
6218 if (!GC
.empty()) Fn
->setGC(GC
);
6219 Fn
->setPrefixData(Prefix
);
6220 Fn
->setPrologueData(Prologue
);
6221 ForwardRefAttrGroups
[Fn
] = FwdRefAttrGrps
;
6223 // Add all of the arguments we parsed to the function.
6224 Function::arg_iterator ArgIt
= Fn
->arg_begin();
6225 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
, ++ArgIt
) {
6226 // If the argument has a name, insert it into the argument symbol table.
6227 if (ArgList
[i
].Name
.empty()) continue;
6229 // Set the name, if it conflicted, it will be auto-renamed.
6230 ArgIt
->setName(ArgList
[i
].Name
);
6232 if (ArgIt
->getName() != ArgList
[i
].Name
)
6233 return error(ArgList
[i
].Loc
,
6234 "redefinition of argument '%" + ArgList
[i
].Name
+ "'");
6238 FwdFn
->replaceAllUsesWith(Fn
);
6239 FwdFn
->eraseFromParent();
6245 // Check the declaration has no block address forward references.
6247 if (FunctionName
.empty()) {
6248 ID
.Kind
= ValID::t_GlobalID
;
6249 ID
.UIntVal
= NumberedVals
.size() - 1;
6251 ID
.Kind
= ValID::t_GlobalName
;
6252 ID
.StrVal
= FunctionName
;
6254 auto Blocks
= ForwardRefBlockAddresses
.find(ID
);
6255 if (Blocks
!= ForwardRefBlockAddresses
.end())
6256 return error(Blocks
->first
.Loc
,
6257 "cannot take blockaddress inside a declaration");
6261 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
6263 if (FunctionNumber
== -1) {
6264 ID
.Kind
= ValID::t_GlobalName
;
6265 ID
.StrVal
= std::string(F
.getName());
6267 ID
.Kind
= ValID::t_GlobalID
;
6268 ID
.UIntVal
= FunctionNumber
;
6271 auto Blocks
= P
.ForwardRefBlockAddresses
.find(ID
);
6272 if (Blocks
== P
.ForwardRefBlockAddresses
.end())
6275 for (const auto &I
: Blocks
->second
) {
6276 const ValID
&BBID
= I
.first
;
6277 GlobalValue
*GV
= I
.second
;
6279 assert((BBID
.Kind
== ValID::t_LocalID
|| BBID
.Kind
== ValID::t_LocalName
) &&
6280 "Expected local id or name");
6282 if (BBID
.Kind
== ValID::t_LocalName
)
6283 BB
= getBB(BBID
.StrVal
, BBID
.Loc
);
6285 BB
= getBB(BBID
.UIntVal
, BBID
.Loc
);
6287 return P
.error(BBID
.Loc
, "referenced value is not a basic block");
6289 Value
*ResolvedVal
= BlockAddress::get(&F
, BB
);
6290 ResolvedVal
= P
.checkValidVariableType(BBID
.Loc
, BBID
.StrVal
, GV
->getType(),
6294 GV
->replaceAllUsesWith(ResolvedVal
);
6295 GV
->eraseFromParent();
6298 P
.ForwardRefBlockAddresses
.erase(Blocks
);
6302 /// parseFunctionBody
6303 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
6304 bool LLParser::parseFunctionBody(Function
&Fn
,
6305 ArrayRef
<unsigned> UnnamedArgNums
) {
6306 if (Lex
.getKind() != lltok::lbrace
)
6307 return tokError("expected '{' in function body");
6308 Lex
.Lex(); // eat the {.
6310 int FunctionNumber
= -1;
6311 if (!Fn
.hasName()) FunctionNumber
= NumberedVals
.size()-1;
6313 PerFunctionState
PFS(*this, Fn
, FunctionNumber
, UnnamedArgNums
);
6315 // Resolve block addresses and allow basic blocks to be forward-declared
6316 // within this function.
6317 if (PFS
.resolveForwardRefBlockAddresses())
6319 SaveAndRestore
ScopeExit(BlockAddressPFS
, &PFS
);
6321 // We need at least one basic block.
6322 if (Lex
.getKind() == lltok::rbrace
|| Lex
.getKind() == lltok::kw_uselistorder
)
6323 return tokError("function body requires at least one basic block");
6325 while (Lex
.getKind() != lltok::rbrace
&&
6326 Lex
.getKind() != lltok::kw_uselistorder
)
6327 if (parseBasicBlock(PFS
))
6330 while (Lex
.getKind() != lltok::rbrace
)
6331 if (parseUseListOrder(&PFS
))
6337 // Verify function is ok.
6338 return PFS
.finishFunction();
6342 /// ::= (LabelStr|LabelID)? Instruction*
6343 bool LLParser::parseBasicBlock(PerFunctionState
&PFS
) {
6344 // If this basic block starts out with a name, remember it.
6347 LocTy NameLoc
= Lex
.getLoc();
6348 if (Lex
.getKind() == lltok::LabelStr
) {
6349 Name
= Lex
.getStrVal();
6351 } else if (Lex
.getKind() == lltok::LabelID
) {
6352 NameID
= Lex
.getUIntVal();
6356 BasicBlock
*BB
= PFS
.defineBB(Name
, NameID
, NameLoc
);
6360 std::string NameStr
;
6362 // parse the instructions in this block until we get a terminator.
6365 // This instruction may have three possibilities for a name: a) none
6366 // specified, b) name specified "%foo =", c) number specified: "%4 =".
6367 LocTy NameLoc
= Lex
.getLoc();
6371 if (Lex
.getKind() == lltok::LocalVarID
) {
6372 NameID
= Lex
.getUIntVal();
6374 if (parseToken(lltok::equal
, "expected '=' after instruction id"))
6376 } else if (Lex
.getKind() == lltok::LocalVar
) {
6377 NameStr
= Lex
.getStrVal();
6379 if (parseToken(lltok::equal
, "expected '=' after instruction name"))
6383 switch (parseInstruction(Inst
, BB
, PFS
)) {
6385 llvm_unreachable("Unknown parseInstruction result!");
6386 case InstError
: return true;
6388 Inst
->insertInto(BB
, BB
->end());
6390 // With a normal result, we check to see if the instruction is followed by
6391 // a comma and metadata.
6392 if (EatIfPresent(lltok::comma
))
6393 if (parseInstructionMetadata(*Inst
))
6396 case InstExtraComma
:
6397 Inst
->insertInto(BB
, BB
->end());
6399 // If the instruction parser ate an extra comma at the end of it, it
6400 // *must* be followed by metadata.
6401 if (parseInstructionMetadata(*Inst
))
6406 // Set the name on the instruction.
6407 if (PFS
.setInstName(NameID
, NameStr
, NameLoc
, Inst
))
6409 } while (!Inst
->isTerminator());
6414 //===----------------------------------------------------------------------===//
6415 // Instruction Parsing.
6416 //===----------------------------------------------------------------------===//
6418 /// parseInstruction - parse one of the many different instructions.
6420 int LLParser::parseInstruction(Instruction
*&Inst
, BasicBlock
*BB
,
6421 PerFunctionState
&PFS
) {
6422 lltok::Kind Token
= Lex
.getKind();
6423 if (Token
== lltok::Eof
)
6424 return tokError("found end of file when expecting more instructions");
6425 LocTy Loc
= Lex
.getLoc();
6426 unsigned KeywordVal
= Lex
.getUIntVal();
6427 Lex
.Lex(); // Eat the keyword.
6431 return error(Loc
, "expected instruction opcode");
6432 // Terminator Instructions.
6433 case lltok::kw_unreachable
: Inst
= new UnreachableInst(Context
); return false;
6435 return parseRet(Inst
, BB
, PFS
);
6437 return parseBr(Inst
, PFS
);
6438 case lltok::kw_switch
:
6439 return parseSwitch(Inst
, PFS
);
6440 case lltok::kw_indirectbr
:
6441 return parseIndirectBr(Inst
, PFS
);
6442 case lltok::kw_invoke
:
6443 return parseInvoke(Inst
, PFS
);
6444 case lltok::kw_resume
:
6445 return parseResume(Inst
, PFS
);
6446 case lltok::kw_cleanupret
:
6447 return parseCleanupRet(Inst
, PFS
);
6448 case lltok::kw_catchret
:
6449 return parseCatchRet(Inst
, PFS
);
6450 case lltok::kw_catchswitch
:
6451 return parseCatchSwitch(Inst
, PFS
);
6452 case lltok::kw_catchpad
:
6453 return parseCatchPad(Inst
, PFS
);
6454 case lltok::kw_cleanuppad
:
6455 return parseCleanupPad(Inst
, PFS
);
6456 case lltok::kw_callbr
:
6457 return parseCallBr(Inst
, PFS
);
6459 case lltok::kw_fneg
: {
6460 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6461 int Res
= parseUnaryOp(Inst
, PFS
, KeywordVal
, /*IsFP*/ true);
6465 Inst
->setFastMathFlags(FMF
);
6468 // Binary Operators.
6472 case lltok::kw_shl
: {
6473 bool NUW
= EatIfPresent(lltok::kw_nuw
);
6474 bool NSW
= EatIfPresent(lltok::kw_nsw
);
6475 if (!NUW
) NUW
= EatIfPresent(lltok::kw_nuw
);
6477 if (parseArithmetic(Inst
, PFS
, KeywordVal
, /*IsFP*/ false))
6480 if (NUW
) cast
<BinaryOperator
>(Inst
)->setHasNoUnsignedWrap(true);
6481 if (NSW
) cast
<BinaryOperator
>(Inst
)->setHasNoSignedWrap(true);
6484 case lltok::kw_fadd
:
6485 case lltok::kw_fsub
:
6486 case lltok::kw_fmul
:
6487 case lltok::kw_fdiv
:
6488 case lltok::kw_frem
: {
6489 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6490 int Res
= parseArithmetic(Inst
, PFS
, KeywordVal
, /*IsFP*/ true);
6494 Inst
->setFastMathFlags(FMF
);
6498 case lltok::kw_sdiv
:
6499 case lltok::kw_udiv
:
6500 case lltok::kw_lshr
:
6501 case lltok::kw_ashr
: {
6502 bool Exact
= EatIfPresent(lltok::kw_exact
);
6504 if (parseArithmetic(Inst
, PFS
, KeywordVal
, /*IsFP*/ false))
6506 if (Exact
) cast
<BinaryOperator
>(Inst
)->setIsExact(true);
6510 case lltok::kw_urem
:
6511 case lltok::kw_srem
:
6512 return parseArithmetic(Inst
, PFS
, KeywordVal
,
6514 case lltok::kw_or
: {
6515 bool Disjoint
= EatIfPresent(lltok::kw_disjoint
);
6516 if (parseLogical(Inst
, PFS
, KeywordVal
))
6519 cast
<PossiblyDisjointInst
>(Inst
)->setIsDisjoint(true);
6524 return parseLogical(Inst
, PFS
, KeywordVal
);
6525 case lltok::kw_icmp
:
6526 return parseCompare(Inst
, PFS
, KeywordVal
);
6527 case lltok::kw_fcmp
: {
6528 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6529 int Res
= parseCompare(Inst
, PFS
, KeywordVal
);
6533 Inst
->setFastMathFlags(FMF
);
6538 case lltok::kw_zext
: {
6539 bool NonNeg
= EatIfPresent(lltok::kw_nneg
);
6540 bool Res
= parseCast(Inst
, PFS
, KeywordVal
);
6547 case lltok::kw_trunc
:
6548 case lltok::kw_sext
:
6549 case lltok::kw_fptrunc
:
6550 case lltok::kw_fpext
:
6551 case lltok::kw_bitcast
:
6552 case lltok::kw_addrspacecast
:
6553 case lltok::kw_uitofp
:
6554 case lltok::kw_sitofp
:
6555 case lltok::kw_fptoui
:
6556 case lltok::kw_fptosi
:
6557 case lltok::kw_inttoptr
:
6558 case lltok::kw_ptrtoint
:
6559 return parseCast(Inst
, PFS
, KeywordVal
);
6561 case lltok::kw_select
: {
6562 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6563 int Res
= parseSelect(Inst
, PFS
);
6567 if (!isa
<FPMathOperator
>(Inst
))
6568 return error(Loc
, "fast-math-flags specified for select without "
6569 "floating-point scalar or vector return type");
6570 Inst
->setFastMathFlags(FMF
);
6574 case lltok::kw_va_arg
:
6575 return parseVAArg(Inst
, PFS
);
6576 case lltok::kw_extractelement
:
6577 return parseExtractElement(Inst
, PFS
);
6578 case lltok::kw_insertelement
:
6579 return parseInsertElement(Inst
, PFS
);
6580 case lltok::kw_shufflevector
:
6581 return parseShuffleVector(Inst
, PFS
);
6582 case lltok::kw_phi
: {
6583 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6584 int Res
= parsePHI(Inst
, PFS
);
6588 if (!isa
<FPMathOperator
>(Inst
))
6589 return error(Loc
, "fast-math-flags specified for phi without "
6590 "floating-point scalar or vector return type");
6591 Inst
->setFastMathFlags(FMF
);
6595 case lltok::kw_landingpad
:
6596 return parseLandingPad(Inst
, PFS
);
6597 case lltok::kw_freeze
:
6598 return parseFreeze(Inst
, PFS
);
6600 case lltok::kw_call
:
6601 return parseCall(Inst
, PFS
, CallInst::TCK_None
);
6602 case lltok::kw_tail
:
6603 return parseCall(Inst
, PFS
, CallInst::TCK_Tail
);
6604 case lltok::kw_musttail
:
6605 return parseCall(Inst
, PFS
, CallInst::TCK_MustTail
);
6606 case lltok::kw_notail
:
6607 return parseCall(Inst
, PFS
, CallInst::TCK_NoTail
);
6609 case lltok::kw_alloca
:
6610 return parseAlloc(Inst
, PFS
);
6611 case lltok::kw_load
:
6612 return parseLoad(Inst
, PFS
);
6613 case lltok::kw_store
:
6614 return parseStore(Inst
, PFS
);
6615 case lltok::kw_cmpxchg
:
6616 return parseCmpXchg(Inst
, PFS
);
6617 case lltok::kw_atomicrmw
:
6618 return parseAtomicRMW(Inst
, PFS
);
6619 case lltok::kw_fence
:
6620 return parseFence(Inst
, PFS
);
6621 case lltok::kw_getelementptr
:
6622 return parseGetElementPtr(Inst
, PFS
);
6623 case lltok::kw_extractvalue
:
6624 return parseExtractValue(Inst
, PFS
);
6625 case lltok::kw_insertvalue
:
6626 return parseInsertValue(Inst
, PFS
);
6630 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
6631 bool LLParser::parseCmpPredicate(unsigned &P
, unsigned Opc
) {
6632 if (Opc
== Instruction::FCmp
) {
6633 switch (Lex
.getKind()) {
6635 return tokError("expected fcmp predicate (e.g. 'oeq')");
6636 case lltok::kw_oeq
: P
= CmpInst::FCMP_OEQ
; break;
6637 case lltok::kw_one
: P
= CmpInst::FCMP_ONE
; break;
6638 case lltok::kw_olt
: P
= CmpInst::FCMP_OLT
; break;
6639 case lltok::kw_ogt
: P
= CmpInst::FCMP_OGT
; break;
6640 case lltok::kw_ole
: P
= CmpInst::FCMP_OLE
; break;
6641 case lltok::kw_oge
: P
= CmpInst::FCMP_OGE
; break;
6642 case lltok::kw_ord
: P
= CmpInst::FCMP_ORD
; break;
6643 case lltok::kw_uno
: P
= CmpInst::FCMP_UNO
; break;
6644 case lltok::kw_ueq
: P
= CmpInst::FCMP_UEQ
; break;
6645 case lltok::kw_une
: P
= CmpInst::FCMP_UNE
; break;
6646 case lltok::kw_ult
: P
= CmpInst::FCMP_ULT
; break;
6647 case lltok::kw_ugt
: P
= CmpInst::FCMP_UGT
; break;
6648 case lltok::kw_ule
: P
= CmpInst::FCMP_ULE
; break;
6649 case lltok::kw_uge
: P
= CmpInst::FCMP_UGE
; break;
6650 case lltok::kw_true
: P
= CmpInst::FCMP_TRUE
; break;
6651 case lltok::kw_false
: P
= CmpInst::FCMP_FALSE
; break;
6654 switch (Lex
.getKind()) {
6656 return tokError("expected icmp predicate (e.g. 'eq')");
6657 case lltok::kw_eq
: P
= CmpInst::ICMP_EQ
; break;
6658 case lltok::kw_ne
: P
= CmpInst::ICMP_NE
; break;
6659 case lltok::kw_slt
: P
= CmpInst::ICMP_SLT
; break;
6660 case lltok::kw_sgt
: P
= CmpInst::ICMP_SGT
; break;
6661 case lltok::kw_sle
: P
= CmpInst::ICMP_SLE
; break;
6662 case lltok::kw_sge
: P
= CmpInst::ICMP_SGE
; break;
6663 case lltok::kw_ult
: P
= CmpInst::ICMP_ULT
; break;
6664 case lltok::kw_ugt
: P
= CmpInst::ICMP_UGT
; break;
6665 case lltok::kw_ule
: P
= CmpInst::ICMP_ULE
; break;
6666 case lltok::kw_uge
: P
= CmpInst::ICMP_UGE
; break;
6673 //===----------------------------------------------------------------------===//
6674 // Terminator Instructions.
6675 //===----------------------------------------------------------------------===//
6677 /// parseRet - parse a return instruction.
6678 /// ::= 'ret' void (',' !dbg, !1)*
6679 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
6680 bool LLParser::parseRet(Instruction
*&Inst
, BasicBlock
*BB
,
6681 PerFunctionState
&PFS
) {
6682 SMLoc TypeLoc
= Lex
.getLoc();
6684 if (parseType(Ty
, true /*void allowed*/))
6687 Type
*ResType
= PFS
.getFunction().getReturnType();
6689 if (Ty
->isVoidTy()) {
6690 if (!ResType
->isVoidTy())
6691 return error(TypeLoc
, "value doesn't match function result type '" +
6692 getTypeString(ResType
) + "'");
6694 Inst
= ReturnInst::Create(Context
);
6699 if (parseValue(Ty
, RV
, PFS
))
6702 if (ResType
!= RV
->getType())
6703 return error(TypeLoc
, "value doesn't match function result type '" +
6704 getTypeString(ResType
) + "'");
6706 Inst
= ReturnInst::Create(Context
, RV
);
6711 /// ::= 'br' TypeAndValue
6712 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6713 bool LLParser::parseBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6716 BasicBlock
*Op1
, *Op2
;
6717 if (parseTypeAndValue(Op0
, Loc
, PFS
))
6720 if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(Op0
)) {
6721 Inst
= BranchInst::Create(BB
);
6725 if (Op0
->getType() != Type::getInt1Ty(Context
))
6726 return error(Loc
, "branch condition must have 'i1' type");
6728 if (parseToken(lltok::comma
, "expected ',' after branch condition") ||
6729 parseTypeAndBasicBlock(Op1
, Loc
, PFS
) ||
6730 parseToken(lltok::comma
, "expected ',' after true destination") ||
6731 parseTypeAndBasicBlock(Op2
, Loc2
, PFS
))
6734 Inst
= BranchInst::Create(Op1
, Op2
, Op0
);
6740 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6742 /// ::= (TypeAndValue ',' TypeAndValue)*
6743 bool LLParser::parseSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6744 LocTy CondLoc
, BBLoc
;
6746 BasicBlock
*DefaultBB
;
6747 if (parseTypeAndValue(Cond
, CondLoc
, PFS
) ||
6748 parseToken(lltok::comma
, "expected ',' after switch condition") ||
6749 parseTypeAndBasicBlock(DefaultBB
, BBLoc
, PFS
) ||
6750 parseToken(lltok::lsquare
, "expected '[' with switch table"))
6753 if (!Cond
->getType()->isIntegerTy())
6754 return error(CondLoc
, "switch condition must have integer type");
6756 // parse the jump table pairs.
6757 SmallPtrSet
<Value
*, 32> SeenCases
;
6758 SmallVector
<std::pair
<ConstantInt
*, BasicBlock
*>, 32> Table
;
6759 while (Lex
.getKind() != lltok::rsquare
) {
6763 if (parseTypeAndValue(Constant
, CondLoc
, PFS
) ||
6764 parseToken(lltok::comma
, "expected ',' after case value") ||
6765 parseTypeAndBasicBlock(DestBB
, PFS
))
6768 if (!SeenCases
.insert(Constant
).second
)
6769 return error(CondLoc
, "duplicate case value in switch");
6770 if (!isa
<ConstantInt
>(Constant
))
6771 return error(CondLoc
, "case value is not a constant integer");
6773 Table
.push_back(std::make_pair(cast
<ConstantInt
>(Constant
), DestBB
));
6776 Lex
.Lex(); // Eat the ']'.
6778 SwitchInst
*SI
= SwitchInst::Create(Cond
, DefaultBB
, Table
.size());
6779 for (unsigned i
= 0, e
= Table
.size(); i
!= e
; ++i
)
6780 SI
->addCase(Table
[i
].first
, Table
[i
].second
);
6787 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
6788 bool LLParser::parseIndirectBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6791 if (parseTypeAndValue(Address
, AddrLoc
, PFS
) ||
6792 parseToken(lltok::comma
, "expected ',' after indirectbr address") ||
6793 parseToken(lltok::lsquare
, "expected '[' with indirectbr"))
6796 if (!Address
->getType()->isPointerTy())
6797 return error(AddrLoc
, "indirectbr address must have pointer type");
6799 // parse the destination list.
6800 SmallVector
<BasicBlock
*, 16> DestList
;
6802 if (Lex
.getKind() != lltok::rsquare
) {
6804 if (parseTypeAndBasicBlock(DestBB
, PFS
))
6806 DestList
.push_back(DestBB
);
6808 while (EatIfPresent(lltok::comma
)) {
6809 if (parseTypeAndBasicBlock(DestBB
, PFS
))
6811 DestList
.push_back(DestBB
);
6815 if (parseToken(lltok::rsquare
, "expected ']' at end of block list"))
6818 IndirectBrInst
*IBI
= IndirectBrInst::Create(Address
, DestList
.size());
6819 for (unsigned i
= 0, e
= DestList
.size(); i
!= e
; ++i
)
6820 IBI
->addDestination(DestList
[i
]);
6825 // If RetType is a non-function pointer type, then this is the short syntax
6826 // for the call, which means that RetType is just the return type. Infer the
6827 // rest of the function argument types from the arguments that are present.
6828 bool LLParser::resolveFunctionType(Type
*RetType
,
6829 const SmallVector
<ParamInfo
, 16> &ArgList
,
6830 FunctionType
*&FuncTy
) {
6831 FuncTy
= dyn_cast
<FunctionType
>(RetType
);
6833 // Pull out the types of all of the arguments...
6834 std::vector
<Type
*> ParamTypes
;
6835 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
6836 ParamTypes
.push_back(ArgList
[i
].V
->getType());
6838 if (!FunctionType::isValidReturnType(RetType
))
6841 FuncTy
= FunctionType::get(RetType
, ParamTypes
, false);
6847 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6848 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6849 bool LLParser::parseInvoke(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6850 LocTy CallLoc
= Lex
.getLoc();
6851 AttrBuilder
RetAttrs(M
->getContext()), FnAttrs(M
->getContext());
6852 std::vector
<unsigned> FwdRefAttrGrps
;
6855 unsigned InvokeAddrSpace
;
6856 Type
*RetType
= nullptr;
6859 SmallVector
<ParamInfo
, 16> ArgList
;
6860 SmallVector
<OperandBundleDef
, 2> BundleList
;
6862 BasicBlock
*NormalBB
, *UnwindBB
;
6863 if (parseOptionalCallingConv(CC
) || parseOptionalReturnAttrs(RetAttrs
) ||
6864 parseOptionalProgramAddrSpace(InvokeAddrSpace
) ||
6865 parseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
6866 parseValID(CalleeID
, &PFS
) || parseParameterList(ArgList
, PFS
) ||
6867 parseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false,
6869 parseOptionalOperandBundles(BundleList
, PFS
) ||
6870 parseToken(lltok::kw_to
, "expected 'to' in invoke") ||
6871 parseTypeAndBasicBlock(NormalBB
, PFS
) ||
6872 parseToken(lltok::kw_unwind
, "expected 'unwind' in invoke") ||
6873 parseTypeAndBasicBlock(UnwindBB
, PFS
))
6876 // If RetType is a non-function pointer type, then this is the short syntax
6877 // for the call, which means that RetType is just the return type. Infer the
6878 // rest of the function argument types from the arguments that are present.
6880 if (resolveFunctionType(RetType
, ArgList
, Ty
))
6881 return error(RetTypeLoc
, "Invalid result type for LLVM function");
6885 // Look up the callee.
6887 if (convertValIDToValue(PointerType::get(Ty
, InvokeAddrSpace
), CalleeID
,
6891 // Set up the Attribute for the function.
6892 SmallVector
<Value
*, 8> Args
;
6893 SmallVector
<AttributeSet
, 8> ArgAttrs
;
6895 // Loop through FunctionType's arguments and ensure they are specified
6896 // correctly. Also, gather any parameter attributes.
6897 FunctionType::param_iterator I
= Ty
->param_begin();
6898 FunctionType::param_iterator E
= Ty
->param_end();
6899 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
6900 Type
*ExpectedTy
= nullptr;
6903 } else if (!Ty
->isVarArg()) {
6904 return error(ArgList
[i
].Loc
, "too many arguments specified");
6907 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
6908 return error(ArgList
[i
].Loc
, "argument is not of expected type '" +
6909 getTypeString(ExpectedTy
) + "'");
6910 Args
.push_back(ArgList
[i
].V
);
6911 ArgAttrs
.push_back(ArgList
[i
].Attrs
);
6915 return error(CallLoc
, "not enough parameters specified for call");
6917 // Finish off the Attribute and check them
6919 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
6920 AttributeSet::get(Context
, RetAttrs
), ArgAttrs
);
6923 InvokeInst::Create(Ty
, Callee
, NormalBB
, UnwindBB
, Args
, BundleList
);
6924 II
->setCallingConv(CC
);
6925 II
->setAttributes(PAL
);
6926 ForwardRefAttrGroups
[II
] = FwdRefAttrGrps
;
6932 /// ::= 'resume' TypeAndValue
6933 bool LLParser::parseResume(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6934 Value
*Exn
; LocTy ExnLoc
;
6935 if (parseTypeAndValue(Exn
, ExnLoc
, PFS
))
6938 ResumeInst
*RI
= ResumeInst::Create(Exn
);
6943 bool LLParser::parseExceptionArgs(SmallVectorImpl
<Value
*> &Args
,
6944 PerFunctionState
&PFS
) {
6945 if (parseToken(lltok::lsquare
, "expected '[' in catchpad/cleanuppad"))
6948 while (Lex
.getKind() != lltok::rsquare
) {
6949 // If this isn't the first argument, we need a comma.
6950 if (!Args
.empty() &&
6951 parseToken(lltok::comma
, "expected ',' in argument list"))
6954 // parse the argument.
6956 Type
*ArgTy
= nullptr;
6957 if (parseType(ArgTy
, ArgLoc
))
6961 if (ArgTy
->isMetadataTy()) {
6962 if (parseMetadataAsValue(V
, PFS
))
6965 if (parseValue(ArgTy
, V
, PFS
))
6971 Lex
.Lex(); // Lex the ']'.
6976 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6977 bool LLParser::parseCleanupRet(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6978 Value
*CleanupPad
= nullptr;
6980 if (parseToken(lltok::kw_from
, "expected 'from' after cleanupret"))
6983 if (parseValue(Type::getTokenTy(Context
), CleanupPad
, PFS
))
6986 if (parseToken(lltok::kw_unwind
, "expected 'unwind' in cleanupret"))
6989 BasicBlock
*UnwindBB
= nullptr;
6990 if (Lex
.getKind() == lltok::kw_to
) {
6992 if (parseToken(lltok::kw_caller
, "expected 'caller' in cleanupret"))
6995 if (parseTypeAndBasicBlock(UnwindBB
, PFS
)) {
7000 Inst
= CleanupReturnInst::Create(CleanupPad
, UnwindBB
);
7005 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
7006 bool LLParser::parseCatchRet(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7007 Value
*CatchPad
= nullptr;
7009 if (parseToken(lltok::kw_from
, "expected 'from' after catchret"))
7012 if (parseValue(Type::getTokenTy(Context
), CatchPad
, PFS
))
7016 if (parseToken(lltok::kw_to
, "expected 'to' in catchret") ||
7017 parseTypeAndBasicBlock(BB
, PFS
))
7020 Inst
= CatchReturnInst::Create(CatchPad
, BB
);
7024 /// parseCatchSwitch
7025 /// ::= 'catchswitch' within Parent
7026 bool LLParser::parseCatchSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7029 if (parseToken(lltok::kw_within
, "expected 'within' after catchswitch"))
7032 if (Lex
.getKind() != lltok::kw_none
&& Lex
.getKind() != lltok::LocalVar
&&
7033 Lex
.getKind() != lltok::LocalVarID
)
7034 return tokError("expected scope value for catchswitch");
7036 if (parseValue(Type::getTokenTy(Context
), ParentPad
, PFS
))
7039 if (parseToken(lltok::lsquare
, "expected '[' with catchswitch labels"))
7042 SmallVector
<BasicBlock
*, 32> Table
;
7045 if (parseTypeAndBasicBlock(DestBB
, PFS
))
7047 Table
.push_back(DestBB
);
7048 } while (EatIfPresent(lltok::comma
));
7050 if (parseToken(lltok::rsquare
, "expected ']' after catchswitch labels"))
7053 if (parseToken(lltok::kw_unwind
, "expected 'unwind' after catchswitch scope"))
7056 BasicBlock
*UnwindBB
= nullptr;
7057 if (EatIfPresent(lltok::kw_to
)) {
7058 if (parseToken(lltok::kw_caller
, "expected 'caller' in catchswitch"))
7061 if (parseTypeAndBasicBlock(UnwindBB
, PFS
))
7066 CatchSwitchInst::Create(ParentPad
, UnwindBB
, Table
.size());
7067 for (BasicBlock
*DestBB
: Table
)
7068 CatchSwitch
->addHandler(DestBB
);
7074 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
7075 bool LLParser::parseCatchPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7076 Value
*CatchSwitch
= nullptr;
7078 if (parseToken(lltok::kw_within
, "expected 'within' after catchpad"))
7081 if (Lex
.getKind() != lltok::LocalVar
&& Lex
.getKind() != lltok::LocalVarID
)
7082 return tokError("expected scope value for catchpad");
7084 if (parseValue(Type::getTokenTy(Context
), CatchSwitch
, PFS
))
7087 SmallVector
<Value
*, 8> Args
;
7088 if (parseExceptionArgs(Args
, PFS
))
7091 Inst
= CatchPadInst::Create(CatchSwitch
, Args
);
7096 /// ::= 'cleanuppad' within Parent ParamList
7097 bool LLParser::parseCleanupPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7098 Value
*ParentPad
= nullptr;
7100 if (parseToken(lltok::kw_within
, "expected 'within' after cleanuppad"))
7103 if (Lex
.getKind() != lltok::kw_none
&& Lex
.getKind() != lltok::LocalVar
&&
7104 Lex
.getKind() != lltok::LocalVarID
)
7105 return tokError("expected scope value for cleanuppad");
7107 if (parseValue(Type::getTokenTy(Context
), ParentPad
, PFS
))
7110 SmallVector
<Value
*, 8> Args
;
7111 if (parseExceptionArgs(Args
, PFS
))
7114 Inst
= CleanupPadInst::Create(ParentPad
, Args
);
7118 //===----------------------------------------------------------------------===//
7120 //===----------------------------------------------------------------------===//
7123 /// ::= UnaryOp TypeAndValue ',' Value
7125 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7126 /// operand is allowed.
7127 bool LLParser::parseUnaryOp(Instruction
*&Inst
, PerFunctionState
&PFS
,
7128 unsigned Opc
, bool IsFP
) {
7129 LocTy Loc
; Value
*LHS
;
7130 if (parseTypeAndValue(LHS
, Loc
, PFS
))
7133 bool Valid
= IsFP
? LHS
->getType()->isFPOrFPVectorTy()
7134 : LHS
->getType()->isIntOrIntVectorTy();
7137 return error(Loc
, "invalid operand type for instruction");
7139 Inst
= UnaryOperator::Create((Instruction::UnaryOps
)Opc
, LHS
);
7144 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
7145 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
7146 /// '[' LabelList ']'
7147 bool LLParser::parseCallBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7148 LocTy CallLoc
= Lex
.getLoc();
7149 AttrBuilder
RetAttrs(M
->getContext()), FnAttrs(M
->getContext());
7150 std::vector
<unsigned> FwdRefAttrGrps
;
7153 Type
*RetType
= nullptr;
7156 SmallVector
<ParamInfo
, 16> ArgList
;
7157 SmallVector
<OperandBundleDef
, 2> BundleList
;
7159 BasicBlock
*DefaultDest
;
7160 if (parseOptionalCallingConv(CC
) || parseOptionalReturnAttrs(RetAttrs
) ||
7161 parseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
7162 parseValID(CalleeID
, &PFS
) || parseParameterList(ArgList
, PFS
) ||
7163 parseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false,
7165 parseOptionalOperandBundles(BundleList
, PFS
) ||
7166 parseToken(lltok::kw_to
, "expected 'to' in callbr") ||
7167 parseTypeAndBasicBlock(DefaultDest
, PFS
) ||
7168 parseToken(lltok::lsquare
, "expected '[' in callbr"))
7171 // parse the destination list.
7172 SmallVector
<BasicBlock
*, 16> IndirectDests
;
7174 if (Lex
.getKind() != lltok::rsquare
) {
7176 if (parseTypeAndBasicBlock(DestBB
, PFS
))
7178 IndirectDests
.push_back(DestBB
);
7180 while (EatIfPresent(lltok::comma
)) {
7181 if (parseTypeAndBasicBlock(DestBB
, PFS
))
7183 IndirectDests
.push_back(DestBB
);
7187 if (parseToken(lltok::rsquare
, "expected ']' at end of block list"))
7190 // If RetType is a non-function pointer type, then this is the short syntax
7191 // for the call, which means that RetType is just the return type. Infer the
7192 // rest of the function argument types from the arguments that are present.
7194 if (resolveFunctionType(RetType
, ArgList
, Ty
))
7195 return error(RetTypeLoc
, "Invalid result type for LLVM function");
7199 // Look up the callee.
7201 if (convertValIDToValue(PointerType::getUnqual(Ty
), CalleeID
, Callee
, &PFS
))
7204 // Set up the Attribute for the function.
7205 SmallVector
<Value
*, 8> Args
;
7206 SmallVector
<AttributeSet
, 8> ArgAttrs
;
7208 // Loop through FunctionType's arguments and ensure they are specified
7209 // correctly. Also, gather any parameter attributes.
7210 FunctionType::param_iterator I
= Ty
->param_begin();
7211 FunctionType::param_iterator E
= Ty
->param_end();
7212 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
7213 Type
*ExpectedTy
= nullptr;
7216 } else if (!Ty
->isVarArg()) {
7217 return error(ArgList
[i
].Loc
, "too many arguments specified");
7220 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
7221 return error(ArgList
[i
].Loc
, "argument is not of expected type '" +
7222 getTypeString(ExpectedTy
) + "'");
7223 Args
.push_back(ArgList
[i
].V
);
7224 ArgAttrs
.push_back(ArgList
[i
].Attrs
);
7228 return error(CallLoc
, "not enough parameters specified for call");
7230 // Finish off the Attribute and check them
7232 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
7233 AttributeSet::get(Context
, RetAttrs
), ArgAttrs
);
7236 CallBrInst::Create(Ty
, Callee
, DefaultDest
, IndirectDests
, Args
,
7238 CBI
->setCallingConv(CC
);
7239 CBI
->setAttributes(PAL
);
7240 ForwardRefAttrGroups
[CBI
] = FwdRefAttrGrps
;
7245 //===----------------------------------------------------------------------===//
7246 // Binary Operators.
7247 //===----------------------------------------------------------------------===//
7250 /// ::= ArithmeticOps TypeAndValue ',' Value
7252 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
7253 /// operand is allowed.
7254 bool LLParser::parseArithmetic(Instruction
*&Inst
, PerFunctionState
&PFS
,
7255 unsigned Opc
, bool IsFP
) {
7256 LocTy Loc
; Value
*LHS
, *RHS
;
7257 if (parseTypeAndValue(LHS
, Loc
, PFS
) ||
7258 parseToken(lltok::comma
, "expected ',' in arithmetic operation") ||
7259 parseValue(LHS
->getType(), RHS
, PFS
))
7262 bool Valid
= IsFP
? LHS
->getType()->isFPOrFPVectorTy()
7263 : LHS
->getType()->isIntOrIntVectorTy();
7266 return error(Loc
, "invalid operand type for instruction");
7268 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
7273 /// ::= ArithmeticOps TypeAndValue ',' Value {
7274 bool LLParser::parseLogical(Instruction
*&Inst
, PerFunctionState
&PFS
,
7276 LocTy Loc
; Value
*LHS
, *RHS
;
7277 if (parseTypeAndValue(LHS
, Loc
, PFS
) ||
7278 parseToken(lltok::comma
, "expected ',' in logical operation") ||
7279 parseValue(LHS
->getType(), RHS
, PFS
))
7282 if (!LHS
->getType()->isIntOrIntVectorTy())
7284 "instruction requires integer or integer vector operands");
7286 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
7291 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
7292 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
7293 bool LLParser::parseCompare(Instruction
*&Inst
, PerFunctionState
&PFS
,
7295 // parse the integer/fp comparison predicate.
7299 if (parseCmpPredicate(Pred
, Opc
) || parseTypeAndValue(LHS
, Loc
, PFS
) ||
7300 parseToken(lltok::comma
, "expected ',' after compare value") ||
7301 parseValue(LHS
->getType(), RHS
, PFS
))
7304 if (Opc
== Instruction::FCmp
) {
7305 if (!LHS
->getType()->isFPOrFPVectorTy())
7306 return error(Loc
, "fcmp requires floating point operands");
7307 Inst
= new FCmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
7309 assert(Opc
== Instruction::ICmp
&& "Unknown opcode for CmpInst!");
7310 if (!LHS
->getType()->isIntOrIntVectorTy() &&
7311 !LHS
->getType()->isPtrOrPtrVectorTy())
7312 return error(Loc
, "icmp requires integer operands");
7313 Inst
= new ICmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
7318 //===----------------------------------------------------------------------===//
7319 // Other Instructions.
7320 //===----------------------------------------------------------------------===//
7323 /// ::= CastOpc TypeAndValue 'to' Type
7324 bool LLParser::parseCast(Instruction
*&Inst
, PerFunctionState
&PFS
,
7328 Type
*DestTy
= nullptr;
7329 if (parseTypeAndValue(Op
, Loc
, PFS
) ||
7330 parseToken(lltok::kw_to
, "expected 'to' after cast value") ||
7334 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
)) {
7335 CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
);
7336 return error(Loc
, "invalid cast opcode for cast from '" +
7337 getTypeString(Op
->getType()) + "' to '" +
7338 getTypeString(DestTy
) + "'");
7340 Inst
= CastInst::Create((Instruction::CastOps
)Opc
, Op
, DestTy
);
7345 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7346 bool LLParser::parseSelect(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7348 Value
*Op0
, *Op1
, *Op2
;
7349 if (parseTypeAndValue(Op0
, Loc
, PFS
) ||
7350 parseToken(lltok::comma
, "expected ',' after select condition") ||
7351 parseTypeAndValue(Op1
, PFS
) ||
7352 parseToken(lltok::comma
, "expected ',' after select value") ||
7353 parseTypeAndValue(Op2
, PFS
))
7356 if (const char *Reason
= SelectInst::areInvalidOperands(Op0
, Op1
, Op2
))
7357 return error(Loc
, Reason
);
7359 Inst
= SelectInst::Create(Op0
, Op1
, Op2
);
7364 /// ::= 'va_arg' TypeAndValue ',' Type
7365 bool LLParser::parseVAArg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7367 Type
*EltTy
= nullptr;
7369 if (parseTypeAndValue(Op
, PFS
) ||
7370 parseToken(lltok::comma
, "expected ',' after vaarg operand") ||
7371 parseType(EltTy
, TypeLoc
))
7374 if (!EltTy
->isFirstClassType())
7375 return error(TypeLoc
, "va_arg requires operand with first class type");
7377 Inst
= new VAArgInst(Op
, EltTy
);
7381 /// parseExtractElement
7382 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
7383 bool LLParser::parseExtractElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7386 if (parseTypeAndValue(Op0
, Loc
, PFS
) ||
7387 parseToken(lltok::comma
, "expected ',' after extract value") ||
7388 parseTypeAndValue(Op1
, PFS
))
7391 if (!ExtractElementInst::isValidOperands(Op0
, Op1
))
7392 return error(Loc
, "invalid extractelement operands");
7394 Inst
= ExtractElementInst::Create(Op0
, Op1
);
7398 /// parseInsertElement
7399 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7400 bool LLParser::parseInsertElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7402 Value
*Op0
, *Op1
, *Op2
;
7403 if (parseTypeAndValue(Op0
, Loc
, PFS
) ||
7404 parseToken(lltok::comma
, "expected ',' after insertelement value") ||
7405 parseTypeAndValue(Op1
, PFS
) ||
7406 parseToken(lltok::comma
, "expected ',' after insertelement value") ||
7407 parseTypeAndValue(Op2
, PFS
))
7410 if (!InsertElementInst::isValidOperands(Op0
, Op1
, Op2
))
7411 return error(Loc
, "invalid insertelement operands");
7413 Inst
= InsertElementInst::Create(Op0
, Op1
, Op2
);
7417 /// parseShuffleVector
7418 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
7419 bool LLParser::parseShuffleVector(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7421 Value
*Op0
, *Op1
, *Op2
;
7422 if (parseTypeAndValue(Op0
, Loc
, PFS
) ||
7423 parseToken(lltok::comma
, "expected ',' after shuffle mask") ||
7424 parseTypeAndValue(Op1
, PFS
) ||
7425 parseToken(lltok::comma
, "expected ',' after shuffle value") ||
7426 parseTypeAndValue(Op2
, PFS
))
7429 if (!ShuffleVectorInst::isValidOperands(Op0
, Op1
, Op2
))
7430 return error(Loc
, "invalid shufflevector operands");
7432 Inst
= new ShuffleVectorInst(Op0
, Op1
, Op2
);
7437 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
7438 int LLParser::parsePHI(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7439 Type
*Ty
= nullptr; LocTy TypeLoc
;
7442 if (parseType(Ty
, TypeLoc
))
7445 if (!Ty
->isFirstClassType())
7446 return error(TypeLoc
, "phi node must have first class type");
7449 bool AteExtraComma
= false;
7450 SmallVector
<std::pair
<Value
*, BasicBlock
*>, 16> PHIVals
;
7454 if (Lex
.getKind() != lltok::lsquare
)
7457 } else if (!EatIfPresent(lltok::comma
))
7460 if (Lex
.getKind() == lltok::MetadataVar
) {
7461 AteExtraComma
= true;
7465 if (parseToken(lltok::lsquare
, "expected '[' in phi value list") ||
7466 parseValue(Ty
, Op0
, PFS
) ||
7467 parseToken(lltok::comma
, "expected ',' after insertelement value") ||
7468 parseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
7469 parseToken(lltok::rsquare
, "expected ']' in phi value list"))
7472 PHIVals
.push_back(std::make_pair(Op0
, cast
<BasicBlock
>(Op1
)));
7475 PHINode
*PN
= PHINode::Create(Ty
, PHIVals
.size());
7476 for (unsigned i
= 0, e
= PHIVals
.size(); i
!= e
; ++i
)
7477 PN
->addIncoming(PHIVals
[i
].first
, PHIVals
[i
].second
);
7479 return AteExtraComma
? InstExtraComma
: InstNormal
;
7483 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7485 /// ::= 'catch' TypeAndValue
7487 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
7488 bool LLParser::parseLandingPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7489 Type
*Ty
= nullptr; LocTy TyLoc
;
7491 if (parseType(Ty
, TyLoc
))
7494 std::unique_ptr
<LandingPadInst
> LP(LandingPadInst::Create(Ty
, 0));
7495 LP
->setCleanup(EatIfPresent(lltok::kw_cleanup
));
7497 while (Lex
.getKind() == lltok::kw_catch
|| Lex
.getKind() == lltok::kw_filter
){
7498 LandingPadInst::ClauseType CT
;
7499 if (EatIfPresent(lltok::kw_catch
))
7500 CT
= LandingPadInst::Catch
;
7501 else if (EatIfPresent(lltok::kw_filter
))
7502 CT
= LandingPadInst::Filter
;
7504 return tokError("expected 'catch' or 'filter' clause type");
7508 if (parseTypeAndValue(V
, VLoc
, PFS
))
7511 // A 'catch' type expects a non-array constant. A filter clause expects an
7513 if (CT
== LandingPadInst::Catch
) {
7514 if (isa
<ArrayType
>(V
->getType()))
7515 error(VLoc
, "'catch' clause has an invalid type");
7517 if (!isa
<ArrayType
>(V
->getType()))
7518 error(VLoc
, "'filter' clause has an invalid type");
7521 Constant
*CV
= dyn_cast
<Constant
>(V
);
7523 return error(VLoc
, "clause argument must be a constant");
7527 Inst
= LP
.release();
7532 /// ::= 'freeze' Type Value
7533 bool LLParser::parseFreeze(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7536 if (parseTypeAndValue(Op
, Loc
, PFS
))
7539 Inst
= new FreezeInst(Op
);
7544 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
7545 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7546 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7547 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7548 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7549 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7550 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
7551 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7552 bool LLParser::parseCall(Instruction
*&Inst
, PerFunctionState
&PFS
,
7553 CallInst::TailCallKind TCK
) {
7554 AttrBuilder
RetAttrs(M
->getContext()), FnAttrs(M
->getContext());
7555 std::vector
<unsigned> FwdRefAttrGrps
;
7557 unsigned CallAddrSpace
;
7559 Type
*RetType
= nullptr;
7562 SmallVector
<ParamInfo
, 16> ArgList
;
7563 SmallVector
<OperandBundleDef
, 2> BundleList
;
7564 LocTy CallLoc
= Lex
.getLoc();
7566 if (TCK
!= CallInst::TCK_None
&&
7567 parseToken(lltok::kw_call
,
7568 "expected 'tail call', 'musttail call', or 'notail call'"))
7571 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
7573 if (parseOptionalCallingConv(CC
) || parseOptionalReturnAttrs(RetAttrs
) ||
7574 parseOptionalProgramAddrSpace(CallAddrSpace
) ||
7575 parseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
7576 parseValID(CalleeID
, &PFS
) ||
7577 parseParameterList(ArgList
, PFS
, TCK
== CallInst::TCK_MustTail
,
7578 PFS
.getFunction().isVarArg()) ||
7579 parseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false, BuiltinLoc
) ||
7580 parseOptionalOperandBundles(BundleList
, PFS
))
7583 // If RetType is a non-function pointer type, then this is the short syntax
7584 // for the call, which means that RetType is just the return type. Infer the
7585 // rest of the function argument types from the arguments that are present.
7587 if (resolveFunctionType(RetType
, ArgList
, Ty
))
7588 return error(RetTypeLoc
, "Invalid result type for LLVM function");
7592 // Look up the callee.
7594 if (convertValIDToValue(PointerType::get(Ty
, CallAddrSpace
), CalleeID
, Callee
,
7598 // Set up the Attribute for the function.
7599 SmallVector
<AttributeSet
, 8> Attrs
;
7601 SmallVector
<Value
*, 8> Args
;
7603 // Loop through FunctionType's arguments and ensure they are specified
7604 // correctly. Also, gather any parameter attributes.
7605 FunctionType::param_iterator I
= Ty
->param_begin();
7606 FunctionType::param_iterator E
= Ty
->param_end();
7607 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
7608 Type
*ExpectedTy
= nullptr;
7611 } else if (!Ty
->isVarArg()) {
7612 return error(ArgList
[i
].Loc
, "too many arguments specified");
7615 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
7616 return error(ArgList
[i
].Loc
, "argument is not of expected type '" +
7617 getTypeString(ExpectedTy
) + "'");
7618 Args
.push_back(ArgList
[i
].V
);
7619 Attrs
.push_back(ArgList
[i
].Attrs
);
7623 return error(CallLoc
, "not enough parameters specified for call");
7625 // Finish off the Attribute and check them
7627 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
7628 AttributeSet::get(Context
, RetAttrs
), Attrs
);
7630 CallInst
*CI
= CallInst::Create(Ty
, Callee
, Args
, BundleList
);
7631 CI
->setTailCallKind(TCK
);
7632 CI
->setCallingConv(CC
);
7634 if (!isa
<FPMathOperator
>(CI
)) {
7636 return error(CallLoc
, "fast-math-flags specified for call without "
7637 "floating-point scalar or vector return type");
7639 CI
->setFastMathFlags(FMF
);
7641 CI
->setAttributes(PAL
);
7642 ForwardRefAttrGroups
[CI
] = FwdRefAttrGrps
;
7647 //===----------------------------------------------------------------------===//
7648 // Memory Instructions.
7649 //===----------------------------------------------------------------------===//
7652 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7653 /// (',' 'align' i32)? (',', 'addrspace(n))?
7654 int LLParser::parseAlloc(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7655 Value
*Size
= nullptr;
7656 LocTy SizeLoc
, TyLoc
, ASLoc
;
7657 MaybeAlign Alignment
;
7658 unsigned AddrSpace
= 0;
7661 bool IsInAlloca
= EatIfPresent(lltok::kw_inalloca
);
7662 bool IsSwiftError
= EatIfPresent(lltok::kw_swifterror
);
7664 if (parseType(Ty
, TyLoc
))
7667 if (Ty
->isFunctionTy() || !PointerType::isValidElementType(Ty
))
7668 return error(TyLoc
, "invalid type for alloca");
7670 bool AteExtraComma
= false;
7671 if (EatIfPresent(lltok::comma
)) {
7672 if (Lex
.getKind() == lltok::kw_align
) {
7673 if (parseOptionalAlignment(Alignment
))
7675 if (parseOptionalCommaAddrSpace(AddrSpace
, ASLoc
, AteExtraComma
))
7677 } else if (Lex
.getKind() == lltok::kw_addrspace
) {
7678 ASLoc
= Lex
.getLoc();
7679 if (parseOptionalAddrSpace(AddrSpace
))
7681 } else if (Lex
.getKind() == lltok::MetadataVar
) {
7682 AteExtraComma
= true;
7684 if (parseTypeAndValue(Size
, SizeLoc
, PFS
))
7686 if (EatIfPresent(lltok::comma
)) {
7687 if (Lex
.getKind() == lltok::kw_align
) {
7688 if (parseOptionalAlignment(Alignment
))
7690 if (parseOptionalCommaAddrSpace(AddrSpace
, ASLoc
, AteExtraComma
))
7692 } else if (Lex
.getKind() == lltok::kw_addrspace
) {
7693 ASLoc
= Lex
.getLoc();
7694 if (parseOptionalAddrSpace(AddrSpace
))
7696 } else if (Lex
.getKind() == lltok::MetadataVar
) {
7697 AteExtraComma
= true;
7703 if (Size
&& !Size
->getType()->isIntegerTy())
7704 return error(SizeLoc
, "element count must have integer type");
7706 SmallPtrSet
<Type
*, 4> Visited
;
7707 if (!Alignment
&& !Ty
->isSized(&Visited
))
7708 return error(TyLoc
, "Cannot allocate unsized type");
7710 Alignment
= M
->getDataLayout().getPrefTypeAlign(Ty
);
7711 AllocaInst
*AI
= new AllocaInst(Ty
, AddrSpace
, Size
, *Alignment
);
7712 AI
->setUsedWithInAlloca(IsInAlloca
);
7713 AI
->setSwiftError(IsSwiftError
);
7715 return AteExtraComma
? InstExtraComma
: InstNormal
;
7719 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7720 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
7721 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7722 int LLParser::parseLoad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7723 Value
*Val
; LocTy Loc
;
7724 MaybeAlign Alignment
;
7725 bool AteExtraComma
= false;
7726 bool isAtomic
= false;
7727 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7728 SyncScope::ID SSID
= SyncScope::System
;
7730 if (Lex
.getKind() == lltok::kw_atomic
) {
7735 bool isVolatile
= false;
7736 if (Lex
.getKind() == lltok::kw_volatile
) {
7742 LocTy ExplicitTypeLoc
= Lex
.getLoc();
7743 if (parseType(Ty
) ||
7744 parseToken(lltok::comma
, "expected comma after load's type") ||
7745 parseTypeAndValue(Val
, Loc
, PFS
) ||
7746 parseScopeAndOrdering(isAtomic
, SSID
, Ordering
) ||
7747 parseOptionalCommaAlign(Alignment
, AteExtraComma
))
7750 if (!Val
->getType()->isPointerTy() || !Ty
->isFirstClassType())
7751 return error(Loc
, "load operand must be a pointer to a first class type");
7752 if (isAtomic
&& !Alignment
)
7753 return error(Loc
, "atomic load must have explicit non-zero alignment");
7754 if (Ordering
== AtomicOrdering::Release
||
7755 Ordering
== AtomicOrdering::AcquireRelease
)
7756 return error(Loc
, "atomic load cannot use Release ordering");
7758 SmallPtrSet
<Type
*, 4> Visited
;
7759 if (!Alignment
&& !Ty
->isSized(&Visited
))
7760 return error(ExplicitTypeLoc
, "loading unsized types is not allowed");
7762 Alignment
= M
->getDataLayout().getABITypeAlign(Ty
);
7763 Inst
= new LoadInst(Ty
, Val
, "", isVolatile
, *Alignment
, Ordering
, SSID
);
7764 return AteExtraComma
? InstExtraComma
: InstNormal
;
7769 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7770 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7771 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7772 int LLParser::parseStore(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7773 Value
*Val
, *Ptr
; LocTy Loc
, PtrLoc
;
7774 MaybeAlign Alignment
;
7775 bool AteExtraComma
= false;
7776 bool isAtomic
= false;
7777 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7778 SyncScope::ID SSID
= SyncScope::System
;
7780 if (Lex
.getKind() == lltok::kw_atomic
) {
7785 bool isVolatile
= false;
7786 if (Lex
.getKind() == lltok::kw_volatile
) {
7791 if (parseTypeAndValue(Val
, Loc
, PFS
) ||
7792 parseToken(lltok::comma
, "expected ',' after store operand") ||
7793 parseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
7794 parseScopeAndOrdering(isAtomic
, SSID
, Ordering
) ||
7795 parseOptionalCommaAlign(Alignment
, AteExtraComma
))
7798 if (!Ptr
->getType()->isPointerTy())
7799 return error(PtrLoc
, "store operand must be a pointer");
7800 if (!Val
->getType()->isFirstClassType())
7801 return error(Loc
, "store operand must be a first class value");
7802 if (isAtomic
&& !Alignment
)
7803 return error(Loc
, "atomic store must have explicit non-zero alignment");
7804 if (Ordering
== AtomicOrdering::Acquire
||
7805 Ordering
== AtomicOrdering::AcquireRelease
)
7806 return error(Loc
, "atomic store cannot use Acquire ordering");
7807 SmallPtrSet
<Type
*, 4> Visited
;
7808 if (!Alignment
&& !Val
->getType()->isSized(&Visited
))
7809 return error(Loc
, "storing unsized types is not allowed");
7811 Alignment
= M
->getDataLayout().getABITypeAlign(Val
->getType());
7813 Inst
= new StoreInst(Val
, Ptr
, isVolatile
, *Alignment
, Ordering
, SSID
);
7814 return AteExtraComma
? InstExtraComma
: InstNormal
;
7818 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7819 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
7821 int LLParser::parseCmpXchg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7822 Value
*Ptr
, *Cmp
, *New
; LocTy PtrLoc
, CmpLoc
, NewLoc
;
7823 bool AteExtraComma
= false;
7824 AtomicOrdering SuccessOrdering
= AtomicOrdering::NotAtomic
;
7825 AtomicOrdering FailureOrdering
= AtomicOrdering::NotAtomic
;
7826 SyncScope::ID SSID
= SyncScope::System
;
7827 bool isVolatile
= false;
7828 bool isWeak
= false;
7829 MaybeAlign Alignment
;
7831 if (EatIfPresent(lltok::kw_weak
))
7834 if (EatIfPresent(lltok::kw_volatile
))
7837 if (parseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
7838 parseToken(lltok::comma
, "expected ',' after cmpxchg address") ||
7839 parseTypeAndValue(Cmp
, CmpLoc
, PFS
) ||
7840 parseToken(lltok::comma
, "expected ',' after cmpxchg cmp operand") ||
7841 parseTypeAndValue(New
, NewLoc
, PFS
) ||
7842 parseScopeAndOrdering(true /*Always atomic*/, SSID
, SuccessOrdering
) ||
7843 parseOrdering(FailureOrdering
) ||
7844 parseOptionalCommaAlign(Alignment
, AteExtraComma
))
7847 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering
))
7848 return tokError("invalid cmpxchg success ordering");
7849 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering
))
7850 return tokError("invalid cmpxchg failure ordering");
7851 if (!Ptr
->getType()->isPointerTy())
7852 return error(PtrLoc
, "cmpxchg operand must be a pointer");
7853 if (Cmp
->getType() != New
->getType())
7854 return error(NewLoc
, "compare value and new value type do not match");
7855 if (!New
->getType()->isFirstClassType())
7856 return error(NewLoc
, "cmpxchg operand must be a first class value");
7858 const Align
DefaultAlignment(
7859 PFS
.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7862 AtomicCmpXchgInst
*CXI
=
7863 new AtomicCmpXchgInst(Ptr
, Cmp
, New
, Alignment
.value_or(DefaultAlignment
),
7864 SuccessOrdering
, FailureOrdering
, SSID
);
7865 CXI
->setVolatile(isVolatile
);
7866 CXI
->setWeak(isWeak
);
7869 return AteExtraComma
? InstExtraComma
: InstNormal
;
7873 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7874 /// 'singlethread'? AtomicOrdering
7875 int LLParser::parseAtomicRMW(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7876 Value
*Ptr
, *Val
; LocTy PtrLoc
, ValLoc
;
7877 bool AteExtraComma
= false;
7878 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7879 SyncScope::ID SSID
= SyncScope::System
;
7880 bool isVolatile
= false;
7882 AtomicRMWInst::BinOp Operation
;
7883 MaybeAlign Alignment
;
7885 if (EatIfPresent(lltok::kw_volatile
))
7888 switch (Lex
.getKind()) {
7890 return tokError("expected binary operation in atomicrmw");
7891 case lltok::kw_xchg
: Operation
= AtomicRMWInst::Xchg
; break;
7892 case lltok::kw_add
: Operation
= AtomicRMWInst::Add
; break;
7893 case lltok::kw_sub
: Operation
= AtomicRMWInst::Sub
; break;
7894 case lltok::kw_and
: Operation
= AtomicRMWInst::And
; break;
7895 case lltok::kw_nand
: Operation
= AtomicRMWInst::Nand
; break;
7896 case lltok::kw_or
: Operation
= AtomicRMWInst::Or
; break;
7897 case lltok::kw_xor
: Operation
= AtomicRMWInst::Xor
; break;
7898 case lltok::kw_max
: Operation
= AtomicRMWInst::Max
; break;
7899 case lltok::kw_min
: Operation
= AtomicRMWInst::Min
; break;
7900 case lltok::kw_umax
: Operation
= AtomicRMWInst::UMax
; break;
7901 case lltok::kw_umin
: Operation
= AtomicRMWInst::UMin
; break;
7902 case lltok::kw_uinc_wrap
:
7903 Operation
= AtomicRMWInst::UIncWrap
;
7905 case lltok::kw_udec_wrap
:
7906 Operation
= AtomicRMWInst::UDecWrap
;
7908 case lltok::kw_fadd
:
7909 Operation
= AtomicRMWInst::FAdd
;
7912 case lltok::kw_fsub
:
7913 Operation
= AtomicRMWInst::FSub
;
7916 case lltok::kw_fmax
:
7917 Operation
= AtomicRMWInst::FMax
;
7920 case lltok::kw_fmin
:
7921 Operation
= AtomicRMWInst::FMin
;
7925 Lex
.Lex(); // Eat the operation.
7927 if (parseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
7928 parseToken(lltok::comma
, "expected ',' after atomicrmw address") ||
7929 parseTypeAndValue(Val
, ValLoc
, PFS
) ||
7930 parseScopeAndOrdering(true /*Always atomic*/, SSID
, Ordering
) ||
7931 parseOptionalCommaAlign(Alignment
, AteExtraComma
))
7934 if (Ordering
== AtomicOrdering::Unordered
)
7935 return tokError("atomicrmw cannot be unordered");
7936 if (!Ptr
->getType()->isPointerTy())
7937 return error(PtrLoc
, "atomicrmw operand must be a pointer");
7939 if (Operation
== AtomicRMWInst::Xchg
) {
7940 if (!Val
->getType()->isIntegerTy() &&
7941 !Val
->getType()->isFloatingPointTy() &&
7942 !Val
->getType()->isPointerTy()) {
7945 "atomicrmw " + AtomicRMWInst::getOperationName(Operation
) +
7946 " operand must be an integer, floating point, or pointer type");
7949 if (!Val
->getType()->isFloatingPointTy()) {
7950 return error(ValLoc
, "atomicrmw " +
7951 AtomicRMWInst::getOperationName(Operation
) +
7952 " operand must be a floating point type");
7955 if (!Val
->getType()->isIntegerTy()) {
7956 return error(ValLoc
, "atomicrmw " +
7957 AtomicRMWInst::getOperationName(Operation
) +
7958 " operand must be an integer");
7963 PFS
.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
7965 if (Size
< 8 || (Size
& (Size
- 1)))
7966 return error(ValLoc
, "atomicrmw operand must be power-of-two byte-sized"
7968 const Align
DefaultAlignment(
7969 PFS
.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7971 AtomicRMWInst
*RMWI
=
7972 new AtomicRMWInst(Operation
, Ptr
, Val
,
7973 Alignment
.value_or(DefaultAlignment
), Ordering
, SSID
);
7974 RMWI
->setVolatile(isVolatile
);
7976 return AteExtraComma
? InstExtraComma
: InstNormal
;
7980 /// ::= 'fence' 'singlethread'? AtomicOrdering
7981 int LLParser::parseFence(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7982 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7983 SyncScope::ID SSID
= SyncScope::System
;
7984 if (parseScopeAndOrdering(true /*Always atomic*/, SSID
, Ordering
))
7987 if (Ordering
== AtomicOrdering::Unordered
)
7988 return tokError("fence cannot be unordered");
7989 if (Ordering
== AtomicOrdering::Monotonic
)
7990 return tokError("fence cannot be monotonic");
7992 Inst
= new FenceInst(Context
, Ordering
, SSID
);
7996 /// parseGetElementPtr
7997 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7998 int LLParser::parseGetElementPtr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7999 Value
*Ptr
= nullptr;
8000 Value
*Val
= nullptr;
8003 bool InBounds
= EatIfPresent(lltok::kw_inbounds
);
8006 if (parseType(Ty
) ||
8007 parseToken(lltok::comma
, "expected comma after getelementptr's type") ||
8008 parseTypeAndValue(Ptr
, Loc
, PFS
))
8011 Type
*BaseType
= Ptr
->getType();
8012 PointerType
*BasePointerType
= dyn_cast
<PointerType
>(BaseType
->getScalarType());
8013 if (!BasePointerType
)
8014 return error(Loc
, "base of getelementptr must be a pointer");
8016 SmallVector
<Value
*, 16> Indices
;
8017 bool AteExtraComma
= false;
8018 // GEP returns a vector of pointers if at least one of parameters is a vector.
8019 // All vector parameters should have the same vector width.
8020 ElementCount GEPWidth
= BaseType
->isVectorTy()
8021 ? cast
<VectorType
>(BaseType
)->getElementCount()
8022 : ElementCount::getFixed(0);
8024 while (EatIfPresent(lltok::comma
)) {
8025 if (Lex
.getKind() == lltok::MetadataVar
) {
8026 AteExtraComma
= true;
8029 if (parseTypeAndValue(Val
, EltLoc
, PFS
))
8031 if (!Val
->getType()->isIntOrIntVectorTy())
8032 return error(EltLoc
, "getelementptr index must be an integer");
8034 if (auto *ValVTy
= dyn_cast
<VectorType
>(Val
->getType())) {
8035 ElementCount ValNumEl
= ValVTy
->getElementCount();
8036 if (GEPWidth
!= ElementCount::getFixed(0) && GEPWidth
!= ValNumEl
)
8039 "getelementptr vector index has a wrong number of elements");
8040 GEPWidth
= ValNumEl
;
8042 Indices
.push_back(Val
);
8045 SmallPtrSet
<Type
*, 4> Visited
;
8046 if (!Indices
.empty() && !Ty
->isSized(&Visited
))
8047 return error(Loc
, "base element of getelementptr must be sized");
8049 auto *STy
= dyn_cast
<StructType
>(Ty
);
8050 if (STy
&& STy
->containsScalableVectorType())
8051 return error(Loc
, "getelementptr cannot target structure that contains "
8052 "scalable vector type");
8054 if (!GetElementPtrInst::getIndexedType(Ty
, Indices
))
8055 return error(Loc
, "invalid getelementptr indices");
8056 Inst
= GetElementPtrInst::Create(Ty
, Ptr
, Indices
);
8058 cast
<GetElementPtrInst
>(Inst
)->setIsInBounds(true);
8059 return AteExtraComma
? InstExtraComma
: InstNormal
;
8062 /// parseExtractValue
8063 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
8064 int LLParser::parseExtractValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
8065 Value
*Val
; LocTy Loc
;
8066 SmallVector
<unsigned, 4> Indices
;
8068 if (parseTypeAndValue(Val
, Loc
, PFS
) ||
8069 parseIndexList(Indices
, AteExtraComma
))
8072 if (!Val
->getType()->isAggregateType())
8073 return error(Loc
, "extractvalue operand must be aggregate type");
8075 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
))
8076 return error(Loc
, "invalid indices for extractvalue");
8077 Inst
= ExtractValueInst::Create(Val
, Indices
);
8078 return AteExtraComma
? InstExtraComma
: InstNormal
;
8081 /// parseInsertValue
8082 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
8083 int LLParser::parseInsertValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
8084 Value
*Val0
, *Val1
; LocTy Loc0
, Loc1
;
8085 SmallVector
<unsigned, 4> Indices
;
8087 if (parseTypeAndValue(Val0
, Loc0
, PFS
) ||
8088 parseToken(lltok::comma
, "expected comma after insertvalue operand") ||
8089 parseTypeAndValue(Val1
, Loc1
, PFS
) ||
8090 parseIndexList(Indices
, AteExtraComma
))
8093 if (!Val0
->getType()->isAggregateType())
8094 return error(Loc0
, "insertvalue operand must be aggregate type");
8096 Type
*IndexedType
= ExtractValueInst::getIndexedType(Val0
->getType(), Indices
);
8098 return error(Loc0
, "invalid indices for insertvalue");
8099 if (IndexedType
!= Val1
->getType())
8100 return error(Loc1
, "insertvalue operand and field disagree in type: '" +
8101 getTypeString(Val1
->getType()) + "' instead of '" +
8102 getTypeString(IndexedType
) + "'");
8103 Inst
= InsertValueInst::Create(Val0
, Val1
, Indices
);
8104 return AteExtraComma
? InstExtraComma
: InstNormal
;
8107 //===----------------------------------------------------------------------===//
8108 // Embedded metadata.
8109 //===----------------------------------------------------------------------===//
8111 /// parseMDNodeVector
8112 /// ::= { Element (',' Element)* }
8114 /// ::= 'null' | TypeAndValue
8115 bool LLParser::parseMDNodeVector(SmallVectorImpl
<Metadata
*> &Elts
) {
8116 if (parseToken(lltok::lbrace
, "expected '{' here"))
8119 // Check for an empty list.
8120 if (EatIfPresent(lltok::rbrace
))
8124 // Null is a special case since it is typeless.
8125 if (EatIfPresent(lltok::kw_null
)) {
8126 Elts
.push_back(nullptr);
8131 if (parseMetadata(MD
, nullptr))
8134 } while (EatIfPresent(lltok::comma
));
8136 return parseToken(lltok::rbrace
, "expected end of metadata node");
8139 //===----------------------------------------------------------------------===//
8140 // Use-list order directives.
8141 //===----------------------------------------------------------------------===//
8142 bool LLParser::sortUseListOrder(Value
*V
, ArrayRef
<unsigned> Indexes
,
8145 return error(Loc
, "value has no uses");
8147 unsigned NumUses
= 0;
8148 SmallDenseMap
<const Use
*, unsigned, 16> Order
;
8149 for (const Use
&U
: V
->uses()) {
8150 if (++NumUses
> Indexes
.size())
8152 Order
[&U
] = Indexes
[NumUses
- 1];
8155 return error(Loc
, "value only has one use");
8156 if (Order
.size() != Indexes
.size() || NumUses
> Indexes
.size())
8158 "wrong number of indexes, expected " + Twine(V
->getNumUses()));
8160 V
->sortUseList([&](const Use
&L
, const Use
&R
) {
8161 return Order
.lookup(&L
) < Order
.lookup(&R
);
8166 /// parseUseListOrderIndexes
8167 /// ::= '{' uint32 (',' uint32)+ '}'
8168 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl
<unsigned> &Indexes
) {
8169 SMLoc Loc
= Lex
.getLoc();
8170 if (parseToken(lltok::lbrace
, "expected '{' here"))
8172 if (Lex
.getKind() == lltok::rbrace
)
8173 return Lex
.Error("expected non-empty list of uselistorder indexes");
8175 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
8176 // indexes should be distinct numbers in the range [0, size-1], and should
8178 unsigned Offset
= 0;
8180 bool IsOrdered
= true;
8181 assert(Indexes
.empty() && "Expected empty order vector");
8184 if (parseUInt32(Index
))
8187 // Update consistency checks.
8188 Offset
+= Index
- Indexes
.size();
8189 Max
= std::max(Max
, Index
);
8190 IsOrdered
&= Index
== Indexes
.size();
8192 Indexes
.push_back(Index
);
8193 } while (EatIfPresent(lltok::comma
));
8195 if (parseToken(lltok::rbrace
, "expected '}' here"))
8198 if (Indexes
.size() < 2)
8199 return error(Loc
, "expected >= 2 uselistorder indexes");
8200 if (Offset
!= 0 || Max
>= Indexes
.size())
8202 "expected distinct uselistorder indexes in range [0, size)");
8204 return error(Loc
, "expected uselistorder indexes to change the order");
8209 /// parseUseListOrder
8210 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
8211 bool LLParser::parseUseListOrder(PerFunctionState
*PFS
) {
8212 SMLoc Loc
= Lex
.getLoc();
8213 if (parseToken(lltok::kw_uselistorder
, "expected uselistorder directive"))
8217 SmallVector
<unsigned, 16> Indexes
;
8218 if (parseTypeAndValue(V
, PFS
) ||
8219 parseToken(lltok::comma
, "expected comma in uselistorder directive") ||
8220 parseUseListOrderIndexes(Indexes
))
8223 return sortUseListOrder(V
, Indexes
, Loc
);
8226 /// parseUseListOrderBB
8227 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
8228 bool LLParser::parseUseListOrderBB() {
8229 assert(Lex
.getKind() == lltok::kw_uselistorder_bb
);
8230 SMLoc Loc
= Lex
.getLoc();
8234 SmallVector
<unsigned, 16> Indexes
;
8235 if (parseValID(Fn
, /*PFS=*/nullptr) ||
8236 parseToken(lltok::comma
, "expected comma in uselistorder_bb directive") ||
8237 parseValID(Label
, /*PFS=*/nullptr) ||
8238 parseToken(lltok::comma
, "expected comma in uselistorder_bb directive") ||
8239 parseUseListOrderIndexes(Indexes
))
8242 // Check the function.
8244 if (Fn
.Kind
== ValID::t_GlobalName
)
8245 GV
= M
->getNamedValue(Fn
.StrVal
);
8246 else if (Fn
.Kind
== ValID::t_GlobalID
)
8247 GV
= Fn
.UIntVal
< NumberedVals
.size() ? NumberedVals
[Fn
.UIntVal
] : nullptr;
8249 return error(Fn
.Loc
, "expected function name in uselistorder_bb");
8251 return error(Fn
.Loc
,
8252 "invalid function forward reference in uselistorder_bb");
8253 auto *F
= dyn_cast
<Function
>(GV
);
8255 return error(Fn
.Loc
, "expected function name in uselistorder_bb");
8256 if (F
->isDeclaration())
8257 return error(Fn
.Loc
, "invalid declaration in uselistorder_bb");
8259 // Check the basic block.
8260 if (Label
.Kind
== ValID::t_LocalID
)
8261 return error(Label
.Loc
, "invalid numeric label in uselistorder_bb");
8262 if (Label
.Kind
!= ValID::t_LocalName
)
8263 return error(Label
.Loc
, "expected basic block name in uselistorder_bb");
8264 Value
*V
= F
->getValueSymbolTable()->lookup(Label
.StrVal
);
8266 return error(Label
.Loc
, "invalid basic block in uselistorder_bb");
8267 if (!isa
<BasicBlock
>(V
))
8268 return error(Label
.Loc
, "expected basic block in uselistorder_bb");
8270 return sortUseListOrder(V
, Indexes
, Loc
);
8274 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
8275 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
8276 bool LLParser::parseModuleEntry(unsigned ID
) {
8277 assert(Lex
.getKind() == lltok::kw_module
);
8281 if (parseToken(lltok::colon
, "expected ':' here") ||
8282 parseToken(lltok::lparen
, "expected '(' here") ||
8283 parseToken(lltok::kw_path
, "expected 'path' here") ||
8284 parseToken(lltok::colon
, "expected ':' here") ||
8285 parseStringConstant(Path
) ||
8286 parseToken(lltok::comma
, "expected ',' here") ||
8287 parseToken(lltok::kw_hash
, "expected 'hash' here") ||
8288 parseToken(lltok::colon
, "expected ':' here") ||
8289 parseToken(lltok::lparen
, "expected '(' here"))
8293 if (parseUInt32(Hash
[0]) || parseToken(lltok::comma
, "expected ',' here") ||
8294 parseUInt32(Hash
[1]) || parseToken(lltok::comma
, "expected ',' here") ||
8295 parseUInt32(Hash
[2]) || parseToken(lltok::comma
, "expected ',' here") ||
8296 parseUInt32(Hash
[3]) || parseToken(lltok::comma
, "expected ',' here") ||
8297 parseUInt32(Hash
[4]))
8300 if (parseToken(lltok::rparen
, "expected ')' here") ||
8301 parseToken(lltok::rparen
, "expected ')' here"))
8304 auto ModuleEntry
= Index
->addModule(Path
, Hash
);
8305 ModuleIdMap
[ID
] = ModuleEntry
->first();
8311 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
8312 bool LLParser::parseTypeIdEntry(unsigned ID
) {
8313 assert(Lex
.getKind() == lltok::kw_typeid
);
8317 if (parseToken(lltok::colon
, "expected ':' here") ||
8318 parseToken(lltok::lparen
, "expected '(' here") ||
8319 parseToken(lltok::kw_name
, "expected 'name' here") ||
8320 parseToken(lltok::colon
, "expected ':' here") ||
8321 parseStringConstant(Name
))
8324 TypeIdSummary
&TIS
= Index
->getOrInsertTypeIdSummary(Name
);
8325 if (parseToken(lltok::comma
, "expected ',' here") ||
8326 parseTypeIdSummary(TIS
) || parseToken(lltok::rparen
, "expected ')' here"))
8329 // Check if this ID was forward referenced, and if so, update the
8330 // corresponding GUIDs.
8331 auto FwdRefTIDs
= ForwardRefTypeIds
.find(ID
);
8332 if (FwdRefTIDs
!= ForwardRefTypeIds
.end()) {
8333 for (auto TIDRef
: FwdRefTIDs
->second
) {
8334 assert(!*TIDRef
.first
&&
8335 "Forward referenced type id GUID expected to be 0");
8336 *TIDRef
.first
= GlobalValue::getGUID(Name
);
8338 ForwardRefTypeIds
.erase(FwdRefTIDs
);
8345 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
8346 bool LLParser::parseTypeIdSummary(TypeIdSummary
&TIS
) {
8347 if (parseToken(lltok::kw_summary
, "expected 'summary' here") ||
8348 parseToken(lltok::colon
, "expected ':' here") ||
8349 parseToken(lltok::lparen
, "expected '(' here") ||
8350 parseTypeTestResolution(TIS
.TTRes
))
8353 if (EatIfPresent(lltok::comma
)) {
8354 // Expect optional wpdResolutions field
8355 if (parseOptionalWpdResolutions(TIS
.WPDRes
))
8359 if (parseToken(lltok::rparen
, "expected ')' here"))
8365 static ValueInfo EmptyVI
=
8366 ValueInfo(false, (GlobalValueSummaryMapTy::value_type
*)-8);
8368 /// TypeIdCompatibleVtableEntry
8369 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
8370 /// TypeIdCompatibleVtableInfo
8372 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID
) {
8373 assert(Lex
.getKind() == lltok::kw_typeidCompatibleVTable
);
8377 if (parseToken(lltok::colon
, "expected ':' here") ||
8378 parseToken(lltok::lparen
, "expected '(' here") ||
8379 parseToken(lltok::kw_name
, "expected 'name' here") ||
8380 parseToken(lltok::colon
, "expected ':' here") ||
8381 parseStringConstant(Name
))
8384 TypeIdCompatibleVtableInfo
&TI
=
8385 Index
->getOrInsertTypeIdCompatibleVtableSummary(Name
);
8386 if (parseToken(lltok::comma
, "expected ',' here") ||
8387 parseToken(lltok::kw_summary
, "expected 'summary' here") ||
8388 parseToken(lltok::colon
, "expected ':' here") ||
8389 parseToken(lltok::lparen
, "expected '(' here"))
8392 IdToIndexMapType IdToIndexMap
;
8393 // parse each call edge
8396 if (parseToken(lltok::lparen
, "expected '(' here") ||
8397 parseToken(lltok::kw_offset
, "expected 'offset' here") ||
8398 parseToken(lltok::colon
, "expected ':' here") || parseUInt64(Offset
) ||
8399 parseToken(lltok::comma
, "expected ',' here"))
8402 LocTy Loc
= Lex
.getLoc();
8405 if (parseGVReference(VI
, GVId
))
8408 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
8409 // forward reference. We will save the location of the ValueInfo needing an
8410 // update, but can only do so once the std::vector is finalized.
8412 IdToIndexMap
[GVId
].push_back(std::make_pair(TI
.size(), Loc
));
8413 TI
.push_back({Offset
, VI
});
8415 if (parseToken(lltok::rparen
, "expected ')' in call"))
8417 } while (EatIfPresent(lltok::comma
));
8419 // Now that the TI vector is finalized, it is safe to save the locations
8420 // of any forward GV references that need updating later.
8421 for (auto I
: IdToIndexMap
) {
8422 auto &Infos
= ForwardRefValueInfos
[I
.first
];
8423 for (auto P
: I
.second
) {
8424 assert(TI
[P
.first
].VTableVI
== EmptyVI
&&
8425 "Forward referenced ValueInfo expected to be empty");
8426 Infos
.emplace_back(&TI
[P
.first
].VTableVI
, P
.second
);
8430 if (parseToken(lltok::rparen
, "expected ')' here") ||
8431 parseToken(lltok::rparen
, "expected ')' here"))
8434 // Check if this ID was forward referenced, and if so, update the
8435 // corresponding GUIDs.
8436 auto FwdRefTIDs
= ForwardRefTypeIds
.find(ID
);
8437 if (FwdRefTIDs
!= ForwardRefTypeIds
.end()) {
8438 for (auto TIDRef
: FwdRefTIDs
->second
) {
8439 assert(!*TIDRef
.first
&&
8440 "Forward referenced type id GUID expected to be 0");
8441 *TIDRef
.first
= GlobalValue::getGUID(Name
);
8443 ForwardRefTypeIds
.erase(FwdRefTIDs
);
8449 /// TypeTestResolution
8450 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
8451 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8452 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8453 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8454 /// [',' 'inlinesBits' ':' UInt64]? ')'
8455 bool LLParser::parseTypeTestResolution(TypeTestResolution
&TTRes
) {
8456 if (parseToken(lltok::kw_typeTestRes
, "expected 'typeTestRes' here") ||
8457 parseToken(lltok::colon
, "expected ':' here") ||
8458 parseToken(lltok::lparen
, "expected '(' here") ||
8459 parseToken(lltok::kw_kind
, "expected 'kind' here") ||
8460 parseToken(lltok::colon
, "expected ':' here"))
8463 switch (Lex
.getKind()) {
8464 case lltok::kw_unknown
:
8465 TTRes
.TheKind
= TypeTestResolution::Unknown
;
8467 case lltok::kw_unsat
:
8468 TTRes
.TheKind
= TypeTestResolution::Unsat
;
8470 case lltok::kw_byteArray
:
8471 TTRes
.TheKind
= TypeTestResolution::ByteArray
;
8473 case lltok::kw_inline
:
8474 TTRes
.TheKind
= TypeTestResolution::Inline
;
8476 case lltok::kw_single
:
8477 TTRes
.TheKind
= TypeTestResolution::Single
;
8479 case lltok::kw_allOnes
:
8480 TTRes
.TheKind
= TypeTestResolution::AllOnes
;
8483 return error(Lex
.getLoc(), "unexpected TypeTestResolution kind");
8487 if (parseToken(lltok::comma
, "expected ',' here") ||
8488 parseToken(lltok::kw_sizeM1BitWidth
, "expected 'sizeM1BitWidth' here") ||
8489 parseToken(lltok::colon
, "expected ':' here") ||
8490 parseUInt32(TTRes
.SizeM1BitWidth
))
8493 // parse optional fields
8494 while (EatIfPresent(lltok::comma
)) {
8495 switch (Lex
.getKind()) {
8496 case lltok::kw_alignLog2
:
8498 if (parseToken(lltok::colon
, "expected ':'") ||
8499 parseUInt64(TTRes
.AlignLog2
))
8502 case lltok::kw_sizeM1
:
8504 if (parseToken(lltok::colon
, "expected ':'") || parseUInt64(TTRes
.SizeM1
))
8507 case lltok::kw_bitMask
: {
8510 if (parseToken(lltok::colon
, "expected ':'") || parseUInt32(Val
))
8512 assert(Val
<= 0xff);
8513 TTRes
.BitMask
= (uint8_t)Val
;
8516 case lltok::kw_inlineBits
:
8518 if (parseToken(lltok::colon
, "expected ':'") ||
8519 parseUInt64(TTRes
.InlineBits
))
8523 return error(Lex
.getLoc(), "expected optional TypeTestResolution field");
8527 if (parseToken(lltok::rparen
, "expected ')' here"))
8533 /// OptionalWpdResolutions
8534 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
8535 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
8536 bool LLParser::parseOptionalWpdResolutions(
8537 std::map
<uint64_t, WholeProgramDevirtResolution
> &WPDResMap
) {
8538 if (parseToken(lltok::kw_wpdResolutions
, "expected 'wpdResolutions' here") ||
8539 parseToken(lltok::colon
, "expected ':' here") ||
8540 parseToken(lltok::lparen
, "expected '(' here"))
8545 WholeProgramDevirtResolution WPDRes
;
8546 if (parseToken(lltok::lparen
, "expected '(' here") ||
8547 parseToken(lltok::kw_offset
, "expected 'offset' here") ||
8548 parseToken(lltok::colon
, "expected ':' here") || parseUInt64(Offset
) ||
8549 parseToken(lltok::comma
, "expected ',' here") || parseWpdRes(WPDRes
) ||
8550 parseToken(lltok::rparen
, "expected ')' here"))
8552 WPDResMap
[Offset
] = WPDRes
;
8553 } while (EatIfPresent(lltok::comma
));
8555 if (parseToken(lltok::rparen
, "expected ')' here"))
8562 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
8563 /// [',' OptionalResByArg]? ')'
8564 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
8565 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
8566 /// [',' OptionalResByArg]? ')'
8567 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
8568 /// [',' OptionalResByArg]? ')'
8569 bool LLParser::parseWpdRes(WholeProgramDevirtResolution
&WPDRes
) {
8570 if (parseToken(lltok::kw_wpdRes
, "expected 'wpdRes' here") ||
8571 parseToken(lltok::colon
, "expected ':' here") ||
8572 parseToken(lltok::lparen
, "expected '(' here") ||
8573 parseToken(lltok::kw_kind
, "expected 'kind' here") ||
8574 parseToken(lltok::colon
, "expected ':' here"))
8577 switch (Lex
.getKind()) {
8578 case lltok::kw_indir
:
8579 WPDRes
.TheKind
= WholeProgramDevirtResolution::Indir
;
8581 case lltok::kw_singleImpl
:
8582 WPDRes
.TheKind
= WholeProgramDevirtResolution::SingleImpl
;
8584 case lltok::kw_branchFunnel
:
8585 WPDRes
.TheKind
= WholeProgramDevirtResolution::BranchFunnel
;
8588 return error(Lex
.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8592 // parse optional fields
8593 while (EatIfPresent(lltok::comma
)) {
8594 switch (Lex
.getKind()) {
8595 case lltok::kw_singleImplName
:
8597 if (parseToken(lltok::colon
, "expected ':' here") ||
8598 parseStringConstant(WPDRes
.SingleImplName
))
8601 case lltok::kw_resByArg
:
8602 if (parseOptionalResByArg(WPDRes
.ResByArg
))
8606 return error(Lex
.getLoc(),
8607 "expected optional WholeProgramDevirtResolution field");
8611 if (parseToken(lltok::rparen
, "expected ')' here"))
8617 /// OptionalResByArg
8618 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8619 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8620 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8621 /// 'virtualConstProp' )
8622 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8623 /// [',' 'bit' ':' UInt32]? ')'
8624 bool LLParser::parseOptionalResByArg(
8625 std::map
<std::vector
<uint64_t>, WholeProgramDevirtResolution::ByArg
>
8627 if (parseToken(lltok::kw_resByArg
, "expected 'resByArg' here") ||
8628 parseToken(lltok::colon
, "expected ':' here") ||
8629 parseToken(lltok::lparen
, "expected '(' here"))
8633 std::vector
<uint64_t> Args
;
8634 if (parseArgs(Args
) || parseToken(lltok::comma
, "expected ',' here") ||
8635 parseToken(lltok::kw_byArg
, "expected 'byArg here") ||
8636 parseToken(lltok::colon
, "expected ':' here") ||
8637 parseToken(lltok::lparen
, "expected '(' here") ||
8638 parseToken(lltok::kw_kind
, "expected 'kind' here") ||
8639 parseToken(lltok::colon
, "expected ':' here"))
8642 WholeProgramDevirtResolution::ByArg ByArg
;
8643 switch (Lex
.getKind()) {
8644 case lltok::kw_indir
:
8645 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::Indir
;
8647 case lltok::kw_uniformRetVal
:
8648 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::UniformRetVal
;
8650 case lltok::kw_uniqueRetVal
:
8651 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::UniqueRetVal
;
8653 case lltok::kw_virtualConstProp
:
8654 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::VirtualConstProp
;
8657 return error(Lex
.getLoc(),
8658 "unexpected WholeProgramDevirtResolution::ByArg kind");
8662 // parse optional fields
8663 while (EatIfPresent(lltok::comma
)) {
8664 switch (Lex
.getKind()) {
8665 case lltok::kw_info
:
8667 if (parseToken(lltok::colon
, "expected ':' here") ||
8668 parseUInt64(ByArg
.Info
))
8671 case lltok::kw_byte
:
8673 if (parseToken(lltok::colon
, "expected ':' here") ||
8674 parseUInt32(ByArg
.Byte
))
8679 if (parseToken(lltok::colon
, "expected ':' here") ||
8680 parseUInt32(ByArg
.Bit
))
8684 return error(Lex
.getLoc(),
8685 "expected optional whole program devirt field");
8689 if (parseToken(lltok::rparen
, "expected ')' here"))
8692 ResByArg
[Args
] = ByArg
;
8693 } while (EatIfPresent(lltok::comma
));
8695 if (parseToken(lltok::rparen
, "expected ')' here"))
8701 /// OptionalResByArg
8702 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
8703 bool LLParser::parseArgs(std::vector
<uint64_t> &Args
) {
8704 if (parseToken(lltok::kw_args
, "expected 'args' here") ||
8705 parseToken(lltok::colon
, "expected ':' here") ||
8706 parseToken(lltok::lparen
, "expected '(' here"))
8711 if (parseUInt64(Val
))
8713 Args
.push_back(Val
);
8714 } while (EatIfPresent(lltok::comma
));
8716 if (parseToken(lltok::rparen
, "expected ')' here"))
8722 static const auto FwdVIRef
= (GlobalValueSummaryMapTy::value_type
*)-8;
8724 static void resolveFwdRef(ValueInfo
*Fwd
, ValueInfo
&Resolved
) {
8725 bool ReadOnly
= Fwd
->isReadOnly();
8726 bool WriteOnly
= Fwd
->isWriteOnly();
8727 assert(!(ReadOnly
&& WriteOnly
));
8732 Fwd
->setWriteOnly();
8735 /// Stores the given Name/GUID and associated summary into the Index.
8736 /// Also updates any forward references to the associated entry ID.
8737 bool LLParser::addGlobalValueToIndex(
8738 std::string Name
, GlobalValue::GUID GUID
, GlobalValue::LinkageTypes Linkage
,
8739 unsigned ID
, std::unique_ptr
<GlobalValueSummary
> Summary
, LocTy Loc
) {
8740 // First create the ValueInfo utilizing the Name or GUID.
8743 assert(Name
.empty());
8744 VI
= Index
->getOrInsertValueInfo(GUID
);
8746 assert(!Name
.empty());
8748 auto *GV
= M
->getNamedValue(Name
);
8750 return error(Loc
, "Reference to undefined global \"" + Name
+ "\"");
8752 VI
= Index
->getOrInsertValueInfo(GV
);
8755 (!GlobalValue::isLocalLinkage(Linkage
) || !SourceFileName
.empty()) &&
8756 "Need a source_filename to compute GUID for local");
8757 GUID
= GlobalValue::getGUID(
8758 GlobalValue::getGlobalIdentifier(Name
, Linkage
, SourceFileName
));
8759 VI
= Index
->getOrInsertValueInfo(GUID
, Index
->saveString(Name
));
8763 // Resolve forward references from calls/refs
8764 auto FwdRefVIs
= ForwardRefValueInfos
.find(ID
);
8765 if (FwdRefVIs
!= ForwardRefValueInfos
.end()) {
8766 for (auto VIRef
: FwdRefVIs
->second
) {
8767 assert(VIRef
.first
->getRef() == FwdVIRef
&&
8768 "Forward referenced ValueInfo expected to be empty");
8769 resolveFwdRef(VIRef
.first
, VI
);
8771 ForwardRefValueInfos
.erase(FwdRefVIs
);
8774 // Resolve forward references from aliases
8775 auto FwdRefAliasees
= ForwardRefAliasees
.find(ID
);
8776 if (FwdRefAliasees
!= ForwardRefAliasees
.end()) {
8777 for (auto AliaseeRef
: FwdRefAliasees
->second
) {
8778 assert(!AliaseeRef
.first
->hasAliasee() &&
8779 "Forward referencing alias already has aliasee");
8780 assert(Summary
&& "Aliasee must be a definition");
8781 AliaseeRef
.first
->setAliasee(VI
, Summary
.get());
8783 ForwardRefAliasees
.erase(FwdRefAliasees
);
8786 // Add the summary if one was provided.
8788 Index
->addGlobalValueSummary(VI
, std::move(Summary
));
8790 // Save the associated ValueInfo for use in later references by ID.
8791 if (ID
== NumberedValueInfos
.size())
8792 NumberedValueInfos
.push_back(VI
);
8794 // Handle non-continuous numbers (to make test simplification easier).
8795 if (ID
> NumberedValueInfos
.size())
8796 NumberedValueInfos
.resize(ID
+ 1);
8797 NumberedValueInfos
[ID
] = VI
;
8803 /// parseSummaryIndexFlags
8804 /// ::= 'flags' ':' UInt64
8805 bool LLParser::parseSummaryIndexFlags() {
8806 assert(Lex
.getKind() == lltok::kw_flags
);
8809 if (parseToken(lltok::colon
, "expected ':' here"))
8812 if (parseUInt64(Flags
))
8815 Index
->setFlags(Flags
);
8820 /// ::= 'blockcount' ':' UInt64
8821 bool LLParser::parseBlockCount() {
8822 assert(Lex
.getKind() == lltok::kw_blockcount
);
8825 if (parseToken(lltok::colon
, "expected ':' here"))
8827 uint64_t BlockCount
;
8828 if (parseUInt64(BlockCount
))
8831 Index
->setBlockCount(BlockCount
);
8836 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8837 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8838 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
8839 bool LLParser::parseGVEntry(unsigned ID
) {
8840 assert(Lex
.getKind() == lltok::kw_gv
);
8843 if (parseToken(lltok::colon
, "expected ':' here") ||
8844 parseToken(lltok::lparen
, "expected '(' here"))
8847 LocTy Loc
= Lex
.getLoc();
8849 GlobalValue::GUID GUID
= 0;
8850 switch (Lex
.getKind()) {
8851 case lltok::kw_name
:
8853 if (parseToken(lltok::colon
, "expected ':' here") ||
8854 parseStringConstant(Name
))
8856 // Can't create GUID/ValueInfo until we have the linkage.
8858 case lltok::kw_guid
:
8860 if (parseToken(lltok::colon
, "expected ':' here") || parseUInt64(GUID
))
8864 return error(Lex
.getLoc(), "expected name or guid tag");
8867 if (!EatIfPresent(lltok::comma
)) {
8868 // No summaries. Wrap up.
8869 if (parseToken(lltok::rparen
, "expected ')' here"))
8871 // This was created for a call to an external or indirect target.
8872 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8873 // created for indirect calls with VP. A Name with no GUID came from
8874 // an external definition. We pass ExternalLinkage since that is only
8875 // used when the GUID must be computed from Name, and in that case
8876 // the symbol must have external linkage.
8877 return addGlobalValueToIndex(Name
, GUID
, GlobalValue::ExternalLinkage
, ID
,
8881 // Have a list of summaries
8882 if (parseToken(lltok::kw_summaries
, "expected 'summaries' here") ||
8883 parseToken(lltok::colon
, "expected ':' here") ||
8884 parseToken(lltok::lparen
, "expected '(' here"))
8887 switch (Lex
.getKind()) {
8888 case lltok::kw_function
:
8889 if (parseFunctionSummary(Name
, GUID
, ID
))
8892 case lltok::kw_variable
:
8893 if (parseVariableSummary(Name
, GUID
, ID
))
8896 case lltok::kw_alias
:
8897 if (parseAliasSummary(Name
, GUID
, ID
))
8901 return error(Lex
.getLoc(), "expected summary type");
8903 } while (EatIfPresent(lltok::comma
));
8905 if (parseToken(lltok::rparen
, "expected ')' here") ||
8906 parseToken(lltok::rparen
, "expected ')' here"))
8913 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8914 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8915 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8916 /// [',' OptionalRefs]? ')'
8917 bool LLParser::parseFunctionSummary(std::string Name
, GlobalValue::GUID GUID
,
8919 LocTy Loc
= Lex
.getLoc();
8920 assert(Lex
.getKind() == lltok::kw_function
);
8923 StringRef ModulePath
;
8924 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
8925 GlobalValue::ExternalLinkage
, GlobalValue::DefaultVisibility
,
8926 /*NotEligibleToImport=*/false,
8927 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8929 std::vector
<FunctionSummary::EdgeTy
> Calls
;
8930 FunctionSummary::TypeIdInfo TypeIdInfo
;
8931 std::vector
<FunctionSummary::ParamAccess
> ParamAccesses
;
8932 std::vector
<ValueInfo
> Refs
;
8933 std::vector
<CallsiteInfo
> Callsites
;
8934 std::vector
<AllocInfo
> Allocs
;
8935 // Default is all-zeros (conservative values).
8936 FunctionSummary::FFlags FFlags
= {};
8937 if (parseToken(lltok::colon
, "expected ':' here") ||
8938 parseToken(lltok::lparen
, "expected '(' here") ||
8939 parseModuleReference(ModulePath
) ||
8940 parseToken(lltok::comma
, "expected ',' here") || parseGVFlags(GVFlags
) ||
8941 parseToken(lltok::comma
, "expected ',' here") ||
8942 parseToken(lltok::kw_insts
, "expected 'insts' here") ||
8943 parseToken(lltok::colon
, "expected ':' here") || parseUInt32(InstCount
))
8946 // parse optional fields
8947 while (EatIfPresent(lltok::comma
)) {
8948 switch (Lex
.getKind()) {
8949 case lltok::kw_funcFlags
:
8950 if (parseOptionalFFlags(FFlags
))
8953 case lltok::kw_calls
:
8954 if (parseOptionalCalls(Calls
))
8957 case lltok::kw_typeIdInfo
:
8958 if (parseOptionalTypeIdInfo(TypeIdInfo
))
8961 case lltok::kw_refs
:
8962 if (parseOptionalRefs(Refs
))
8965 case lltok::kw_params
:
8966 if (parseOptionalParamAccesses(ParamAccesses
))
8969 case lltok::kw_allocs
:
8970 if (parseOptionalAllocs(Allocs
))
8973 case lltok::kw_callsites
:
8974 if (parseOptionalCallsites(Callsites
))
8978 return error(Lex
.getLoc(), "expected optional function summary field");
8982 if (parseToken(lltok::rparen
, "expected ')' here"))
8985 auto FS
= std::make_unique
<FunctionSummary
>(
8986 GVFlags
, InstCount
, FFlags
, /*EntryCount=*/0, std::move(Refs
),
8987 std::move(Calls
), std::move(TypeIdInfo
.TypeTests
),
8988 std::move(TypeIdInfo
.TypeTestAssumeVCalls
),
8989 std::move(TypeIdInfo
.TypeCheckedLoadVCalls
),
8990 std::move(TypeIdInfo
.TypeTestAssumeConstVCalls
),
8991 std::move(TypeIdInfo
.TypeCheckedLoadConstVCalls
),
8992 std::move(ParamAccesses
), std::move(Callsites
), std::move(Allocs
));
8994 FS
->setModulePath(ModulePath
);
8996 return addGlobalValueToIndex(Name
, GUID
,
8997 (GlobalValue::LinkageTypes
)GVFlags
.Linkage
, ID
,
8998 std::move(FS
), Loc
);
9002 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
9003 /// [',' OptionalRefs]? ')'
9004 bool LLParser::parseVariableSummary(std::string Name
, GlobalValue::GUID GUID
,
9006 LocTy Loc
= Lex
.getLoc();
9007 assert(Lex
.getKind() == lltok::kw_variable
);
9010 StringRef ModulePath
;
9011 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
9012 GlobalValue::ExternalLinkage
, GlobalValue::DefaultVisibility
,
9013 /*NotEligibleToImport=*/false,
9014 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
9015 GlobalVarSummary::GVarFlags
GVarFlags(/*ReadOnly*/ false,
9016 /* WriteOnly */ false,
9017 /* Constant */ false,
9018 GlobalObject::VCallVisibilityPublic
);
9019 std::vector
<ValueInfo
> Refs
;
9020 VTableFuncList VTableFuncs
;
9021 if (parseToken(lltok::colon
, "expected ':' here") ||
9022 parseToken(lltok::lparen
, "expected '(' here") ||
9023 parseModuleReference(ModulePath
) ||
9024 parseToken(lltok::comma
, "expected ',' here") || parseGVFlags(GVFlags
) ||
9025 parseToken(lltok::comma
, "expected ',' here") ||
9026 parseGVarFlags(GVarFlags
))
9029 // parse optional fields
9030 while (EatIfPresent(lltok::comma
)) {
9031 switch (Lex
.getKind()) {
9032 case lltok::kw_vTableFuncs
:
9033 if (parseOptionalVTableFuncs(VTableFuncs
))
9036 case lltok::kw_refs
:
9037 if (parseOptionalRefs(Refs
))
9041 return error(Lex
.getLoc(), "expected optional variable summary field");
9045 if (parseToken(lltok::rparen
, "expected ')' here"))
9049 std::make_unique
<GlobalVarSummary
>(GVFlags
, GVarFlags
, std::move(Refs
));
9051 GS
->setModulePath(ModulePath
);
9052 GS
->setVTableFuncs(std::move(VTableFuncs
));
9054 return addGlobalValueToIndex(Name
, GUID
,
9055 (GlobalValue::LinkageTypes
)GVFlags
.Linkage
, ID
,
9056 std::move(GS
), Loc
);
9060 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
9061 /// 'aliasee' ':' GVReference ')'
9062 bool LLParser::parseAliasSummary(std::string Name
, GlobalValue::GUID GUID
,
9064 assert(Lex
.getKind() == lltok::kw_alias
);
9065 LocTy Loc
= Lex
.getLoc();
9068 StringRef ModulePath
;
9069 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
9070 GlobalValue::ExternalLinkage
, GlobalValue::DefaultVisibility
,
9071 /*NotEligibleToImport=*/false,
9072 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
9073 if (parseToken(lltok::colon
, "expected ':' here") ||
9074 parseToken(lltok::lparen
, "expected '(' here") ||
9075 parseModuleReference(ModulePath
) ||
9076 parseToken(lltok::comma
, "expected ',' here") || parseGVFlags(GVFlags
) ||
9077 parseToken(lltok::comma
, "expected ',' here") ||
9078 parseToken(lltok::kw_aliasee
, "expected 'aliasee' here") ||
9079 parseToken(lltok::colon
, "expected ':' here"))
9082 ValueInfo AliaseeVI
;
9084 if (parseGVReference(AliaseeVI
, GVId
))
9087 if (parseToken(lltok::rparen
, "expected ')' here"))
9090 auto AS
= std::make_unique
<AliasSummary
>(GVFlags
);
9092 AS
->setModulePath(ModulePath
);
9094 // Record forward reference if the aliasee is not parsed yet.
9095 if (AliaseeVI
.getRef() == FwdVIRef
) {
9096 ForwardRefAliasees
[GVId
].emplace_back(AS
.get(), Loc
);
9098 auto Summary
= Index
->findSummaryInModule(AliaseeVI
, ModulePath
);
9099 assert(Summary
&& "Aliasee must be a definition");
9100 AS
->setAliasee(AliaseeVI
, Summary
);
9103 return addGlobalValueToIndex(Name
, GUID
,
9104 (GlobalValue::LinkageTypes
)GVFlags
.Linkage
, ID
,
9105 std::move(AS
), Loc
);
9110 bool LLParser::parseFlag(unsigned &Val
) {
9111 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
9112 return tokError("expected integer");
9113 Val
= (unsigned)Lex
.getAPSIntVal().getBoolValue();
9119 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
9120 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
9121 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
9122 /// [',' 'noInline' ':' Flag]? ')'
9123 /// [',' 'alwaysInline' ':' Flag]? ')'
9124 /// [',' 'noUnwind' ':' Flag]? ')'
9125 /// [',' 'mayThrow' ':' Flag]? ')'
9126 /// [',' 'hasUnknownCall' ':' Flag]? ')'
9127 /// [',' 'mustBeUnreachable' ':' Flag]? ')'
9129 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags
&FFlags
) {
9130 assert(Lex
.getKind() == lltok::kw_funcFlags
);
9133 if (parseToken(lltok::colon
, "expected ':' in funcFlags") ||
9134 parseToken(lltok::lparen
, "expected '(' in funcFlags"))
9139 switch (Lex
.getKind()) {
9140 case lltok::kw_readNone
:
9142 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9144 FFlags
.ReadNone
= Val
;
9146 case lltok::kw_readOnly
:
9148 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9150 FFlags
.ReadOnly
= Val
;
9152 case lltok::kw_noRecurse
:
9154 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9156 FFlags
.NoRecurse
= Val
;
9158 case lltok::kw_returnDoesNotAlias
:
9160 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9162 FFlags
.ReturnDoesNotAlias
= Val
;
9164 case lltok::kw_noInline
:
9166 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9168 FFlags
.NoInline
= Val
;
9170 case lltok::kw_alwaysInline
:
9172 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9174 FFlags
.AlwaysInline
= Val
;
9176 case lltok::kw_noUnwind
:
9178 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9180 FFlags
.NoUnwind
= Val
;
9182 case lltok::kw_mayThrow
:
9184 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9186 FFlags
.MayThrow
= Val
;
9188 case lltok::kw_hasUnknownCall
:
9190 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9192 FFlags
.HasUnknownCall
= Val
;
9194 case lltok::kw_mustBeUnreachable
:
9196 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Val
))
9198 FFlags
.MustBeUnreachable
= Val
;
9201 return error(Lex
.getLoc(), "expected function flag type");
9203 } while (EatIfPresent(lltok::comma
));
9205 if (parseToken(lltok::rparen
, "expected ')' in funcFlags"))
9212 /// := 'calls' ':' '(' Call [',' Call]* ')'
9213 /// Call ::= '(' 'callee' ':' GVReference
9214 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]?
9215 /// [ ',' 'tail' ]? ')'
9216 bool LLParser::parseOptionalCalls(std::vector
<FunctionSummary::EdgeTy
> &Calls
) {
9217 assert(Lex
.getKind() == lltok::kw_calls
);
9220 if (parseToken(lltok::colon
, "expected ':' in calls") ||
9221 parseToken(lltok::lparen
, "expected '(' in calls"))
9224 IdToIndexMapType IdToIndexMap
;
9225 // parse each call edge
9228 if (parseToken(lltok::lparen
, "expected '(' in call") ||
9229 parseToken(lltok::kw_callee
, "expected 'callee' in call") ||
9230 parseToken(lltok::colon
, "expected ':'"))
9233 LocTy Loc
= Lex
.getLoc();
9235 if (parseGVReference(VI
, GVId
))
9238 CalleeInfo::HotnessType Hotness
= CalleeInfo::HotnessType::Unknown
;
9240 unsigned HasTailCall
= false;
9242 // parse optional fields
9243 while (EatIfPresent(lltok::comma
)) {
9244 switch (Lex
.getKind()) {
9245 case lltok::kw_hotness
:
9247 if (parseToken(lltok::colon
, "expected ':'") || parseHotness(Hotness
))
9250 case lltok::kw_relbf
:
9252 if (parseToken(lltok::colon
, "expected ':'") || parseUInt32(RelBF
))
9255 case lltok::kw_tail
:
9257 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(HasTailCall
))
9261 return error(Lex
.getLoc(), "expected hotness, relbf, or tail");
9264 if (Hotness
!= CalleeInfo::HotnessType::Unknown
&& RelBF
> 0)
9265 return tokError("Expected only one of hotness or relbf");
9266 // Keep track of the Call array index needing a forward reference.
9267 // We will save the location of the ValueInfo needing an update, but
9268 // can only do so once the std::vector is finalized.
9269 if (VI
.getRef() == FwdVIRef
)
9270 IdToIndexMap
[GVId
].push_back(std::make_pair(Calls
.size(), Loc
));
9272 FunctionSummary::EdgeTy
{VI
, CalleeInfo(Hotness
, HasTailCall
, RelBF
)});
9274 if (parseToken(lltok::rparen
, "expected ')' in call"))
9276 } while (EatIfPresent(lltok::comma
));
9278 // Now that the Calls vector is finalized, it is safe to save the locations
9279 // of any forward GV references that need updating later.
9280 for (auto I
: IdToIndexMap
) {
9281 auto &Infos
= ForwardRefValueInfos
[I
.first
];
9282 for (auto P
: I
.second
) {
9283 assert(Calls
[P
.first
].first
.getRef() == FwdVIRef
&&
9284 "Forward referenced ValueInfo expected to be empty");
9285 Infos
.emplace_back(&Calls
[P
.first
].first
, P
.second
);
9289 if (parseToken(lltok::rparen
, "expected ')' in calls"))
9296 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
9297 bool LLParser::parseHotness(CalleeInfo::HotnessType
&Hotness
) {
9298 switch (Lex
.getKind()) {
9299 case lltok::kw_unknown
:
9300 Hotness
= CalleeInfo::HotnessType::Unknown
;
9302 case lltok::kw_cold
:
9303 Hotness
= CalleeInfo::HotnessType::Cold
;
9305 case lltok::kw_none
:
9306 Hotness
= CalleeInfo::HotnessType::None
;
9309 Hotness
= CalleeInfo::HotnessType::Hot
;
9311 case lltok::kw_critical
:
9312 Hotness
= CalleeInfo::HotnessType::Critical
;
9315 return error(Lex
.getLoc(), "invalid call edge hotness");
9321 /// OptionalVTableFuncs
9322 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
9323 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
9324 bool LLParser::parseOptionalVTableFuncs(VTableFuncList
&VTableFuncs
) {
9325 assert(Lex
.getKind() == lltok::kw_vTableFuncs
);
9328 if (parseToken(lltok::colon
, "expected ':' in vTableFuncs") ||
9329 parseToken(lltok::lparen
, "expected '(' in vTableFuncs"))
9332 IdToIndexMapType IdToIndexMap
;
9333 // parse each virtual function pair
9336 if (parseToken(lltok::lparen
, "expected '(' in vTableFunc") ||
9337 parseToken(lltok::kw_virtFunc
, "expected 'callee' in vTableFunc") ||
9338 parseToken(lltok::colon
, "expected ':'"))
9341 LocTy Loc
= Lex
.getLoc();
9343 if (parseGVReference(VI
, GVId
))
9347 if (parseToken(lltok::comma
, "expected comma") ||
9348 parseToken(lltok::kw_offset
, "expected offset") ||
9349 parseToken(lltok::colon
, "expected ':'") || parseUInt64(Offset
))
9352 // Keep track of the VTableFuncs array index needing a forward reference.
9353 // We will save the location of the ValueInfo needing an update, but
9354 // can only do so once the std::vector is finalized.
9356 IdToIndexMap
[GVId
].push_back(std::make_pair(VTableFuncs
.size(), Loc
));
9357 VTableFuncs
.push_back({VI
, Offset
});
9359 if (parseToken(lltok::rparen
, "expected ')' in vTableFunc"))
9361 } while (EatIfPresent(lltok::comma
));
9363 // Now that the VTableFuncs vector is finalized, it is safe to save the
9364 // locations of any forward GV references that need updating later.
9365 for (auto I
: IdToIndexMap
) {
9366 auto &Infos
= ForwardRefValueInfos
[I
.first
];
9367 for (auto P
: I
.second
) {
9368 assert(VTableFuncs
[P
.first
].FuncVI
== EmptyVI
&&
9369 "Forward referenced ValueInfo expected to be empty");
9370 Infos
.emplace_back(&VTableFuncs
[P
.first
].FuncVI
, P
.second
);
9374 if (parseToken(lltok::rparen
, "expected ')' in vTableFuncs"))
9380 /// ParamNo := 'param' ':' UInt64
9381 bool LLParser::parseParamNo(uint64_t &ParamNo
) {
9382 if (parseToken(lltok::kw_param
, "expected 'param' here") ||
9383 parseToken(lltok::colon
, "expected ':' here") || parseUInt64(ParamNo
))
9388 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
9389 bool LLParser::parseParamAccessOffset(ConstantRange
&Range
) {
9392 auto ParseAPSInt
= [&](APSInt
&Val
) {
9393 if (Lex
.getKind() != lltok::APSInt
)
9394 return tokError("expected integer");
9395 Val
= Lex
.getAPSIntVal();
9396 Val
= Val
.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth
);
9397 Val
.setIsSigned(true);
9401 if (parseToken(lltok::kw_offset
, "expected 'offset' here") ||
9402 parseToken(lltok::colon
, "expected ':' here") ||
9403 parseToken(lltok::lsquare
, "expected '[' here") || ParseAPSInt(Lower
) ||
9404 parseToken(lltok::comma
, "expected ',' here") || ParseAPSInt(Upper
) ||
9405 parseToken(lltok::rsquare
, "expected ']' here"))
9410 (Lower
== Upper
&& !Lower
.isMaxValue())
9411 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth
)
9412 : ConstantRange(Lower
, Upper
);
9418 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
9419 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call
&Call
,
9420 IdLocListType
&IdLocList
) {
9421 if (parseToken(lltok::lparen
, "expected '(' here") ||
9422 parseToken(lltok::kw_callee
, "expected 'callee' here") ||
9423 parseToken(lltok::colon
, "expected ':' here"))
9428 LocTy Loc
= Lex
.getLoc();
9429 if (parseGVReference(VI
, GVId
))
9433 IdLocList
.emplace_back(GVId
, Loc
);
9435 if (parseToken(lltok::comma
, "expected ',' here") ||
9436 parseParamNo(Call
.ParamNo
) ||
9437 parseToken(lltok::comma
, "expected ',' here") ||
9438 parseParamAccessOffset(Call
.Offsets
))
9441 if (parseToken(lltok::rparen
, "expected ')' here"))
9448 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
9449 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
9450 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess
&Param
,
9451 IdLocListType
&IdLocList
) {
9452 if (parseToken(lltok::lparen
, "expected '(' here") ||
9453 parseParamNo(Param
.ParamNo
) ||
9454 parseToken(lltok::comma
, "expected ',' here") ||
9455 parseParamAccessOffset(Param
.Use
))
9458 if (EatIfPresent(lltok::comma
)) {
9459 if (parseToken(lltok::kw_calls
, "expected 'calls' here") ||
9460 parseToken(lltok::colon
, "expected ':' here") ||
9461 parseToken(lltok::lparen
, "expected '(' here"))
9464 FunctionSummary::ParamAccess::Call Call
;
9465 if (parseParamAccessCall(Call
, IdLocList
))
9467 Param
.Calls
.push_back(Call
);
9468 } while (EatIfPresent(lltok::comma
));
9470 if (parseToken(lltok::rparen
, "expected ')' here"))
9474 if (parseToken(lltok::rparen
, "expected ')' here"))
9480 /// OptionalParamAccesses
9481 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
9482 bool LLParser::parseOptionalParamAccesses(
9483 std::vector
<FunctionSummary::ParamAccess
> &Params
) {
9484 assert(Lex
.getKind() == lltok::kw_params
);
9487 if (parseToken(lltok::colon
, "expected ':' here") ||
9488 parseToken(lltok::lparen
, "expected '(' here"))
9491 IdLocListType VContexts
;
9492 size_t CallsNum
= 0;
9494 FunctionSummary::ParamAccess ParamAccess
;
9495 if (parseParamAccess(ParamAccess
, VContexts
))
9497 CallsNum
+= ParamAccess
.Calls
.size();
9498 assert(VContexts
.size() == CallsNum
);
9500 Params
.emplace_back(std::move(ParamAccess
));
9501 } while (EatIfPresent(lltok::comma
));
9503 if (parseToken(lltok::rparen
, "expected ')' here"))
9506 // Now that the Params is finalized, it is safe to save the locations
9507 // of any forward GV references that need updating later.
9508 IdLocListType::const_iterator ItContext
= VContexts
.begin();
9509 for (auto &PA
: Params
) {
9510 for (auto &C
: PA
.Calls
) {
9511 if (C
.Callee
.getRef() == FwdVIRef
)
9512 ForwardRefValueInfos
[ItContext
->first
].emplace_back(&C
.Callee
,
9517 assert(ItContext
== VContexts
.end());
9523 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
9524 bool LLParser::parseOptionalRefs(std::vector
<ValueInfo
> &Refs
) {
9525 assert(Lex
.getKind() == lltok::kw_refs
);
9528 if (parseToken(lltok::colon
, "expected ':' in refs") ||
9529 parseToken(lltok::lparen
, "expected '(' in refs"))
9532 struct ValueContext
{
9537 std::vector
<ValueContext
> VContexts
;
9538 // parse each ref edge
9541 VC
.Loc
= Lex
.getLoc();
9542 if (parseGVReference(VC
.VI
, VC
.GVId
))
9544 VContexts
.push_back(VC
);
9545 } while (EatIfPresent(lltok::comma
));
9547 // Sort value contexts so that ones with writeonly
9548 // and readonly ValueInfo are at the end of VContexts vector.
9549 // See FunctionSummary::specialRefCounts()
9550 llvm::sort(VContexts
, [](const ValueContext
&VC1
, const ValueContext
&VC2
) {
9551 return VC1
.VI
.getAccessSpecifier() < VC2
.VI
.getAccessSpecifier();
9554 IdToIndexMapType IdToIndexMap
;
9555 for (auto &VC
: VContexts
) {
9556 // Keep track of the Refs array index needing a forward reference.
9557 // We will save the location of the ValueInfo needing an update, but
9558 // can only do so once the std::vector is finalized.
9559 if (VC
.VI
.getRef() == FwdVIRef
)
9560 IdToIndexMap
[VC
.GVId
].push_back(std::make_pair(Refs
.size(), VC
.Loc
));
9561 Refs
.push_back(VC
.VI
);
9564 // Now that the Refs vector is finalized, it is safe to save the locations
9565 // of any forward GV references that need updating later.
9566 for (auto I
: IdToIndexMap
) {
9567 auto &Infos
= ForwardRefValueInfos
[I
.first
];
9568 for (auto P
: I
.second
) {
9569 assert(Refs
[P
.first
].getRef() == FwdVIRef
&&
9570 "Forward referenced ValueInfo expected to be empty");
9571 Infos
.emplace_back(&Refs
[P
.first
], P
.second
);
9575 if (parseToken(lltok::rparen
, "expected ')' in refs"))
9581 /// OptionalTypeIdInfo
9582 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
9583 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
9584 /// [',' TypeCheckedLoadConstVCalls]? ')'
9585 bool LLParser::parseOptionalTypeIdInfo(
9586 FunctionSummary::TypeIdInfo
&TypeIdInfo
) {
9587 assert(Lex
.getKind() == lltok::kw_typeIdInfo
);
9590 if (parseToken(lltok::colon
, "expected ':' here") ||
9591 parseToken(lltok::lparen
, "expected '(' in typeIdInfo"))
9595 switch (Lex
.getKind()) {
9596 case lltok::kw_typeTests
:
9597 if (parseTypeTests(TypeIdInfo
.TypeTests
))
9600 case lltok::kw_typeTestAssumeVCalls
:
9601 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls
,
9602 TypeIdInfo
.TypeTestAssumeVCalls
))
9605 case lltok::kw_typeCheckedLoadVCalls
:
9606 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls
,
9607 TypeIdInfo
.TypeCheckedLoadVCalls
))
9610 case lltok::kw_typeTestAssumeConstVCalls
:
9611 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls
,
9612 TypeIdInfo
.TypeTestAssumeConstVCalls
))
9615 case lltok::kw_typeCheckedLoadConstVCalls
:
9616 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls
,
9617 TypeIdInfo
.TypeCheckedLoadConstVCalls
))
9621 return error(Lex
.getLoc(), "invalid typeIdInfo list type");
9623 } while (EatIfPresent(lltok::comma
));
9625 if (parseToken(lltok::rparen
, "expected ')' in typeIdInfo"))
9632 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9633 /// [',' (SummaryID | UInt64)]* ')'
9634 bool LLParser::parseTypeTests(std::vector
<GlobalValue::GUID
> &TypeTests
) {
9635 assert(Lex
.getKind() == lltok::kw_typeTests
);
9638 if (parseToken(lltok::colon
, "expected ':' here") ||
9639 parseToken(lltok::lparen
, "expected '(' in typeIdInfo"))
9642 IdToIndexMapType IdToIndexMap
;
9644 GlobalValue::GUID GUID
= 0;
9645 if (Lex
.getKind() == lltok::SummaryID
) {
9646 unsigned ID
= Lex
.getUIntVal();
9647 LocTy Loc
= Lex
.getLoc();
9648 // Keep track of the TypeTests array index needing a forward reference.
9649 // We will save the location of the GUID needing an update, but
9650 // can only do so once the std::vector is finalized.
9651 IdToIndexMap
[ID
].push_back(std::make_pair(TypeTests
.size(), Loc
));
9653 } else if (parseUInt64(GUID
))
9655 TypeTests
.push_back(GUID
);
9656 } while (EatIfPresent(lltok::comma
));
9658 // Now that the TypeTests vector is finalized, it is safe to save the
9659 // locations of any forward GV references that need updating later.
9660 for (auto I
: IdToIndexMap
) {
9661 auto &Ids
= ForwardRefTypeIds
[I
.first
];
9662 for (auto P
: I
.second
) {
9663 assert(TypeTests
[P
.first
] == 0 &&
9664 "Forward referenced type id GUID expected to be 0");
9665 Ids
.emplace_back(&TypeTests
[P
.first
], P
.second
);
9669 if (parseToken(lltok::rparen
, "expected ')' in typeIdInfo"))
9676 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
9677 bool LLParser::parseVFuncIdList(
9678 lltok::Kind Kind
, std::vector
<FunctionSummary::VFuncId
> &VFuncIdList
) {
9679 assert(Lex
.getKind() == Kind
);
9682 if (parseToken(lltok::colon
, "expected ':' here") ||
9683 parseToken(lltok::lparen
, "expected '(' here"))
9686 IdToIndexMapType IdToIndexMap
;
9688 FunctionSummary::VFuncId VFuncId
;
9689 if (parseVFuncId(VFuncId
, IdToIndexMap
, VFuncIdList
.size()))
9691 VFuncIdList
.push_back(VFuncId
);
9692 } while (EatIfPresent(lltok::comma
));
9694 if (parseToken(lltok::rparen
, "expected ')' here"))
9697 // Now that the VFuncIdList vector is finalized, it is safe to save the
9698 // locations of any forward GV references that need updating later.
9699 for (auto I
: IdToIndexMap
) {
9700 auto &Ids
= ForwardRefTypeIds
[I
.first
];
9701 for (auto P
: I
.second
) {
9702 assert(VFuncIdList
[P
.first
].GUID
== 0 &&
9703 "Forward referenced type id GUID expected to be 0");
9704 Ids
.emplace_back(&VFuncIdList
[P
.first
].GUID
, P
.second
);
9712 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
9713 bool LLParser::parseConstVCallList(
9715 std::vector
<FunctionSummary::ConstVCall
> &ConstVCallList
) {
9716 assert(Lex
.getKind() == Kind
);
9719 if (parseToken(lltok::colon
, "expected ':' here") ||
9720 parseToken(lltok::lparen
, "expected '(' here"))
9723 IdToIndexMapType IdToIndexMap
;
9725 FunctionSummary::ConstVCall ConstVCall
;
9726 if (parseConstVCall(ConstVCall
, IdToIndexMap
, ConstVCallList
.size()))
9728 ConstVCallList
.push_back(ConstVCall
);
9729 } while (EatIfPresent(lltok::comma
));
9731 if (parseToken(lltok::rparen
, "expected ')' here"))
9734 // Now that the ConstVCallList vector is finalized, it is safe to save the
9735 // locations of any forward GV references that need updating later.
9736 for (auto I
: IdToIndexMap
) {
9737 auto &Ids
= ForwardRefTypeIds
[I
.first
];
9738 for (auto P
: I
.second
) {
9739 assert(ConstVCallList
[P
.first
].VFunc
.GUID
== 0 &&
9740 "Forward referenced type id GUID expected to be 0");
9741 Ids
.emplace_back(&ConstVCallList
[P
.first
].VFunc
.GUID
, P
.second
);
9749 /// ::= '(' VFuncId ',' Args ')'
9750 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall
&ConstVCall
,
9751 IdToIndexMapType
&IdToIndexMap
, unsigned Index
) {
9752 if (parseToken(lltok::lparen
, "expected '(' here") ||
9753 parseVFuncId(ConstVCall
.VFunc
, IdToIndexMap
, Index
))
9756 if (EatIfPresent(lltok::comma
))
9757 if (parseArgs(ConstVCall
.Args
))
9760 if (parseToken(lltok::rparen
, "expected ')' here"))
9767 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9768 /// 'offset' ':' UInt64 ')'
9769 bool LLParser::parseVFuncId(FunctionSummary::VFuncId
&VFuncId
,
9770 IdToIndexMapType
&IdToIndexMap
, unsigned Index
) {
9771 assert(Lex
.getKind() == lltok::kw_vFuncId
);
9774 if (parseToken(lltok::colon
, "expected ':' here") ||
9775 parseToken(lltok::lparen
, "expected '(' here"))
9778 if (Lex
.getKind() == lltok::SummaryID
) {
9780 unsigned ID
= Lex
.getUIntVal();
9781 LocTy Loc
= Lex
.getLoc();
9782 // Keep track of the array index needing a forward reference.
9783 // We will save the location of the GUID needing an update, but
9784 // can only do so once the caller's std::vector is finalized.
9785 IdToIndexMap
[ID
].push_back(std::make_pair(Index
, Loc
));
9787 } else if (parseToken(lltok::kw_guid
, "expected 'guid' here") ||
9788 parseToken(lltok::colon
, "expected ':' here") ||
9789 parseUInt64(VFuncId
.GUID
))
9792 if (parseToken(lltok::comma
, "expected ',' here") ||
9793 parseToken(lltok::kw_offset
, "expected 'offset' here") ||
9794 parseToken(lltok::colon
, "expected ':' here") ||
9795 parseUInt64(VFuncId
.Offset
) ||
9796 parseToken(lltok::rparen
, "expected ')' here"))
9803 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9804 /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
9805 /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
9806 /// 'canAutoHide' ':' Flag ',' ')'
9807 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags
&GVFlags
) {
9808 assert(Lex
.getKind() == lltok::kw_flags
);
9811 if (parseToken(lltok::colon
, "expected ':' here") ||
9812 parseToken(lltok::lparen
, "expected '(' here"))
9817 switch (Lex
.getKind()) {
9818 case lltok::kw_linkage
:
9820 if (parseToken(lltok::colon
, "expected ':'"))
9823 GVFlags
.Linkage
= parseOptionalLinkageAux(Lex
.getKind(), HasLinkage
);
9824 assert(HasLinkage
&& "Linkage not optional in summary entry");
9827 case lltok::kw_visibility
:
9829 if (parseToken(lltok::colon
, "expected ':'"))
9831 parseOptionalVisibility(Flag
);
9832 GVFlags
.Visibility
= Flag
;
9834 case lltok::kw_notEligibleToImport
:
9836 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Flag
))
9838 GVFlags
.NotEligibleToImport
= Flag
;
9840 case lltok::kw_live
:
9842 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Flag
))
9844 GVFlags
.Live
= Flag
;
9846 case lltok::kw_dsoLocal
:
9848 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Flag
))
9850 GVFlags
.DSOLocal
= Flag
;
9852 case lltok::kw_canAutoHide
:
9854 if (parseToken(lltok::colon
, "expected ':'") || parseFlag(Flag
))
9856 GVFlags
.CanAutoHide
= Flag
;
9859 return error(Lex
.getLoc(), "expected gv flag type");
9861 } while (EatIfPresent(lltok::comma
));
9863 if (parseToken(lltok::rparen
, "expected ')' here"))
9870 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9871 /// ',' 'writeonly' ':' Flag
9872 /// ',' 'constant' ':' Flag ')'
9873 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags
&GVarFlags
) {
9874 assert(Lex
.getKind() == lltok::kw_varFlags
);
9877 if (parseToken(lltok::colon
, "expected ':' here") ||
9878 parseToken(lltok::lparen
, "expected '(' here"))
9881 auto ParseRest
= [this](unsigned int &Val
) {
9883 if (parseToken(lltok::colon
, "expected ':'"))
9885 return parseFlag(Val
);
9890 switch (Lex
.getKind()) {
9891 case lltok::kw_readonly
:
9892 if (ParseRest(Flag
))
9894 GVarFlags
.MaybeReadOnly
= Flag
;
9896 case lltok::kw_writeonly
:
9897 if (ParseRest(Flag
))
9899 GVarFlags
.MaybeWriteOnly
= Flag
;
9901 case lltok::kw_constant
:
9902 if (ParseRest(Flag
))
9904 GVarFlags
.Constant
= Flag
;
9906 case lltok::kw_vcall_visibility
:
9907 if (ParseRest(Flag
))
9909 GVarFlags
.VCallVisibility
= Flag
;
9912 return error(Lex
.getLoc(), "expected gvar flag type");
9914 } while (EatIfPresent(lltok::comma
));
9915 return parseToken(lltok::rparen
, "expected ')' here");
9919 /// ::= 'module' ':' UInt
9920 bool LLParser::parseModuleReference(StringRef
&ModulePath
) {
9922 if (parseToken(lltok::kw_module
, "expected 'module' here") ||
9923 parseToken(lltok::colon
, "expected ':' here") ||
9924 parseToken(lltok::SummaryID
, "expected module ID"))
9927 unsigned ModuleID
= Lex
.getUIntVal();
9928 auto I
= ModuleIdMap
.find(ModuleID
);
9929 // We should have already parsed all module IDs
9930 assert(I
!= ModuleIdMap
.end());
9931 ModulePath
= I
->second
;
9937 bool LLParser::parseGVReference(ValueInfo
&VI
, unsigned &GVId
) {
9938 bool WriteOnly
= false, ReadOnly
= EatIfPresent(lltok::kw_readonly
);
9940 WriteOnly
= EatIfPresent(lltok::kw_writeonly
);
9941 if (parseToken(lltok::SummaryID
, "expected GV ID"))
9944 GVId
= Lex
.getUIntVal();
9945 // Check if we already have a VI for this GV
9946 if (GVId
< NumberedValueInfos
.size() && NumberedValueInfos
[GVId
]) {
9947 assert(NumberedValueInfos
[GVId
].getRef() != FwdVIRef
);
9948 VI
= NumberedValueInfos
[GVId
];
9950 // We will create a forward reference to the stored location.
9951 VI
= ValueInfo(false, FwdVIRef
);
9961 /// := 'allocs' ':' '(' Alloc [',' Alloc]* ')'
9962 /// Alloc ::= '(' 'versions' ':' '(' Version [',' Version]* ')'
9963 /// ',' MemProfs ')'
9964 /// Version ::= UInt32
9965 bool LLParser::parseOptionalAllocs(std::vector
<AllocInfo
> &Allocs
) {
9966 assert(Lex
.getKind() == lltok::kw_allocs
);
9969 if (parseToken(lltok::colon
, "expected ':' in allocs") ||
9970 parseToken(lltok::lparen
, "expected '(' in allocs"))
9975 if (parseToken(lltok::lparen
, "expected '(' in alloc") ||
9976 parseToken(lltok::kw_versions
, "expected 'versions' in alloc") ||
9977 parseToken(lltok::colon
, "expected ':'") ||
9978 parseToken(lltok::lparen
, "expected '(' in versions"))
9981 SmallVector
<uint8_t> Versions
;
9984 if (parseAllocType(V
))
9986 Versions
.push_back(V
);
9987 } while (EatIfPresent(lltok::comma
));
9989 if (parseToken(lltok::rparen
, "expected ')' in versions") ||
9990 parseToken(lltok::comma
, "expected ',' in alloc"))
9993 std::vector
<MIBInfo
> MIBs
;
9994 if (parseMemProfs(MIBs
))
9997 Allocs
.push_back({Versions
, MIBs
});
9999 if (parseToken(lltok::rparen
, "expected ')' in alloc"))
10001 } while (EatIfPresent(lltok::comma
));
10003 if (parseToken(lltok::rparen
, "expected ')' in allocs"))
10010 /// := 'memProf' ':' '(' MemProf [',' MemProf]* ')'
10011 /// MemProf ::= '(' 'type' ':' AllocType
10012 /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10013 /// StackId ::= UInt64
10014 bool LLParser::parseMemProfs(std::vector
<MIBInfo
> &MIBs
) {
10015 assert(Lex
.getKind() == lltok::kw_memProf
);
10018 if (parseToken(lltok::colon
, "expected ':' in memprof") ||
10019 parseToken(lltok::lparen
, "expected '(' in memprof"))
10024 if (parseToken(lltok::lparen
, "expected '(' in memprof") ||
10025 parseToken(lltok::kw_type
, "expected 'type' in memprof") ||
10026 parseToken(lltok::colon
, "expected ':'"))
10030 if (parseAllocType(AllocType
))
10033 if (parseToken(lltok::comma
, "expected ',' in memprof") ||
10034 parseToken(lltok::kw_stackIds
, "expected 'stackIds' in memprof") ||
10035 parseToken(lltok::colon
, "expected ':'") ||
10036 parseToken(lltok::lparen
, "expected '(' in stackIds"))
10039 SmallVector
<unsigned> StackIdIndices
;
10041 uint64_t StackId
= 0;
10042 if (parseUInt64(StackId
))
10044 StackIdIndices
.push_back(Index
->addOrGetStackIdIndex(StackId
));
10045 } while (EatIfPresent(lltok::comma
));
10047 if (parseToken(lltok::rparen
, "expected ')' in stackIds"))
10050 MIBs
.push_back({(AllocationType
)AllocType
, StackIdIndices
});
10052 if (parseToken(lltok::rparen
, "expected ')' in memprof"))
10054 } while (EatIfPresent(lltok::comma
));
10056 if (parseToken(lltok::rparen
, "expected ')' in memprof"))
10063 /// := ('none'|'notcold'|'cold'|'hot')
10064 bool LLParser::parseAllocType(uint8_t &AllocType
) {
10065 switch (Lex
.getKind()) {
10066 case lltok::kw_none
:
10067 AllocType
= (uint8_t)AllocationType::None
;
10069 case lltok::kw_notcold
:
10070 AllocType
= (uint8_t)AllocationType::NotCold
;
10072 case lltok::kw_cold
:
10073 AllocType
= (uint8_t)AllocationType::Cold
;
10075 case lltok::kw_hot
:
10076 AllocType
= (uint8_t)AllocationType::Hot
;
10079 return error(Lex
.getLoc(), "invalid alloc type");
10085 /// OptionalCallsites
10086 /// := 'callsites' ':' '(' Callsite [',' Callsite]* ')'
10087 /// Callsite ::= '(' 'callee' ':' GVReference
10088 /// ',' 'clones' ':' '(' Version [',' Version]* ')'
10089 /// ',' 'stackIds' ':' '(' StackId [',' StackId]* ')' ')'
10090 /// Version ::= UInt32
10091 /// StackId ::= UInt64
10092 bool LLParser::parseOptionalCallsites(std::vector
<CallsiteInfo
> &Callsites
) {
10093 assert(Lex
.getKind() == lltok::kw_callsites
);
10096 if (parseToken(lltok::colon
, "expected ':' in callsites") ||
10097 parseToken(lltok::lparen
, "expected '(' in callsites"))
10100 IdToIndexMapType IdToIndexMap
;
10101 // parse each callsite
10103 if (parseToken(lltok::lparen
, "expected '(' in callsite") ||
10104 parseToken(lltok::kw_callee
, "expected 'callee' in callsite") ||
10105 parseToken(lltok::colon
, "expected ':'"))
10110 LocTy Loc
= Lex
.getLoc();
10111 if (!EatIfPresent(lltok::kw_null
)) {
10112 if (parseGVReference(VI
, GVId
))
10116 if (parseToken(lltok::comma
, "expected ',' in callsite") ||
10117 parseToken(lltok::kw_clones
, "expected 'clones' in callsite") ||
10118 parseToken(lltok::colon
, "expected ':'") ||
10119 parseToken(lltok::lparen
, "expected '(' in clones"))
10122 SmallVector
<unsigned> Clones
;
10125 if (parseUInt32(V
))
10127 Clones
.push_back(V
);
10128 } while (EatIfPresent(lltok::comma
));
10130 if (parseToken(lltok::rparen
, "expected ')' in clones") ||
10131 parseToken(lltok::comma
, "expected ',' in callsite") ||
10132 parseToken(lltok::kw_stackIds
, "expected 'stackIds' in callsite") ||
10133 parseToken(lltok::colon
, "expected ':'") ||
10134 parseToken(lltok::lparen
, "expected '(' in stackIds"))
10137 SmallVector
<unsigned> StackIdIndices
;
10139 uint64_t StackId
= 0;
10140 if (parseUInt64(StackId
))
10142 StackIdIndices
.push_back(Index
->addOrGetStackIdIndex(StackId
));
10143 } while (EatIfPresent(lltok::comma
));
10145 if (parseToken(lltok::rparen
, "expected ')' in stackIds"))
10148 // Keep track of the Callsites array index needing a forward reference.
10149 // We will save the location of the ValueInfo needing an update, but
10150 // can only do so once the SmallVector is finalized.
10151 if (VI
.getRef() == FwdVIRef
)
10152 IdToIndexMap
[GVId
].push_back(std::make_pair(Callsites
.size(), Loc
));
10153 Callsites
.push_back({VI
, Clones
, StackIdIndices
});
10155 if (parseToken(lltok::rparen
, "expected ')' in callsite"))
10157 } while (EatIfPresent(lltok::comma
));
10159 // Now that the Callsites vector is finalized, it is safe to save the
10160 // locations of any forward GV references that need updating later.
10161 for (auto I
: IdToIndexMap
) {
10162 auto &Infos
= ForwardRefValueInfos
[I
.first
];
10163 for (auto P
: I
.second
) {
10164 assert(Callsites
[P
.first
].Callee
.getRef() == FwdVIRef
&&
10165 "Forward referenced ValueInfo expected to be empty");
10166 Infos
.emplace_back(&Callsites
[P
.first
].Callee
, P
.second
);
10170 if (parseToken(lltok::rparen
, "expected ')' in callsites"))