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 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/SlotMapping.h"
20 #include "llvm/BinaryFormat/Dwarf.h"
21 #include "llvm/IR/Argument.h"
22 #include "llvm/IR/AutoUpgrade.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Comdat.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugInfoMetadata.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalIFunc.h"
31 #include "llvm/IR/GlobalObject.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/IR/ValueSymbolTable.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/SaveAndRestore.h"
47 #include "llvm/Support/raw_ostream.h"
56 static std::string
getTypeString(Type
*T
) {
58 raw_string_ostream
Tmp(Result
);
63 /// Run: module ::= toplevelentity*
64 bool LLParser::Run() {
68 if (Context
.shouldDiscardValueNames())
71 "Can't read textual IR with a Context that discards named Values");
73 return ParseTopLevelEntities() || ValidateEndOfModule() ||
77 bool LLParser::parseStandaloneConstantValue(Constant
*&C
,
78 const SlotMapping
*Slots
) {
79 restoreParsingState(Slots
);
83 if (ParseType(Ty
) || parseConstantValue(Ty
, C
))
85 if (Lex
.getKind() != lltok::Eof
)
86 return Error(Lex
.getLoc(), "expected end of string");
90 bool LLParser::parseTypeAtBeginning(Type
*&Ty
, unsigned &Read
,
91 const SlotMapping
*Slots
) {
92 restoreParsingState(Slots
);
96 SMLoc Start
= Lex
.getLoc();
100 SMLoc End
= Lex
.getLoc();
101 Read
= End
.getPointer() - Start
.getPointer();
106 void LLParser::restoreParsingState(const SlotMapping
*Slots
) {
109 NumberedVals
= Slots
->GlobalValues
;
110 NumberedMetadata
= Slots
->MetadataNodes
;
111 for (const auto &I
: Slots
->NamedTypes
)
113 std::make_pair(I
.getKey(), std::make_pair(I
.second
, LocTy())));
114 for (const auto &I
: Slots
->Types
)
115 NumberedTypes
.insert(
116 std::make_pair(I
.first
, std::make_pair(I
.second
, LocTy())));
119 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121 bool LLParser::ValidateEndOfModule() {
124 // Handle any function attribute group forward references.
125 for (const auto &RAG
: ForwardRefAttrGroups
) {
126 Value
*V
= RAG
.first
;
127 const std::vector
<unsigned> &Attrs
= RAG
.second
;
130 for (const auto &Attr
: Attrs
)
131 B
.merge(NumberedAttrBuilders
[Attr
]);
133 if (Function
*Fn
= dyn_cast
<Function
>(V
)) {
134 AttributeList AS
= Fn
->getAttributes();
135 AttrBuilder
FnAttrs(AS
.getFnAttributes());
136 AS
= AS
.removeAttributes(Context
, AttributeList::FunctionIndex
);
140 // If the alignment was parsed as an attribute, move to the alignment
142 if (FnAttrs
.hasAlignmentAttr()) {
143 Fn
->setAlignment(FnAttrs
.getAlignment());
144 FnAttrs
.removeAttribute(Attribute::Alignment
);
147 AS
= AS
.addAttributes(Context
, AttributeList::FunctionIndex
,
148 AttributeSet::get(Context
, FnAttrs
));
149 Fn
->setAttributes(AS
);
150 } else if (CallInst
*CI
= dyn_cast
<CallInst
>(V
)) {
151 AttributeList AS
= CI
->getAttributes();
152 AttrBuilder
FnAttrs(AS
.getFnAttributes());
153 AS
= AS
.removeAttributes(Context
, AttributeList::FunctionIndex
);
155 AS
= AS
.addAttributes(Context
, AttributeList::FunctionIndex
,
156 AttributeSet::get(Context
, FnAttrs
));
157 CI
->setAttributes(AS
);
158 } else if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(V
)) {
159 AttributeList AS
= II
->getAttributes();
160 AttrBuilder
FnAttrs(AS
.getFnAttributes());
161 AS
= AS
.removeAttributes(Context
, AttributeList::FunctionIndex
);
163 AS
= AS
.addAttributes(Context
, AttributeList::FunctionIndex
,
164 AttributeSet::get(Context
, FnAttrs
));
165 II
->setAttributes(AS
);
166 } else if (CallBrInst
*CBI
= dyn_cast
<CallBrInst
>(V
)) {
167 AttributeList AS
= CBI
->getAttributes();
168 AttrBuilder
FnAttrs(AS
.getFnAttributes());
169 AS
= AS
.removeAttributes(Context
, AttributeList::FunctionIndex
);
171 AS
= AS
.addAttributes(Context
, AttributeList::FunctionIndex
,
172 AttributeSet::get(Context
, FnAttrs
));
173 CBI
->setAttributes(AS
);
174 } else if (auto *GV
= dyn_cast
<GlobalVariable
>(V
)) {
175 AttrBuilder
Attrs(GV
->getAttributes());
177 GV
->setAttributes(AttributeSet::get(Context
,Attrs
));
179 llvm_unreachable("invalid object with forward attribute group reference");
183 // If there are entries in ForwardRefBlockAddresses at this point, the
184 // function was never defined.
185 if (!ForwardRefBlockAddresses
.empty())
186 return Error(ForwardRefBlockAddresses
.begin()->first
.Loc
,
187 "expected function name in blockaddress");
189 for (const auto &NT
: NumberedTypes
)
190 if (NT
.second
.second
.isValid())
191 return Error(NT
.second
.second
,
192 "use of undefined type '%" + Twine(NT
.first
) + "'");
194 for (StringMap
<std::pair
<Type
*, LocTy
> >::iterator I
=
195 NamedTypes
.begin(), E
= NamedTypes
.end(); I
!= E
; ++I
)
196 if (I
->second
.second
.isValid())
197 return Error(I
->second
.second
,
198 "use of undefined type named '" + I
->getKey() + "'");
200 if (!ForwardRefComdats
.empty())
201 return Error(ForwardRefComdats
.begin()->second
,
202 "use of undefined comdat '$" +
203 ForwardRefComdats
.begin()->first
+ "'");
205 if (!ForwardRefVals
.empty())
206 return Error(ForwardRefVals
.begin()->second
.second
,
207 "use of undefined value '@" + ForwardRefVals
.begin()->first
+
210 if (!ForwardRefValIDs
.empty())
211 return Error(ForwardRefValIDs
.begin()->second
.second
,
212 "use of undefined value '@" +
213 Twine(ForwardRefValIDs
.begin()->first
) + "'");
215 if (!ForwardRefMDNodes
.empty())
216 return Error(ForwardRefMDNodes
.begin()->second
.second
,
217 "use of undefined metadata '!" +
218 Twine(ForwardRefMDNodes
.begin()->first
) + "'");
220 // Resolve metadata cycles.
221 for (auto &N
: NumberedMetadata
) {
222 if (N
.second
&& !N
.second
->isResolved())
223 N
.second
->resolveCycles();
226 for (auto *Inst
: InstsWithTBAATag
) {
227 MDNode
*MD
= Inst
->getMetadata(LLVMContext::MD_tbaa
);
228 assert(MD
&& "UpgradeInstWithTBAATag should have a TBAA tag");
229 auto *UpgradedMD
= UpgradeTBAANode(*MD
);
230 if (MD
!= UpgradedMD
)
231 Inst
->setMetadata(LLVMContext::MD_tbaa
, UpgradedMD
);
234 // Look for intrinsic functions and CallInst that need to be upgraded
235 for (Module::iterator FI
= M
->begin(), FE
= M
->end(); FI
!= FE
; )
236 UpgradeCallsToIntrinsic(&*FI
++); // must be post-increment, as we remove
238 // Some types could be renamed during loading if several modules are
239 // loaded in the same LLVMContext (LTO scenario). In this case we should
240 // remangle intrinsics names as well.
241 for (Module::iterator FI
= M
->begin(), FE
= M
->end(); FI
!= FE
; ) {
242 Function
*F
= &*FI
++;
243 if (auto Remangled
= Intrinsic::remangleIntrinsicFunction(F
)) {
244 F
->replaceAllUsesWith(Remangled
.getValue());
245 F
->eraseFromParent();
249 if (UpgradeDebugInfo
)
250 llvm::UpgradeDebugInfo(*M
);
252 UpgradeModuleFlags(*M
);
253 UpgradeSectionAttributes(*M
);
257 // Initialize the slot mapping.
258 // Because by this point we've parsed and validated everything, we can "steal"
259 // the mapping from LLParser as it doesn't need it anymore.
260 Slots
->GlobalValues
= std::move(NumberedVals
);
261 Slots
->MetadataNodes
= std::move(NumberedMetadata
);
262 for (const auto &I
: NamedTypes
)
263 Slots
->NamedTypes
.insert(std::make_pair(I
.getKey(), I
.second
.first
));
264 for (const auto &I
: NumberedTypes
)
265 Slots
->Types
.insert(std::make_pair(I
.first
, I
.second
.first
));
270 /// Do final validity and sanity checks at the end of the index.
271 bool LLParser::ValidateEndOfIndex() {
275 if (!ForwardRefValueInfos
.empty())
276 return Error(ForwardRefValueInfos
.begin()->second
.front().second
,
277 "use of undefined summary '^" +
278 Twine(ForwardRefValueInfos
.begin()->first
) + "'");
280 if (!ForwardRefAliasees
.empty())
281 return Error(ForwardRefAliasees
.begin()->second
.front().second
,
282 "use of undefined summary '^" +
283 Twine(ForwardRefAliasees
.begin()->first
) + "'");
285 if (!ForwardRefTypeIds
.empty())
286 return Error(ForwardRefTypeIds
.begin()->second
.front().second
,
287 "use of undefined type id summary '^" +
288 Twine(ForwardRefTypeIds
.begin()->first
) + "'");
293 //===----------------------------------------------------------------------===//
294 // Top-Level Entities
295 //===----------------------------------------------------------------------===//
297 bool LLParser::ParseTopLevelEntities() {
298 // If there is no Module, then parse just the summary index entries.
301 switch (Lex
.getKind()) {
304 case lltok::SummaryID
:
305 if (ParseSummaryEntry())
308 case lltok::kw_source_filename
:
309 if (ParseSourceFileName())
313 // Skip everything else
319 switch (Lex
.getKind()) {
320 default: return TokError("expected top-level entity");
321 case lltok::Eof
: return false;
322 case lltok::kw_declare
: if (ParseDeclare()) return true; break;
323 case lltok::kw_define
: if (ParseDefine()) return true; break;
324 case lltok::kw_module
: if (ParseModuleAsm()) return true; break;
325 case lltok::kw_target
: if (ParseTargetDefinition()) return true; break;
326 case lltok::kw_source_filename
:
327 if (ParseSourceFileName())
330 case lltok::kw_deplibs
: if (ParseDepLibs()) return true; break;
331 case lltok::LocalVarID
: if (ParseUnnamedType()) return true; break;
332 case lltok::LocalVar
: if (ParseNamedType()) return true; break;
333 case lltok::GlobalID
: if (ParseUnnamedGlobal()) return true; break;
334 case lltok::GlobalVar
: if (ParseNamedGlobal()) return true; break;
335 case lltok::ComdatVar
: if (parseComdat()) return true; break;
336 case lltok::exclaim
: if (ParseStandaloneMetadata()) return true; break;
337 case lltok::SummaryID
:
338 if (ParseSummaryEntry())
341 case lltok::MetadataVar
:if (ParseNamedMetadata()) return true; break;
342 case lltok::kw_attributes
: if (ParseUnnamedAttrGrp()) return true; break;
343 case lltok::kw_uselistorder
: if (ParseUseListOrder()) return true; break;
344 case lltok::kw_uselistorder_bb
:
345 if (ParseUseListOrderBB())
353 /// ::= 'module' 'asm' STRINGCONSTANT
354 bool LLParser::ParseModuleAsm() {
355 assert(Lex
.getKind() == lltok::kw_module
);
359 if (ParseToken(lltok::kw_asm
, "expected 'module asm'") ||
360 ParseStringConstant(AsmStr
)) return true;
362 M
->appendModuleInlineAsm(AsmStr
);
367 /// ::= 'target' 'triple' '=' STRINGCONSTANT
368 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
369 bool LLParser::ParseTargetDefinition() {
370 assert(Lex
.getKind() == lltok::kw_target
);
373 default: return TokError("unknown target property");
374 case lltok::kw_triple
:
376 if (ParseToken(lltok::equal
, "expected '=' after target triple") ||
377 ParseStringConstant(Str
))
379 M
->setTargetTriple(Str
);
381 case lltok::kw_datalayout
:
383 if (ParseToken(lltok::equal
, "expected '=' after target datalayout") ||
384 ParseStringConstant(Str
))
386 if (DataLayoutStr
.empty())
387 M
->setDataLayout(Str
);
393 /// ::= 'source_filename' '=' STRINGCONSTANT
394 bool LLParser::ParseSourceFileName() {
395 assert(Lex
.getKind() == lltok::kw_source_filename
);
397 if (ParseToken(lltok::equal
, "expected '=' after source_filename") ||
398 ParseStringConstant(SourceFileName
))
401 M
->setSourceFileName(SourceFileName
);
406 /// ::= 'deplibs' '=' '[' ']'
407 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
408 /// FIXME: Remove in 4.0. Currently parse, but ignore.
409 bool LLParser::ParseDepLibs() {
410 assert(Lex
.getKind() == lltok::kw_deplibs
);
412 if (ParseToken(lltok::equal
, "expected '=' after deplibs") ||
413 ParseToken(lltok::lsquare
, "expected '=' after deplibs"))
416 if (EatIfPresent(lltok::rsquare
))
421 if (ParseStringConstant(Str
)) return true;
422 } while (EatIfPresent(lltok::comma
));
424 return ParseToken(lltok::rsquare
, "expected ']' at end of list");
427 /// ParseUnnamedType:
428 /// ::= LocalVarID '=' 'type' type
429 bool LLParser::ParseUnnamedType() {
430 LocTy TypeLoc
= Lex
.getLoc();
431 unsigned TypeID
= Lex
.getUIntVal();
432 Lex
.Lex(); // eat LocalVarID;
434 if (ParseToken(lltok::equal
, "expected '=' after name") ||
435 ParseToken(lltok::kw_type
, "expected 'type' after '='"))
438 Type
*Result
= nullptr;
439 if (ParseStructDefinition(TypeLoc
, "",
440 NumberedTypes
[TypeID
], Result
)) return true;
442 if (!isa
<StructType
>(Result
)) {
443 std::pair
<Type
*, LocTy
> &Entry
= NumberedTypes
[TypeID
];
445 return Error(TypeLoc
, "non-struct types may not be recursive");
446 Entry
.first
= Result
;
447 Entry
.second
= SMLoc();
454 /// ::= LocalVar '=' 'type' type
455 bool LLParser::ParseNamedType() {
456 std::string Name
= Lex
.getStrVal();
457 LocTy NameLoc
= Lex
.getLoc();
458 Lex
.Lex(); // eat LocalVar.
460 if (ParseToken(lltok::equal
, "expected '=' after name") ||
461 ParseToken(lltok::kw_type
, "expected 'type' after name"))
464 Type
*Result
= nullptr;
465 if (ParseStructDefinition(NameLoc
, Name
,
466 NamedTypes
[Name
], Result
)) return true;
468 if (!isa
<StructType
>(Result
)) {
469 std::pair
<Type
*, LocTy
> &Entry
= NamedTypes
[Name
];
471 return Error(NameLoc
, "non-struct types may not be recursive");
472 Entry
.first
= Result
;
473 Entry
.second
= SMLoc();
480 /// ::= 'declare' FunctionHeader
481 bool LLParser::ParseDeclare() {
482 assert(Lex
.getKind() == lltok::kw_declare
);
485 std::vector
<std::pair
<unsigned, MDNode
*>> MDs
;
486 while (Lex
.getKind() == lltok::MetadataVar
) {
489 if (ParseMetadataAttachment(MDK
, N
))
491 MDs
.push_back({MDK
, N
});
495 if (ParseFunctionHeader(F
, false))
498 F
->addMetadata(MD
.first
, *MD
.second
);
503 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
504 bool LLParser::ParseDefine() {
505 assert(Lex
.getKind() == lltok::kw_define
);
509 return ParseFunctionHeader(F
, true) ||
510 ParseOptionalFunctionMetadata(*F
) ||
511 ParseFunctionBody(*F
);
517 bool LLParser::ParseGlobalType(bool &IsConstant
) {
518 if (Lex
.getKind() == lltok::kw_constant
)
520 else if (Lex
.getKind() == lltok::kw_global
)
524 return TokError("expected 'global' or 'constant'");
530 bool LLParser::ParseOptionalUnnamedAddr(
531 GlobalVariable::UnnamedAddr
&UnnamedAddr
) {
532 if (EatIfPresent(lltok::kw_unnamed_addr
))
533 UnnamedAddr
= GlobalValue::UnnamedAddr::Global
;
534 else if (EatIfPresent(lltok::kw_local_unnamed_addr
))
535 UnnamedAddr
= GlobalValue::UnnamedAddr::Local
;
537 UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
541 /// ParseUnnamedGlobal:
542 /// OptionalVisibility (ALIAS | IFUNC) ...
543 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
544 /// OptionalDLLStorageClass
545 /// ... -> global variable
546 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
547 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
548 /// OptionalDLLStorageClass
549 /// ... -> global variable
550 bool LLParser::ParseUnnamedGlobal() {
551 unsigned VarID
= NumberedVals
.size();
553 LocTy NameLoc
= Lex
.getLoc();
555 // Handle the GlobalID form.
556 if (Lex
.getKind() == lltok::GlobalID
) {
557 if (Lex
.getUIntVal() != VarID
)
558 return Error(Lex
.getLoc(), "variable expected to be numbered '%" +
560 Lex
.Lex(); // eat GlobalID;
562 if (ParseToken(lltok::equal
, "expected '=' after name"))
567 unsigned Linkage
, Visibility
, DLLStorageClass
;
569 GlobalVariable::ThreadLocalMode TLM
;
570 GlobalVariable::UnnamedAddr UnnamedAddr
;
571 if (ParseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
573 ParseOptionalThreadLocal(TLM
) || ParseOptionalUnnamedAddr(UnnamedAddr
))
576 if (Lex
.getKind() != lltok::kw_alias
&& Lex
.getKind() != lltok::kw_ifunc
)
577 return ParseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
,
578 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
580 return parseIndirectSymbol(Name
, NameLoc
, Linkage
, Visibility
,
581 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
584 /// ParseNamedGlobal:
585 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
586 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
587 /// OptionalVisibility OptionalDLLStorageClass
588 /// ... -> global variable
589 bool LLParser::ParseNamedGlobal() {
590 assert(Lex
.getKind() == lltok::GlobalVar
);
591 LocTy NameLoc
= Lex
.getLoc();
592 std::string Name
= Lex
.getStrVal();
596 unsigned Linkage
, Visibility
, DLLStorageClass
;
598 GlobalVariable::ThreadLocalMode TLM
;
599 GlobalVariable::UnnamedAddr UnnamedAddr
;
600 if (ParseToken(lltok::equal
, "expected '=' in global variable") ||
601 ParseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
603 ParseOptionalThreadLocal(TLM
) || ParseOptionalUnnamedAddr(UnnamedAddr
))
606 if (Lex
.getKind() != lltok::kw_alias
&& Lex
.getKind() != lltok::kw_ifunc
)
607 return ParseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
,
608 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
610 return parseIndirectSymbol(Name
, NameLoc
, Linkage
, Visibility
,
611 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
614 bool LLParser::parseComdat() {
615 assert(Lex
.getKind() == lltok::ComdatVar
);
616 std::string Name
= Lex
.getStrVal();
617 LocTy NameLoc
= Lex
.getLoc();
620 if (ParseToken(lltok::equal
, "expected '=' here"))
623 if (ParseToken(lltok::kw_comdat
, "expected comdat keyword"))
624 return TokError("expected comdat type");
626 Comdat::SelectionKind SK
;
627 switch (Lex
.getKind()) {
629 return TokError("unknown selection kind");
633 case lltok::kw_exactmatch
:
634 SK
= Comdat::ExactMatch
;
636 case lltok::kw_largest
:
637 SK
= Comdat::Largest
;
639 case lltok::kw_noduplicates
:
640 SK
= Comdat::NoDuplicates
;
642 case lltok::kw_samesize
:
643 SK
= Comdat::SameSize
;
648 // See if the comdat was forward referenced, if so, use the comdat.
649 Module::ComdatSymTabType
&ComdatSymTab
= M
->getComdatSymbolTable();
650 Module::ComdatSymTabType::iterator I
= ComdatSymTab
.find(Name
);
651 if (I
!= ComdatSymTab
.end() && !ForwardRefComdats
.erase(Name
))
652 return Error(NameLoc
, "redefinition of comdat '$" + Name
+ "'");
655 if (I
!= ComdatSymTab
.end())
658 C
= M
->getOrInsertComdat(Name
);
659 C
->setSelectionKind(SK
);
665 // ::= '!' STRINGCONSTANT
666 bool LLParser::ParseMDString(MDString
*&Result
) {
668 if (ParseStringConstant(Str
)) return true;
669 Result
= MDString::get(Context
, Str
);
674 // ::= '!' MDNodeNumber
675 bool LLParser::ParseMDNodeID(MDNode
*&Result
) {
676 // !{ ..., !42, ... }
677 LocTy IDLoc
= Lex
.getLoc();
679 if (ParseUInt32(MID
))
682 // If not a forward reference, just return it now.
683 if (NumberedMetadata
.count(MID
)) {
684 Result
= NumberedMetadata
[MID
];
688 // Otherwise, create MDNode forward reference.
689 auto &FwdRef
= ForwardRefMDNodes
[MID
];
690 FwdRef
= std::make_pair(MDTuple::getTemporary(Context
, None
), IDLoc
);
692 Result
= FwdRef
.first
.get();
693 NumberedMetadata
[MID
].reset(Result
);
697 /// ParseNamedMetadata:
698 /// !foo = !{ !1, !2 }
699 bool LLParser::ParseNamedMetadata() {
700 assert(Lex
.getKind() == lltok::MetadataVar
);
701 std::string Name
= Lex
.getStrVal();
704 if (ParseToken(lltok::equal
, "expected '=' here") ||
705 ParseToken(lltok::exclaim
, "Expected '!' here") ||
706 ParseToken(lltok::lbrace
, "Expected '{' here"))
709 NamedMDNode
*NMD
= M
->getOrInsertNamedMetadata(Name
);
710 if (Lex
.getKind() != lltok::rbrace
)
713 // Parse DIExpressions inline as a special case. They are still MDNodes,
714 // so they can still appear in named metadata. Remove this logic if they
715 // become plain Metadata.
716 if (Lex
.getKind() == lltok::MetadataVar
&&
717 Lex
.getStrVal() == "DIExpression") {
718 if (ParseDIExpression(N
, /*IsDistinct=*/false))
720 } else if (ParseToken(lltok::exclaim
, "Expected '!' here") ||
725 } while (EatIfPresent(lltok::comma
));
727 return ParseToken(lltok::rbrace
, "expected end of metadata node");
730 /// ParseStandaloneMetadata:
732 bool LLParser::ParseStandaloneMetadata() {
733 assert(Lex
.getKind() == lltok::exclaim
);
735 unsigned MetadataID
= 0;
738 if (ParseUInt32(MetadataID
) ||
739 ParseToken(lltok::equal
, "expected '=' here"))
742 // Detect common error, from old metadata syntax.
743 if (Lex
.getKind() == lltok::Type
)
744 return TokError("unexpected type in metadata definition");
746 bool IsDistinct
= EatIfPresent(lltok::kw_distinct
);
747 if (Lex
.getKind() == lltok::MetadataVar
) {
748 if (ParseSpecializedMDNode(Init
, IsDistinct
))
750 } else if (ParseToken(lltok::exclaim
, "Expected '!' here") ||
751 ParseMDTuple(Init
, IsDistinct
))
754 // See if this was forward referenced, if so, handle it.
755 auto FI
= ForwardRefMDNodes
.find(MetadataID
);
756 if (FI
!= ForwardRefMDNodes
.end()) {
757 FI
->second
.first
->replaceAllUsesWith(Init
);
758 ForwardRefMDNodes
.erase(FI
);
760 assert(NumberedMetadata
[MetadataID
] == Init
&& "Tracking VH didn't work");
762 if (NumberedMetadata
.count(MetadataID
))
763 return TokError("Metadata id is already used");
764 NumberedMetadata
[MetadataID
].reset(Init
);
770 // Skips a single module summary entry.
771 bool LLParser::SkipModuleSummaryEntry() {
772 // Each module summary entry consists of a tag for the entry
773 // type, followed by a colon, then the fields surrounded by nested sets of
774 // parentheses. The "tag:" looks like a Label. Once parsing support is
775 // in place we will look for the tokens corresponding to the expected tags.
776 if (Lex
.getKind() != lltok::kw_gv
&& Lex
.getKind() != lltok::kw_module
&&
777 Lex
.getKind() != lltok::kw_typeid
)
779 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
781 if (ParseToken(lltok::colon
, "expected ':' at start of summary entry") ||
782 ParseToken(lltok::lparen
, "expected '(' at start of summary entry"))
784 // Now walk through the parenthesized entry, until the number of open
785 // parentheses goes back down to 0 (the first '(' was parsed above).
786 unsigned NumOpenParen
= 1;
788 switch (Lex
.getKind()) {
796 return TokError("found end of file while parsing summary entry");
798 // Skip everything in between parentheses.
802 } while (NumOpenParen
> 0);
807 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
808 bool LLParser::ParseSummaryEntry() {
809 assert(Lex
.getKind() == lltok::SummaryID
);
810 unsigned SummaryID
= Lex
.getUIntVal();
812 // For summary entries, colons should be treated as distinct tokens,
813 // not an indication of the end of a label token.
814 Lex
.setIgnoreColonInIdentifiers(true);
817 if (ParseToken(lltok::equal
, "expected '=' here"))
820 // If we don't have an index object, skip the summary entry.
822 return SkipModuleSummaryEntry();
825 switch (Lex
.getKind()) {
827 result
= ParseGVEntry(SummaryID
);
829 case lltok::kw_module
:
830 result
= ParseModuleEntry(SummaryID
);
832 case lltok::kw_typeid
:
833 result
= ParseTypeIdEntry(SummaryID
);
835 case lltok::kw_typeidCompatibleVTable
:
836 result
= ParseTypeIdCompatibleVtableEntry(SummaryID
);
839 result
= Error(Lex
.getLoc(), "unexpected summary kind");
842 Lex
.setIgnoreColonInIdentifiers(false);
846 static bool isValidVisibilityForLinkage(unsigned V
, unsigned L
) {
847 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes
)L
) ||
848 (GlobalValue::VisibilityTypes
)V
== GlobalValue::DefaultVisibility
;
851 // If there was an explicit dso_local, update GV. In the absence of an explicit
852 // dso_local we keep the default value.
853 static void maybeSetDSOLocal(bool DSOLocal
, GlobalValue
&GV
) {
855 GV
.setDSOLocal(true);
858 /// parseIndirectSymbol:
859 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
860 /// OptionalVisibility OptionalDLLStorageClass
861 /// OptionalThreadLocal OptionalUnnamedAddr
862 /// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
867 /// IndirectSymbolAttr
868 /// ::= ',' 'partition' StringConstant
870 /// Everything through OptionalUnnamedAddr has already been parsed.
872 bool LLParser::parseIndirectSymbol(const std::string
&Name
, LocTy NameLoc
,
873 unsigned L
, unsigned Visibility
,
874 unsigned DLLStorageClass
, bool DSOLocal
,
875 GlobalVariable::ThreadLocalMode TLM
,
876 GlobalVariable::UnnamedAddr UnnamedAddr
) {
878 if (Lex
.getKind() == lltok::kw_alias
)
880 else if (Lex
.getKind() == lltok::kw_ifunc
)
883 llvm_unreachable("Not an alias or ifunc!");
886 GlobalValue::LinkageTypes Linkage
= (GlobalValue::LinkageTypes
) L
;
888 if(IsAlias
&& !GlobalAlias::isValidLinkage(Linkage
))
889 return Error(NameLoc
, "invalid linkage type for alias");
891 if (!isValidVisibilityForLinkage(Visibility
, L
))
892 return Error(NameLoc
,
893 "symbol with local linkage must have default visibility");
896 LocTy ExplicitTypeLoc
= Lex
.getLoc();
898 ParseToken(lltok::comma
, "expected comma after alias or ifunc's type"))
902 LocTy AliaseeLoc
= Lex
.getLoc();
903 if (Lex
.getKind() != lltok::kw_bitcast
&&
904 Lex
.getKind() != lltok::kw_getelementptr
&&
905 Lex
.getKind() != lltok::kw_addrspacecast
&&
906 Lex
.getKind() != lltok::kw_inttoptr
) {
907 if (ParseGlobalTypeAndValue(Aliasee
))
910 // The bitcast dest type is not present, it is implied by the dest type.
914 if (ID
.Kind
!= ValID::t_Constant
)
915 return Error(AliaseeLoc
, "invalid aliasee");
916 Aliasee
= ID
.ConstantVal
;
919 Type
*AliaseeType
= Aliasee
->getType();
920 auto *PTy
= dyn_cast
<PointerType
>(AliaseeType
);
922 return Error(AliaseeLoc
, "An alias or ifunc must have pointer type");
923 unsigned AddrSpace
= PTy
->getAddressSpace();
925 if (IsAlias
&& Ty
!= PTy
->getElementType())
928 "explicit pointee type doesn't match operand's pointee type");
930 if (!IsAlias
&& !PTy
->getElementType()->isFunctionTy())
933 "explicit pointee type should be a function type");
935 GlobalValue
*GVal
= nullptr;
937 // See if the alias was forward referenced, if so, prepare to replace the
938 // forward reference.
940 GVal
= M
->getNamedValue(Name
);
942 if (!ForwardRefVals
.erase(Name
))
943 return Error(NameLoc
, "redefinition of global '@" + Name
+ "'");
946 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
947 if (I
!= ForwardRefValIDs
.end()) {
948 GVal
= I
->second
.first
;
949 ForwardRefValIDs
.erase(I
);
953 // Okay, create the alias but do not insert it into the module yet.
954 std::unique_ptr
<GlobalIndirectSymbol
> GA
;
956 GA
.reset(GlobalAlias::create(Ty
, AddrSpace
,
957 (GlobalValue::LinkageTypes
)Linkage
, Name
,
958 Aliasee
, /*Parent*/ nullptr));
960 GA
.reset(GlobalIFunc::create(Ty
, AddrSpace
,
961 (GlobalValue::LinkageTypes
)Linkage
, Name
,
962 Aliasee
, /*Parent*/ nullptr));
963 GA
->setThreadLocalMode(TLM
);
964 GA
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
965 GA
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
966 GA
->setUnnamedAddr(UnnamedAddr
);
967 maybeSetDSOLocal(DSOLocal
, *GA
);
969 // At this point we've parsed everything except for the IndirectSymbolAttrs.
970 // Now parse them if there are any.
971 while (Lex
.getKind() == lltok::comma
) {
974 if (Lex
.getKind() == lltok::kw_partition
) {
976 GA
->setPartition(Lex
.getStrVal());
977 if (ParseToken(lltok::StringConstant
, "expected partition string"))
980 return TokError("unknown alias or ifunc property!");
985 NumberedVals
.push_back(GA
.get());
988 // Verify that types agree.
989 if (GVal
->getType() != GA
->getType())
992 "forward reference and definition of alias have different types");
994 // If they agree, just RAUW the old value with the alias and remove the
996 GVal
->replaceAllUsesWith(GA
.get());
997 GVal
->eraseFromParent();
1000 // Insert into the module, we know its name won't collide now.
1002 M
->getAliasList().push_back(cast
<GlobalAlias
>(GA
.get()));
1004 M
->getIFuncList().push_back(cast
<GlobalIFunc
>(GA
.get()));
1005 assert(GA
->getName() == Name
&& "Should not be a name conflict!");
1007 // The module owns this now
1014 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1015 /// OptionalVisibility OptionalDLLStorageClass
1016 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1017 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1018 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1019 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1020 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1021 /// Const OptionalAttrs
1023 /// Everything up to and including OptionalUnnamedAddr has been parsed
1026 bool LLParser::ParseGlobal(const std::string
&Name
, LocTy NameLoc
,
1027 unsigned Linkage
, bool HasLinkage
,
1028 unsigned Visibility
, unsigned DLLStorageClass
,
1029 bool DSOLocal
, GlobalVariable::ThreadLocalMode TLM
,
1030 GlobalVariable::UnnamedAddr UnnamedAddr
) {
1031 if (!isValidVisibilityForLinkage(Visibility
, Linkage
))
1032 return Error(NameLoc
,
1033 "symbol with local linkage must have default visibility");
1036 bool IsConstant
, IsExternallyInitialized
;
1037 LocTy IsExternallyInitializedLoc
;
1041 if (ParseOptionalAddrSpace(AddrSpace
) ||
1042 ParseOptionalToken(lltok::kw_externally_initialized
,
1043 IsExternallyInitialized
,
1044 &IsExternallyInitializedLoc
) ||
1045 ParseGlobalType(IsConstant
) ||
1046 ParseType(Ty
, TyLoc
))
1049 // If the linkage is specified and is external, then no initializer is
1051 Constant
*Init
= nullptr;
1053 !GlobalValue::isValidDeclarationLinkage(
1054 (GlobalValue::LinkageTypes
)Linkage
)) {
1055 if (ParseGlobalValue(Ty
, Init
))
1059 if (Ty
->isFunctionTy() || !PointerType::isValidElementType(Ty
))
1060 return Error(TyLoc
, "invalid type for global variable");
1062 GlobalValue
*GVal
= nullptr;
1064 // See if the global was forward referenced, if so, use the global.
1065 if (!Name
.empty()) {
1066 GVal
= M
->getNamedValue(Name
);
1068 if (!ForwardRefVals
.erase(Name
))
1069 return Error(NameLoc
, "redefinition of global '@" + Name
+ "'");
1072 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
1073 if (I
!= ForwardRefValIDs
.end()) {
1074 GVal
= I
->second
.first
;
1075 ForwardRefValIDs
.erase(I
);
1081 GV
= new GlobalVariable(*M
, Ty
, false, GlobalValue::ExternalLinkage
, nullptr,
1082 Name
, nullptr, GlobalVariable::NotThreadLocal
,
1085 if (GVal
->getValueType() != Ty
)
1087 "forward reference and definition of global have different types");
1089 GV
= cast
<GlobalVariable
>(GVal
);
1091 // Move the forward-reference to the correct spot in the module.
1092 M
->getGlobalList().splice(M
->global_end(), M
->getGlobalList(), GV
);
1096 NumberedVals
.push_back(GV
);
1098 // Set the parsed properties on the global.
1100 GV
->setInitializer(Init
);
1101 GV
->setConstant(IsConstant
);
1102 GV
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
1103 maybeSetDSOLocal(DSOLocal
, *GV
);
1104 GV
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
1105 GV
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
1106 GV
->setExternallyInitialized(IsExternallyInitialized
);
1107 GV
->setThreadLocalMode(TLM
);
1108 GV
->setUnnamedAddr(UnnamedAddr
);
1110 // Parse attributes on the global.
1111 while (Lex
.getKind() == lltok::comma
) {
1114 if (Lex
.getKind() == lltok::kw_section
) {
1116 GV
->setSection(Lex
.getStrVal());
1117 if (ParseToken(lltok::StringConstant
, "expected global section string"))
1119 } else if (Lex
.getKind() == lltok::kw_partition
) {
1121 GV
->setPartition(Lex
.getStrVal());
1122 if (ParseToken(lltok::StringConstant
, "expected partition string"))
1124 } else if (Lex
.getKind() == lltok::kw_align
) {
1126 if (ParseOptionalAlignment(Alignment
)) return true;
1127 GV
->setAlignment(Alignment
);
1128 } else if (Lex
.getKind() == lltok::MetadataVar
) {
1129 if (ParseGlobalObjectMetadataAttachment(*GV
))
1133 if (parseOptionalComdat(Name
, C
))
1138 return TokError("unknown global variable property!");
1144 std::vector
<unsigned> FwdRefAttrGrps
;
1145 if (ParseFnAttributeValuePairs(Attrs
, FwdRefAttrGrps
, false, BuiltinLoc
))
1147 if (Attrs
.hasAttributes() || !FwdRefAttrGrps
.empty()) {
1148 GV
->setAttributes(AttributeSet::get(Context
, Attrs
));
1149 ForwardRefAttrGroups
[GV
] = FwdRefAttrGrps
;
1155 /// ParseUnnamedAttrGrp
1156 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1157 bool LLParser::ParseUnnamedAttrGrp() {
1158 assert(Lex
.getKind() == lltok::kw_attributes
);
1159 LocTy AttrGrpLoc
= Lex
.getLoc();
1162 if (Lex
.getKind() != lltok::AttrGrpID
)
1163 return TokError("expected attribute group id");
1165 unsigned VarID
= Lex
.getUIntVal();
1166 std::vector
<unsigned> unused
;
1170 if (ParseToken(lltok::equal
, "expected '=' here") ||
1171 ParseToken(lltok::lbrace
, "expected '{' here") ||
1172 ParseFnAttributeValuePairs(NumberedAttrBuilders
[VarID
], unused
, true,
1174 ParseToken(lltok::rbrace
, "expected end of attribute group"))
1177 if (!NumberedAttrBuilders
[VarID
].hasAttributes())
1178 return Error(AttrGrpLoc
, "attribute group has no attributes");
1183 /// ParseFnAttributeValuePairs
1184 /// ::= <attr> | <attr> '=' <value>
1185 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder
&B
,
1186 std::vector
<unsigned> &FwdRefAttrGrps
,
1187 bool inAttrGrp
, LocTy
&BuiltinLoc
) {
1188 bool HaveError
= false;
1193 lltok::Kind Token
= Lex
.getKind();
1194 if (Token
== lltok::kw_builtin
)
1195 BuiltinLoc
= Lex
.getLoc();
1198 if (!inAttrGrp
) return HaveError
;
1199 return Error(Lex
.getLoc(), "unterminated attribute group");
1204 case lltok::AttrGrpID
: {
1205 // Allow a function to reference an attribute group:
1207 // define void @foo() #1 { ... }
1211 "cannot have an attribute group reference in an attribute group");
1213 unsigned AttrGrpNum
= Lex
.getUIntVal();
1214 if (inAttrGrp
) break;
1216 // Save the reference to the attribute group. We'll fill it in later.
1217 FwdRefAttrGrps
.push_back(AttrGrpNum
);
1220 // Target-dependent attributes:
1221 case lltok::StringConstant
: {
1222 if (ParseStringAttribute(B
))
1227 // Target-independent attributes:
1228 case lltok::kw_align
: {
1229 // As a hack, we allow function alignment to be initially parsed as an
1230 // attribute on a function declaration/definition or added to an attribute
1231 // group and later moved to the alignment field.
1235 if (ParseToken(lltok::equal
, "expected '=' here") ||
1236 ParseUInt32(Alignment
))
1239 if (ParseOptionalAlignment(Alignment
))
1242 B
.addAlignmentAttr(Alignment
);
1245 case lltok::kw_alignstack
: {
1249 if (ParseToken(lltok::equal
, "expected '=' here") ||
1250 ParseUInt32(Alignment
))
1253 if (ParseOptionalStackAlignment(Alignment
))
1256 B
.addStackAlignmentAttr(Alignment
);
1259 case lltok::kw_allocsize
: {
1260 unsigned ElemSizeArg
;
1261 Optional
<unsigned> NumElemsArg
;
1262 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1263 if (parseAllocSizeArguments(ElemSizeArg
, NumElemsArg
))
1265 B
.addAllocSizeAttr(ElemSizeArg
, NumElemsArg
);
1268 case lltok::kw_alwaysinline
: B
.addAttribute(Attribute::AlwaysInline
); break;
1269 case lltok::kw_argmemonly
: B
.addAttribute(Attribute::ArgMemOnly
); break;
1270 case lltok::kw_builtin
: B
.addAttribute(Attribute::Builtin
); break;
1271 case lltok::kw_cold
: B
.addAttribute(Attribute::Cold
); break;
1272 case lltok::kw_convergent
: B
.addAttribute(Attribute::Convergent
); break;
1273 case lltok::kw_inaccessiblememonly
:
1274 B
.addAttribute(Attribute::InaccessibleMemOnly
); break;
1275 case lltok::kw_inaccessiblemem_or_argmemonly
:
1276 B
.addAttribute(Attribute::InaccessibleMemOrArgMemOnly
); break;
1277 case lltok::kw_inlinehint
: B
.addAttribute(Attribute::InlineHint
); break;
1278 case lltok::kw_jumptable
: B
.addAttribute(Attribute::JumpTable
); break;
1279 case lltok::kw_minsize
: B
.addAttribute(Attribute::MinSize
); break;
1280 case lltok::kw_naked
: B
.addAttribute(Attribute::Naked
); break;
1281 case lltok::kw_nobuiltin
: B
.addAttribute(Attribute::NoBuiltin
); break;
1282 case lltok::kw_noduplicate
: B
.addAttribute(Attribute::NoDuplicate
); break;
1283 case lltok::kw_nofree
: B
.addAttribute(Attribute::NoFree
); break;
1284 case lltok::kw_noimplicitfloat
:
1285 B
.addAttribute(Attribute::NoImplicitFloat
); break;
1286 case lltok::kw_noinline
: B
.addAttribute(Attribute::NoInline
); break;
1287 case lltok::kw_nonlazybind
: B
.addAttribute(Attribute::NonLazyBind
); break;
1288 case lltok::kw_noredzone
: B
.addAttribute(Attribute::NoRedZone
); break;
1289 case lltok::kw_noreturn
: B
.addAttribute(Attribute::NoReturn
); break;
1290 case lltok::kw_nosync
: B
.addAttribute(Attribute::NoSync
); break;
1291 case lltok::kw_nocf_check
: B
.addAttribute(Attribute::NoCfCheck
); break;
1292 case lltok::kw_norecurse
: B
.addAttribute(Attribute::NoRecurse
); break;
1293 case lltok::kw_nounwind
: B
.addAttribute(Attribute::NoUnwind
); break;
1294 case lltok::kw_optforfuzzing
:
1295 B
.addAttribute(Attribute::OptForFuzzing
); break;
1296 case lltok::kw_optnone
: B
.addAttribute(Attribute::OptimizeNone
); break;
1297 case lltok::kw_optsize
: B
.addAttribute(Attribute::OptimizeForSize
); break;
1298 case lltok::kw_readnone
: B
.addAttribute(Attribute::ReadNone
); break;
1299 case lltok::kw_readonly
: B
.addAttribute(Attribute::ReadOnly
); break;
1300 case lltok::kw_returns_twice
:
1301 B
.addAttribute(Attribute::ReturnsTwice
); break;
1302 case lltok::kw_speculatable
: B
.addAttribute(Attribute::Speculatable
); break;
1303 case lltok::kw_ssp
: B
.addAttribute(Attribute::StackProtect
); break;
1304 case lltok::kw_sspreq
: B
.addAttribute(Attribute::StackProtectReq
); break;
1305 case lltok::kw_sspstrong
:
1306 B
.addAttribute(Attribute::StackProtectStrong
); break;
1307 case lltok::kw_safestack
: B
.addAttribute(Attribute::SafeStack
); break;
1308 case lltok::kw_shadowcallstack
:
1309 B
.addAttribute(Attribute::ShadowCallStack
); break;
1310 case lltok::kw_sanitize_address
:
1311 B
.addAttribute(Attribute::SanitizeAddress
); break;
1312 case lltok::kw_sanitize_hwaddress
:
1313 B
.addAttribute(Attribute::SanitizeHWAddress
); break;
1314 case lltok::kw_sanitize_memtag
:
1315 B
.addAttribute(Attribute::SanitizeMemTag
); break;
1316 case lltok::kw_sanitize_thread
:
1317 B
.addAttribute(Attribute::SanitizeThread
); break;
1318 case lltok::kw_sanitize_memory
:
1319 B
.addAttribute(Attribute::SanitizeMemory
); break;
1320 case lltok::kw_speculative_load_hardening
:
1321 B
.addAttribute(Attribute::SpeculativeLoadHardening
);
1323 case lltok::kw_strictfp
: B
.addAttribute(Attribute::StrictFP
); break;
1324 case lltok::kw_uwtable
: B
.addAttribute(Attribute::UWTable
); break;
1325 case lltok::kw_willreturn
: B
.addAttribute(Attribute::WillReturn
); break;
1326 case lltok::kw_writeonly
: B
.addAttribute(Attribute::WriteOnly
); break;
1329 case lltok::kw_inreg
:
1330 case lltok::kw_signext
:
1331 case lltok::kw_zeroext
:
1334 "invalid use of attribute on a function");
1336 case lltok::kw_byval
:
1337 case lltok::kw_dereferenceable
:
1338 case lltok::kw_dereferenceable_or_null
:
1339 case lltok::kw_inalloca
:
1340 case lltok::kw_nest
:
1341 case lltok::kw_noalias
:
1342 case lltok::kw_nocapture
:
1343 case lltok::kw_nonnull
:
1344 case lltok::kw_returned
:
1345 case lltok::kw_sret
:
1346 case lltok::kw_swifterror
:
1347 case lltok::kw_swiftself
:
1348 case lltok::kw_immarg
:
1351 "invalid use of parameter-only attribute on a function");
1359 //===----------------------------------------------------------------------===//
1360 // GlobalValue Reference/Resolution Routines.
1361 //===----------------------------------------------------------------------===//
1363 static inline GlobalValue
*createGlobalFwdRef(Module
*M
, PointerType
*PTy
,
1364 const std::string
&Name
) {
1365 if (auto *FT
= dyn_cast
<FunctionType
>(PTy
->getElementType()))
1366 return Function::Create(FT
, GlobalValue::ExternalWeakLinkage
,
1367 PTy
->getAddressSpace(), Name
, M
);
1369 return new GlobalVariable(*M
, PTy
->getElementType(), false,
1370 GlobalValue::ExternalWeakLinkage
, nullptr, Name
,
1371 nullptr, GlobalVariable::NotThreadLocal
,
1372 PTy
->getAddressSpace());
1375 Value
*LLParser::checkValidVariableType(LocTy Loc
, const Twine
&Name
, Type
*Ty
,
1376 Value
*Val
, bool IsCall
) {
1377 if (Val
->getType() == Ty
)
1379 // For calls we also accept variables in the program address space.
1380 Type
*SuggestedTy
= Ty
;
1381 if (IsCall
&& isa
<PointerType
>(Ty
)) {
1382 Type
*TyInProgAS
= cast
<PointerType
>(Ty
)->getElementType()->getPointerTo(
1383 M
->getDataLayout().getProgramAddressSpace());
1384 SuggestedTy
= TyInProgAS
;
1385 if (Val
->getType() == TyInProgAS
)
1388 if (Ty
->isLabelTy())
1389 Error(Loc
, "'" + Name
+ "' is not a basic block");
1391 Error(Loc
, "'" + Name
+ "' defined with type '" +
1392 getTypeString(Val
->getType()) + "' but expected '" +
1393 getTypeString(SuggestedTy
) + "'");
1397 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1398 /// forward reference record if needed. This can return null if the value
1399 /// exists but does not have the right type.
1400 GlobalValue
*LLParser::GetGlobalVal(const std::string
&Name
, Type
*Ty
,
1401 LocTy Loc
, bool IsCall
) {
1402 PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
1404 Error(Loc
, "global variable reference must have pointer type");
1408 // Look this name up in the normal function symbol table.
1410 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
));
1412 // If this is a forward reference for the value, see if we already created a
1413 // forward ref record.
1415 auto I
= ForwardRefVals
.find(Name
);
1416 if (I
!= ForwardRefVals
.end())
1417 Val
= I
->second
.first
;
1420 // If we have the value in the symbol table or fwd-ref table, return it.
1422 return cast_or_null
<GlobalValue
>(
1423 checkValidVariableType(Loc
, "@" + Name
, Ty
, Val
, IsCall
));
1425 // Otherwise, create a new forward reference for this value and remember it.
1426 GlobalValue
*FwdVal
= createGlobalFwdRef(M
, PTy
, Name
);
1427 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
1431 GlobalValue
*LLParser::GetGlobalVal(unsigned ID
, Type
*Ty
, LocTy Loc
,
1433 PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
1435 Error(Loc
, "global variable reference must have pointer type");
1439 GlobalValue
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : nullptr;
1441 // If this is a forward reference for the value, see if we already created a
1442 // forward ref record.
1444 auto I
= ForwardRefValIDs
.find(ID
);
1445 if (I
!= ForwardRefValIDs
.end())
1446 Val
= I
->second
.first
;
1449 // If we have the value in the symbol table or fwd-ref table, return it.
1451 return cast_or_null
<GlobalValue
>(
1452 checkValidVariableType(Loc
, "@" + Twine(ID
), Ty
, Val
, IsCall
));
1454 // Otherwise, create a new forward reference for this value and remember it.
1455 GlobalValue
*FwdVal
= createGlobalFwdRef(M
, PTy
, "");
1456 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
1460 //===----------------------------------------------------------------------===//
1461 // Comdat Reference/Resolution Routines.
1462 //===----------------------------------------------------------------------===//
1464 Comdat
*LLParser::getComdat(const std::string
&Name
, LocTy Loc
) {
1465 // Look this name up in the comdat symbol table.
1466 Module::ComdatSymTabType
&ComdatSymTab
= M
->getComdatSymbolTable();
1467 Module::ComdatSymTabType::iterator I
= ComdatSymTab
.find(Name
);
1468 if (I
!= ComdatSymTab
.end())
1471 // Otherwise, create a new forward reference for this value and remember it.
1472 Comdat
*C
= M
->getOrInsertComdat(Name
);
1473 ForwardRefComdats
[Name
] = Loc
;
1477 //===----------------------------------------------------------------------===//
1479 //===----------------------------------------------------------------------===//
1481 /// ParseToken - If the current token has the specified kind, eat it and return
1482 /// success. Otherwise, emit the specified error and return failure.
1483 bool LLParser::ParseToken(lltok::Kind T
, const char *ErrMsg
) {
1484 if (Lex
.getKind() != T
)
1485 return TokError(ErrMsg
);
1490 /// ParseStringConstant
1491 /// ::= StringConstant
1492 bool LLParser::ParseStringConstant(std::string
&Result
) {
1493 if (Lex
.getKind() != lltok::StringConstant
)
1494 return TokError("expected string constant");
1495 Result
= Lex
.getStrVal();
1502 bool LLParser::ParseUInt32(uint32_t &Val
) {
1503 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
1504 return TokError("expected integer");
1505 uint64_t Val64
= Lex
.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL
+1);
1506 if (Val64
!= unsigned(Val64
))
1507 return TokError("expected 32-bit integer (too large)");
1515 bool LLParser::ParseUInt64(uint64_t &Val
) {
1516 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
1517 return TokError("expected integer");
1518 Val
= Lex
.getAPSIntVal().getLimitedValue();
1524 /// := 'localdynamic'
1525 /// := 'initialexec'
1527 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode
&TLM
) {
1528 switch (Lex
.getKind()) {
1530 return TokError("expected localdynamic, initialexec or localexec");
1531 case lltok::kw_localdynamic
:
1532 TLM
= GlobalVariable::LocalDynamicTLSModel
;
1534 case lltok::kw_initialexec
:
1535 TLM
= GlobalVariable::InitialExecTLSModel
;
1537 case lltok::kw_localexec
:
1538 TLM
= GlobalVariable::LocalExecTLSModel
;
1546 /// ParseOptionalThreadLocal
1548 /// := 'thread_local'
1549 /// := 'thread_local' '(' tlsmodel ')'
1550 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode
&TLM
) {
1551 TLM
= GlobalVariable::NotThreadLocal
;
1552 if (!EatIfPresent(lltok::kw_thread_local
))
1555 TLM
= GlobalVariable::GeneralDynamicTLSModel
;
1556 if (Lex
.getKind() == lltok::lparen
) {
1558 return ParseTLSModel(TLM
) ||
1559 ParseToken(lltok::rparen
, "expected ')' after thread local model");
1564 /// ParseOptionalAddrSpace
1566 /// := 'addrspace' '(' uint32 ')'
1567 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace
, unsigned DefaultAS
) {
1568 AddrSpace
= DefaultAS
;
1569 if (!EatIfPresent(lltok::kw_addrspace
))
1571 return ParseToken(lltok::lparen
, "expected '(' in address space") ||
1572 ParseUInt32(AddrSpace
) ||
1573 ParseToken(lltok::rparen
, "expected ')' in address space");
1576 /// ParseStringAttribute
1577 /// := StringConstant
1578 /// := StringConstant '=' StringConstant
1579 bool LLParser::ParseStringAttribute(AttrBuilder
&B
) {
1580 std::string Attr
= Lex
.getStrVal();
1583 if (EatIfPresent(lltok::equal
) && ParseStringConstant(Val
))
1585 B
.addAttribute(Attr
, Val
);
1589 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1590 bool LLParser::ParseOptionalParamAttrs(AttrBuilder
&B
) {
1591 bool HaveError
= false;
1596 lltok::Kind Token
= Lex
.getKind();
1598 default: // End of attributes.
1600 case lltok::StringConstant
: {
1601 if (ParseStringAttribute(B
))
1605 case lltok::kw_align
: {
1607 if (ParseOptionalAlignment(Alignment
))
1609 B
.addAlignmentAttr(Alignment
);
1612 case lltok::kw_byval
: {
1614 if (ParseByValWithOptionalType(Ty
))
1619 case lltok::kw_dereferenceable
: {
1621 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable
, Bytes
))
1623 B
.addDereferenceableAttr(Bytes
);
1626 case lltok::kw_dereferenceable_or_null
: {
1628 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null
, Bytes
))
1630 B
.addDereferenceableOrNullAttr(Bytes
);
1633 case lltok::kw_inalloca
: B
.addAttribute(Attribute::InAlloca
); break;
1634 case lltok::kw_inreg
: B
.addAttribute(Attribute::InReg
); break;
1635 case lltok::kw_nest
: B
.addAttribute(Attribute::Nest
); break;
1636 case lltok::kw_noalias
: B
.addAttribute(Attribute::NoAlias
); break;
1637 case lltok::kw_nocapture
: B
.addAttribute(Attribute::NoCapture
); break;
1638 case lltok::kw_nonnull
: B
.addAttribute(Attribute::NonNull
); break;
1639 case lltok::kw_readnone
: B
.addAttribute(Attribute::ReadNone
); break;
1640 case lltok::kw_readonly
: B
.addAttribute(Attribute::ReadOnly
); break;
1641 case lltok::kw_returned
: B
.addAttribute(Attribute::Returned
); break;
1642 case lltok::kw_signext
: B
.addAttribute(Attribute::SExt
); break;
1643 case lltok::kw_sret
: B
.addAttribute(Attribute::StructRet
); break;
1644 case lltok::kw_swifterror
: B
.addAttribute(Attribute::SwiftError
); break;
1645 case lltok::kw_swiftself
: B
.addAttribute(Attribute::SwiftSelf
); break;
1646 case lltok::kw_writeonly
: B
.addAttribute(Attribute::WriteOnly
); break;
1647 case lltok::kw_zeroext
: B
.addAttribute(Attribute::ZExt
); break;
1648 case lltok::kw_immarg
: B
.addAttribute(Attribute::ImmArg
); break;
1650 case lltok::kw_alignstack
:
1651 case lltok::kw_alwaysinline
:
1652 case lltok::kw_argmemonly
:
1653 case lltok::kw_builtin
:
1654 case lltok::kw_inlinehint
:
1655 case lltok::kw_jumptable
:
1656 case lltok::kw_minsize
:
1657 case lltok::kw_naked
:
1658 case lltok::kw_nobuiltin
:
1659 case lltok::kw_noduplicate
:
1660 case lltok::kw_noimplicitfloat
:
1661 case lltok::kw_noinline
:
1662 case lltok::kw_nonlazybind
:
1663 case lltok::kw_noredzone
:
1664 case lltok::kw_noreturn
:
1665 case lltok::kw_nocf_check
:
1666 case lltok::kw_nounwind
:
1667 case lltok::kw_optforfuzzing
:
1668 case lltok::kw_optnone
:
1669 case lltok::kw_optsize
:
1670 case lltok::kw_returns_twice
:
1671 case lltok::kw_sanitize_address
:
1672 case lltok::kw_sanitize_hwaddress
:
1673 case lltok::kw_sanitize_memtag
:
1674 case lltok::kw_sanitize_memory
:
1675 case lltok::kw_sanitize_thread
:
1676 case lltok::kw_speculative_load_hardening
:
1678 case lltok::kw_sspreq
:
1679 case lltok::kw_sspstrong
:
1680 case lltok::kw_safestack
:
1681 case lltok::kw_shadowcallstack
:
1682 case lltok::kw_strictfp
:
1683 case lltok::kw_uwtable
:
1684 HaveError
|= Error(Lex
.getLoc(), "invalid use of function-only attribute");
1692 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1693 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder
&B
) {
1694 bool HaveError
= false;
1699 lltok::Kind Token
= Lex
.getKind();
1701 default: // End of attributes.
1703 case lltok::StringConstant
: {
1704 if (ParseStringAttribute(B
))
1708 case lltok::kw_dereferenceable
: {
1710 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable
, Bytes
))
1712 B
.addDereferenceableAttr(Bytes
);
1715 case lltok::kw_dereferenceable_or_null
: {
1717 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null
, Bytes
))
1719 B
.addDereferenceableOrNullAttr(Bytes
);
1722 case lltok::kw_align
: {
1724 if (ParseOptionalAlignment(Alignment
))
1726 B
.addAlignmentAttr(Alignment
);
1729 case lltok::kw_inreg
: B
.addAttribute(Attribute::InReg
); break;
1730 case lltok::kw_noalias
: B
.addAttribute(Attribute::NoAlias
); break;
1731 case lltok::kw_nonnull
: B
.addAttribute(Attribute::NonNull
); break;
1732 case lltok::kw_signext
: B
.addAttribute(Attribute::SExt
); break;
1733 case lltok::kw_zeroext
: B
.addAttribute(Attribute::ZExt
); break;
1736 case lltok::kw_byval
:
1737 case lltok::kw_inalloca
:
1738 case lltok::kw_nest
:
1739 case lltok::kw_nocapture
:
1740 case lltok::kw_returned
:
1741 case lltok::kw_sret
:
1742 case lltok::kw_swifterror
:
1743 case lltok::kw_swiftself
:
1744 case lltok::kw_immarg
:
1745 HaveError
|= Error(Lex
.getLoc(), "invalid use of parameter-only attribute");
1748 case lltok::kw_alignstack
:
1749 case lltok::kw_alwaysinline
:
1750 case lltok::kw_argmemonly
:
1751 case lltok::kw_builtin
:
1752 case lltok::kw_cold
:
1753 case lltok::kw_inlinehint
:
1754 case lltok::kw_jumptable
:
1755 case lltok::kw_minsize
:
1756 case lltok::kw_naked
:
1757 case lltok::kw_nobuiltin
:
1758 case lltok::kw_noduplicate
:
1759 case lltok::kw_noimplicitfloat
:
1760 case lltok::kw_noinline
:
1761 case lltok::kw_nonlazybind
:
1762 case lltok::kw_noredzone
:
1763 case lltok::kw_noreturn
:
1764 case lltok::kw_nocf_check
:
1765 case lltok::kw_nounwind
:
1766 case lltok::kw_optforfuzzing
:
1767 case lltok::kw_optnone
:
1768 case lltok::kw_optsize
:
1769 case lltok::kw_returns_twice
:
1770 case lltok::kw_sanitize_address
:
1771 case lltok::kw_sanitize_hwaddress
:
1772 case lltok::kw_sanitize_memtag
:
1773 case lltok::kw_sanitize_memory
:
1774 case lltok::kw_sanitize_thread
:
1775 case lltok::kw_speculative_load_hardening
:
1777 case lltok::kw_sspreq
:
1778 case lltok::kw_sspstrong
:
1779 case lltok::kw_safestack
:
1780 case lltok::kw_shadowcallstack
:
1781 case lltok::kw_strictfp
:
1782 case lltok::kw_uwtable
:
1783 HaveError
|= Error(Lex
.getLoc(), "invalid use of function-only attribute");
1786 case lltok::kw_readnone
:
1787 case lltok::kw_readonly
:
1788 HaveError
|= Error(Lex
.getLoc(), "invalid use of attribute on return type");
1795 static unsigned parseOptionalLinkageAux(lltok::Kind Kind
, bool &HasLinkage
) {
1800 return GlobalValue::ExternalLinkage
;
1801 case lltok::kw_private
:
1802 return GlobalValue::PrivateLinkage
;
1803 case lltok::kw_internal
:
1804 return GlobalValue::InternalLinkage
;
1805 case lltok::kw_weak
:
1806 return GlobalValue::WeakAnyLinkage
;
1807 case lltok::kw_weak_odr
:
1808 return GlobalValue::WeakODRLinkage
;
1809 case lltok::kw_linkonce
:
1810 return GlobalValue::LinkOnceAnyLinkage
;
1811 case lltok::kw_linkonce_odr
:
1812 return GlobalValue::LinkOnceODRLinkage
;
1813 case lltok::kw_available_externally
:
1814 return GlobalValue::AvailableExternallyLinkage
;
1815 case lltok::kw_appending
:
1816 return GlobalValue::AppendingLinkage
;
1817 case lltok::kw_common
:
1818 return GlobalValue::CommonLinkage
;
1819 case lltok::kw_extern_weak
:
1820 return GlobalValue::ExternalWeakLinkage
;
1821 case lltok::kw_external
:
1822 return GlobalValue::ExternalLinkage
;
1826 /// ParseOptionalLinkage
1833 /// ::= 'linkonce_odr'
1834 /// ::= 'available_externally'
1837 /// ::= 'extern_weak'
1839 bool LLParser::ParseOptionalLinkage(unsigned &Res
, bool &HasLinkage
,
1840 unsigned &Visibility
,
1841 unsigned &DLLStorageClass
,
1843 Res
= parseOptionalLinkageAux(Lex
.getKind(), HasLinkage
);
1846 ParseOptionalDSOLocal(DSOLocal
);
1847 ParseOptionalVisibility(Visibility
);
1848 ParseOptionalDLLStorageClass(DLLStorageClass
);
1850 if (DSOLocal
&& DLLStorageClass
== GlobalValue::DLLImportStorageClass
) {
1851 return Error(Lex
.getLoc(), "dso_location and DLL-StorageClass mismatch");
1857 void LLParser::ParseOptionalDSOLocal(bool &DSOLocal
) {
1858 switch (Lex
.getKind()) {
1862 case lltok::kw_dso_local
:
1866 case lltok::kw_dso_preemptable
:
1873 /// ParseOptionalVisibility
1879 void LLParser::ParseOptionalVisibility(unsigned &Res
) {
1880 switch (Lex
.getKind()) {
1882 Res
= GlobalValue::DefaultVisibility
;
1884 case lltok::kw_default
:
1885 Res
= GlobalValue::DefaultVisibility
;
1887 case lltok::kw_hidden
:
1888 Res
= GlobalValue::HiddenVisibility
;
1890 case lltok::kw_protected
:
1891 Res
= GlobalValue::ProtectedVisibility
;
1897 /// ParseOptionalDLLStorageClass
1902 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res
) {
1903 switch (Lex
.getKind()) {
1905 Res
= GlobalValue::DefaultStorageClass
;
1907 case lltok::kw_dllimport
:
1908 Res
= GlobalValue::DLLImportStorageClass
;
1910 case lltok::kw_dllexport
:
1911 Res
= GlobalValue::DLLExportStorageClass
;
1917 /// ParseOptionalCallingConv
1921 /// ::= 'intel_ocl_bicc'
1923 /// ::= 'x86_stdcallcc'
1924 /// ::= 'x86_fastcallcc'
1925 /// ::= 'x86_thiscallcc'
1926 /// ::= 'x86_vectorcallcc'
1927 /// ::= 'arm_apcscc'
1928 /// ::= 'arm_aapcscc'
1929 /// ::= 'arm_aapcs_vfpcc'
1930 /// ::= 'aarch64_vector_pcs'
1931 /// ::= 'msp430_intrcc'
1932 /// ::= 'avr_intrcc'
1933 /// ::= 'avr_signalcc'
1934 /// ::= 'ptx_kernel'
1935 /// ::= 'ptx_device'
1937 /// ::= 'spir_kernel'
1938 /// ::= 'x86_64_sysvcc'
1940 /// ::= 'webkit_jscc'
1942 /// ::= 'preserve_mostcc'
1943 /// ::= 'preserve_allcc'
1946 /// ::= 'x86_intrcc'
1949 /// ::= 'cxx_fast_tlscc'
1957 /// ::= 'amdgpu_kernel'
1960 bool LLParser::ParseOptionalCallingConv(unsigned &CC
) {
1961 switch (Lex
.getKind()) {
1962 default: CC
= CallingConv::C
; return false;
1963 case lltok::kw_ccc
: CC
= CallingConv::C
; break;
1964 case lltok::kw_fastcc
: CC
= CallingConv::Fast
; break;
1965 case lltok::kw_coldcc
: CC
= CallingConv::Cold
; break;
1966 case lltok::kw_x86_stdcallcc
: CC
= CallingConv::X86_StdCall
; break;
1967 case lltok::kw_x86_fastcallcc
: CC
= CallingConv::X86_FastCall
; break;
1968 case lltok::kw_x86_regcallcc
: CC
= CallingConv::X86_RegCall
; break;
1969 case lltok::kw_x86_thiscallcc
: CC
= CallingConv::X86_ThisCall
; break;
1970 case lltok::kw_x86_vectorcallcc
:CC
= CallingConv::X86_VectorCall
; break;
1971 case lltok::kw_arm_apcscc
: CC
= CallingConv::ARM_APCS
; break;
1972 case lltok::kw_arm_aapcscc
: CC
= CallingConv::ARM_AAPCS
; break;
1973 case lltok::kw_arm_aapcs_vfpcc
:CC
= CallingConv::ARM_AAPCS_VFP
; break;
1974 case lltok::kw_aarch64_vector_pcs
:CC
= CallingConv::AArch64_VectorCall
; break;
1975 case lltok::kw_msp430_intrcc
: CC
= CallingConv::MSP430_INTR
; break;
1976 case lltok::kw_avr_intrcc
: CC
= CallingConv::AVR_INTR
; break;
1977 case lltok::kw_avr_signalcc
: CC
= CallingConv::AVR_SIGNAL
; break;
1978 case lltok::kw_ptx_kernel
: CC
= CallingConv::PTX_Kernel
; break;
1979 case lltok::kw_ptx_device
: CC
= CallingConv::PTX_Device
; break;
1980 case lltok::kw_spir_kernel
: CC
= CallingConv::SPIR_KERNEL
; break;
1981 case lltok::kw_spir_func
: CC
= CallingConv::SPIR_FUNC
; break;
1982 case lltok::kw_intel_ocl_bicc
: CC
= CallingConv::Intel_OCL_BI
; break;
1983 case lltok::kw_x86_64_sysvcc
: CC
= CallingConv::X86_64_SysV
; break;
1984 case lltok::kw_win64cc
: CC
= CallingConv::Win64
; break;
1985 case lltok::kw_webkit_jscc
: CC
= CallingConv::WebKit_JS
; break;
1986 case lltok::kw_anyregcc
: CC
= CallingConv::AnyReg
; break;
1987 case lltok::kw_preserve_mostcc
:CC
= CallingConv::PreserveMost
; break;
1988 case lltok::kw_preserve_allcc
: CC
= CallingConv::PreserveAll
; break;
1989 case lltok::kw_ghccc
: CC
= CallingConv::GHC
; break;
1990 case lltok::kw_swiftcc
: CC
= CallingConv::Swift
; break;
1991 case lltok::kw_x86_intrcc
: CC
= CallingConv::X86_INTR
; break;
1992 case lltok::kw_hhvmcc
: CC
= CallingConv::HHVM
; break;
1993 case lltok::kw_hhvm_ccc
: CC
= CallingConv::HHVM_C
; break;
1994 case lltok::kw_cxx_fast_tlscc
: CC
= CallingConv::CXX_FAST_TLS
; break;
1995 case lltok::kw_amdgpu_vs
: CC
= CallingConv::AMDGPU_VS
; break;
1996 case lltok::kw_amdgpu_ls
: CC
= CallingConv::AMDGPU_LS
; break;
1997 case lltok::kw_amdgpu_hs
: CC
= CallingConv::AMDGPU_HS
; break;
1998 case lltok::kw_amdgpu_es
: CC
= CallingConv::AMDGPU_ES
; break;
1999 case lltok::kw_amdgpu_gs
: CC
= CallingConv::AMDGPU_GS
; break;
2000 case lltok::kw_amdgpu_ps
: CC
= CallingConv::AMDGPU_PS
; break;
2001 case lltok::kw_amdgpu_cs
: CC
= CallingConv::AMDGPU_CS
; break;
2002 case lltok::kw_amdgpu_kernel
: CC
= CallingConv::AMDGPU_KERNEL
; break;
2003 case lltok::kw_cc
: {
2005 return ParseUInt32(CC
);
2013 /// ParseMetadataAttachment
2015 bool LLParser::ParseMetadataAttachment(unsigned &Kind
, MDNode
*&MD
) {
2016 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata attachment");
2018 std::string Name
= Lex
.getStrVal();
2019 Kind
= M
->getMDKindID(Name
);
2022 return ParseMDNode(MD
);
2025 /// ParseInstructionMetadata
2026 /// ::= !dbg !42 (',' !dbg !57)*
2027 bool LLParser::ParseInstructionMetadata(Instruction
&Inst
) {
2029 if (Lex
.getKind() != lltok::MetadataVar
)
2030 return TokError("expected metadata after comma");
2034 if (ParseMetadataAttachment(MDK
, N
))
2037 Inst
.setMetadata(MDK
, N
);
2038 if (MDK
== LLVMContext::MD_tbaa
)
2039 InstsWithTBAATag
.push_back(&Inst
);
2041 // If this is the end of the list, we're done.
2042 } while (EatIfPresent(lltok::comma
));
2046 /// ParseGlobalObjectMetadataAttachment
2048 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject
&GO
) {
2051 if (ParseMetadataAttachment(MDK
, N
))
2054 GO
.addMetadata(MDK
, *N
);
2058 /// ParseOptionalFunctionMetadata
2060 bool LLParser::ParseOptionalFunctionMetadata(Function
&F
) {
2061 while (Lex
.getKind() == lltok::MetadataVar
)
2062 if (ParseGlobalObjectMetadataAttachment(F
))
2067 /// ParseOptionalAlignment
2070 bool LLParser::ParseOptionalAlignment(unsigned &Alignment
) {
2072 if (!EatIfPresent(lltok::kw_align
))
2074 LocTy AlignLoc
= Lex
.getLoc();
2075 if (ParseUInt32(Alignment
)) return true;
2076 if (!isPowerOf2_32(Alignment
))
2077 return Error(AlignLoc
, "alignment is not a power of two");
2078 if (Alignment
> Value::MaximumAlignment
)
2079 return Error(AlignLoc
, "huge alignments are not supported yet");
2083 /// ParseOptionalDerefAttrBytes
2085 /// ::= AttrKind '(' 4 ')'
2087 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2088 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind
,
2090 assert((AttrKind
== lltok::kw_dereferenceable
||
2091 AttrKind
== lltok::kw_dereferenceable_or_null
) &&
2095 if (!EatIfPresent(AttrKind
))
2097 LocTy ParenLoc
= Lex
.getLoc();
2098 if (!EatIfPresent(lltok::lparen
))
2099 return Error(ParenLoc
, "expected '('");
2100 LocTy DerefLoc
= Lex
.getLoc();
2101 if (ParseUInt64(Bytes
)) return true;
2102 ParenLoc
= Lex
.getLoc();
2103 if (!EatIfPresent(lltok::rparen
))
2104 return Error(ParenLoc
, "expected ')'");
2106 return Error(DerefLoc
, "dereferenceable bytes must be non-zero");
2110 /// ParseOptionalCommaAlign
2114 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2116 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment
,
2117 bool &AteExtraComma
) {
2118 AteExtraComma
= false;
2119 while (EatIfPresent(lltok::comma
)) {
2120 // Metadata at the end is an early exit.
2121 if (Lex
.getKind() == lltok::MetadataVar
) {
2122 AteExtraComma
= true;
2126 if (Lex
.getKind() != lltok::kw_align
)
2127 return Error(Lex
.getLoc(), "expected metadata or 'align'");
2129 if (ParseOptionalAlignment(Alignment
)) return true;
2135 /// ParseOptionalCommaAddrSpace
2137 /// ::= ',' addrspace(1)
2139 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2141 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace
,
2143 bool &AteExtraComma
) {
2144 AteExtraComma
= false;
2145 while (EatIfPresent(lltok::comma
)) {
2146 // Metadata at the end is an early exit.
2147 if (Lex
.getKind() == lltok::MetadataVar
) {
2148 AteExtraComma
= true;
2153 if (Lex
.getKind() != lltok::kw_addrspace
)
2154 return Error(Lex
.getLoc(), "expected metadata or 'addrspace'");
2156 if (ParseOptionalAddrSpace(AddrSpace
))
2163 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg
,
2164 Optional
<unsigned> &HowManyArg
) {
2167 auto StartParen
= Lex
.getLoc();
2168 if (!EatIfPresent(lltok::lparen
))
2169 return Error(StartParen
, "expected '('");
2171 if (ParseUInt32(BaseSizeArg
))
2174 if (EatIfPresent(lltok::comma
)) {
2175 auto HowManyAt
= Lex
.getLoc();
2177 if (ParseUInt32(HowMany
))
2179 if (HowMany
== BaseSizeArg
)
2180 return Error(HowManyAt
,
2181 "'allocsize' indices can't refer to the same parameter");
2182 HowManyArg
= HowMany
;
2186 auto EndParen
= Lex
.getLoc();
2187 if (!EatIfPresent(lltok::rparen
))
2188 return Error(EndParen
, "expected ')'");
2192 /// ParseScopeAndOrdering
2193 /// if isAtomic: ::= SyncScope? AtomicOrdering
2196 /// This sets Scope and Ordering to the parsed values.
2197 bool LLParser::ParseScopeAndOrdering(bool isAtomic
, SyncScope::ID
&SSID
,
2198 AtomicOrdering
&Ordering
) {
2202 return ParseScope(SSID
) || ParseOrdering(Ordering
);
2206 /// ::= syncscope("singlethread" | "<target scope>")?
2208 /// This sets synchronization scope ID to the ID of the parsed value.
2209 bool LLParser::ParseScope(SyncScope::ID
&SSID
) {
2210 SSID
= SyncScope::System
;
2211 if (EatIfPresent(lltok::kw_syncscope
)) {
2212 auto StartParenAt
= Lex
.getLoc();
2213 if (!EatIfPresent(lltok::lparen
))
2214 return Error(StartParenAt
, "Expected '(' in syncscope");
2217 auto SSNAt
= Lex
.getLoc();
2218 if (ParseStringConstant(SSN
))
2219 return Error(SSNAt
, "Expected synchronization scope name");
2221 auto EndParenAt
= Lex
.getLoc();
2222 if (!EatIfPresent(lltok::rparen
))
2223 return Error(EndParenAt
, "Expected ')' in syncscope");
2225 SSID
= Context
.getOrInsertSyncScopeID(SSN
);
2232 /// ::= AtomicOrdering
2234 /// This sets Ordering to the parsed value.
2235 bool LLParser::ParseOrdering(AtomicOrdering
&Ordering
) {
2236 switch (Lex
.getKind()) {
2237 default: return TokError("Expected ordering on atomic instruction");
2238 case lltok::kw_unordered
: Ordering
= AtomicOrdering::Unordered
; break;
2239 case lltok::kw_monotonic
: Ordering
= AtomicOrdering::Monotonic
; break;
2240 // Not specified yet:
2241 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2242 case lltok::kw_acquire
: Ordering
= AtomicOrdering::Acquire
; break;
2243 case lltok::kw_release
: Ordering
= AtomicOrdering::Release
; break;
2244 case lltok::kw_acq_rel
: Ordering
= AtomicOrdering::AcquireRelease
; break;
2245 case lltok::kw_seq_cst
:
2246 Ordering
= AtomicOrdering::SequentiallyConsistent
;
2253 /// ParseOptionalStackAlignment
2255 /// ::= 'alignstack' '(' 4 ')'
2256 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment
) {
2258 if (!EatIfPresent(lltok::kw_alignstack
))
2260 LocTy ParenLoc
= Lex
.getLoc();
2261 if (!EatIfPresent(lltok::lparen
))
2262 return Error(ParenLoc
, "expected '('");
2263 LocTy AlignLoc
= Lex
.getLoc();
2264 if (ParseUInt32(Alignment
)) return true;
2265 ParenLoc
= Lex
.getLoc();
2266 if (!EatIfPresent(lltok::rparen
))
2267 return Error(ParenLoc
, "expected ')'");
2268 if (!isPowerOf2_32(Alignment
))
2269 return Error(AlignLoc
, "stack alignment is not a power of two");
2273 /// ParseIndexList - This parses the index list for an insert/extractvalue
2274 /// instruction. This sets AteExtraComma in the case where we eat an extra
2275 /// comma at the end of the line and find that it is followed by metadata.
2276 /// Clients that don't allow metadata can call the version of this function that
2277 /// only takes one argument.
2280 /// ::= (',' uint32)+
2282 bool LLParser::ParseIndexList(SmallVectorImpl
<unsigned> &Indices
,
2283 bool &AteExtraComma
) {
2284 AteExtraComma
= false;
2286 if (Lex
.getKind() != lltok::comma
)
2287 return TokError("expected ',' as start of index list");
2289 while (EatIfPresent(lltok::comma
)) {
2290 if (Lex
.getKind() == lltok::MetadataVar
) {
2291 if (Indices
.empty()) return TokError("expected index");
2292 AteExtraComma
= true;
2296 if (ParseUInt32(Idx
)) return true;
2297 Indices
.push_back(Idx
);
2303 //===----------------------------------------------------------------------===//
2305 //===----------------------------------------------------------------------===//
2307 /// ParseType - Parse a type.
2308 bool LLParser::ParseType(Type
*&Result
, const Twine
&Msg
, bool AllowVoid
) {
2309 SMLoc TypeLoc
= Lex
.getLoc();
2310 switch (Lex
.getKind()) {
2312 return TokError(Msg
);
2314 // Type ::= 'float' | 'void' (etc)
2315 Result
= Lex
.getTyVal();
2319 // Type ::= StructType
2320 if (ParseAnonStructType(Result
, false))
2323 case lltok::lsquare
:
2324 // Type ::= '[' ... ']'
2325 Lex
.Lex(); // eat the lsquare.
2326 if (ParseArrayVectorType(Result
, false))
2329 case lltok::less
: // Either vector or packed struct.
2330 // Type ::= '<' ... '>'
2332 if (Lex
.getKind() == lltok::lbrace
) {
2333 if (ParseAnonStructType(Result
, true) ||
2334 ParseToken(lltok::greater
, "expected '>' at end of packed struct"))
2336 } else if (ParseArrayVectorType(Result
, true))
2339 case lltok::LocalVar
: {
2341 std::pair
<Type
*, LocTy
> &Entry
= NamedTypes
[Lex
.getStrVal()];
2343 // If the type hasn't been defined yet, create a forward definition and
2344 // remember where that forward def'n was seen (in case it never is defined).
2346 Entry
.first
= StructType::create(Context
, Lex
.getStrVal());
2347 Entry
.second
= Lex
.getLoc();
2349 Result
= Entry
.first
;
2354 case lltok::LocalVarID
: {
2356 std::pair
<Type
*, LocTy
> &Entry
= NumberedTypes
[Lex
.getUIntVal()];
2358 // If the type hasn't been defined yet, create a forward definition and
2359 // remember where that forward def'n was seen (in case it never is defined).
2361 Entry
.first
= StructType::create(Context
);
2362 Entry
.second
= Lex
.getLoc();
2364 Result
= Entry
.first
;
2370 // Parse the type suffixes.
2372 switch (Lex
.getKind()) {
2375 if (!AllowVoid
&& Result
->isVoidTy())
2376 return Error(TypeLoc
, "void type only allowed for function results");
2379 // Type ::= Type '*'
2381 if (Result
->isLabelTy())
2382 return TokError("basic block pointers are invalid");
2383 if (Result
->isVoidTy())
2384 return TokError("pointers to void are invalid - use i8* instead");
2385 if (!PointerType::isValidElementType(Result
))
2386 return TokError("pointer to this type is invalid");
2387 Result
= PointerType::getUnqual(Result
);
2391 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2392 case lltok::kw_addrspace
: {
2393 if (Result
->isLabelTy())
2394 return TokError("basic block pointers are invalid");
2395 if (Result
->isVoidTy())
2396 return TokError("pointers to void are invalid; use i8* instead");
2397 if (!PointerType::isValidElementType(Result
))
2398 return TokError("pointer to this type is invalid");
2400 if (ParseOptionalAddrSpace(AddrSpace
) ||
2401 ParseToken(lltok::star
, "expected '*' in address space"))
2404 Result
= PointerType::get(Result
, AddrSpace
);
2408 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2410 if (ParseFunctionType(Result
))
2417 /// ParseParameterList
2419 /// ::= '(' Arg (',' Arg)* ')'
2421 /// ::= Type OptionalAttributes Value OptionalAttributes
2422 bool LLParser::ParseParameterList(SmallVectorImpl
<ParamInfo
> &ArgList
,
2423 PerFunctionState
&PFS
, bool IsMustTailCall
,
2424 bool InVarArgsFunc
) {
2425 if (ParseToken(lltok::lparen
, "expected '(' in call"))
2428 while (Lex
.getKind() != lltok::rparen
) {
2429 // If this isn't the first argument, we need a comma.
2430 if (!ArgList
.empty() &&
2431 ParseToken(lltok::comma
, "expected ',' in argument list"))
2434 // Parse an ellipsis if this is a musttail call in a variadic function.
2435 if (Lex
.getKind() == lltok::dotdotdot
) {
2436 const char *Msg
= "unexpected ellipsis in argument list for ";
2437 if (!IsMustTailCall
)
2438 return TokError(Twine(Msg
) + "non-musttail call");
2440 return TokError(Twine(Msg
) + "musttail call in non-varargs function");
2441 Lex
.Lex(); // Lex the '...', it is purely for readability.
2442 return ParseToken(lltok::rparen
, "expected ')' at end of argument list");
2445 // Parse the argument.
2447 Type
*ArgTy
= nullptr;
2448 AttrBuilder ArgAttrs
;
2450 if (ParseType(ArgTy
, ArgLoc
))
2453 if (ArgTy
->isMetadataTy()) {
2454 if (ParseMetadataAsValue(V
, PFS
))
2457 // Otherwise, handle normal operands.
2458 if (ParseOptionalParamAttrs(ArgAttrs
) || ParseValue(ArgTy
, V
, PFS
))
2461 ArgList
.push_back(ParamInfo(
2462 ArgLoc
, V
, AttributeSet::get(V
->getContext(), ArgAttrs
)));
2465 if (IsMustTailCall
&& InVarArgsFunc
)
2466 return TokError("expected '...' at end of argument list for musttail call "
2467 "in varargs function");
2469 Lex
.Lex(); // Lex the ')'.
2473 /// ParseByValWithOptionalType
2476 bool LLParser::ParseByValWithOptionalType(Type
*&Result
) {
2478 if (!EatIfPresent(lltok::kw_byval
))
2480 if (!EatIfPresent(lltok::lparen
))
2482 if (ParseType(Result
))
2484 if (!EatIfPresent(lltok::rparen
))
2485 return Error(Lex
.getLoc(), "expected ')'");
2489 /// ParseOptionalOperandBundles
2491 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2494 /// ::= bundle-tag '(' ')'
2495 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2497 /// bundle-tag ::= String Constant
2498 bool LLParser::ParseOptionalOperandBundles(
2499 SmallVectorImpl
<OperandBundleDef
> &BundleList
, PerFunctionState
&PFS
) {
2500 LocTy BeginLoc
= Lex
.getLoc();
2501 if (!EatIfPresent(lltok::lsquare
))
2504 while (Lex
.getKind() != lltok::rsquare
) {
2505 // If this isn't the first operand bundle, we need a comma.
2506 if (!BundleList
.empty() &&
2507 ParseToken(lltok::comma
, "expected ',' in input list"))
2511 if (ParseStringConstant(Tag
))
2514 if (ParseToken(lltok::lparen
, "expected '(' in operand bundle"))
2517 std::vector
<Value
*> Inputs
;
2518 while (Lex
.getKind() != lltok::rparen
) {
2519 // If this isn't the first input, we need a comma.
2520 if (!Inputs
.empty() &&
2521 ParseToken(lltok::comma
, "expected ',' in input list"))
2525 Value
*Input
= nullptr;
2526 if (ParseType(Ty
) || ParseValue(Ty
, Input
, PFS
))
2528 Inputs
.push_back(Input
);
2531 BundleList
.emplace_back(std::move(Tag
), std::move(Inputs
));
2533 Lex
.Lex(); // Lex the ')'.
2536 if (BundleList
.empty())
2537 return Error(BeginLoc
, "operand bundle set must not be empty");
2539 Lex
.Lex(); // Lex the ']'.
2543 /// ParseArgumentList - Parse the argument list for a function type or function
2545 /// ::= '(' ArgTypeListI ')'
2549 /// ::= ArgTypeList ',' '...'
2550 /// ::= ArgType (',' ArgType)*
2552 bool LLParser::ParseArgumentList(SmallVectorImpl
<ArgInfo
> &ArgList
,
2554 unsigned CurValID
= 0;
2556 assert(Lex
.getKind() == lltok::lparen
);
2557 Lex
.Lex(); // eat the (.
2559 if (Lex
.getKind() == lltok::rparen
) {
2561 } else if (Lex
.getKind() == lltok::dotdotdot
) {
2565 LocTy TypeLoc
= Lex
.getLoc();
2566 Type
*ArgTy
= nullptr;
2570 if (ParseType(ArgTy
) ||
2571 ParseOptionalParamAttrs(Attrs
)) return true;
2573 if (ArgTy
->isVoidTy())
2574 return Error(TypeLoc
, "argument can not have void type");
2576 if (Lex
.getKind() == lltok::LocalVar
) {
2577 Name
= Lex
.getStrVal();
2579 } else if (Lex
.getKind() == lltok::LocalVarID
) {
2580 if (Lex
.getUIntVal() != CurValID
)
2581 return Error(TypeLoc
, "argument expected to be numbered '%" +
2582 Twine(CurValID
) + "'");
2587 if (!FunctionType::isValidArgumentType(ArgTy
))
2588 return Error(TypeLoc
, "invalid type for function argument");
2590 ArgList
.emplace_back(TypeLoc
, ArgTy
,
2591 AttributeSet::get(ArgTy
->getContext(), Attrs
),
2594 while (EatIfPresent(lltok::comma
)) {
2595 // Handle ... at end of arg list.
2596 if (EatIfPresent(lltok::dotdotdot
)) {
2601 // Otherwise must be an argument type.
2602 TypeLoc
= Lex
.getLoc();
2603 if (ParseType(ArgTy
) || ParseOptionalParamAttrs(Attrs
)) return true;
2605 if (ArgTy
->isVoidTy())
2606 return Error(TypeLoc
, "argument can not have void type");
2608 if (Lex
.getKind() == lltok::LocalVar
) {
2609 Name
= Lex
.getStrVal();
2612 if (Lex
.getKind() == lltok::LocalVarID
) {
2613 if (Lex
.getUIntVal() != CurValID
)
2614 return Error(TypeLoc
, "argument expected to be numbered '%" +
2615 Twine(CurValID
) + "'");
2622 if (!ArgTy
->isFirstClassType())
2623 return Error(TypeLoc
, "invalid type for function argument");
2625 ArgList
.emplace_back(TypeLoc
, ArgTy
,
2626 AttributeSet::get(ArgTy
->getContext(), Attrs
),
2631 return ParseToken(lltok::rparen
, "expected ')' at end of argument list");
2634 /// ParseFunctionType
2635 /// ::= Type ArgumentList OptionalAttrs
2636 bool LLParser::ParseFunctionType(Type
*&Result
) {
2637 assert(Lex
.getKind() == lltok::lparen
);
2639 if (!FunctionType::isValidReturnType(Result
))
2640 return TokError("invalid function return type");
2642 SmallVector
<ArgInfo
, 8> ArgList
;
2644 if (ParseArgumentList(ArgList
, isVarArg
))
2647 // Reject names on the arguments lists.
2648 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
2649 if (!ArgList
[i
].Name
.empty())
2650 return Error(ArgList
[i
].Loc
, "argument name invalid in function type");
2651 if (ArgList
[i
].Attrs
.hasAttributes())
2652 return Error(ArgList
[i
].Loc
,
2653 "argument attributes invalid in function type");
2656 SmallVector
<Type
*, 16> ArgListTy
;
2657 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
2658 ArgListTy
.push_back(ArgList
[i
].Ty
);
2660 Result
= FunctionType::get(Result
, ArgListTy
, isVarArg
);
2664 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2666 bool LLParser::ParseAnonStructType(Type
*&Result
, bool Packed
) {
2667 SmallVector
<Type
*, 8> Elts
;
2668 if (ParseStructBody(Elts
)) return true;
2670 Result
= StructType::get(Context
, Elts
, Packed
);
2674 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2675 bool LLParser::ParseStructDefinition(SMLoc TypeLoc
, StringRef Name
,
2676 std::pair
<Type
*, LocTy
> &Entry
,
2678 // If the type was already defined, diagnose the redefinition.
2679 if (Entry
.first
&& !Entry
.second
.isValid())
2680 return Error(TypeLoc
, "redefinition of type");
2682 // If we have opaque, just return without filling in the definition for the
2683 // struct. This counts as a definition as far as the .ll file goes.
2684 if (EatIfPresent(lltok::kw_opaque
)) {
2685 // This type is being defined, so clear the location to indicate this.
2686 Entry
.second
= SMLoc();
2688 // If this type number has never been uttered, create it.
2690 Entry
.first
= StructType::create(Context
, Name
);
2691 ResultTy
= Entry
.first
;
2695 // If the type starts with '<', then it is either a packed struct or a vector.
2696 bool isPacked
= EatIfPresent(lltok::less
);
2698 // If we don't have a struct, then we have a random type alias, which we
2699 // accept for compatibility with old files. These types are not allowed to be
2700 // forward referenced and not allowed to be recursive.
2701 if (Lex
.getKind() != lltok::lbrace
) {
2703 return Error(TypeLoc
, "forward references to non-struct type");
2707 return ParseArrayVectorType(ResultTy
, true);
2708 return ParseType(ResultTy
);
2711 // This type is being defined, so clear the location to indicate this.
2712 Entry
.second
= SMLoc();
2714 // If this type number has never been uttered, create it.
2716 Entry
.first
= StructType::create(Context
, Name
);
2718 StructType
*STy
= cast
<StructType
>(Entry
.first
);
2720 SmallVector
<Type
*, 8> Body
;
2721 if (ParseStructBody(Body
) ||
2722 (isPacked
&& ParseToken(lltok::greater
, "expected '>' in packed struct")))
2725 STy
->setBody(Body
, isPacked
);
2730 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2733 /// ::= '{' Type (',' Type)* '}'
2734 /// ::= '<' '{' '}' '>'
2735 /// ::= '<' '{' Type (',' Type)* '}' '>'
2736 bool LLParser::ParseStructBody(SmallVectorImpl
<Type
*> &Body
) {
2737 assert(Lex
.getKind() == lltok::lbrace
);
2738 Lex
.Lex(); // Consume the '{'
2740 // Handle the empty struct.
2741 if (EatIfPresent(lltok::rbrace
))
2744 LocTy EltTyLoc
= Lex
.getLoc();
2746 if (ParseType(Ty
)) return true;
2749 if (!StructType::isValidElementType(Ty
))
2750 return Error(EltTyLoc
, "invalid element type for struct");
2752 while (EatIfPresent(lltok::comma
)) {
2753 EltTyLoc
= Lex
.getLoc();
2754 if (ParseType(Ty
)) return true;
2756 if (!StructType::isValidElementType(Ty
))
2757 return Error(EltTyLoc
, "invalid element type for struct");
2762 return ParseToken(lltok::rbrace
, "expected '}' at end of struct");
2765 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2766 /// token has already been consumed.
2768 /// ::= '[' APSINTVAL 'x' Types ']'
2769 /// ::= '<' APSINTVAL 'x' Types '>'
2770 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
2771 bool LLParser::ParseArrayVectorType(Type
*&Result
, bool isVector
) {
2772 bool Scalable
= false;
2774 if (isVector
&& Lex
.getKind() == lltok::kw_vscale
) {
2775 Lex
.Lex(); // consume the 'vscale'
2776 if (ParseToken(lltok::kw_x
, "expected 'x' after vscale"))
2782 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned() ||
2783 Lex
.getAPSIntVal().getBitWidth() > 64)
2784 return TokError("expected number in address space");
2786 LocTy SizeLoc
= Lex
.getLoc();
2787 uint64_t Size
= Lex
.getAPSIntVal().getZExtValue();
2790 if (ParseToken(lltok::kw_x
, "expected 'x' after element count"))
2793 LocTy TypeLoc
= Lex
.getLoc();
2794 Type
*EltTy
= nullptr;
2795 if (ParseType(EltTy
)) return true;
2797 if (ParseToken(isVector
? lltok::greater
: lltok::rsquare
,
2798 "expected end of sequential type"))
2803 return Error(SizeLoc
, "zero element vector is illegal");
2804 if ((unsigned)Size
!= Size
)
2805 return Error(SizeLoc
, "size too large for vector");
2806 if (!VectorType::isValidElementType(EltTy
))
2807 return Error(TypeLoc
, "invalid vector element type");
2808 Result
= VectorType::get(EltTy
, unsigned(Size
), Scalable
);
2810 if (!ArrayType::isValidElementType(EltTy
))
2811 return Error(TypeLoc
, "invalid array element type");
2812 Result
= ArrayType::get(EltTy
, Size
);
2817 //===----------------------------------------------------------------------===//
2818 // Function Semantic Analysis.
2819 //===----------------------------------------------------------------------===//
2821 LLParser::PerFunctionState::PerFunctionState(LLParser
&p
, Function
&f
,
2823 : P(p
), F(f
), FunctionNumber(functionNumber
) {
2825 // Insert unnamed arguments into the NumberedVals list.
2826 for (Argument
&A
: F
.args())
2828 NumberedVals
.push_back(&A
);
2831 LLParser::PerFunctionState::~PerFunctionState() {
2832 // If there were any forward referenced non-basicblock values, delete them.
2834 for (const auto &P
: ForwardRefVals
) {
2835 if (isa
<BasicBlock
>(P
.second
.first
))
2837 P
.second
.first
->replaceAllUsesWith(
2838 UndefValue::get(P
.second
.first
->getType()));
2839 P
.second
.first
->deleteValue();
2842 for (const auto &P
: ForwardRefValIDs
) {
2843 if (isa
<BasicBlock
>(P
.second
.first
))
2845 P
.second
.first
->replaceAllUsesWith(
2846 UndefValue::get(P
.second
.first
->getType()));
2847 P
.second
.first
->deleteValue();
2851 bool LLParser::PerFunctionState::FinishFunction() {
2852 if (!ForwardRefVals
.empty())
2853 return P
.Error(ForwardRefVals
.begin()->second
.second
,
2854 "use of undefined value '%" + ForwardRefVals
.begin()->first
+
2856 if (!ForwardRefValIDs
.empty())
2857 return P
.Error(ForwardRefValIDs
.begin()->second
.second
,
2858 "use of undefined value '%" +
2859 Twine(ForwardRefValIDs
.begin()->first
) + "'");
2863 /// GetVal - Get a value with the specified name or ID, creating a
2864 /// forward reference record if needed. This can return null if the value
2865 /// exists but does not have the right type.
2866 Value
*LLParser::PerFunctionState::GetVal(const std::string
&Name
, Type
*Ty
,
2867 LocTy Loc
, bool IsCall
) {
2868 // Look this name up in the normal function symbol table.
2869 Value
*Val
= F
.getValueSymbolTable()->lookup(Name
);
2871 // If this is a forward reference for the value, see if we already created a
2872 // forward ref record.
2874 auto I
= ForwardRefVals
.find(Name
);
2875 if (I
!= ForwardRefVals
.end())
2876 Val
= I
->second
.first
;
2879 // If we have the value in the symbol table or fwd-ref table, return it.
2881 return P
.checkValidVariableType(Loc
, "%" + Name
, Ty
, Val
, IsCall
);
2883 // Don't make placeholders with invalid type.
2884 if (!Ty
->isFirstClassType()) {
2885 P
.Error(Loc
, "invalid use of a non-first-class type");
2889 // Otherwise, create a new forward reference for this value and remember it.
2891 if (Ty
->isLabelTy()) {
2892 FwdVal
= BasicBlock::Create(F
.getContext(), Name
, &F
);
2894 FwdVal
= new Argument(Ty
, Name
);
2897 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
2901 Value
*LLParser::PerFunctionState::GetVal(unsigned ID
, Type
*Ty
, LocTy Loc
,
2903 // Look this name up in the normal function symbol table.
2904 Value
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : nullptr;
2906 // If this is a forward reference for the value, see if we already created a
2907 // forward ref record.
2909 auto I
= ForwardRefValIDs
.find(ID
);
2910 if (I
!= ForwardRefValIDs
.end())
2911 Val
= I
->second
.first
;
2914 // If we have the value in the symbol table or fwd-ref table, return it.
2916 return P
.checkValidVariableType(Loc
, "%" + Twine(ID
), Ty
, Val
, IsCall
);
2918 if (!Ty
->isFirstClassType()) {
2919 P
.Error(Loc
, "invalid use of a non-first-class type");
2923 // Otherwise, create a new forward reference for this value and remember it.
2925 if (Ty
->isLabelTy()) {
2926 FwdVal
= BasicBlock::Create(F
.getContext(), "", &F
);
2928 FwdVal
= new Argument(Ty
);
2931 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
2935 /// SetInstName - After an instruction is parsed and inserted into its
2936 /// basic block, this installs its name.
2937 bool LLParser::PerFunctionState::SetInstName(int NameID
,
2938 const std::string
&NameStr
,
2939 LocTy NameLoc
, Instruction
*Inst
) {
2940 // If this instruction has void type, it cannot have a name or ID specified.
2941 if (Inst
->getType()->isVoidTy()) {
2942 if (NameID
!= -1 || !NameStr
.empty())
2943 return P
.Error(NameLoc
, "instructions returning void cannot have a name");
2947 // If this was a numbered instruction, verify that the instruction is the
2948 // expected value and resolve any forward references.
2949 if (NameStr
.empty()) {
2950 // If neither a name nor an ID was specified, just use the next ID.
2952 NameID
= NumberedVals
.size();
2954 if (unsigned(NameID
) != NumberedVals
.size())
2955 return P
.Error(NameLoc
, "instruction expected to be numbered '%" +
2956 Twine(NumberedVals
.size()) + "'");
2958 auto FI
= ForwardRefValIDs
.find(NameID
);
2959 if (FI
!= ForwardRefValIDs
.end()) {
2960 Value
*Sentinel
= FI
->second
.first
;
2961 if (Sentinel
->getType() != Inst
->getType())
2962 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
2963 getTypeString(FI
->second
.first
->getType()) + "'");
2965 Sentinel
->replaceAllUsesWith(Inst
);
2966 Sentinel
->deleteValue();
2967 ForwardRefValIDs
.erase(FI
);
2970 NumberedVals
.push_back(Inst
);
2974 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2975 auto FI
= ForwardRefVals
.find(NameStr
);
2976 if (FI
!= ForwardRefVals
.end()) {
2977 Value
*Sentinel
= FI
->second
.first
;
2978 if (Sentinel
->getType() != Inst
->getType())
2979 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
2980 getTypeString(FI
->second
.first
->getType()) + "'");
2982 Sentinel
->replaceAllUsesWith(Inst
);
2983 Sentinel
->deleteValue();
2984 ForwardRefVals
.erase(FI
);
2987 // Set the name on the instruction.
2988 Inst
->setName(NameStr
);
2990 if (Inst
->getName() != NameStr
)
2991 return P
.Error(NameLoc
, "multiple definition of local value named '" +
2996 /// GetBB - Get a basic block with the specified name or ID, creating a
2997 /// forward reference record if needed.
2998 BasicBlock
*LLParser::PerFunctionState::GetBB(const std::string
&Name
,
3000 return dyn_cast_or_null
<BasicBlock
>(
3001 GetVal(Name
, Type::getLabelTy(F
.getContext()), Loc
, /*IsCall=*/false));
3004 BasicBlock
*LLParser::PerFunctionState::GetBB(unsigned ID
, LocTy Loc
) {
3005 return dyn_cast_or_null
<BasicBlock
>(
3006 GetVal(ID
, Type::getLabelTy(F
.getContext()), Loc
, /*IsCall=*/false));
3009 /// DefineBB - Define the specified basic block, which is either named or
3010 /// unnamed. If there is an error, this returns null otherwise it returns
3011 /// the block being defined.
3012 BasicBlock
*LLParser::PerFunctionState::DefineBB(const std::string
&Name
,
3013 int NameID
, LocTy Loc
) {
3016 if (NameID
!= -1 && unsigned(NameID
) != NumberedVals
.size()) {
3017 P
.Error(Loc
, "label expected to be numbered '" +
3018 Twine(NumberedVals
.size()) + "'");
3021 BB
= GetBB(NumberedVals
.size(), Loc
);
3023 P
.Error(Loc
, "unable to create block numbered '" +
3024 Twine(NumberedVals
.size()) + "'");
3028 BB
= GetBB(Name
, Loc
);
3030 P
.Error(Loc
, "unable to create block named '" + Name
+ "'");
3035 // Move the block to the end of the function. Forward ref'd blocks are
3036 // inserted wherever they happen to be referenced.
3037 F
.getBasicBlockList().splice(F
.end(), F
.getBasicBlockList(), BB
);
3039 // Remove the block from forward ref sets.
3041 ForwardRefValIDs
.erase(NumberedVals
.size());
3042 NumberedVals
.push_back(BB
);
3044 // BB forward references are already in the function symbol table.
3045 ForwardRefVals
.erase(Name
);
3051 //===----------------------------------------------------------------------===//
3053 //===----------------------------------------------------------------------===//
3055 /// ParseValID - Parse an abstract value that doesn't necessarily have a
3056 /// type implied. For example, if we parse "4" we don't know what integer type
3057 /// it has. The value will later be combined with its type and checked for
3058 /// sanity. PFS is used to convert function-local operands of metadata (since
3059 /// metadata operands are not just parsed here but also converted to values).
3060 /// PFS can be null when we are not parsing metadata values inside a function.
3061 bool LLParser::ParseValID(ValID
&ID
, PerFunctionState
*PFS
) {
3062 ID
.Loc
= Lex
.getLoc();
3063 switch (Lex
.getKind()) {
3064 default: return TokError("expected value token");
3065 case lltok::GlobalID
: // @42
3066 ID
.UIntVal
= Lex
.getUIntVal();
3067 ID
.Kind
= ValID::t_GlobalID
;
3069 case lltok::GlobalVar
: // @foo
3070 ID
.StrVal
= Lex
.getStrVal();
3071 ID
.Kind
= ValID::t_GlobalName
;
3073 case lltok::LocalVarID
: // %42
3074 ID
.UIntVal
= Lex
.getUIntVal();
3075 ID
.Kind
= ValID::t_LocalID
;
3077 case lltok::LocalVar
: // %foo
3078 ID
.StrVal
= Lex
.getStrVal();
3079 ID
.Kind
= ValID::t_LocalName
;
3082 ID
.APSIntVal
= Lex
.getAPSIntVal();
3083 ID
.Kind
= ValID::t_APSInt
;
3085 case lltok::APFloat
:
3086 ID
.APFloatVal
= Lex
.getAPFloatVal();
3087 ID
.Kind
= ValID::t_APFloat
;
3089 case lltok::kw_true
:
3090 ID
.ConstantVal
= ConstantInt::getTrue(Context
);
3091 ID
.Kind
= ValID::t_Constant
;
3093 case lltok::kw_false
:
3094 ID
.ConstantVal
= ConstantInt::getFalse(Context
);
3095 ID
.Kind
= ValID::t_Constant
;
3097 case lltok::kw_null
: ID
.Kind
= ValID::t_Null
; break;
3098 case lltok::kw_undef
: ID
.Kind
= ValID::t_Undef
; break;
3099 case lltok::kw_zeroinitializer
: ID
.Kind
= ValID::t_Zero
; break;
3100 case lltok::kw_none
: ID
.Kind
= ValID::t_None
; break;
3102 case lltok::lbrace
: {
3103 // ValID ::= '{' ConstVector '}'
3105 SmallVector
<Constant
*, 16> Elts
;
3106 if (ParseGlobalValueVector(Elts
) ||
3107 ParseToken(lltok::rbrace
, "expected end of struct constant"))
3110 ID
.ConstantStructElts
= std::make_unique
<Constant
*[]>(Elts
.size());
3111 ID
.UIntVal
= Elts
.size();
3112 memcpy(ID
.ConstantStructElts
.get(), Elts
.data(),
3113 Elts
.size() * sizeof(Elts
[0]));
3114 ID
.Kind
= ValID::t_ConstantStruct
;
3118 // ValID ::= '<' ConstVector '>' --> Vector.
3119 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3121 bool isPackedStruct
= EatIfPresent(lltok::lbrace
);
3123 SmallVector
<Constant
*, 16> Elts
;
3124 LocTy FirstEltLoc
= Lex
.getLoc();
3125 if (ParseGlobalValueVector(Elts
) ||
3127 ParseToken(lltok::rbrace
, "expected end of packed struct")) ||
3128 ParseToken(lltok::greater
, "expected end of constant"))
3131 if (isPackedStruct
) {
3132 ID
.ConstantStructElts
= std::make_unique
<Constant
*[]>(Elts
.size());
3133 memcpy(ID
.ConstantStructElts
.get(), Elts
.data(),
3134 Elts
.size() * sizeof(Elts
[0]));
3135 ID
.UIntVal
= Elts
.size();
3136 ID
.Kind
= ValID::t_PackedConstantStruct
;
3141 return Error(ID
.Loc
, "constant vector must not be empty");
3143 if (!Elts
[0]->getType()->isIntegerTy() &&
3144 !Elts
[0]->getType()->isFloatingPointTy() &&
3145 !Elts
[0]->getType()->isPointerTy())
3146 return Error(FirstEltLoc
,
3147 "vector elements must have integer, pointer or floating point type");
3149 // Verify that all the vector elements have the same type.
3150 for (unsigned i
= 1, e
= Elts
.size(); i
!= e
; ++i
)
3151 if (Elts
[i
]->getType() != Elts
[0]->getType())
3152 return Error(FirstEltLoc
,
3153 "vector element #" + Twine(i
) +
3154 " is not of type '" + getTypeString(Elts
[0]->getType()));
3156 ID
.ConstantVal
= ConstantVector::get(Elts
);
3157 ID
.Kind
= ValID::t_Constant
;
3160 case lltok::lsquare
: { // Array Constant
3162 SmallVector
<Constant
*, 16> Elts
;
3163 LocTy FirstEltLoc
= Lex
.getLoc();
3164 if (ParseGlobalValueVector(Elts
) ||
3165 ParseToken(lltok::rsquare
, "expected end of array constant"))
3168 // Handle empty element.
3170 // Use undef instead of an array because it's inconvenient to determine
3171 // the element type at this point, there being no elements to examine.
3172 ID
.Kind
= ValID::t_EmptyArray
;
3176 if (!Elts
[0]->getType()->isFirstClassType())
3177 return Error(FirstEltLoc
, "invalid array element type: " +
3178 getTypeString(Elts
[0]->getType()));
3180 ArrayType
*ATy
= ArrayType::get(Elts
[0]->getType(), Elts
.size());
3182 // Verify all elements are correct type!
3183 for (unsigned i
= 0, e
= Elts
.size(); i
!= e
; ++i
) {
3184 if (Elts
[i
]->getType() != Elts
[0]->getType())
3185 return Error(FirstEltLoc
,
3186 "array element #" + Twine(i
) +
3187 " is not of type '" + getTypeString(Elts
[0]->getType()));
3190 ID
.ConstantVal
= ConstantArray::get(ATy
, Elts
);
3191 ID
.Kind
= ValID::t_Constant
;
3194 case lltok::kw_c
: // c "foo"
3196 ID
.ConstantVal
= ConstantDataArray::getString(Context
, Lex
.getStrVal(),
3198 if (ParseToken(lltok::StringConstant
, "expected string")) return true;
3199 ID
.Kind
= ValID::t_Constant
;
3202 case lltok::kw_asm
: {
3203 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3205 bool HasSideEffect
, AlignStack
, AsmDialect
;
3207 if (ParseOptionalToken(lltok::kw_sideeffect
, HasSideEffect
) ||
3208 ParseOptionalToken(lltok::kw_alignstack
, AlignStack
) ||
3209 ParseOptionalToken(lltok::kw_inteldialect
, AsmDialect
) ||
3210 ParseStringConstant(ID
.StrVal
) ||
3211 ParseToken(lltok::comma
, "expected comma in inline asm expression") ||
3212 ParseToken(lltok::StringConstant
, "expected constraint string"))
3214 ID
.StrVal2
= Lex
.getStrVal();
3215 ID
.UIntVal
= unsigned(HasSideEffect
) | (unsigned(AlignStack
)<<1) |
3216 (unsigned(AsmDialect
)<<2);
3217 ID
.Kind
= ValID::t_InlineAsm
;
3221 case lltok::kw_blockaddress
: {
3222 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3227 if (ParseToken(lltok::lparen
, "expected '(' in block address expression") ||
3229 ParseToken(lltok::comma
, "expected comma in block address expression")||
3230 ParseValID(Label
) ||
3231 ParseToken(lltok::rparen
, "expected ')' in block address expression"))
3234 if (Fn
.Kind
!= ValID::t_GlobalID
&& Fn
.Kind
!= ValID::t_GlobalName
)
3235 return Error(Fn
.Loc
, "expected function name in blockaddress");
3236 if (Label
.Kind
!= ValID::t_LocalID
&& Label
.Kind
!= ValID::t_LocalName
)
3237 return Error(Label
.Loc
, "expected basic block name in blockaddress");
3239 // Try to find the function (but skip it if it's forward-referenced).
3240 GlobalValue
*GV
= nullptr;
3241 if (Fn
.Kind
== ValID::t_GlobalID
) {
3242 if (Fn
.UIntVal
< NumberedVals
.size())
3243 GV
= NumberedVals
[Fn
.UIntVal
];
3244 } else if (!ForwardRefVals
.count(Fn
.StrVal
)) {
3245 GV
= M
->getNamedValue(Fn
.StrVal
);
3247 Function
*F
= nullptr;
3249 // Confirm that it's actually a function with a definition.
3250 if (!isa
<Function
>(GV
))
3251 return Error(Fn
.Loc
, "expected function name in blockaddress");
3252 F
= cast
<Function
>(GV
);
3253 if (F
->isDeclaration())
3254 return Error(Fn
.Loc
, "cannot take blockaddress inside a declaration");
3258 // Make a global variable as a placeholder for this reference.
3259 GlobalValue
*&FwdRef
=
3260 ForwardRefBlockAddresses
.insert(std::make_pair(
3262 std::map
<ValID
, GlobalValue
*>()))
3263 .first
->second
.insert(std::make_pair(std::move(Label
), nullptr))
3266 FwdRef
= new GlobalVariable(*M
, Type::getInt8Ty(Context
), false,
3267 GlobalValue::InternalLinkage
, nullptr, "");
3268 ID
.ConstantVal
= FwdRef
;
3269 ID
.Kind
= ValID::t_Constant
;
3273 // We found the function; now find the basic block. Don't use PFS, since we
3274 // might be inside a constant expression.
3276 if (BlockAddressPFS
&& F
== &BlockAddressPFS
->getFunction()) {
3277 if (Label
.Kind
== ValID::t_LocalID
)
3278 BB
= BlockAddressPFS
->GetBB(Label
.UIntVal
, Label
.Loc
);
3280 BB
= BlockAddressPFS
->GetBB(Label
.StrVal
, Label
.Loc
);
3282 return Error(Label
.Loc
, "referenced value is not a basic block");
3284 if (Label
.Kind
== ValID::t_LocalID
)
3285 return Error(Label
.Loc
, "cannot take address of numeric label after "
3286 "the function is defined");
3287 BB
= dyn_cast_or_null
<BasicBlock
>(
3288 F
->getValueSymbolTable()->lookup(Label
.StrVal
));
3290 return Error(Label
.Loc
, "referenced value is not a basic block");
3293 ID
.ConstantVal
= BlockAddress::get(F
, BB
);
3294 ID
.Kind
= ValID::t_Constant
;
3298 case lltok::kw_trunc
:
3299 case lltok::kw_zext
:
3300 case lltok::kw_sext
:
3301 case lltok::kw_fptrunc
:
3302 case lltok::kw_fpext
:
3303 case lltok::kw_bitcast
:
3304 case lltok::kw_addrspacecast
:
3305 case lltok::kw_uitofp
:
3306 case lltok::kw_sitofp
:
3307 case lltok::kw_fptoui
:
3308 case lltok::kw_fptosi
:
3309 case lltok::kw_inttoptr
:
3310 case lltok::kw_ptrtoint
: {
3311 unsigned Opc
= Lex
.getUIntVal();
3312 Type
*DestTy
= nullptr;
3315 if (ParseToken(lltok::lparen
, "expected '(' after constantexpr cast") ||
3316 ParseGlobalTypeAndValue(SrcVal
) ||
3317 ParseToken(lltok::kw_to
, "expected 'to' in constantexpr cast") ||
3318 ParseType(DestTy
) ||
3319 ParseToken(lltok::rparen
, "expected ')' at end of constantexpr cast"))
3321 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, SrcVal
, DestTy
))
3322 return Error(ID
.Loc
, "invalid cast opcode for cast from '" +
3323 getTypeString(SrcVal
->getType()) + "' to '" +
3324 getTypeString(DestTy
) + "'");
3325 ID
.ConstantVal
= ConstantExpr::getCast((Instruction::CastOps
)Opc
,
3327 ID
.Kind
= ValID::t_Constant
;
3330 case lltok::kw_extractvalue
: {
3333 SmallVector
<unsigned, 4> Indices
;
3334 if (ParseToken(lltok::lparen
, "expected '(' in extractvalue constantexpr")||
3335 ParseGlobalTypeAndValue(Val
) ||
3336 ParseIndexList(Indices
) ||
3337 ParseToken(lltok::rparen
, "expected ')' in extractvalue constantexpr"))
3340 if (!Val
->getType()->isAggregateType())
3341 return Error(ID
.Loc
, "extractvalue operand must be aggregate type");
3342 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
))
3343 return Error(ID
.Loc
, "invalid indices for extractvalue");
3344 ID
.ConstantVal
= ConstantExpr::getExtractValue(Val
, Indices
);
3345 ID
.Kind
= ValID::t_Constant
;
3348 case lltok::kw_insertvalue
: {
3350 Constant
*Val0
, *Val1
;
3351 SmallVector
<unsigned, 4> Indices
;
3352 if (ParseToken(lltok::lparen
, "expected '(' in insertvalue constantexpr")||
3353 ParseGlobalTypeAndValue(Val0
) ||
3354 ParseToken(lltok::comma
, "expected comma in insertvalue constantexpr")||
3355 ParseGlobalTypeAndValue(Val1
) ||
3356 ParseIndexList(Indices
) ||
3357 ParseToken(lltok::rparen
, "expected ')' in insertvalue constantexpr"))
3359 if (!Val0
->getType()->isAggregateType())
3360 return Error(ID
.Loc
, "insertvalue operand must be aggregate type");
3362 ExtractValueInst::getIndexedType(Val0
->getType(), Indices
);
3364 return Error(ID
.Loc
, "invalid indices for insertvalue");
3365 if (IndexedType
!= Val1
->getType())
3366 return Error(ID
.Loc
, "insertvalue operand and field disagree in type: '" +
3367 getTypeString(Val1
->getType()) +
3368 "' instead of '" + getTypeString(IndexedType
) +
3370 ID
.ConstantVal
= ConstantExpr::getInsertValue(Val0
, Val1
, Indices
);
3371 ID
.Kind
= ValID::t_Constant
;
3374 case lltok::kw_icmp
:
3375 case lltok::kw_fcmp
: {
3376 unsigned PredVal
, Opc
= Lex
.getUIntVal();
3377 Constant
*Val0
, *Val1
;
3379 if (ParseCmpPredicate(PredVal
, Opc
) ||
3380 ParseToken(lltok::lparen
, "expected '(' in compare constantexpr") ||
3381 ParseGlobalTypeAndValue(Val0
) ||
3382 ParseToken(lltok::comma
, "expected comma in compare constantexpr") ||
3383 ParseGlobalTypeAndValue(Val1
) ||
3384 ParseToken(lltok::rparen
, "expected ')' in compare constantexpr"))
3387 if (Val0
->getType() != Val1
->getType())
3388 return Error(ID
.Loc
, "compare operands must have the same type");
3390 CmpInst::Predicate Pred
= (CmpInst::Predicate
)PredVal
;
3392 if (Opc
== Instruction::FCmp
) {
3393 if (!Val0
->getType()->isFPOrFPVectorTy())
3394 return Error(ID
.Loc
, "fcmp requires floating point operands");
3395 ID
.ConstantVal
= ConstantExpr::getFCmp(Pred
, Val0
, Val1
);
3397 assert(Opc
== Instruction::ICmp
&& "Unexpected opcode for CmpInst!");
3398 if (!Val0
->getType()->isIntOrIntVectorTy() &&
3399 !Val0
->getType()->isPtrOrPtrVectorTy())
3400 return Error(ID
.Loc
, "icmp requires pointer or integer operands");
3401 ID
.ConstantVal
= ConstantExpr::getICmp(Pred
, Val0
, Val1
);
3403 ID
.Kind
= ValID::t_Constant
;
3408 case lltok::kw_fneg
: {
3409 unsigned Opc
= Lex
.getUIntVal();
3412 if (ParseToken(lltok::lparen
, "expected '(' in unary constantexpr") ||
3413 ParseGlobalTypeAndValue(Val
) ||
3414 ParseToken(lltok::rparen
, "expected ')' in unary constantexpr"))
3417 // Check that the type is valid for the operator.
3419 case Instruction::FNeg
:
3420 if (!Val
->getType()->isFPOrFPVectorTy())
3421 return Error(ID
.Loc
, "constexpr requires fp operands");
3423 default: llvm_unreachable("Unknown unary operator!");
3426 Constant
*C
= ConstantExpr::get(Opc
, Val
, Flags
);
3428 ID
.Kind
= ValID::t_Constant
;
3431 // Binary Operators.
3433 case lltok::kw_fadd
:
3435 case lltok::kw_fsub
:
3437 case lltok::kw_fmul
:
3438 case lltok::kw_udiv
:
3439 case lltok::kw_sdiv
:
3440 case lltok::kw_fdiv
:
3441 case lltok::kw_urem
:
3442 case lltok::kw_srem
:
3443 case lltok::kw_frem
:
3445 case lltok::kw_lshr
:
3446 case lltok::kw_ashr
: {
3450 unsigned Opc
= Lex
.getUIntVal();
3451 Constant
*Val0
, *Val1
;
3453 if (Opc
== Instruction::Add
|| Opc
== Instruction::Sub
||
3454 Opc
== Instruction::Mul
|| Opc
== Instruction::Shl
) {
3455 if (EatIfPresent(lltok::kw_nuw
))
3457 if (EatIfPresent(lltok::kw_nsw
)) {
3459 if (EatIfPresent(lltok::kw_nuw
))
3462 } else if (Opc
== Instruction::SDiv
|| Opc
== Instruction::UDiv
||
3463 Opc
== Instruction::LShr
|| Opc
== Instruction::AShr
) {
3464 if (EatIfPresent(lltok::kw_exact
))
3467 if (ParseToken(lltok::lparen
, "expected '(' in binary constantexpr") ||
3468 ParseGlobalTypeAndValue(Val0
) ||
3469 ParseToken(lltok::comma
, "expected comma in binary constantexpr") ||
3470 ParseGlobalTypeAndValue(Val1
) ||
3471 ParseToken(lltok::rparen
, "expected ')' in binary constantexpr"))
3473 if (Val0
->getType() != Val1
->getType())
3474 return Error(ID
.Loc
, "operands of constexpr must have same type");
3475 // Check that the type is valid for the operator.
3477 case Instruction::Add
:
3478 case Instruction::Sub
:
3479 case Instruction::Mul
:
3480 case Instruction::UDiv
:
3481 case Instruction::SDiv
:
3482 case Instruction::URem
:
3483 case Instruction::SRem
:
3484 case Instruction::Shl
:
3485 case Instruction::AShr
:
3486 case Instruction::LShr
:
3487 if (!Val0
->getType()->isIntOrIntVectorTy())
3488 return Error(ID
.Loc
, "constexpr requires integer operands");
3490 case Instruction::FAdd
:
3491 case Instruction::FSub
:
3492 case Instruction::FMul
:
3493 case Instruction::FDiv
:
3494 case Instruction::FRem
:
3495 if (!Val0
->getType()->isFPOrFPVectorTy())
3496 return Error(ID
.Loc
, "constexpr requires fp operands");
3498 default: llvm_unreachable("Unknown binary operator!");
3501 if (NUW
) Flags
|= OverflowingBinaryOperator::NoUnsignedWrap
;
3502 if (NSW
) Flags
|= OverflowingBinaryOperator::NoSignedWrap
;
3503 if (Exact
) Flags
|= PossiblyExactOperator::IsExact
;
3504 Constant
*C
= ConstantExpr::get(Opc
, Val0
, Val1
, Flags
);
3506 ID
.Kind
= ValID::t_Constant
;
3510 // Logical Operations
3513 case lltok::kw_xor
: {
3514 unsigned Opc
= Lex
.getUIntVal();
3515 Constant
*Val0
, *Val1
;
3517 if (ParseToken(lltok::lparen
, "expected '(' in logical constantexpr") ||
3518 ParseGlobalTypeAndValue(Val0
) ||
3519 ParseToken(lltok::comma
, "expected comma in logical constantexpr") ||
3520 ParseGlobalTypeAndValue(Val1
) ||
3521 ParseToken(lltok::rparen
, "expected ')' in logical constantexpr"))
3523 if (Val0
->getType() != Val1
->getType())
3524 return Error(ID
.Loc
, "operands of constexpr must have same type");
3525 if (!Val0
->getType()->isIntOrIntVectorTy())
3526 return Error(ID
.Loc
,
3527 "constexpr requires integer or integer vector operands");
3528 ID
.ConstantVal
= ConstantExpr::get(Opc
, Val0
, Val1
);
3529 ID
.Kind
= ValID::t_Constant
;
3533 case lltok::kw_getelementptr
:
3534 case lltok::kw_shufflevector
:
3535 case lltok::kw_insertelement
:
3536 case lltok::kw_extractelement
:
3537 case lltok::kw_select
: {
3538 unsigned Opc
= Lex
.getUIntVal();
3539 SmallVector
<Constant
*, 16> Elts
;
3540 bool InBounds
= false;
3544 if (Opc
== Instruction::GetElementPtr
)
3545 InBounds
= EatIfPresent(lltok::kw_inbounds
);
3547 if (ParseToken(lltok::lparen
, "expected '(' in constantexpr"))
3550 LocTy ExplicitTypeLoc
= Lex
.getLoc();
3551 if (Opc
== Instruction::GetElementPtr
) {
3552 if (ParseType(Ty
) ||
3553 ParseToken(lltok::comma
, "expected comma after getelementptr's type"))
3557 Optional
<unsigned> InRangeOp
;
3558 if (ParseGlobalValueVector(
3559 Elts
, Opc
== Instruction::GetElementPtr
? &InRangeOp
: nullptr) ||
3560 ParseToken(lltok::rparen
, "expected ')' in constantexpr"))
3563 if (Opc
== Instruction::GetElementPtr
) {
3564 if (Elts
.size() == 0 ||
3565 !Elts
[0]->getType()->isPtrOrPtrVectorTy())
3566 return Error(ID
.Loc
, "base of getelementptr must be a pointer");
3568 Type
*BaseType
= Elts
[0]->getType();
3569 auto *BasePointerType
= cast
<PointerType
>(BaseType
->getScalarType());
3570 if (Ty
!= BasePointerType
->getElementType())
3573 "explicit pointee type doesn't match operand's pointee type");
3576 BaseType
->isVectorTy() ? BaseType
->getVectorNumElements() : 0;
3578 ArrayRef
<Constant
*> Indices(Elts
.begin() + 1, Elts
.end());
3579 for (Constant
*Val
: Indices
) {
3580 Type
*ValTy
= Val
->getType();
3581 if (!ValTy
->isIntOrIntVectorTy())
3582 return Error(ID
.Loc
, "getelementptr index must be an integer");
3583 if (ValTy
->isVectorTy()) {
3584 unsigned ValNumEl
= ValTy
->getVectorNumElements();
3585 if (GEPWidth
&& (ValNumEl
!= GEPWidth
))
3588 "getelementptr vector index has a wrong number of elements");
3589 // GEPWidth may have been unknown because the base is a scalar,
3590 // but it is known now.
3591 GEPWidth
= ValNumEl
;
3595 SmallPtrSet
<Type
*, 4> Visited
;
3596 if (!Indices
.empty() && !Ty
->isSized(&Visited
))
3597 return Error(ID
.Loc
, "base element of getelementptr must be sized");
3599 if (!GetElementPtrInst::getIndexedType(Ty
, Indices
))
3600 return Error(ID
.Loc
, "invalid getelementptr indices");
3603 if (*InRangeOp
== 0)
3604 return Error(ID
.Loc
,
3605 "inrange keyword may not appear on pointer operand");
3609 ID
.ConstantVal
= ConstantExpr::getGetElementPtr(Ty
, Elts
[0], Indices
,
3610 InBounds
, InRangeOp
);
3611 } else if (Opc
== Instruction::Select
) {
3612 if (Elts
.size() != 3)
3613 return Error(ID
.Loc
, "expected three operands to select");
3614 if (const char *Reason
= SelectInst::areInvalidOperands(Elts
[0], Elts
[1],
3616 return Error(ID
.Loc
, Reason
);
3617 ID
.ConstantVal
= ConstantExpr::getSelect(Elts
[0], Elts
[1], Elts
[2]);
3618 } else if (Opc
== Instruction::ShuffleVector
) {
3619 if (Elts
.size() != 3)
3620 return Error(ID
.Loc
, "expected three operands to shufflevector");
3621 if (!ShuffleVectorInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
3622 return Error(ID
.Loc
, "invalid operands to shufflevector");
3624 ConstantExpr::getShuffleVector(Elts
[0], Elts
[1],Elts
[2]);
3625 } else if (Opc
== Instruction::ExtractElement
) {
3626 if (Elts
.size() != 2)
3627 return Error(ID
.Loc
, "expected two operands to extractelement");
3628 if (!ExtractElementInst::isValidOperands(Elts
[0], Elts
[1]))
3629 return Error(ID
.Loc
, "invalid extractelement operands");
3630 ID
.ConstantVal
= ConstantExpr::getExtractElement(Elts
[0], Elts
[1]);
3632 assert(Opc
== Instruction::InsertElement
&& "Unknown opcode");
3633 if (Elts
.size() != 3)
3634 return Error(ID
.Loc
, "expected three operands to insertelement");
3635 if (!InsertElementInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
3636 return Error(ID
.Loc
, "invalid insertelement operands");
3638 ConstantExpr::getInsertElement(Elts
[0], Elts
[1],Elts
[2]);
3641 ID
.Kind
= ValID::t_Constant
;
3650 /// ParseGlobalValue - Parse a global value with the specified type.
3651 bool LLParser::ParseGlobalValue(Type
*Ty
, Constant
*&C
) {
3655 bool Parsed
= ParseValID(ID
) ||
3656 ConvertValIDToValue(Ty
, ID
, V
, nullptr, /*IsCall=*/false);
3657 if (V
&& !(C
= dyn_cast
<Constant
>(V
)))
3658 return Error(ID
.Loc
, "global values must be constants");
3662 bool LLParser::ParseGlobalTypeAndValue(Constant
*&V
) {
3664 return ParseType(Ty
) ||
3665 ParseGlobalValue(Ty
, V
);
3668 bool LLParser::parseOptionalComdat(StringRef GlobalName
, Comdat
*&C
) {
3671 LocTy KwLoc
= Lex
.getLoc();
3672 if (!EatIfPresent(lltok::kw_comdat
))
3675 if (EatIfPresent(lltok::lparen
)) {
3676 if (Lex
.getKind() != lltok::ComdatVar
)
3677 return TokError("expected comdat variable");
3678 C
= getComdat(Lex
.getStrVal(), Lex
.getLoc());
3680 if (ParseToken(lltok::rparen
, "expected ')' after comdat var"))
3683 if (GlobalName
.empty())
3684 return TokError("comdat cannot be unnamed");
3685 C
= getComdat(GlobalName
, KwLoc
);
3691 /// ParseGlobalValueVector
3693 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3694 bool LLParser::ParseGlobalValueVector(SmallVectorImpl
<Constant
*> &Elts
,
3695 Optional
<unsigned> *InRangeOp
) {
3697 if (Lex
.getKind() == lltok::rbrace
||
3698 Lex
.getKind() == lltok::rsquare
||
3699 Lex
.getKind() == lltok::greater
||
3700 Lex
.getKind() == lltok::rparen
)
3704 if (InRangeOp
&& !*InRangeOp
&& EatIfPresent(lltok::kw_inrange
))
3705 *InRangeOp
= Elts
.size();
3708 if (ParseGlobalTypeAndValue(C
)) return true;
3710 } while (EatIfPresent(lltok::comma
));
3715 bool LLParser::ParseMDTuple(MDNode
*&MD
, bool IsDistinct
) {
3716 SmallVector
<Metadata
*, 16> Elts
;
3717 if (ParseMDNodeVector(Elts
))
3720 MD
= (IsDistinct
? MDTuple::getDistinct
: MDTuple::get
)(Context
, Elts
);
3727 /// ::= !DILocation(...)
3728 bool LLParser::ParseMDNode(MDNode
*&N
) {
3729 if (Lex
.getKind() == lltok::MetadataVar
)
3730 return ParseSpecializedMDNode(N
);
3732 return ParseToken(lltok::exclaim
, "expected '!' here") ||
3736 bool LLParser::ParseMDNodeTail(MDNode
*&N
) {
3738 if (Lex
.getKind() == lltok::lbrace
)
3739 return ParseMDTuple(N
);
3742 return ParseMDNodeID(N
);
3747 /// Structure to represent an optional metadata field.
3748 template <class FieldTy
> struct MDFieldImpl
{
3749 typedef MDFieldImpl ImplTy
;
3753 void assign(FieldTy Val
) {
3755 this->Val
= std::move(Val
);
3758 explicit MDFieldImpl(FieldTy Default
)
3759 : Val(std::move(Default
)), Seen(false) {}
3762 /// Structure to represent an optional metadata field that
3763 /// can be of either type (A or B) and encapsulates the
3764 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3765 /// to reimplement the specifics for representing each Field.
3766 template <class FieldTypeA
, class FieldTypeB
> struct MDEitherFieldImpl
{
3767 typedef MDEitherFieldImpl
<FieldTypeA
, FieldTypeB
> ImplTy
;
3778 void assign(FieldTypeA A
) {
3780 this->A
= std::move(A
);
3784 void assign(FieldTypeB B
) {
3786 this->B
= std::move(B
);
3790 explicit MDEitherFieldImpl(FieldTypeA DefaultA
, FieldTypeB DefaultB
)
3791 : A(std::move(DefaultA
)), B(std::move(DefaultB
)), Seen(false),
3792 WhatIs(IsInvalid
) {}
3795 struct MDUnsignedField
: public MDFieldImpl
<uint64_t> {
3798 MDUnsignedField(uint64_t Default
= 0, uint64_t Max
= UINT64_MAX
)
3799 : ImplTy(Default
), Max(Max
) {}
3802 struct LineField
: public MDUnsignedField
{
3803 LineField() : MDUnsignedField(0, UINT32_MAX
) {}
3806 struct ColumnField
: public MDUnsignedField
{
3807 ColumnField() : MDUnsignedField(0, UINT16_MAX
) {}
3810 struct DwarfTagField
: public MDUnsignedField
{
3811 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user
) {}
3812 DwarfTagField(dwarf::Tag DefaultTag
)
3813 : MDUnsignedField(DefaultTag
, dwarf::DW_TAG_hi_user
) {}
3816 struct DwarfMacinfoTypeField
: public MDUnsignedField
{
3817 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext
) {}
3818 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType
)
3819 : MDUnsignedField(DefaultType
, dwarf::DW_MACINFO_vendor_ext
) {}
3822 struct DwarfAttEncodingField
: public MDUnsignedField
{
3823 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user
) {}
3826 struct DwarfVirtualityField
: public MDUnsignedField
{
3827 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max
) {}
3830 struct DwarfLangField
: public MDUnsignedField
{
3831 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user
) {}
3834 struct DwarfCCField
: public MDUnsignedField
{
3835 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user
) {}
3838 struct EmissionKindField
: public MDUnsignedField
{
3839 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind
) {}
3842 struct NameTableKindField
: public MDUnsignedField
{
3843 NameTableKindField()
3846 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind
) {}
3849 struct DIFlagField
: public MDFieldImpl
<DINode::DIFlags
> {
3850 DIFlagField() : MDFieldImpl(DINode::FlagZero
) {}
3853 struct DISPFlagField
: public MDFieldImpl
<DISubprogram::DISPFlags
> {
3854 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero
) {}
3857 struct MDSignedField
: public MDFieldImpl
<int64_t> {
3861 MDSignedField(int64_t Default
= 0)
3862 : ImplTy(Default
), Min(INT64_MIN
), Max(INT64_MAX
) {}
3863 MDSignedField(int64_t Default
, int64_t Min
, int64_t Max
)
3864 : ImplTy(Default
), Min(Min
), Max(Max
) {}
3867 struct MDBoolField
: public MDFieldImpl
<bool> {
3868 MDBoolField(bool Default
= false) : ImplTy(Default
) {}
3871 struct MDField
: public MDFieldImpl
<Metadata
*> {
3874 MDField(bool AllowNull
= true) : ImplTy(nullptr), AllowNull(AllowNull
) {}
3877 struct MDConstant
: public MDFieldImpl
<ConstantAsMetadata
*> {
3878 MDConstant() : ImplTy(nullptr) {}
3881 struct MDStringField
: public MDFieldImpl
<MDString
*> {
3883 MDStringField(bool AllowEmpty
= true)
3884 : ImplTy(nullptr), AllowEmpty(AllowEmpty
) {}
3887 struct MDFieldList
: public MDFieldImpl
<SmallVector
<Metadata
*, 4>> {
3888 MDFieldList() : ImplTy(SmallVector
<Metadata
*, 4>()) {}
3891 struct ChecksumKindField
: public MDFieldImpl
<DIFile::ChecksumKind
> {
3892 ChecksumKindField(DIFile::ChecksumKind CSKind
) : ImplTy(CSKind
) {}
3895 struct MDSignedOrMDField
: MDEitherFieldImpl
<MDSignedField
, MDField
> {
3896 MDSignedOrMDField(int64_t Default
= 0, bool AllowNull
= true)
3897 : ImplTy(MDSignedField(Default
), MDField(AllowNull
)) {}
3899 MDSignedOrMDField(int64_t Default
, int64_t Min
, int64_t Max
,
3900 bool AllowNull
= true)
3901 : ImplTy(MDSignedField(Default
, Min
, Max
), MDField(AllowNull
)) {}
3903 bool isMDSignedField() const { return WhatIs
== IsTypeA
; }
3904 bool isMDField() const { return WhatIs
== IsTypeB
; }
3905 int64_t getMDSignedValue() const {
3906 assert(isMDSignedField() && "Wrong field type");
3909 Metadata
*getMDFieldValue() const {
3910 assert(isMDField() && "Wrong field type");
3915 struct MDSignedOrUnsignedField
3916 : MDEitherFieldImpl
<MDSignedField
, MDUnsignedField
> {
3917 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3919 bool isMDSignedField() const { return WhatIs
== IsTypeA
; }
3920 bool isMDUnsignedField() const { return WhatIs
== IsTypeB
; }
3921 int64_t getMDSignedValue() const {
3922 assert(isMDSignedField() && "Wrong field type");
3925 uint64_t getMDUnsignedValue() const {
3926 assert(isMDUnsignedField() && "Wrong field type");
3931 } // end anonymous namespace
3936 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
3937 MDUnsignedField
&Result
) {
3938 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
3939 return TokError("expected unsigned integer");
3941 auto &U
= Lex
.getAPSIntVal();
3942 if (U
.ugt(Result
.Max
))
3943 return TokError("value for '" + Name
+ "' too large, limit is " +
3945 Result
.assign(U
.getZExtValue());
3946 assert(Result
.Val
<= Result
.Max
&& "Expected value in range");
3952 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, LineField
&Result
) {
3953 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3956 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, ColumnField
&Result
) {
3957 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3961 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DwarfTagField
&Result
) {
3962 if (Lex
.getKind() == lltok::APSInt
)
3963 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3965 if (Lex
.getKind() != lltok::DwarfTag
)
3966 return TokError("expected DWARF tag");
3968 unsigned Tag
= dwarf::getTag(Lex
.getStrVal());
3969 if (Tag
== dwarf::DW_TAG_invalid
)
3970 return TokError("invalid DWARF tag" + Twine(" '") + Lex
.getStrVal() + "'");
3971 assert(Tag
<= Result
.Max
&& "Expected valid DWARF tag");
3979 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
3980 DwarfMacinfoTypeField
&Result
) {
3981 if (Lex
.getKind() == lltok::APSInt
)
3982 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3984 if (Lex
.getKind() != lltok::DwarfMacinfo
)
3985 return TokError("expected DWARF macinfo type");
3987 unsigned Macinfo
= dwarf::getMacinfo(Lex
.getStrVal());
3988 if (Macinfo
== dwarf::DW_MACINFO_invalid
)
3990 "invalid DWARF macinfo type" + Twine(" '") + Lex
.getStrVal() + "'");
3991 assert(Macinfo
<= Result
.Max
&& "Expected valid DWARF macinfo type");
3993 Result
.assign(Macinfo
);
3999 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4000 DwarfVirtualityField
&Result
) {
4001 if (Lex
.getKind() == lltok::APSInt
)
4002 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4004 if (Lex
.getKind() != lltok::DwarfVirtuality
)
4005 return TokError("expected DWARF virtuality code");
4007 unsigned Virtuality
= dwarf::getVirtuality(Lex
.getStrVal());
4008 if (Virtuality
== dwarf::DW_VIRTUALITY_invalid
)
4009 return TokError("invalid DWARF virtuality code" + Twine(" '") +
4010 Lex
.getStrVal() + "'");
4011 assert(Virtuality
<= Result
.Max
&& "Expected valid DWARF virtuality code");
4012 Result
.assign(Virtuality
);
4018 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DwarfLangField
&Result
) {
4019 if (Lex
.getKind() == lltok::APSInt
)
4020 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4022 if (Lex
.getKind() != lltok::DwarfLang
)
4023 return TokError("expected DWARF language");
4025 unsigned Lang
= dwarf::getLanguage(Lex
.getStrVal());
4027 return TokError("invalid DWARF language" + Twine(" '") + Lex
.getStrVal() +
4029 assert(Lang
<= Result
.Max
&& "Expected valid DWARF language");
4030 Result
.assign(Lang
);
4036 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DwarfCCField
&Result
) {
4037 if (Lex
.getKind() == lltok::APSInt
)
4038 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4040 if (Lex
.getKind() != lltok::DwarfCC
)
4041 return TokError("expected DWARF calling convention");
4043 unsigned CC
= dwarf::getCallingConvention(Lex
.getStrVal());
4045 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex
.getStrVal() +
4047 assert(CC
<= Result
.Max
&& "Expected valid DWARF calling convention");
4054 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, EmissionKindField
&Result
) {
4055 if (Lex
.getKind() == lltok::APSInt
)
4056 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4058 if (Lex
.getKind() != lltok::EmissionKind
)
4059 return TokError("expected emission kind");
4061 auto Kind
= DICompileUnit::getEmissionKind(Lex
.getStrVal());
4063 return TokError("invalid emission kind" + Twine(" '") + Lex
.getStrVal() +
4065 assert(*Kind
<= Result
.Max
&& "Expected valid emission kind");
4066 Result
.assign(*Kind
);
4072 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4073 NameTableKindField
&Result
) {
4074 if (Lex
.getKind() == lltok::APSInt
)
4075 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4077 if (Lex
.getKind() != lltok::NameTableKind
)
4078 return TokError("expected nameTable kind");
4080 auto Kind
= DICompileUnit::getNameTableKind(Lex
.getStrVal());
4082 return TokError("invalid nameTable kind" + Twine(" '") + Lex
.getStrVal() +
4084 assert(((unsigned)*Kind
) <= Result
.Max
&& "Expected valid nameTable kind");
4085 Result
.assign((unsigned)*Kind
);
4091 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4092 DwarfAttEncodingField
&Result
) {
4093 if (Lex
.getKind() == lltok::APSInt
)
4094 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4096 if (Lex
.getKind() != lltok::DwarfAttEncoding
)
4097 return TokError("expected DWARF type attribute encoding");
4099 unsigned Encoding
= dwarf::getAttributeEncoding(Lex
.getStrVal());
4101 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4102 Lex
.getStrVal() + "'");
4103 assert(Encoding
<= Result
.Max
&& "Expected valid DWARF language");
4104 Result
.assign(Encoding
);
4111 /// ::= DIFlagVector
4112 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4114 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DIFlagField
&Result
) {
4116 // Parser for a single flag.
4117 auto parseFlag
= [&](DINode::DIFlags
&Val
) {
4118 if (Lex
.getKind() == lltok::APSInt
&& !Lex
.getAPSIntVal().isSigned()) {
4119 uint32_t TempVal
= static_cast<uint32_t>(Val
);
4120 bool Res
= ParseUInt32(TempVal
);
4121 Val
= static_cast<DINode::DIFlags
>(TempVal
);
4125 if (Lex
.getKind() != lltok::DIFlag
)
4126 return TokError("expected debug info flag");
4128 Val
= DINode::getFlag(Lex
.getStrVal());
4130 return TokError(Twine("invalid debug info flag flag '") +
4131 Lex
.getStrVal() + "'");
4136 // Parse the flags and combine them together.
4137 DINode::DIFlags Combined
= DINode::FlagZero
;
4139 DINode::DIFlags Val
;
4143 } while (EatIfPresent(lltok::bar
));
4145 Result
.assign(Combined
);
4151 /// ::= DISPFlagVector
4152 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4154 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DISPFlagField
&Result
) {
4156 // Parser for a single flag.
4157 auto parseFlag
= [&](DISubprogram::DISPFlags
&Val
) {
4158 if (Lex
.getKind() == lltok::APSInt
&& !Lex
.getAPSIntVal().isSigned()) {
4159 uint32_t TempVal
= static_cast<uint32_t>(Val
);
4160 bool Res
= ParseUInt32(TempVal
);
4161 Val
= static_cast<DISubprogram::DISPFlags
>(TempVal
);
4165 if (Lex
.getKind() != lltok::DISPFlag
)
4166 return TokError("expected debug info flag");
4168 Val
= DISubprogram::getFlag(Lex
.getStrVal());
4170 return TokError(Twine("invalid subprogram debug info flag '") +
4171 Lex
.getStrVal() + "'");
4176 // Parse the flags and combine them together.
4177 DISubprogram::DISPFlags Combined
= DISubprogram::SPFlagZero
;
4179 DISubprogram::DISPFlags Val
;
4183 } while (EatIfPresent(lltok::bar
));
4185 Result
.assign(Combined
);
4190 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4191 MDSignedField
&Result
) {
4192 if (Lex
.getKind() != lltok::APSInt
)
4193 return TokError("expected signed integer");
4195 auto &S
= Lex
.getAPSIntVal();
4197 return TokError("value for '" + Name
+ "' too small, limit is " +
4200 return TokError("value for '" + Name
+ "' too large, limit is " +
4202 Result
.assign(S
.getExtValue());
4203 assert(Result
.Val
>= Result
.Min
&& "Expected value in range");
4204 assert(Result
.Val
<= Result
.Max
&& "Expected value in range");
4210 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, MDBoolField
&Result
) {
4211 switch (Lex
.getKind()) {
4213 return TokError("expected 'true' or 'false'");
4214 case lltok::kw_true
:
4215 Result
.assign(true);
4217 case lltok::kw_false
:
4218 Result
.assign(false);
4226 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, MDField
&Result
) {
4227 if (Lex
.getKind() == lltok::kw_null
) {
4228 if (!Result
.AllowNull
)
4229 return TokError("'" + Name
+ "' cannot be null");
4231 Result
.assign(nullptr);
4236 if (ParseMetadata(MD
, nullptr))
4244 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4245 MDSignedOrMDField
&Result
) {
4246 // Try to parse a signed int.
4247 if (Lex
.getKind() == lltok::APSInt
) {
4248 MDSignedField Res
= Result
.A
;
4249 if (!ParseMDField(Loc
, Name
, Res
)) {
4256 // Otherwise, try to parse as an MDField.
4257 MDField Res
= Result
.B
;
4258 if (!ParseMDField(Loc
, Name
, Res
)) {
4267 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4268 MDSignedOrUnsignedField
&Result
) {
4269 if (Lex
.getKind() != lltok::APSInt
)
4272 if (Lex
.getAPSIntVal().isSigned()) {
4273 MDSignedField Res
= Result
.A
;
4274 if (ParseMDField(Loc
, Name
, Res
))
4280 MDUnsignedField Res
= Result
.B
;
4281 if (ParseMDField(Loc
, Name
, Res
))
4288 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, MDStringField
&Result
) {
4289 LocTy ValueLoc
= Lex
.getLoc();
4291 if (ParseStringConstant(S
))
4294 if (!Result
.AllowEmpty
&& S
.empty())
4295 return Error(ValueLoc
, "'" + Name
+ "' cannot be empty");
4297 Result
.assign(S
.empty() ? nullptr : MDString::get(Context
, S
));
4302 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, MDFieldList
&Result
) {
4303 SmallVector
<Metadata
*, 4> MDs
;
4304 if (ParseMDNodeVector(MDs
))
4307 Result
.assign(std::move(MDs
));
4312 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4313 ChecksumKindField
&Result
) {
4314 Optional
<DIFile::ChecksumKind
> CSKind
=
4315 DIFile::getChecksumKind(Lex
.getStrVal());
4317 if (Lex
.getKind() != lltok::ChecksumKind
|| !CSKind
)
4319 "invalid checksum kind" + Twine(" '") + Lex
.getStrVal() + "'");
4321 Result
.assign(*CSKind
);
4326 } // end namespace llvm
4328 template <class ParserTy
>
4329 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField
) {
4331 if (Lex
.getKind() != lltok::LabelStr
)
4332 return TokError("expected field label here");
4336 } while (EatIfPresent(lltok::comma
));
4341 template <class ParserTy
>
4342 bool LLParser::ParseMDFieldsImpl(ParserTy parseField
, LocTy
&ClosingLoc
) {
4343 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4346 if (ParseToken(lltok::lparen
, "expected '(' here"))
4348 if (Lex
.getKind() != lltok::rparen
)
4349 if (ParseMDFieldsImplBody(parseField
))
4352 ClosingLoc
= Lex
.getLoc();
4353 return ParseToken(lltok::rparen
, "expected ')' here");
4356 template <class FieldTy
>
4357 bool LLParser::ParseMDField(StringRef Name
, FieldTy
&Result
) {
4359 return TokError("field '" + Name
+ "' cannot be specified more than once");
4361 LocTy Loc
= Lex
.getLoc();
4363 return ParseMDField(Loc
, Name
, Result
);
4366 bool LLParser::ParseSpecializedMDNode(MDNode
*&N
, bool IsDistinct
) {
4367 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4369 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4370 if (Lex.getStrVal() == #CLASS) \
4371 return Parse##CLASS(N, IsDistinct);
4372 #include "llvm/IR/Metadata.def"
4374 return TokError("expected metadata type");
4377 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4378 #define NOP_FIELD(NAME, TYPE, INIT)
4379 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4381 return Error(ClosingLoc, "missing required field '" #NAME "'");
4382 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4383 if (Lex.getStrVal() == #NAME) \
4384 return ParseMDField(#NAME, NAME);
4385 #define PARSE_MD_FIELDS() \
4386 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4389 if (ParseMDFieldsImpl([&]() -> bool { \
4390 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4391 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4394 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4396 #define GET_OR_DISTINCT(CLASS, ARGS) \
4397 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4399 /// ParseDILocationFields:
4400 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4401 /// isImplicitCode: true)
4402 bool LLParser::ParseDILocation(MDNode
*&Result
, bool IsDistinct
) {
4403 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4404 OPTIONAL(line, LineField, ); \
4405 OPTIONAL(column, ColumnField, ); \
4406 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4407 OPTIONAL(inlinedAt, MDField, ); \
4408 OPTIONAL(isImplicitCode, MDBoolField, (false));
4410 #undef VISIT_MD_FIELDS
4413 GET_OR_DISTINCT(DILocation
, (Context
, line
.Val
, column
.Val
, scope
.Val
,
4414 inlinedAt
.Val
, isImplicitCode
.Val
));
4418 /// ParseGenericDINode:
4419 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4420 bool LLParser::ParseGenericDINode(MDNode
*&Result
, bool IsDistinct
) {
4421 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4422 REQUIRED(tag, DwarfTagField, ); \
4423 OPTIONAL(header, MDStringField, ); \
4424 OPTIONAL(operands, MDFieldList, );
4426 #undef VISIT_MD_FIELDS
4428 Result
= GET_OR_DISTINCT(GenericDINode
,
4429 (Context
, tag
.Val
, header
.Val
, operands
.Val
));
4433 /// ParseDISubrange:
4434 /// ::= !DISubrange(count: 30, lowerBound: 2)
4435 /// ::= !DISubrange(count: !node, lowerBound: 2)
4436 bool LLParser::ParseDISubrange(MDNode
*&Result
, bool IsDistinct
) {
4437 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4438 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4439 OPTIONAL(lowerBound, MDSignedField, );
4441 #undef VISIT_MD_FIELDS
4443 if (count
.isMDSignedField())
4444 Result
= GET_OR_DISTINCT(
4445 DISubrange
, (Context
, count
.getMDSignedValue(), lowerBound
.Val
));
4446 else if (count
.isMDField())
4447 Result
= GET_OR_DISTINCT(
4448 DISubrange
, (Context
, count
.getMDFieldValue(), lowerBound
.Val
));
4455 /// ParseDIEnumerator:
4456 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4457 bool LLParser::ParseDIEnumerator(MDNode
*&Result
, bool IsDistinct
) {
4458 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4459 REQUIRED(name, MDStringField, ); \
4460 REQUIRED(value, MDSignedOrUnsignedField, ); \
4461 OPTIONAL(isUnsigned, MDBoolField, (false));
4463 #undef VISIT_MD_FIELDS
4465 if (isUnsigned
.Val
&& value
.isMDSignedField())
4466 return TokError("unsigned enumerator with negative value");
4468 int64_t Value
= value
.isMDSignedField()
4469 ? value
.getMDSignedValue()
4470 : static_cast<int64_t>(value
.getMDUnsignedValue());
4472 GET_OR_DISTINCT(DIEnumerator
, (Context
, Value
, isUnsigned
.Val
, name
.Val
));
4477 /// ParseDIBasicType:
4478 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4479 /// encoding: DW_ATE_encoding, flags: 0)
4480 bool LLParser::ParseDIBasicType(MDNode
*&Result
, bool IsDistinct
) {
4481 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4482 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4483 OPTIONAL(name, MDStringField, ); \
4484 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4485 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4486 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4487 OPTIONAL(flags, DIFlagField, );
4489 #undef VISIT_MD_FIELDS
4491 Result
= GET_OR_DISTINCT(DIBasicType
, (Context
, tag
.Val
, name
.Val
, size
.Val
,
4492 align
.Val
, encoding
.Val
, flags
.Val
));
4496 /// ParseDIDerivedType:
4497 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4498 /// line: 7, scope: !1, baseType: !2, size: 32,
4499 /// align: 32, offset: 0, flags: 0, extraData: !3,
4500 /// dwarfAddressSpace: 3)
4501 bool LLParser::ParseDIDerivedType(MDNode
*&Result
, bool IsDistinct
) {
4502 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4503 REQUIRED(tag, DwarfTagField, ); \
4504 OPTIONAL(name, MDStringField, ); \
4505 OPTIONAL(file, MDField, ); \
4506 OPTIONAL(line, LineField, ); \
4507 OPTIONAL(scope, MDField, ); \
4508 REQUIRED(baseType, MDField, ); \
4509 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4510 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4511 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4512 OPTIONAL(flags, DIFlagField, ); \
4513 OPTIONAL(extraData, MDField, ); \
4514 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4516 #undef VISIT_MD_FIELDS
4518 Optional
<unsigned> DWARFAddressSpace
;
4519 if (dwarfAddressSpace
.Val
!= UINT32_MAX
)
4520 DWARFAddressSpace
= dwarfAddressSpace
.Val
;
4522 Result
= GET_OR_DISTINCT(DIDerivedType
,
4523 (Context
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
,
4524 scope
.Val
, baseType
.Val
, size
.Val
, align
.Val
,
4525 offset
.Val
, DWARFAddressSpace
, flags
.Val
,
4530 bool LLParser::ParseDICompositeType(MDNode
*&Result
, bool IsDistinct
) {
4531 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4532 REQUIRED(tag, DwarfTagField, ); \
4533 OPTIONAL(name, MDStringField, ); \
4534 OPTIONAL(file, MDField, ); \
4535 OPTIONAL(line, LineField, ); \
4536 OPTIONAL(scope, MDField, ); \
4537 OPTIONAL(baseType, MDField, ); \
4538 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4539 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4540 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4541 OPTIONAL(flags, DIFlagField, ); \
4542 OPTIONAL(elements, MDField, ); \
4543 OPTIONAL(runtimeLang, DwarfLangField, ); \
4544 OPTIONAL(vtableHolder, MDField, ); \
4545 OPTIONAL(templateParams, MDField, ); \
4546 OPTIONAL(identifier, MDStringField, ); \
4547 OPTIONAL(discriminator, MDField, );
4549 #undef VISIT_MD_FIELDS
4551 // If this has an identifier try to build an ODR type.
4553 if (auto *CT
= DICompositeType::buildODRType(
4554 Context
, *identifier
.Val
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
,
4555 scope
.Val
, baseType
.Val
, size
.Val
, align
.Val
, offset
.Val
, flags
.Val
,
4556 elements
.Val
, runtimeLang
.Val
, vtableHolder
.Val
,
4557 templateParams
.Val
, discriminator
.Val
)) {
4562 // Create a new node, and save it in the context if it belongs in the type
4564 Result
= GET_OR_DISTINCT(
4566 (Context
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
, scope
.Val
, baseType
.Val
,
4567 size
.Val
, align
.Val
, offset
.Val
, flags
.Val
, elements
.Val
,
4568 runtimeLang
.Val
, vtableHolder
.Val
, templateParams
.Val
, identifier
.Val
,
4569 discriminator
.Val
));
4573 bool LLParser::ParseDISubroutineType(MDNode
*&Result
, bool IsDistinct
) {
4574 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4575 OPTIONAL(flags, DIFlagField, ); \
4576 OPTIONAL(cc, DwarfCCField, ); \
4577 REQUIRED(types, MDField, );
4579 #undef VISIT_MD_FIELDS
4581 Result
= GET_OR_DISTINCT(DISubroutineType
,
4582 (Context
, flags
.Val
, cc
.Val
, types
.Val
));
4586 /// ParseDIFileType:
4587 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4588 /// checksumkind: CSK_MD5,
4589 /// checksum: "000102030405060708090a0b0c0d0e0f",
4590 /// source: "source file contents")
4591 bool LLParser::ParseDIFile(MDNode
*&Result
, bool IsDistinct
) {
4592 // The default constructed value for checksumkind is required, but will never
4593 // be used, as the parser checks if the field was actually Seen before using
4595 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4596 REQUIRED(filename, MDStringField, ); \
4597 REQUIRED(directory, MDStringField, ); \
4598 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4599 OPTIONAL(checksum, MDStringField, ); \
4600 OPTIONAL(source, MDStringField, );
4602 #undef VISIT_MD_FIELDS
4604 Optional
<DIFile::ChecksumInfo
<MDString
*>> OptChecksum
;
4605 if (checksumkind
.Seen
&& checksum
.Seen
)
4606 OptChecksum
.emplace(checksumkind
.Val
, checksum
.Val
);
4607 else if (checksumkind
.Seen
|| checksum
.Seen
)
4608 return Lex
.Error("'checksumkind' and 'checksum' must be provided together");
4610 Optional
<MDString
*> OptSource
;
4612 OptSource
= source
.Val
;
4613 Result
= GET_OR_DISTINCT(DIFile
, (Context
, filename
.Val
, directory
.Val
,
4614 OptChecksum
, OptSource
));
4618 /// ParseDICompileUnit:
4619 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4620 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4621 /// splitDebugFilename: "abc.debug",
4622 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4623 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4624 bool LLParser::ParseDICompileUnit(MDNode
*&Result
, bool IsDistinct
) {
4626 return Lex
.Error("missing 'distinct', required for !DICompileUnit");
4628 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4629 REQUIRED(language, DwarfLangField, ); \
4630 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4631 OPTIONAL(producer, MDStringField, ); \
4632 OPTIONAL(isOptimized, MDBoolField, ); \
4633 OPTIONAL(flags, MDStringField, ); \
4634 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4635 OPTIONAL(splitDebugFilename, MDStringField, ); \
4636 OPTIONAL(emissionKind, EmissionKindField, ); \
4637 OPTIONAL(enums, MDField, ); \
4638 OPTIONAL(retainedTypes, MDField, ); \
4639 OPTIONAL(globals, MDField, ); \
4640 OPTIONAL(imports, MDField, ); \
4641 OPTIONAL(macros, MDField, ); \
4642 OPTIONAL(dwoId, MDUnsignedField, ); \
4643 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4644 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4645 OPTIONAL(nameTableKind, NameTableKindField, ); \
4646 OPTIONAL(debugBaseAddress, MDBoolField, = false);
4648 #undef VISIT_MD_FIELDS
4650 Result
= DICompileUnit::getDistinct(
4651 Context
, language
.Val
, file
.Val
, producer
.Val
, isOptimized
.Val
, flags
.Val
,
4652 runtimeVersion
.Val
, splitDebugFilename
.Val
, emissionKind
.Val
, enums
.Val
,
4653 retainedTypes
.Val
, globals
.Val
, imports
.Val
, macros
.Val
, dwoId
.Val
,
4654 splitDebugInlining
.Val
, debugInfoForProfiling
.Val
, nameTableKind
.Val
,
4655 debugBaseAddress
.Val
);
4659 /// ParseDISubprogram:
4660 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4661 /// file: !1, line: 7, type: !2, isLocal: false,
4662 /// isDefinition: true, scopeLine: 8, containingType: !3,
4663 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4664 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4665 /// spFlags: 10, isOptimized: false, templateParams: !4,
4666 /// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4667 bool LLParser::ParseDISubprogram(MDNode
*&Result
, bool IsDistinct
) {
4668 auto Loc
= Lex
.getLoc();
4669 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4670 OPTIONAL(scope, MDField, ); \
4671 OPTIONAL(name, MDStringField, ); \
4672 OPTIONAL(linkageName, MDStringField, ); \
4673 OPTIONAL(file, MDField, ); \
4674 OPTIONAL(line, LineField, ); \
4675 OPTIONAL(type, MDField, ); \
4676 OPTIONAL(isLocal, MDBoolField, ); \
4677 OPTIONAL(isDefinition, MDBoolField, (true)); \
4678 OPTIONAL(scopeLine, LineField, ); \
4679 OPTIONAL(containingType, MDField, ); \
4680 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4681 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4682 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4683 OPTIONAL(flags, DIFlagField, ); \
4684 OPTIONAL(spFlags, DISPFlagField, ); \
4685 OPTIONAL(isOptimized, MDBoolField, ); \
4686 OPTIONAL(unit, MDField, ); \
4687 OPTIONAL(templateParams, MDField, ); \
4688 OPTIONAL(declaration, MDField, ); \
4689 OPTIONAL(retainedNodes, MDField, ); \
4690 OPTIONAL(thrownTypes, MDField, );
4692 #undef VISIT_MD_FIELDS
4694 // An explicit spFlags field takes precedence over individual fields in
4695 // older IR versions.
4696 DISubprogram::DISPFlags SPFlags
=
4697 spFlags
.Seen
? spFlags
.Val
4698 : DISubprogram::toSPFlags(isLocal
.Val
, isDefinition
.Val
,
4699 isOptimized
.Val
, virtuality
.Val
);
4700 if ((SPFlags
& DISubprogram::SPFlagDefinition
) && !IsDistinct
)
4703 "missing 'distinct', required for !DISubprogram that is a Definition");
4704 Result
= GET_OR_DISTINCT(
4706 (Context
, scope
.Val
, name
.Val
, linkageName
.Val
, file
.Val
, line
.Val
,
4707 type
.Val
, scopeLine
.Val
, containingType
.Val
, virtualIndex
.Val
,
4708 thisAdjustment
.Val
, flags
.Val
, SPFlags
, unit
.Val
, templateParams
.Val
,
4709 declaration
.Val
, retainedNodes
.Val
, thrownTypes
.Val
));
4713 /// ParseDILexicalBlock:
4714 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4715 bool LLParser::ParseDILexicalBlock(MDNode
*&Result
, bool IsDistinct
) {
4716 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4717 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4718 OPTIONAL(file, MDField, ); \
4719 OPTIONAL(line, LineField, ); \
4720 OPTIONAL(column, ColumnField, );
4722 #undef VISIT_MD_FIELDS
4724 Result
= GET_OR_DISTINCT(
4725 DILexicalBlock
, (Context
, scope
.Val
, file
.Val
, line
.Val
, column
.Val
));
4729 /// ParseDILexicalBlockFile:
4730 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4731 bool LLParser::ParseDILexicalBlockFile(MDNode
*&Result
, bool IsDistinct
) {
4732 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4733 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4734 OPTIONAL(file, MDField, ); \
4735 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4737 #undef VISIT_MD_FIELDS
4739 Result
= GET_OR_DISTINCT(DILexicalBlockFile
,
4740 (Context
, scope
.Val
, file
.Val
, discriminator
.Val
));
4744 /// ParseDICommonBlock:
4745 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4746 bool LLParser::ParseDICommonBlock(MDNode
*&Result
, bool IsDistinct
) {
4747 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4748 REQUIRED(scope, MDField, ); \
4749 OPTIONAL(declaration, MDField, ); \
4750 OPTIONAL(name, MDStringField, ); \
4751 OPTIONAL(file, MDField, ); \
4752 OPTIONAL(line, LineField, );
4754 #undef VISIT_MD_FIELDS
4756 Result
= GET_OR_DISTINCT(DICommonBlock
,
4757 (Context
, scope
.Val
, declaration
.Val
, name
.Val
,
4758 file
.Val
, line
.Val
));
4762 /// ParseDINamespace:
4763 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4764 bool LLParser::ParseDINamespace(MDNode
*&Result
, bool IsDistinct
) {
4765 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4766 REQUIRED(scope, MDField, ); \
4767 OPTIONAL(name, MDStringField, ); \
4768 OPTIONAL(exportSymbols, MDBoolField, );
4770 #undef VISIT_MD_FIELDS
4772 Result
= GET_OR_DISTINCT(DINamespace
,
4773 (Context
, scope
.Val
, name
.Val
, exportSymbols
.Val
));
4778 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4779 bool LLParser::ParseDIMacro(MDNode
*&Result
, bool IsDistinct
) {
4780 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4781 REQUIRED(type, DwarfMacinfoTypeField, ); \
4782 OPTIONAL(line, LineField, ); \
4783 REQUIRED(name, MDStringField, ); \
4784 OPTIONAL(value, MDStringField, );
4786 #undef VISIT_MD_FIELDS
4788 Result
= GET_OR_DISTINCT(DIMacro
,
4789 (Context
, type
.Val
, line
.Val
, name
.Val
, value
.Val
));
4793 /// ParseDIMacroFile:
4794 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4795 bool LLParser::ParseDIMacroFile(MDNode
*&Result
, bool IsDistinct
) {
4796 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4797 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4798 OPTIONAL(line, LineField, ); \
4799 REQUIRED(file, MDField, ); \
4800 OPTIONAL(nodes, MDField, );
4802 #undef VISIT_MD_FIELDS
4804 Result
= GET_OR_DISTINCT(DIMacroFile
,
4805 (Context
, type
.Val
, line
.Val
, file
.Val
, nodes
.Val
));
4810 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4811 /// includePath: "/usr/include", isysroot: "/")
4812 bool LLParser::ParseDIModule(MDNode
*&Result
, bool IsDistinct
) {
4813 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4814 REQUIRED(scope, MDField, ); \
4815 REQUIRED(name, MDStringField, ); \
4816 OPTIONAL(configMacros, MDStringField, ); \
4817 OPTIONAL(includePath, MDStringField, ); \
4818 OPTIONAL(isysroot, MDStringField, );
4820 #undef VISIT_MD_FIELDS
4822 Result
= GET_OR_DISTINCT(DIModule
, (Context
, scope
.Val
, name
.Val
,
4823 configMacros
.Val
, includePath
.Val
, isysroot
.Val
));
4827 /// ParseDITemplateTypeParameter:
4828 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4829 bool LLParser::ParseDITemplateTypeParameter(MDNode
*&Result
, bool IsDistinct
) {
4830 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4831 OPTIONAL(name, MDStringField, ); \
4832 REQUIRED(type, MDField, );
4834 #undef VISIT_MD_FIELDS
4837 GET_OR_DISTINCT(DITemplateTypeParameter
, (Context
, name
.Val
, type
.Val
));
4841 /// ParseDITemplateValueParameter:
4842 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4843 /// name: "V", type: !1, value: i32 7)
4844 bool LLParser::ParseDITemplateValueParameter(MDNode
*&Result
, bool IsDistinct
) {
4845 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4846 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4847 OPTIONAL(name, MDStringField, ); \
4848 OPTIONAL(type, MDField, ); \
4849 REQUIRED(value, MDField, );
4851 #undef VISIT_MD_FIELDS
4853 Result
= GET_OR_DISTINCT(DITemplateValueParameter
,
4854 (Context
, tag
.Val
, name
.Val
, type
.Val
, value
.Val
));
4858 /// ParseDIGlobalVariable:
4859 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4860 /// file: !1, line: 7, type: !2, isLocal: false,
4861 /// isDefinition: true, templateParams: !3,
4862 /// declaration: !4, align: 8)
4863 bool LLParser::ParseDIGlobalVariable(MDNode
*&Result
, bool IsDistinct
) {
4864 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4865 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4866 OPTIONAL(scope, MDField, ); \
4867 OPTIONAL(linkageName, MDStringField, ); \
4868 OPTIONAL(file, MDField, ); \
4869 OPTIONAL(line, LineField, ); \
4870 OPTIONAL(type, MDField, ); \
4871 OPTIONAL(isLocal, MDBoolField, ); \
4872 OPTIONAL(isDefinition, MDBoolField, (true)); \
4873 OPTIONAL(templateParams, MDField, ); \
4874 OPTIONAL(declaration, MDField, ); \
4875 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4877 #undef VISIT_MD_FIELDS
4880 GET_OR_DISTINCT(DIGlobalVariable
,
4881 (Context
, scope
.Val
, name
.Val
, linkageName
.Val
, file
.Val
,
4882 line
.Val
, type
.Val
, isLocal
.Val
, isDefinition
.Val
,
4883 declaration
.Val
, templateParams
.Val
, align
.Val
));
4887 /// ParseDILocalVariable:
4888 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4889 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4891 /// ::= !DILocalVariable(scope: !0, name: "foo",
4892 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4894 bool LLParser::ParseDILocalVariable(MDNode
*&Result
, bool IsDistinct
) {
4895 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4896 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4897 OPTIONAL(name, MDStringField, ); \
4898 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4899 OPTIONAL(file, MDField, ); \
4900 OPTIONAL(line, LineField, ); \
4901 OPTIONAL(type, MDField, ); \
4902 OPTIONAL(flags, DIFlagField, ); \
4903 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4905 #undef VISIT_MD_FIELDS
4907 Result
= GET_OR_DISTINCT(DILocalVariable
,
4908 (Context
, scope
.Val
, name
.Val
, file
.Val
, line
.Val
,
4909 type
.Val
, arg
.Val
, flags
.Val
, align
.Val
));
4914 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4915 bool LLParser::ParseDILabel(MDNode
*&Result
, bool IsDistinct
) {
4916 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4917 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4918 REQUIRED(name, MDStringField, ); \
4919 REQUIRED(file, MDField, ); \
4920 REQUIRED(line, LineField, );
4922 #undef VISIT_MD_FIELDS
4924 Result
= GET_OR_DISTINCT(DILabel
,
4925 (Context
, scope
.Val
, name
.Val
, file
.Val
, line
.Val
));
4929 /// ParseDIExpression:
4930 /// ::= !DIExpression(0, 7, -1)
4931 bool LLParser::ParseDIExpression(MDNode
*&Result
, bool IsDistinct
) {
4932 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4935 if (ParseToken(lltok::lparen
, "expected '(' here"))
4938 SmallVector
<uint64_t, 8> Elements
;
4939 if (Lex
.getKind() != lltok::rparen
)
4941 if (Lex
.getKind() == lltok::DwarfOp
) {
4942 if (unsigned Op
= dwarf::getOperationEncoding(Lex
.getStrVal())) {
4944 Elements
.push_back(Op
);
4947 return TokError(Twine("invalid DWARF op '") + Lex
.getStrVal() + "'");
4950 if (Lex
.getKind() == lltok::DwarfAttEncoding
) {
4951 if (unsigned Op
= dwarf::getAttributeEncoding(Lex
.getStrVal())) {
4953 Elements
.push_back(Op
);
4956 return TokError(Twine("invalid DWARF attribute encoding '") + Lex
.getStrVal() + "'");
4959 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
4960 return TokError("expected unsigned integer");
4962 auto &U
= Lex
.getAPSIntVal();
4963 if (U
.ugt(UINT64_MAX
))
4964 return TokError("element too large, limit is " + Twine(UINT64_MAX
));
4965 Elements
.push_back(U
.getZExtValue());
4967 } while (EatIfPresent(lltok::comma
));
4969 if (ParseToken(lltok::rparen
, "expected ')' here"))
4972 Result
= GET_OR_DISTINCT(DIExpression
, (Context
, Elements
));
4976 /// ParseDIGlobalVariableExpression:
4977 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4978 bool LLParser::ParseDIGlobalVariableExpression(MDNode
*&Result
,
4980 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4981 REQUIRED(var, MDField, ); \
4982 REQUIRED(expr, MDField, );
4984 #undef VISIT_MD_FIELDS
4987 GET_OR_DISTINCT(DIGlobalVariableExpression
, (Context
, var
.Val
, expr
.Val
));
4991 /// ParseDIObjCProperty:
4992 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4993 /// getter: "getFoo", attributes: 7, type: !2)
4994 bool LLParser::ParseDIObjCProperty(MDNode
*&Result
, bool IsDistinct
) {
4995 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4996 OPTIONAL(name, MDStringField, ); \
4997 OPTIONAL(file, MDField, ); \
4998 OPTIONAL(line, LineField, ); \
4999 OPTIONAL(setter, MDStringField, ); \
5000 OPTIONAL(getter, MDStringField, ); \
5001 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5002 OPTIONAL(type, MDField, );
5004 #undef VISIT_MD_FIELDS
5006 Result
= GET_OR_DISTINCT(DIObjCProperty
,
5007 (Context
, name
.Val
, file
.Val
, line
.Val
, setter
.Val
,
5008 getter
.Val
, attributes
.Val
, type
.Val
));
5012 /// ParseDIImportedEntity:
5013 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5014 /// line: 7, name: "foo")
5015 bool LLParser::ParseDIImportedEntity(MDNode
*&Result
, bool IsDistinct
) {
5016 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5017 REQUIRED(tag, DwarfTagField, ); \
5018 REQUIRED(scope, MDField, ); \
5019 OPTIONAL(entity, MDField, ); \
5020 OPTIONAL(file, MDField, ); \
5021 OPTIONAL(line, LineField, ); \
5022 OPTIONAL(name, MDStringField, );
5024 #undef VISIT_MD_FIELDS
5026 Result
= GET_OR_DISTINCT(
5028 (Context
, tag
.Val
, scope
.Val
, entity
.Val
, file
.Val
, line
.Val
, name
.Val
));
5032 #undef PARSE_MD_FIELD
5034 #undef REQUIRE_FIELD
5035 #undef DECLARE_FIELD
5037 /// ParseMetadataAsValue
5038 /// ::= metadata i32 %local
5039 /// ::= metadata i32 @global
5040 /// ::= metadata i32 7
5042 /// ::= metadata !{...}
5043 /// ::= metadata !"string"
5044 bool LLParser::ParseMetadataAsValue(Value
*&V
, PerFunctionState
&PFS
) {
5045 // Note: the type 'metadata' has already been parsed.
5047 if (ParseMetadata(MD
, &PFS
))
5050 V
= MetadataAsValue::get(Context
, MD
);
5054 /// ParseValueAsMetadata
5058 bool LLParser::ParseValueAsMetadata(Metadata
*&MD
, const Twine
&TypeMsg
,
5059 PerFunctionState
*PFS
) {
5062 if (ParseType(Ty
, TypeMsg
, Loc
))
5064 if (Ty
->isMetadataTy())
5065 return Error(Loc
, "invalid metadata-value-metadata roundtrip");
5068 if (ParseValue(Ty
, V
, PFS
))
5071 MD
= ValueAsMetadata::get(V
);
5082 /// ::= !DILocation(...)
5083 bool LLParser::ParseMetadata(Metadata
*&MD
, PerFunctionState
*PFS
) {
5084 if (Lex
.getKind() == lltok::MetadataVar
) {
5086 if (ParseSpecializedMDNode(N
))
5094 if (Lex
.getKind() != lltok::exclaim
)
5095 return ParseValueAsMetadata(MD
, "expected metadata operand", PFS
);
5098 assert(Lex
.getKind() == lltok::exclaim
&& "Expected '!' here");
5102 // ::= '!' STRINGCONSTANT
5103 if (Lex
.getKind() == lltok::StringConstant
) {
5105 if (ParseMDString(S
))
5115 if (ParseMDNodeTail(N
))
5121 //===----------------------------------------------------------------------===//
5122 // Function Parsing.
5123 //===----------------------------------------------------------------------===//
5125 bool LLParser::ConvertValIDToValue(Type
*Ty
, ValID
&ID
, Value
*&V
,
5126 PerFunctionState
*PFS
, bool IsCall
) {
5127 if (Ty
->isFunctionTy())
5128 return Error(ID
.Loc
, "functions are not values, refer to them as pointers");
5131 case ValID::t_LocalID
:
5132 if (!PFS
) return Error(ID
.Loc
, "invalid use of function-local name");
5133 V
= PFS
->GetVal(ID
.UIntVal
, Ty
, ID
.Loc
, IsCall
);
5134 return V
== nullptr;
5135 case ValID::t_LocalName
:
5136 if (!PFS
) return Error(ID
.Loc
, "invalid use of function-local name");
5137 V
= PFS
->GetVal(ID
.StrVal
, Ty
, ID
.Loc
, IsCall
);
5138 return V
== nullptr;
5139 case ValID::t_InlineAsm
: {
5140 if (!ID
.FTy
|| !InlineAsm::Verify(ID
.FTy
, ID
.StrVal2
))
5141 return Error(ID
.Loc
, "invalid type for inline asm constraint string");
5142 V
= InlineAsm::get(ID
.FTy
, ID
.StrVal
, ID
.StrVal2
, ID
.UIntVal
& 1,
5143 (ID
.UIntVal
>> 1) & 1,
5144 (InlineAsm::AsmDialect(ID
.UIntVal
>> 2)));
5147 case ValID::t_GlobalName
:
5148 V
= GetGlobalVal(ID
.StrVal
, Ty
, ID
.Loc
, IsCall
);
5149 return V
== nullptr;
5150 case ValID::t_GlobalID
:
5151 V
= GetGlobalVal(ID
.UIntVal
, Ty
, ID
.Loc
, IsCall
);
5152 return V
== nullptr;
5153 case ValID::t_APSInt
:
5154 if (!Ty
->isIntegerTy())
5155 return Error(ID
.Loc
, "integer constant must have integer type");
5156 ID
.APSIntVal
= ID
.APSIntVal
.extOrTrunc(Ty
->getPrimitiveSizeInBits());
5157 V
= ConstantInt::get(Context
, ID
.APSIntVal
);
5159 case ValID::t_APFloat
:
5160 if (!Ty
->isFloatingPointTy() ||
5161 !ConstantFP::isValueValidForType(Ty
, ID
.APFloatVal
))
5162 return Error(ID
.Loc
, "floating point constant invalid for type");
5164 // The lexer has no type info, so builds all half, float, and double FP
5165 // constants as double. Fix this here. Long double does not need this.
5166 if (&ID
.APFloatVal
.getSemantics() == &APFloat::IEEEdouble()) {
5169 ID
.APFloatVal
.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven
,
5171 else if (Ty
->isFloatTy())
5172 ID
.APFloatVal
.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven
,
5175 V
= ConstantFP::get(Context
, ID
.APFloatVal
);
5177 if (V
->getType() != Ty
)
5178 return Error(ID
.Loc
, "floating point constant does not have type '" +
5179 getTypeString(Ty
) + "'");
5183 if (!Ty
->isPointerTy())
5184 return Error(ID
.Loc
, "null must be a pointer type");
5185 V
= ConstantPointerNull::get(cast
<PointerType
>(Ty
));
5187 case ValID::t_Undef
:
5188 // FIXME: LabelTy should not be a first-class type.
5189 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5190 return Error(ID
.Loc
, "invalid type for undef constant");
5191 V
= UndefValue::get(Ty
);
5193 case ValID::t_EmptyArray
:
5194 if (!Ty
->isArrayTy() || cast
<ArrayType
>(Ty
)->getNumElements() != 0)
5195 return Error(ID
.Loc
, "invalid empty array initializer");
5196 V
= UndefValue::get(Ty
);
5199 // FIXME: LabelTy should not be a first-class type.
5200 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5201 return Error(ID
.Loc
, "invalid type for null constant");
5202 V
= Constant::getNullValue(Ty
);
5205 if (!Ty
->isTokenTy())
5206 return Error(ID
.Loc
, "invalid type for none constant");
5207 V
= Constant::getNullValue(Ty
);
5209 case ValID::t_Constant
:
5210 if (ID
.ConstantVal
->getType() != Ty
)
5211 return Error(ID
.Loc
, "constant expression type mismatch");
5215 case ValID::t_ConstantStruct
:
5216 case ValID::t_PackedConstantStruct
:
5217 if (StructType
*ST
= dyn_cast
<StructType
>(Ty
)) {
5218 if (ST
->getNumElements() != ID
.UIntVal
)
5219 return Error(ID
.Loc
,
5220 "initializer with struct type has wrong # elements");
5221 if (ST
->isPacked() != (ID
.Kind
== ValID::t_PackedConstantStruct
))
5222 return Error(ID
.Loc
, "packed'ness of initializer and type don't match");
5224 // Verify that the elements are compatible with the structtype.
5225 for (unsigned i
= 0, e
= ID
.UIntVal
; i
!= e
; ++i
)
5226 if (ID
.ConstantStructElts
[i
]->getType() != ST
->getElementType(i
))
5227 return Error(ID
.Loc
, "element " + Twine(i
) +
5228 " of struct initializer doesn't match struct element type");
5230 V
= ConstantStruct::get(
5231 ST
, makeArrayRef(ID
.ConstantStructElts
.get(), ID
.UIntVal
));
5233 return Error(ID
.Loc
, "constant expression type mismatch");
5236 llvm_unreachable("Invalid ValID");
5239 bool LLParser::parseConstantValue(Type
*Ty
, Constant
*&C
) {
5242 auto Loc
= Lex
.getLoc();
5243 if (ParseValID(ID
, /*PFS=*/nullptr))
5246 case ValID::t_APSInt
:
5247 case ValID::t_APFloat
:
5248 case ValID::t_Undef
:
5249 case ValID::t_Constant
:
5250 case ValID::t_ConstantStruct
:
5251 case ValID::t_PackedConstantStruct
: {
5253 if (ConvertValIDToValue(Ty
, ID
, V
, /*PFS=*/nullptr, /*IsCall=*/false))
5255 assert(isa
<Constant
>(V
) && "Expected a constant value");
5256 C
= cast
<Constant
>(V
);
5260 C
= Constant::getNullValue(Ty
);
5263 return Error(Loc
, "expected a constant value");
5267 bool LLParser::ParseValue(Type
*Ty
, Value
*&V
, PerFunctionState
*PFS
) {
5270 return ParseValID(ID
, PFS
) ||
5271 ConvertValIDToValue(Ty
, ID
, V
, PFS
, /*IsCall=*/false);
5274 bool LLParser::ParseTypeAndValue(Value
*&V
, PerFunctionState
*PFS
) {
5276 return ParseType(Ty
) ||
5277 ParseValue(Ty
, V
, PFS
);
5280 bool LLParser::ParseTypeAndBasicBlock(BasicBlock
*&BB
, LocTy
&Loc
,
5281 PerFunctionState
&PFS
) {
5284 if (ParseTypeAndValue(V
, PFS
)) return true;
5285 if (!isa
<BasicBlock
>(V
))
5286 return Error(Loc
, "expected a basic block");
5287 BB
= cast
<BasicBlock
>(V
);
5292 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5293 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5294 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5295 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5296 bool LLParser::ParseFunctionHeader(Function
*&Fn
, bool isDefine
) {
5297 // Parse the linkage.
5298 LocTy LinkageLoc
= Lex
.getLoc();
5300 unsigned Visibility
;
5301 unsigned DLLStorageClass
;
5303 AttrBuilder RetAttrs
;
5306 Type
*RetType
= nullptr;
5307 LocTy RetTypeLoc
= Lex
.getLoc();
5308 if (ParseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
5310 ParseOptionalCallingConv(CC
) || ParseOptionalReturnAttrs(RetAttrs
) ||
5311 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/))
5314 // Verify that the linkage is ok.
5315 switch ((GlobalValue::LinkageTypes
)Linkage
) {
5316 case GlobalValue::ExternalLinkage
:
5317 break; // always ok.
5318 case GlobalValue::ExternalWeakLinkage
:
5320 return Error(LinkageLoc
, "invalid linkage for function definition");
5322 case GlobalValue::PrivateLinkage
:
5323 case GlobalValue::InternalLinkage
:
5324 case GlobalValue::AvailableExternallyLinkage
:
5325 case GlobalValue::LinkOnceAnyLinkage
:
5326 case GlobalValue::LinkOnceODRLinkage
:
5327 case GlobalValue::WeakAnyLinkage
:
5328 case GlobalValue::WeakODRLinkage
:
5330 return Error(LinkageLoc
, "invalid linkage for function declaration");
5332 case GlobalValue::AppendingLinkage
:
5333 case GlobalValue::CommonLinkage
:
5334 return Error(LinkageLoc
, "invalid function linkage type");
5337 if (!isValidVisibilityForLinkage(Visibility
, Linkage
))
5338 return Error(LinkageLoc
,
5339 "symbol with local linkage must have default visibility");
5341 if (!FunctionType::isValidReturnType(RetType
))
5342 return Error(RetTypeLoc
, "invalid function return type");
5344 LocTy NameLoc
= Lex
.getLoc();
5346 std::string FunctionName
;
5347 if (Lex
.getKind() == lltok::GlobalVar
) {
5348 FunctionName
= Lex
.getStrVal();
5349 } else if (Lex
.getKind() == lltok::GlobalID
) { // @42 is ok.
5350 unsigned NameID
= Lex
.getUIntVal();
5352 if (NameID
!= NumberedVals
.size())
5353 return TokError("function expected to be numbered '%" +
5354 Twine(NumberedVals
.size()) + "'");
5356 return TokError("expected function name");
5361 if (Lex
.getKind() != lltok::lparen
)
5362 return TokError("expected '(' in function argument list");
5364 SmallVector
<ArgInfo
, 8> ArgList
;
5366 AttrBuilder FuncAttrs
;
5367 std::vector
<unsigned> FwdRefAttrGrps
;
5369 std::string Section
;
5370 std::string Partition
;
5373 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
5374 unsigned AddrSpace
= 0;
5375 Constant
*Prefix
= nullptr;
5376 Constant
*Prologue
= nullptr;
5377 Constant
*PersonalityFn
= nullptr;
5380 if (ParseArgumentList(ArgList
, isVarArg
) ||
5381 ParseOptionalUnnamedAddr(UnnamedAddr
) ||
5382 ParseOptionalProgramAddrSpace(AddrSpace
) ||
5383 ParseFnAttributeValuePairs(FuncAttrs
, FwdRefAttrGrps
, false,
5385 (EatIfPresent(lltok::kw_section
) &&
5386 ParseStringConstant(Section
)) ||
5387 (EatIfPresent(lltok::kw_partition
) &&
5388 ParseStringConstant(Partition
)) ||
5389 parseOptionalComdat(FunctionName
, C
) ||
5390 ParseOptionalAlignment(Alignment
) ||
5391 (EatIfPresent(lltok::kw_gc
) &&
5392 ParseStringConstant(GC
)) ||
5393 (EatIfPresent(lltok::kw_prefix
) &&
5394 ParseGlobalTypeAndValue(Prefix
)) ||
5395 (EatIfPresent(lltok::kw_prologue
) &&
5396 ParseGlobalTypeAndValue(Prologue
)) ||
5397 (EatIfPresent(lltok::kw_personality
) &&
5398 ParseGlobalTypeAndValue(PersonalityFn
)))
5401 if (FuncAttrs
.contains(Attribute::Builtin
))
5402 return Error(BuiltinLoc
, "'builtin' attribute not valid on function");
5404 // If the alignment was parsed as an attribute, move to the alignment field.
5405 if (FuncAttrs
.hasAlignmentAttr()) {
5406 Alignment
= FuncAttrs
.getAlignment();
5407 FuncAttrs
.removeAttribute(Attribute::Alignment
);
5410 // Okay, if we got here, the function is syntactically valid. Convert types
5411 // and do semantic checks.
5412 std::vector
<Type
*> ParamTypeList
;
5413 SmallVector
<AttributeSet
, 8> Attrs
;
5415 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
5416 ParamTypeList
.push_back(ArgList
[i
].Ty
);
5417 Attrs
.push_back(ArgList
[i
].Attrs
);
5421 AttributeList::get(Context
, AttributeSet::get(Context
, FuncAttrs
),
5422 AttributeSet::get(Context
, RetAttrs
), Attrs
);
5424 if (PAL
.hasAttribute(1, Attribute::StructRet
) && !RetType
->isVoidTy())
5425 return Error(RetTypeLoc
, "functions with 'sret' argument must return void");
5428 FunctionType::get(RetType
, ParamTypeList
, isVarArg
);
5429 PointerType
*PFT
= PointerType::get(FT
, AddrSpace
);
5432 if (!FunctionName
.empty()) {
5433 // If this was a definition of a forward reference, remove the definition
5434 // from the forward reference table and fill in the forward ref.
5435 auto FRVI
= ForwardRefVals
.find(FunctionName
);
5436 if (FRVI
!= ForwardRefVals
.end()) {
5437 Fn
= M
->getFunction(FunctionName
);
5439 return Error(FRVI
->second
.second
, "invalid forward reference to "
5440 "function as global value!");
5441 if (Fn
->getType() != PFT
)
5442 return Error(FRVI
->second
.second
, "invalid forward reference to "
5443 "function '" + FunctionName
+ "' with wrong type: "
5444 "expected '" + getTypeString(PFT
) + "' but was '" +
5445 getTypeString(Fn
->getType()) + "'");
5446 ForwardRefVals
.erase(FRVI
);
5447 } else if ((Fn
= M
->getFunction(FunctionName
))) {
5448 // Reject redefinitions.
5449 return Error(NameLoc
, "invalid redefinition of function '" +
5450 FunctionName
+ "'");
5451 } else if (M
->getNamedValue(FunctionName
)) {
5452 return Error(NameLoc
, "redefinition of function '@" + FunctionName
+ "'");
5456 // If this is a definition of a forward referenced function, make sure the
5458 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
5459 if (I
!= ForwardRefValIDs
.end()) {
5460 Fn
= cast
<Function
>(I
->second
.first
);
5461 if (Fn
->getType() != PFT
)
5462 return Error(NameLoc
, "type of definition and forward reference of '@" +
5463 Twine(NumberedVals
.size()) + "' disagree: "
5464 "expected '" + getTypeString(PFT
) + "' but was '" +
5465 getTypeString(Fn
->getType()) + "'");
5466 ForwardRefValIDs
.erase(I
);
5471 Fn
= Function::Create(FT
, GlobalValue::ExternalLinkage
, AddrSpace
,
5473 else // Move the forward-reference to the correct spot in the module.
5474 M
->getFunctionList().splice(M
->end(), M
->getFunctionList(), Fn
);
5476 assert(Fn
->getAddressSpace() == AddrSpace
&& "Created function in wrong AS");
5478 if (FunctionName
.empty())
5479 NumberedVals
.push_back(Fn
);
5481 Fn
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
5482 maybeSetDSOLocal(DSOLocal
, *Fn
);
5483 Fn
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
5484 Fn
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
5485 Fn
->setCallingConv(CC
);
5486 Fn
->setAttributes(PAL
);
5487 Fn
->setUnnamedAddr(UnnamedAddr
);
5488 Fn
->setAlignment(Alignment
);
5489 Fn
->setSection(Section
);
5490 Fn
->setPartition(Partition
);
5492 Fn
->setPersonalityFn(PersonalityFn
);
5493 if (!GC
.empty()) Fn
->setGC(GC
);
5494 Fn
->setPrefixData(Prefix
);
5495 Fn
->setPrologueData(Prologue
);
5496 ForwardRefAttrGroups
[Fn
] = FwdRefAttrGrps
;
5498 // Add all of the arguments we parsed to the function.
5499 Function::arg_iterator ArgIt
= Fn
->arg_begin();
5500 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
, ++ArgIt
) {
5501 // If the argument has a name, insert it into the argument symbol table.
5502 if (ArgList
[i
].Name
.empty()) continue;
5504 // Set the name, if it conflicted, it will be auto-renamed.
5505 ArgIt
->setName(ArgList
[i
].Name
);
5507 if (ArgIt
->getName() != ArgList
[i
].Name
)
5508 return Error(ArgList
[i
].Loc
, "redefinition of argument '%" +
5509 ArgList
[i
].Name
+ "'");
5515 // Check the declaration has no block address forward references.
5517 if (FunctionName
.empty()) {
5518 ID
.Kind
= ValID::t_GlobalID
;
5519 ID
.UIntVal
= NumberedVals
.size() - 1;
5521 ID
.Kind
= ValID::t_GlobalName
;
5522 ID
.StrVal
= FunctionName
;
5524 auto Blocks
= ForwardRefBlockAddresses
.find(ID
);
5525 if (Blocks
!= ForwardRefBlockAddresses
.end())
5526 return Error(Blocks
->first
.Loc
,
5527 "cannot take blockaddress inside a declaration");
5531 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5533 if (FunctionNumber
== -1) {
5534 ID
.Kind
= ValID::t_GlobalName
;
5535 ID
.StrVal
= F
.getName();
5537 ID
.Kind
= ValID::t_GlobalID
;
5538 ID
.UIntVal
= FunctionNumber
;
5541 auto Blocks
= P
.ForwardRefBlockAddresses
.find(ID
);
5542 if (Blocks
== P
.ForwardRefBlockAddresses
.end())
5545 for (const auto &I
: Blocks
->second
) {
5546 const ValID
&BBID
= I
.first
;
5547 GlobalValue
*GV
= I
.second
;
5549 assert((BBID
.Kind
== ValID::t_LocalID
|| BBID
.Kind
== ValID::t_LocalName
) &&
5550 "Expected local id or name");
5552 if (BBID
.Kind
== ValID::t_LocalName
)
5553 BB
= GetBB(BBID
.StrVal
, BBID
.Loc
);
5555 BB
= GetBB(BBID
.UIntVal
, BBID
.Loc
);
5557 return P
.Error(BBID
.Loc
, "referenced value is not a basic block");
5559 GV
->replaceAllUsesWith(BlockAddress::get(&F
, BB
));
5560 GV
->eraseFromParent();
5563 P
.ForwardRefBlockAddresses
.erase(Blocks
);
5567 /// ParseFunctionBody
5568 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5569 bool LLParser::ParseFunctionBody(Function
&Fn
) {
5570 if (Lex
.getKind() != lltok::lbrace
)
5571 return TokError("expected '{' in function body");
5572 Lex
.Lex(); // eat the {.
5574 int FunctionNumber
= -1;
5575 if (!Fn
.hasName()) FunctionNumber
= NumberedVals
.size()-1;
5577 PerFunctionState
PFS(*this, Fn
, FunctionNumber
);
5579 // Resolve block addresses and allow basic blocks to be forward-declared
5580 // within this function.
5581 if (PFS
.resolveForwardRefBlockAddresses())
5583 SaveAndRestore
<PerFunctionState
*> ScopeExit(BlockAddressPFS
, &PFS
);
5585 // We need at least one basic block.
5586 if (Lex
.getKind() == lltok::rbrace
|| Lex
.getKind() == lltok::kw_uselistorder
)
5587 return TokError("function body requires at least one basic block");
5589 while (Lex
.getKind() != lltok::rbrace
&&
5590 Lex
.getKind() != lltok::kw_uselistorder
)
5591 if (ParseBasicBlock(PFS
)) return true;
5593 while (Lex
.getKind() != lltok::rbrace
)
5594 if (ParseUseListOrder(&PFS
))
5600 // Verify function is ok.
5601 return PFS
.FinishFunction();
5605 /// ::= (LabelStr|LabelID)? Instruction*
5606 bool LLParser::ParseBasicBlock(PerFunctionState
&PFS
) {
5607 // If this basic block starts out with a name, remember it.
5610 LocTy NameLoc
= Lex
.getLoc();
5611 if (Lex
.getKind() == lltok::LabelStr
) {
5612 Name
= Lex
.getStrVal();
5614 } else if (Lex
.getKind() == lltok::LabelID
) {
5615 NameID
= Lex
.getUIntVal();
5619 BasicBlock
*BB
= PFS
.DefineBB(Name
, NameID
, NameLoc
);
5623 std::string NameStr
;
5625 // Parse the instructions in this block until we get a terminator.
5628 // This instruction may have three possibilities for a name: a) none
5629 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5630 LocTy NameLoc
= Lex
.getLoc();
5634 if (Lex
.getKind() == lltok::LocalVarID
) {
5635 NameID
= Lex
.getUIntVal();
5637 if (ParseToken(lltok::equal
, "expected '=' after instruction id"))
5639 } else if (Lex
.getKind() == lltok::LocalVar
) {
5640 NameStr
= Lex
.getStrVal();
5642 if (ParseToken(lltok::equal
, "expected '=' after instruction name"))
5646 switch (ParseInstruction(Inst
, BB
, PFS
)) {
5647 default: llvm_unreachable("Unknown ParseInstruction result!");
5648 case InstError
: return true;
5650 BB
->getInstList().push_back(Inst
);
5652 // With a normal result, we check to see if the instruction is followed by
5653 // a comma and metadata.
5654 if (EatIfPresent(lltok::comma
))
5655 if (ParseInstructionMetadata(*Inst
))
5658 case InstExtraComma
:
5659 BB
->getInstList().push_back(Inst
);
5661 // If the instruction parser ate an extra comma at the end of it, it
5662 // *must* be followed by metadata.
5663 if (ParseInstructionMetadata(*Inst
))
5668 // Set the name on the instruction.
5669 if (PFS
.SetInstName(NameID
, NameStr
, NameLoc
, Inst
)) return true;
5670 } while (!Inst
->isTerminator());
5675 //===----------------------------------------------------------------------===//
5676 // Instruction Parsing.
5677 //===----------------------------------------------------------------------===//
5679 /// ParseInstruction - Parse one of the many different instructions.
5681 int LLParser::ParseInstruction(Instruction
*&Inst
, BasicBlock
*BB
,
5682 PerFunctionState
&PFS
) {
5683 lltok::Kind Token
= Lex
.getKind();
5684 if (Token
== lltok::Eof
)
5685 return TokError("found end of file when expecting more instructions");
5686 LocTy Loc
= Lex
.getLoc();
5687 unsigned KeywordVal
= Lex
.getUIntVal();
5688 Lex
.Lex(); // Eat the keyword.
5691 default: return Error(Loc
, "expected instruction opcode");
5692 // Terminator Instructions.
5693 case lltok::kw_unreachable
: Inst
= new UnreachableInst(Context
); return false;
5694 case lltok::kw_ret
: return ParseRet(Inst
, BB
, PFS
);
5695 case lltok::kw_br
: return ParseBr(Inst
, PFS
);
5696 case lltok::kw_switch
: return ParseSwitch(Inst
, PFS
);
5697 case lltok::kw_indirectbr
: return ParseIndirectBr(Inst
, PFS
);
5698 case lltok::kw_invoke
: return ParseInvoke(Inst
, PFS
);
5699 case lltok::kw_resume
: return ParseResume(Inst
, PFS
);
5700 case lltok::kw_cleanupret
: return ParseCleanupRet(Inst
, PFS
);
5701 case lltok::kw_catchret
: return ParseCatchRet(Inst
, PFS
);
5702 case lltok::kw_catchswitch
: return ParseCatchSwitch(Inst
, PFS
);
5703 case lltok::kw_catchpad
: return ParseCatchPad(Inst
, PFS
);
5704 case lltok::kw_cleanuppad
: return ParseCleanupPad(Inst
, PFS
);
5705 case lltok::kw_callbr
: return ParseCallBr(Inst
, PFS
);
5707 case lltok::kw_fneg
: {
5708 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5709 int Res
= ParseUnaryOp(Inst
, PFS
, KeywordVal
, /*IsFP*/true);
5713 Inst
->setFastMathFlags(FMF
);
5716 // Binary Operators.
5720 case lltok::kw_shl
: {
5721 bool NUW
= EatIfPresent(lltok::kw_nuw
);
5722 bool NSW
= EatIfPresent(lltok::kw_nsw
);
5723 if (!NUW
) NUW
= EatIfPresent(lltok::kw_nuw
);
5725 if (ParseArithmetic(Inst
, PFS
, KeywordVal
, /*IsFP*/false)) return true;
5727 if (NUW
) cast
<BinaryOperator
>(Inst
)->setHasNoUnsignedWrap(true);
5728 if (NSW
) cast
<BinaryOperator
>(Inst
)->setHasNoSignedWrap(true);
5731 case lltok::kw_fadd
:
5732 case lltok::kw_fsub
:
5733 case lltok::kw_fmul
:
5734 case lltok::kw_fdiv
:
5735 case lltok::kw_frem
: {
5736 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5737 int Res
= ParseArithmetic(Inst
, PFS
, KeywordVal
, /*IsFP*/true);
5741 Inst
->setFastMathFlags(FMF
);
5745 case lltok::kw_sdiv
:
5746 case lltok::kw_udiv
:
5747 case lltok::kw_lshr
:
5748 case lltok::kw_ashr
: {
5749 bool Exact
= EatIfPresent(lltok::kw_exact
);
5751 if (ParseArithmetic(Inst
, PFS
, KeywordVal
, /*IsFP*/false)) return true;
5752 if (Exact
) cast
<BinaryOperator
>(Inst
)->setIsExact(true);
5756 case lltok::kw_urem
:
5757 case lltok::kw_srem
: return ParseArithmetic(Inst
, PFS
, KeywordVal
,
5761 case lltok::kw_xor
: return ParseLogical(Inst
, PFS
, KeywordVal
);
5762 case lltok::kw_icmp
: return ParseCompare(Inst
, PFS
, KeywordVal
);
5763 case lltok::kw_fcmp
: {
5764 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5765 int Res
= ParseCompare(Inst
, PFS
, KeywordVal
);
5769 Inst
->setFastMathFlags(FMF
);
5774 case lltok::kw_trunc
:
5775 case lltok::kw_zext
:
5776 case lltok::kw_sext
:
5777 case lltok::kw_fptrunc
:
5778 case lltok::kw_fpext
:
5779 case lltok::kw_bitcast
:
5780 case lltok::kw_addrspacecast
:
5781 case lltok::kw_uitofp
:
5782 case lltok::kw_sitofp
:
5783 case lltok::kw_fptoui
:
5784 case lltok::kw_fptosi
:
5785 case lltok::kw_inttoptr
:
5786 case lltok::kw_ptrtoint
: return ParseCast(Inst
, PFS
, KeywordVal
);
5788 case lltok::kw_select
: {
5789 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5790 int Res
= ParseSelect(Inst
, PFS
);
5794 if (!Inst
->getType()->isFPOrFPVectorTy())
5795 return Error(Loc
, "fast-math-flags specified for select without "
5796 "floating-point scalar or vector return type");
5797 Inst
->setFastMathFlags(FMF
);
5801 case lltok::kw_va_arg
: return ParseVA_Arg(Inst
, PFS
);
5802 case lltok::kw_extractelement
: return ParseExtractElement(Inst
, PFS
);
5803 case lltok::kw_insertelement
: return ParseInsertElement(Inst
, PFS
);
5804 case lltok::kw_shufflevector
: return ParseShuffleVector(Inst
, PFS
);
5805 case lltok::kw_phi
: return ParsePHI(Inst
, PFS
);
5806 case lltok::kw_landingpad
: return ParseLandingPad(Inst
, PFS
);
5808 case lltok::kw_call
: return ParseCall(Inst
, PFS
, CallInst::TCK_None
);
5809 case lltok::kw_tail
: return ParseCall(Inst
, PFS
, CallInst::TCK_Tail
);
5810 case lltok::kw_musttail
: return ParseCall(Inst
, PFS
, CallInst::TCK_MustTail
);
5811 case lltok::kw_notail
: return ParseCall(Inst
, PFS
, CallInst::TCK_NoTail
);
5813 case lltok::kw_alloca
: return ParseAlloc(Inst
, PFS
);
5814 case lltok::kw_load
: return ParseLoad(Inst
, PFS
);
5815 case lltok::kw_store
: return ParseStore(Inst
, PFS
);
5816 case lltok::kw_cmpxchg
: return ParseCmpXchg(Inst
, PFS
);
5817 case lltok::kw_atomicrmw
: return ParseAtomicRMW(Inst
, PFS
);
5818 case lltok::kw_fence
: return ParseFence(Inst
, PFS
);
5819 case lltok::kw_getelementptr
: return ParseGetElementPtr(Inst
, PFS
);
5820 case lltok::kw_extractvalue
: return ParseExtractValue(Inst
, PFS
);
5821 case lltok::kw_insertvalue
: return ParseInsertValue(Inst
, PFS
);
5825 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5826 bool LLParser::ParseCmpPredicate(unsigned &P
, unsigned Opc
) {
5827 if (Opc
== Instruction::FCmp
) {
5828 switch (Lex
.getKind()) {
5829 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5830 case lltok::kw_oeq
: P
= CmpInst::FCMP_OEQ
; break;
5831 case lltok::kw_one
: P
= CmpInst::FCMP_ONE
; break;
5832 case lltok::kw_olt
: P
= CmpInst::FCMP_OLT
; break;
5833 case lltok::kw_ogt
: P
= CmpInst::FCMP_OGT
; break;
5834 case lltok::kw_ole
: P
= CmpInst::FCMP_OLE
; break;
5835 case lltok::kw_oge
: P
= CmpInst::FCMP_OGE
; break;
5836 case lltok::kw_ord
: P
= CmpInst::FCMP_ORD
; break;
5837 case lltok::kw_uno
: P
= CmpInst::FCMP_UNO
; break;
5838 case lltok::kw_ueq
: P
= CmpInst::FCMP_UEQ
; break;
5839 case lltok::kw_une
: P
= CmpInst::FCMP_UNE
; break;
5840 case lltok::kw_ult
: P
= CmpInst::FCMP_ULT
; break;
5841 case lltok::kw_ugt
: P
= CmpInst::FCMP_UGT
; break;
5842 case lltok::kw_ule
: P
= CmpInst::FCMP_ULE
; break;
5843 case lltok::kw_uge
: P
= CmpInst::FCMP_UGE
; break;
5844 case lltok::kw_true
: P
= CmpInst::FCMP_TRUE
; break;
5845 case lltok::kw_false
: P
= CmpInst::FCMP_FALSE
; break;
5848 switch (Lex
.getKind()) {
5849 default: return TokError("expected icmp predicate (e.g. 'eq')");
5850 case lltok::kw_eq
: P
= CmpInst::ICMP_EQ
; break;
5851 case lltok::kw_ne
: P
= CmpInst::ICMP_NE
; break;
5852 case lltok::kw_slt
: P
= CmpInst::ICMP_SLT
; break;
5853 case lltok::kw_sgt
: P
= CmpInst::ICMP_SGT
; break;
5854 case lltok::kw_sle
: P
= CmpInst::ICMP_SLE
; break;
5855 case lltok::kw_sge
: P
= CmpInst::ICMP_SGE
; break;
5856 case lltok::kw_ult
: P
= CmpInst::ICMP_ULT
; break;
5857 case lltok::kw_ugt
: P
= CmpInst::ICMP_UGT
; break;
5858 case lltok::kw_ule
: P
= CmpInst::ICMP_ULE
; break;
5859 case lltok::kw_uge
: P
= CmpInst::ICMP_UGE
; break;
5866 //===----------------------------------------------------------------------===//
5867 // Terminator Instructions.
5868 //===----------------------------------------------------------------------===//
5870 /// ParseRet - Parse a return instruction.
5871 /// ::= 'ret' void (',' !dbg, !1)*
5872 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5873 bool LLParser::ParseRet(Instruction
*&Inst
, BasicBlock
*BB
,
5874 PerFunctionState
&PFS
) {
5875 SMLoc TypeLoc
= Lex
.getLoc();
5877 if (ParseType(Ty
, true /*void allowed*/)) return true;
5879 Type
*ResType
= PFS
.getFunction().getReturnType();
5881 if (Ty
->isVoidTy()) {
5882 if (!ResType
->isVoidTy())
5883 return Error(TypeLoc
, "value doesn't match function result type '" +
5884 getTypeString(ResType
) + "'");
5886 Inst
= ReturnInst::Create(Context
);
5891 if (ParseValue(Ty
, RV
, PFS
)) return true;
5893 if (ResType
!= RV
->getType())
5894 return Error(TypeLoc
, "value doesn't match function result type '" +
5895 getTypeString(ResType
) + "'");
5897 Inst
= ReturnInst::Create(Context
, RV
);
5902 /// ::= 'br' TypeAndValue
5903 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5904 bool LLParser::ParseBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
5907 BasicBlock
*Op1
, *Op2
;
5908 if (ParseTypeAndValue(Op0
, Loc
, PFS
)) return true;
5910 if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(Op0
)) {
5911 Inst
= BranchInst::Create(BB
);
5915 if (Op0
->getType() != Type::getInt1Ty(Context
))
5916 return Error(Loc
, "branch condition must have 'i1' type");
5918 if (ParseToken(lltok::comma
, "expected ',' after branch condition") ||
5919 ParseTypeAndBasicBlock(Op1
, Loc
, PFS
) ||
5920 ParseToken(lltok::comma
, "expected ',' after true destination") ||
5921 ParseTypeAndBasicBlock(Op2
, Loc2
, PFS
))
5924 Inst
= BranchInst::Create(Op1
, Op2
, Op0
);
5930 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5932 /// ::= (TypeAndValue ',' TypeAndValue)*
5933 bool LLParser::ParseSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
5934 LocTy CondLoc
, BBLoc
;
5936 BasicBlock
*DefaultBB
;
5937 if (ParseTypeAndValue(Cond
, CondLoc
, PFS
) ||
5938 ParseToken(lltok::comma
, "expected ',' after switch condition") ||
5939 ParseTypeAndBasicBlock(DefaultBB
, BBLoc
, PFS
) ||
5940 ParseToken(lltok::lsquare
, "expected '[' with switch table"))
5943 if (!Cond
->getType()->isIntegerTy())
5944 return Error(CondLoc
, "switch condition must have integer type");
5946 // Parse the jump table pairs.
5947 SmallPtrSet
<Value
*, 32> SeenCases
;
5948 SmallVector
<std::pair
<ConstantInt
*, BasicBlock
*>, 32> Table
;
5949 while (Lex
.getKind() != lltok::rsquare
) {
5953 if (ParseTypeAndValue(Constant
, CondLoc
, PFS
) ||
5954 ParseToken(lltok::comma
, "expected ',' after case value") ||
5955 ParseTypeAndBasicBlock(DestBB
, PFS
))
5958 if (!SeenCases
.insert(Constant
).second
)
5959 return Error(CondLoc
, "duplicate case value in switch");
5960 if (!isa
<ConstantInt
>(Constant
))
5961 return Error(CondLoc
, "case value is not a constant integer");
5963 Table
.push_back(std::make_pair(cast
<ConstantInt
>(Constant
), DestBB
));
5966 Lex
.Lex(); // Eat the ']'.
5968 SwitchInst
*SI
= SwitchInst::Create(Cond
, DefaultBB
, Table
.size());
5969 for (unsigned i
= 0, e
= Table
.size(); i
!= e
; ++i
)
5970 SI
->addCase(Table
[i
].first
, Table
[i
].second
);
5977 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5978 bool LLParser::ParseIndirectBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
5981 if (ParseTypeAndValue(Address
, AddrLoc
, PFS
) ||
5982 ParseToken(lltok::comma
, "expected ',' after indirectbr address") ||
5983 ParseToken(lltok::lsquare
, "expected '[' with indirectbr"))
5986 if (!Address
->getType()->isPointerTy())
5987 return Error(AddrLoc
, "indirectbr address must have pointer type");
5989 // Parse the destination list.
5990 SmallVector
<BasicBlock
*, 16> DestList
;
5992 if (Lex
.getKind() != lltok::rsquare
) {
5994 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
5996 DestList
.push_back(DestBB
);
5998 while (EatIfPresent(lltok::comma
)) {
5999 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
6001 DestList
.push_back(DestBB
);
6005 if (ParseToken(lltok::rsquare
, "expected ']' at end of block list"))
6008 IndirectBrInst
*IBI
= IndirectBrInst::Create(Address
, DestList
.size());
6009 for (unsigned i
= 0, e
= DestList
.size(); i
!= e
; ++i
)
6010 IBI
->addDestination(DestList
[i
]);
6016 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6017 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6018 bool LLParser::ParseInvoke(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6019 LocTy CallLoc
= Lex
.getLoc();
6020 AttrBuilder RetAttrs
, FnAttrs
;
6021 std::vector
<unsigned> FwdRefAttrGrps
;
6024 unsigned InvokeAddrSpace
;
6025 Type
*RetType
= nullptr;
6028 SmallVector
<ParamInfo
, 16> ArgList
;
6029 SmallVector
<OperandBundleDef
, 2> BundleList
;
6031 BasicBlock
*NormalBB
, *UnwindBB
;
6032 if (ParseOptionalCallingConv(CC
) || ParseOptionalReturnAttrs(RetAttrs
) ||
6033 ParseOptionalProgramAddrSpace(InvokeAddrSpace
) ||
6034 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
6035 ParseValID(CalleeID
) || ParseParameterList(ArgList
, PFS
) ||
6036 ParseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false,
6038 ParseOptionalOperandBundles(BundleList
, PFS
) ||
6039 ParseToken(lltok::kw_to
, "expected 'to' in invoke") ||
6040 ParseTypeAndBasicBlock(NormalBB
, PFS
) ||
6041 ParseToken(lltok::kw_unwind
, "expected 'unwind' in invoke") ||
6042 ParseTypeAndBasicBlock(UnwindBB
, PFS
))
6045 // If RetType is a non-function pointer type, then this is the short syntax
6046 // for the call, which means that RetType is just the return type. Infer the
6047 // rest of the function argument types from the arguments that are present.
6048 FunctionType
*Ty
= dyn_cast
<FunctionType
>(RetType
);
6050 // Pull out the types of all of the arguments...
6051 std::vector
<Type
*> ParamTypes
;
6052 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
6053 ParamTypes
.push_back(ArgList
[i
].V
->getType());
6055 if (!FunctionType::isValidReturnType(RetType
))
6056 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
6058 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
6063 // Look up the callee.
6065 if (ConvertValIDToValue(PointerType::get(Ty
, InvokeAddrSpace
), CalleeID
,
6066 Callee
, &PFS
, /*IsCall=*/true))
6069 // Set up the Attribute for the function.
6070 SmallVector
<Value
*, 8> Args
;
6071 SmallVector
<AttributeSet
, 8> ArgAttrs
;
6073 // Loop through FunctionType's arguments and ensure they are specified
6074 // correctly. Also, gather any parameter attributes.
6075 FunctionType::param_iterator I
= Ty
->param_begin();
6076 FunctionType::param_iterator E
= Ty
->param_end();
6077 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
6078 Type
*ExpectedTy
= nullptr;
6081 } else if (!Ty
->isVarArg()) {
6082 return Error(ArgList
[i
].Loc
, "too many arguments specified");
6085 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
6086 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
6087 getTypeString(ExpectedTy
) + "'");
6088 Args
.push_back(ArgList
[i
].V
);
6089 ArgAttrs
.push_back(ArgList
[i
].Attrs
);
6093 return Error(CallLoc
, "not enough parameters specified for call");
6095 if (FnAttrs
.hasAlignmentAttr())
6096 return Error(CallLoc
, "invoke instructions may not have an alignment");
6098 // Finish off the Attribute and check them
6100 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
6101 AttributeSet::get(Context
, RetAttrs
), ArgAttrs
);
6104 InvokeInst::Create(Ty
, Callee
, NormalBB
, UnwindBB
, Args
, BundleList
);
6105 II
->setCallingConv(CC
);
6106 II
->setAttributes(PAL
);
6107 ForwardRefAttrGroups
[II
] = FwdRefAttrGrps
;
6113 /// ::= 'resume' TypeAndValue
6114 bool LLParser::ParseResume(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6115 Value
*Exn
; LocTy ExnLoc
;
6116 if (ParseTypeAndValue(Exn
, ExnLoc
, PFS
))
6119 ResumeInst
*RI
= ResumeInst::Create(Exn
);
6124 bool LLParser::ParseExceptionArgs(SmallVectorImpl
<Value
*> &Args
,
6125 PerFunctionState
&PFS
) {
6126 if (ParseToken(lltok::lsquare
, "expected '[' in catchpad/cleanuppad"))
6129 while (Lex
.getKind() != lltok::rsquare
) {
6130 // If this isn't the first argument, we need a comma.
6131 if (!Args
.empty() &&
6132 ParseToken(lltok::comma
, "expected ',' in argument list"))
6135 // Parse the argument.
6137 Type
*ArgTy
= nullptr;
6138 if (ParseType(ArgTy
, ArgLoc
))
6142 if (ArgTy
->isMetadataTy()) {
6143 if (ParseMetadataAsValue(V
, PFS
))
6146 if (ParseValue(ArgTy
, V
, PFS
))
6152 Lex
.Lex(); // Lex the ']'.
6157 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6158 bool LLParser::ParseCleanupRet(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6159 Value
*CleanupPad
= nullptr;
6161 if (ParseToken(lltok::kw_from
, "expected 'from' after cleanupret"))
6164 if (ParseValue(Type::getTokenTy(Context
), CleanupPad
, PFS
))
6167 if (ParseToken(lltok::kw_unwind
, "expected 'unwind' in cleanupret"))
6170 BasicBlock
*UnwindBB
= nullptr;
6171 if (Lex
.getKind() == lltok::kw_to
) {
6173 if (ParseToken(lltok::kw_caller
, "expected 'caller' in cleanupret"))
6176 if (ParseTypeAndBasicBlock(UnwindBB
, PFS
)) {
6181 Inst
= CleanupReturnInst::Create(CleanupPad
, UnwindBB
);
6186 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6187 bool LLParser::ParseCatchRet(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6188 Value
*CatchPad
= nullptr;
6190 if (ParseToken(lltok::kw_from
, "expected 'from' after catchret"))
6193 if (ParseValue(Type::getTokenTy(Context
), CatchPad
, PFS
))
6197 if (ParseToken(lltok::kw_to
, "expected 'to' in catchret") ||
6198 ParseTypeAndBasicBlock(BB
, PFS
))
6201 Inst
= CatchReturnInst::Create(CatchPad
, BB
);
6205 /// ParseCatchSwitch
6206 /// ::= 'catchswitch' within Parent
6207 bool LLParser::ParseCatchSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6210 if (ParseToken(lltok::kw_within
, "expected 'within' after catchswitch"))
6213 if (Lex
.getKind() != lltok::kw_none
&& Lex
.getKind() != lltok::LocalVar
&&
6214 Lex
.getKind() != lltok::LocalVarID
)
6215 return TokError("expected scope value for catchswitch");
6217 if (ParseValue(Type::getTokenTy(Context
), ParentPad
, PFS
))
6220 if (ParseToken(lltok::lsquare
, "expected '[' with catchswitch labels"))
6223 SmallVector
<BasicBlock
*, 32> Table
;
6226 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
6228 Table
.push_back(DestBB
);
6229 } while (EatIfPresent(lltok::comma
));
6231 if (ParseToken(lltok::rsquare
, "expected ']' after catchswitch labels"))
6234 if (ParseToken(lltok::kw_unwind
,
6235 "expected 'unwind' after catchswitch scope"))
6238 BasicBlock
*UnwindBB
= nullptr;
6239 if (EatIfPresent(lltok::kw_to
)) {
6240 if (ParseToken(lltok::kw_caller
, "expected 'caller' in catchswitch"))
6243 if (ParseTypeAndBasicBlock(UnwindBB
, PFS
))
6248 CatchSwitchInst::Create(ParentPad
, UnwindBB
, Table
.size());
6249 for (BasicBlock
*DestBB
: Table
)
6250 CatchSwitch
->addHandler(DestBB
);
6256 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6257 bool LLParser::ParseCatchPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6258 Value
*CatchSwitch
= nullptr;
6260 if (ParseToken(lltok::kw_within
, "expected 'within' after catchpad"))
6263 if (Lex
.getKind() != lltok::LocalVar
&& Lex
.getKind() != lltok::LocalVarID
)
6264 return TokError("expected scope value for catchpad");
6266 if (ParseValue(Type::getTokenTy(Context
), CatchSwitch
, PFS
))
6269 SmallVector
<Value
*, 8> Args
;
6270 if (ParseExceptionArgs(Args
, PFS
))
6273 Inst
= CatchPadInst::Create(CatchSwitch
, Args
);
6278 /// ::= 'cleanuppad' within Parent ParamList
6279 bool LLParser::ParseCleanupPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6280 Value
*ParentPad
= nullptr;
6282 if (ParseToken(lltok::kw_within
, "expected 'within' after cleanuppad"))
6285 if (Lex
.getKind() != lltok::kw_none
&& Lex
.getKind() != lltok::LocalVar
&&
6286 Lex
.getKind() != lltok::LocalVarID
)
6287 return TokError("expected scope value for cleanuppad");
6289 if (ParseValue(Type::getTokenTy(Context
), ParentPad
, PFS
))
6292 SmallVector
<Value
*, 8> Args
;
6293 if (ParseExceptionArgs(Args
, PFS
))
6296 Inst
= CleanupPadInst::Create(ParentPad
, Args
);
6300 //===----------------------------------------------------------------------===//
6302 //===----------------------------------------------------------------------===//
6305 /// ::= UnaryOp TypeAndValue ',' Value
6307 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6308 /// operand is allowed.
6309 bool LLParser::ParseUnaryOp(Instruction
*&Inst
, PerFunctionState
&PFS
,
6310 unsigned Opc
, bool IsFP
) {
6311 LocTy Loc
; Value
*LHS
;
6312 if (ParseTypeAndValue(LHS
, Loc
, PFS
))
6315 bool Valid
= IsFP
? LHS
->getType()->isFPOrFPVectorTy()
6316 : LHS
->getType()->isIntOrIntVectorTy();
6319 return Error(Loc
, "invalid operand type for instruction");
6321 Inst
= UnaryOperator::Create((Instruction::UnaryOps
)Opc
, LHS
);
6326 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6327 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6328 /// '[' LabelList ']'
6329 bool LLParser::ParseCallBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6330 LocTy CallLoc
= Lex
.getLoc();
6331 AttrBuilder RetAttrs
, FnAttrs
;
6332 std::vector
<unsigned> FwdRefAttrGrps
;
6335 Type
*RetType
= nullptr;
6338 SmallVector
<ParamInfo
, 16> ArgList
;
6339 SmallVector
<OperandBundleDef
, 2> BundleList
;
6341 BasicBlock
*DefaultDest
;
6342 if (ParseOptionalCallingConv(CC
) || ParseOptionalReturnAttrs(RetAttrs
) ||
6343 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
6344 ParseValID(CalleeID
) || ParseParameterList(ArgList
, PFS
) ||
6345 ParseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false,
6347 ParseOptionalOperandBundles(BundleList
, PFS
) ||
6348 ParseToken(lltok::kw_to
, "expected 'to' in callbr") ||
6349 ParseTypeAndBasicBlock(DefaultDest
, PFS
) ||
6350 ParseToken(lltok::lsquare
, "expected '[' in callbr"))
6353 // Parse the destination list.
6354 SmallVector
<BasicBlock
*, 16> IndirectDests
;
6356 if (Lex
.getKind() != lltok::rsquare
) {
6358 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
6360 IndirectDests
.push_back(DestBB
);
6362 while (EatIfPresent(lltok::comma
)) {
6363 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
6365 IndirectDests
.push_back(DestBB
);
6369 if (ParseToken(lltok::rsquare
, "expected ']' at end of block list"))
6372 // If RetType is a non-function pointer type, then this is the short syntax
6373 // for the call, which means that RetType is just the return type. Infer the
6374 // rest of the function argument types from the arguments that are present.
6375 FunctionType
*Ty
= dyn_cast
<FunctionType
>(RetType
);
6377 // Pull out the types of all of the arguments...
6378 std::vector
<Type
*> ParamTypes
;
6379 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
6380 ParamTypes
.push_back(ArgList
[i
].V
->getType());
6382 if (!FunctionType::isValidReturnType(RetType
))
6383 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
6385 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
6390 // Look up the callee.
6392 if (ConvertValIDToValue(PointerType::getUnqual(Ty
), CalleeID
, Callee
, &PFS
,
6396 if (isa
<InlineAsm
>(Callee
) && !Ty
->getReturnType()->isVoidTy())
6397 return Error(RetTypeLoc
, "asm-goto outputs not supported");
6399 // Set up the Attribute for the function.
6400 SmallVector
<Value
*, 8> Args
;
6401 SmallVector
<AttributeSet
, 8> ArgAttrs
;
6403 // Loop through FunctionType's arguments and ensure they are specified
6404 // correctly. Also, gather any parameter attributes.
6405 FunctionType::param_iterator I
= Ty
->param_begin();
6406 FunctionType::param_iterator E
= Ty
->param_end();
6407 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
6408 Type
*ExpectedTy
= nullptr;
6411 } else if (!Ty
->isVarArg()) {
6412 return Error(ArgList
[i
].Loc
, "too many arguments specified");
6415 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
6416 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
6417 getTypeString(ExpectedTy
) + "'");
6418 Args
.push_back(ArgList
[i
].V
);
6419 ArgAttrs
.push_back(ArgList
[i
].Attrs
);
6423 return Error(CallLoc
, "not enough parameters specified for call");
6425 if (FnAttrs
.hasAlignmentAttr())
6426 return Error(CallLoc
, "callbr instructions may not have an alignment");
6428 // Finish off the Attribute and check them
6430 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
6431 AttributeSet::get(Context
, RetAttrs
), ArgAttrs
);
6434 CallBrInst::Create(Ty
, Callee
, DefaultDest
, IndirectDests
, Args
,
6436 CBI
->setCallingConv(CC
);
6437 CBI
->setAttributes(PAL
);
6438 ForwardRefAttrGroups
[CBI
] = FwdRefAttrGrps
;
6443 //===----------------------------------------------------------------------===//
6444 // Binary Operators.
6445 //===----------------------------------------------------------------------===//
6448 /// ::= ArithmeticOps TypeAndValue ',' Value
6450 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6451 /// operand is allowed.
6452 bool LLParser::ParseArithmetic(Instruction
*&Inst
, PerFunctionState
&PFS
,
6453 unsigned Opc
, bool IsFP
) {
6454 LocTy Loc
; Value
*LHS
, *RHS
;
6455 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
6456 ParseToken(lltok::comma
, "expected ',' in arithmetic operation") ||
6457 ParseValue(LHS
->getType(), RHS
, PFS
))
6460 bool Valid
= IsFP
? LHS
->getType()->isFPOrFPVectorTy()
6461 : LHS
->getType()->isIntOrIntVectorTy();
6464 return Error(Loc
, "invalid operand type for instruction");
6466 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
6471 /// ::= ArithmeticOps TypeAndValue ',' Value {
6472 bool LLParser::ParseLogical(Instruction
*&Inst
, PerFunctionState
&PFS
,
6474 LocTy Loc
; Value
*LHS
, *RHS
;
6475 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
6476 ParseToken(lltok::comma
, "expected ',' in logical operation") ||
6477 ParseValue(LHS
->getType(), RHS
, PFS
))
6480 if (!LHS
->getType()->isIntOrIntVectorTy())
6481 return Error(Loc
,"instruction requires integer or integer vector operands");
6483 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
6488 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
6489 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
6490 bool LLParser::ParseCompare(Instruction
*&Inst
, PerFunctionState
&PFS
,
6492 // Parse the integer/fp comparison predicate.
6496 if (ParseCmpPredicate(Pred
, Opc
) ||
6497 ParseTypeAndValue(LHS
, Loc
, PFS
) ||
6498 ParseToken(lltok::comma
, "expected ',' after compare value") ||
6499 ParseValue(LHS
->getType(), RHS
, PFS
))
6502 if (Opc
== Instruction::FCmp
) {
6503 if (!LHS
->getType()->isFPOrFPVectorTy())
6504 return Error(Loc
, "fcmp requires floating point operands");
6505 Inst
= new FCmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
6507 assert(Opc
== Instruction::ICmp
&& "Unknown opcode for CmpInst!");
6508 if (!LHS
->getType()->isIntOrIntVectorTy() &&
6509 !LHS
->getType()->isPtrOrPtrVectorTy())
6510 return Error(Loc
, "icmp requires integer operands");
6511 Inst
= new ICmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
6516 //===----------------------------------------------------------------------===//
6517 // Other Instructions.
6518 //===----------------------------------------------------------------------===//
6522 /// ::= CastOpc TypeAndValue 'to' Type
6523 bool LLParser::ParseCast(Instruction
*&Inst
, PerFunctionState
&PFS
,
6527 Type
*DestTy
= nullptr;
6528 if (ParseTypeAndValue(Op
, Loc
, PFS
) ||
6529 ParseToken(lltok::kw_to
, "expected 'to' after cast value") ||
6533 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
)) {
6534 CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
);
6535 return Error(Loc
, "invalid cast opcode for cast from '" +
6536 getTypeString(Op
->getType()) + "' to '" +
6537 getTypeString(DestTy
) + "'");
6539 Inst
= CastInst::Create((Instruction::CastOps
)Opc
, Op
, DestTy
);
6544 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6545 bool LLParser::ParseSelect(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6547 Value
*Op0
, *Op1
, *Op2
;
6548 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
6549 ParseToken(lltok::comma
, "expected ',' after select condition") ||
6550 ParseTypeAndValue(Op1
, PFS
) ||
6551 ParseToken(lltok::comma
, "expected ',' after select value") ||
6552 ParseTypeAndValue(Op2
, PFS
))
6555 if (const char *Reason
= SelectInst::areInvalidOperands(Op0
, Op1
, Op2
))
6556 return Error(Loc
, Reason
);
6558 Inst
= SelectInst::Create(Op0
, Op1
, Op2
);
6563 /// ::= 'va_arg' TypeAndValue ',' Type
6564 bool LLParser::ParseVA_Arg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6566 Type
*EltTy
= nullptr;
6568 if (ParseTypeAndValue(Op
, PFS
) ||
6569 ParseToken(lltok::comma
, "expected ',' after vaarg operand") ||
6570 ParseType(EltTy
, TypeLoc
))
6573 if (!EltTy
->isFirstClassType())
6574 return Error(TypeLoc
, "va_arg requires operand with first class type");
6576 Inst
= new VAArgInst(Op
, EltTy
);
6580 /// ParseExtractElement
6581 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6582 bool LLParser::ParseExtractElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6585 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
6586 ParseToken(lltok::comma
, "expected ',' after extract value") ||
6587 ParseTypeAndValue(Op1
, PFS
))
6590 if (!ExtractElementInst::isValidOperands(Op0
, Op1
))
6591 return Error(Loc
, "invalid extractelement operands");
6593 Inst
= ExtractElementInst::Create(Op0
, Op1
);
6597 /// ParseInsertElement
6598 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6599 bool LLParser::ParseInsertElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6601 Value
*Op0
, *Op1
, *Op2
;
6602 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
6603 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
6604 ParseTypeAndValue(Op1
, PFS
) ||
6605 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
6606 ParseTypeAndValue(Op2
, PFS
))
6609 if (!InsertElementInst::isValidOperands(Op0
, Op1
, Op2
))
6610 return Error(Loc
, "invalid insertelement operands");
6612 Inst
= InsertElementInst::Create(Op0
, Op1
, Op2
);
6616 /// ParseShuffleVector
6617 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6618 bool LLParser::ParseShuffleVector(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6620 Value
*Op0
, *Op1
, *Op2
;
6621 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
6622 ParseToken(lltok::comma
, "expected ',' after shuffle mask") ||
6623 ParseTypeAndValue(Op1
, PFS
) ||
6624 ParseToken(lltok::comma
, "expected ',' after shuffle value") ||
6625 ParseTypeAndValue(Op2
, PFS
))
6628 if (!ShuffleVectorInst::isValidOperands(Op0
, Op1
, Op2
))
6629 return Error(Loc
, "invalid shufflevector operands");
6631 Inst
= new ShuffleVectorInst(Op0
, Op1
, Op2
);
6636 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6637 int LLParser::ParsePHI(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6638 Type
*Ty
= nullptr; LocTy TypeLoc
;
6641 if (ParseType(Ty
, TypeLoc
) ||
6642 ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
6643 ParseValue(Ty
, Op0
, PFS
) ||
6644 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
6645 ParseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
6646 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
6649 bool AteExtraComma
= false;
6650 SmallVector
<std::pair
<Value
*, BasicBlock
*>, 16> PHIVals
;
6653 PHIVals
.push_back(std::make_pair(Op0
, cast
<BasicBlock
>(Op1
)));
6655 if (!EatIfPresent(lltok::comma
))
6658 if (Lex
.getKind() == lltok::MetadataVar
) {
6659 AteExtraComma
= true;
6663 if (ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
6664 ParseValue(Ty
, Op0
, PFS
) ||
6665 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
6666 ParseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
6667 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
6671 if (!Ty
->isFirstClassType())
6672 return Error(TypeLoc
, "phi node must have first class type");
6674 PHINode
*PN
= PHINode::Create(Ty
, PHIVals
.size());
6675 for (unsigned i
= 0, e
= PHIVals
.size(); i
!= e
; ++i
)
6676 PN
->addIncoming(PHIVals
[i
].first
, PHIVals
[i
].second
);
6678 return AteExtraComma
? InstExtraComma
: InstNormal
;
6682 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6684 /// ::= 'catch' TypeAndValue
6686 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6687 bool LLParser::ParseLandingPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6688 Type
*Ty
= nullptr; LocTy TyLoc
;
6690 if (ParseType(Ty
, TyLoc
))
6693 std::unique_ptr
<LandingPadInst
> LP(LandingPadInst::Create(Ty
, 0));
6694 LP
->setCleanup(EatIfPresent(lltok::kw_cleanup
));
6696 while (Lex
.getKind() == lltok::kw_catch
|| Lex
.getKind() == lltok::kw_filter
){
6697 LandingPadInst::ClauseType CT
;
6698 if (EatIfPresent(lltok::kw_catch
))
6699 CT
= LandingPadInst::Catch
;
6700 else if (EatIfPresent(lltok::kw_filter
))
6701 CT
= LandingPadInst::Filter
;
6703 return TokError("expected 'catch' or 'filter' clause type");
6707 if (ParseTypeAndValue(V
, VLoc
, PFS
))
6710 // A 'catch' type expects a non-array constant. A filter clause expects an
6712 if (CT
== LandingPadInst::Catch
) {
6713 if (isa
<ArrayType
>(V
->getType()))
6714 Error(VLoc
, "'catch' clause has an invalid type");
6716 if (!isa
<ArrayType
>(V
->getType()))
6717 Error(VLoc
, "'filter' clause has an invalid type");
6720 Constant
*CV
= dyn_cast
<Constant
>(V
);
6722 return Error(VLoc
, "clause argument must be a constant");
6726 Inst
= LP
.release();
6731 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6732 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6733 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6734 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6735 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6736 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6737 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6738 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6739 bool LLParser::ParseCall(Instruction
*&Inst
, PerFunctionState
&PFS
,
6740 CallInst::TailCallKind TCK
) {
6741 AttrBuilder RetAttrs
, FnAttrs
;
6742 std::vector
<unsigned> FwdRefAttrGrps
;
6744 unsigned CallAddrSpace
;
6746 Type
*RetType
= nullptr;
6749 SmallVector
<ParamInfo
, 16> ArgList
;
6750 SmallVector
<OperandBundleDef
, 2> BundleList
;
6751 LocTy CallLoc
= Lex
.getLoc();
6753 if (TCK
!= CallInst::TCK_None
&&
6754 ParseToken(lltok::kw_call
,
6755 "expected 'tail call', 'musttail call', or 'notail call'"))
6758 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6760 if (ParseOptionalCallingConv(CC
) || ParseOptionalReturnAttrs(RetAttrs
) ||
6761 ParseOptionalProgramAddrSpace(CallAddrSpace
) ||
6762 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
6763 ParseValID(CalleeID
) ||
6764 ParseParameterList(ArgList
, PFS
, TCK
== CallInst::TCK_MustTail
,
6765 PFS
.getFunction().isVarArg()) ||
6766 ParseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false, BuiltinLoc
) ||
6767 ParseOptionalOperandBundles(BundleList
, PFS
))
6770 if (FMF
.any() && !RetType
->isFPOrFPVectorTy())
6771 return Error(CallLoc
, "fast-math-flags specified for call without "
6772 "floating-point scalar or vector return type");
6774 // If RetType is a non-function pointer type, then this is the short syntax
6775 // for the call, which means that RetType is just the return type. Infer the
6776 // rest of the function argument types from the arguments that are present.
6777 FunctionType
*Ty
= dyn_cast
<FunctionType
>(RetType
);
6779 // Pull out the types of all of the arguments...
6780 std::vector
<Type
*> ParamTypes
;
6781 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
6782 ParamTypes
.push_back(ArgList
[i
].V
->getType());
6784 if (!FunctionType::isValidReturnType(RetType
))
6785 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
6787 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
6792 // Look up the callee.
6794 if (ConvertValIDToValue(PointerType::get(Ty
, CallAddrSpace
), CalleeID
, Callee
,
6795 &PFS
, /*IsCall=*/true))
6798 // Set up the Attribute for the function.
6799 SmallVector
<AttributeSet
, 8> Attrs
;
6801 SmallVector
<Value
*, 8> Args
;
6803 // Loop through FunctionType's arguments and ensure they are specified
6804 // correctly. Also, gather any parameter attributes.
6805 FunctionType::param_iterator I
= Ty
->param_begin();
6806 FunctionType::param_iterator E
= Ty
->param_end();
6807 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
6808 Type
*ExpectedTy
= nullptr;
6811 } else if (!Ty
->isVarArg()) {
6812 return Error(ArgList
[i
].Loc
, "too many arguments specified");
6815 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
6816 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
6817 getTypeString(ExpectedTy
) + "'");
6818 Args
.push_back(ArgList
[i
].V
);
6819 Attrs
.push_back(ArgList
[i
].Attrs
);
6823 return Error(CallLoc
, "not enough parameters specified for call");
6825 if (FnAttrs
.hasAlignmentAttr())
6826 return Error(CallLoc
, "call instructions may not have an alignment");
6828 // Finish off the Attribute and check them
6830 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
6831 AttributeSet::get(Context
, RetAttrs
), Attrs
);
6833 CallInst
*CI
= CallInst::Create(Ty
, Callee
, Args
, BundleList
);
6834 CI
->setTailCallKind(TCK
);
6835 CI
->setCallingConv(CC
);
6837 CI
->setFastMathFlags(FMF
);
6838 CI
->setAttributes(PAL
);
6839 ForwardRefAttrGroups
[CI
] = FwdRefAttrGrps
;
6844 //===----------------------------------------------------------------------===//
6845 // Memory Instructions.
6846 //===----------------------------------------------------------------------===//
6849 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6850 /// (',' 'align' i32)? (',', 'addrspace(n))?
6851 int LLParser::ParseAlloc(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6852 Value
*Size
= nullptr;
6853 LocTy SizeLoc
, TyLoc
, ASLoc
;
6854 unsigned Alignment
= 0;
6855 unsigned AddrSpace
= 0;
6858 bool IsInAlloca
= EatIfPresent(lltok::kw_inalloca
);
6859 bool IsSwiftError
= EatIfPresent(lltok::kw_swifterror
);
6861 if (ParseType(Ty
, TyLoc
)) return true;
6863 if (Ty
->isFunctionTy() || !PointerType::isValidElementType(Ty
))
6864 return Error(TyLoc
, "invalid type for alloca");
6866 bool AteExtraComma
= false;
6867 if (EatIfPresent(lltok::comma
)) {
6868 if (Lex
.getKind() == lltok::kw_align
) {
6869 if (ParseOptionalAlignment(Alignment
))
6871 if (ParseOptionalCommaAddrSpace(AddrSpace
, ASLoc
, AteExtraComma
))
6873 } else if (Lex
.getKind() == lltok::kw_addrspace
) {
6874 ASLoc
= Lex
.getLoc();
6875 if (ParseOptionalAddrSpace(AddrSpace
))
6877 } else if (Lex
.getKind() == lltok::MetadataVar
) {
6878 AteExtraComma
= true;
6880 if (ParseTypeAndValue(Size
, SizeLoc
, PFS
))
6882 if (EatIfPresent(lltok::comma
)) {
6883 if (Lex
.getKind() == lltok::kw_align
) {
6884 if (ParseOptionalAlignment(Alignment
))
6886 if (ParseOptionalCommaAddrSpace(AddrSpace
, ASLoc
, AteExtraComma
))
6888 } else if (Lex
.getKind() == lltok::kw_addrspace
) {
6889 ASLoc
= Lex
.getLoc();
6890 if (ParseOptionalAddrSpace(AddrSpace
))
6892 } else if (Lex
.getKind() == lltok::MetadataVar
) {
6893 AteExtraComma
= true;
6899 if (Size
&& !Size
->getType()->isIntegerTy())
6900 return Error(SizeLoc
, "element count must have integer type");
6902 AllocaInst
*AI
= new AllocaInst(Ty
, AddrSpace
, Size
, Alignment
);
6903 AI
->setUsedWithInAlloca(IsInAlloca
);
6904 AI
->setSwiftError(IsSwiftError
);
6906 return AteExtraComma
? InstExtraComma
: InstNormal
;
6910 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6911 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6912 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6913 int LLParser::ParseLoad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6914 Value
*Val
; LocTy Loc
;
6915 unsigned Alignment
= 0;
6916 bool AteExtraComma
= false;
6917 bool isAtomic
= false;
6918 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
6919 SyncScope::ID SSID
= SyncScope::System
;
6921 if (Lex
.getKind() == lltok::kw_atomic
) {
6926 bool isVolatile
= false;
6927 if (Lex
.getKind() == lltok::kw_volatile
) {
6933 LocTy ExplicitTypeLoc
= Lex
.getLoc();
6934 if (ParseType(Ty
) ||
6935 ParseToken(lltok::comma
, "expected comma after load's type") ||
6936 ParseTypeAndValue(Val
, Loc
, PFS
) ||
6937 ParseScopeAndOrdering(isAtomic
, SSID
, Ordering
) ||
6938 ParseOptionalCommaAlign(Alignment
, AteExtraComma
))
6941 if (!Val
->getType()->isPointerTy() || !Ty
->isFirstClassType())
6942 return Error(Loc
, "load operand must be a pointer to a first class type");
6943 if (isAtomic
&& !Alignment
)
6944 return Error(Loc
, "atomic load must have explicit non-zero alignment");
6945 if (Ordering
== AtomicOrdering::Release
||
6946 Ordering
== AtomicOrdering::AcquireRelease
)
6947 return Error(Loc
, "atomic load cannot use Release ordering");
6949 if (Ty
!= cast
<PointerType
>(Val
->getType())->getElementType())
6950 return Error(ExplicitTypeLoc
,
6951 "explicit pointee type doesn't match operand's pointee type");
6953 Inst
= new LoadInst(Ty
, Val
, "", isVolatile
, Alignment
, Ordering
, SSID
);
6954 return AteExtraComma
? InstExtraComma
: InstNormal
;
6959 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6960 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6961 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6962 int LLParser::ParseStore(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6963 Value
*Val
, *Ptr
; LocTy Loc
, PtrLoc
;
6964 unsigned Alignment
= 0;
6965 bool AteExtraComma
= false;
6966 bool isAtomic
= false;
6967 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
6968 SyncScope::ID SSID
= SyncScope::System
;
6970 if (Lex
.getKind() == lltok::kw_atomic
) {
6975 bool isVolatile
= false;
6976 if (Lex
.getKind() == lltok::kw_volatile
) {
6981 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
6982 ParseToken(lltok::comma
, "expected ',' after store operand") ||
6983 ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
6984 ParseScopeAndOrdering(isAtomic
, SSID
, Ordering
) ||
6985 ParseOptionalCommaAlign(Alignment
, AteExtraComma
))
6988 if (!Ptr
->getType()->isPointerTy())
6989 return Error(PtrLoc
, "store operand must be a pointer");
6990 if (!Val
->getType()->isFirstClassType())
6991 return Error(Loc
, "store operand must be a first class value");
6992 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Val
->getType())
6993 return Error(Loc
, "stored value and pointer type do not match");
6994 if (isAtomic
&& !Alignment
)
6995 return Error(Loc
, "atomic store must have explicit non-zero alignment");
6996 if (Ordering
== AtomicOrdering::Acquire
||
6997 Ordering
== AtomicOrdering::AcquireRelease
)
6998 return Error(Loc
, "atomic store cannot use Acquire ordering");
7000 Inst
= new StoreInst(Val
, Ptr
, isVolatile
, Alignment
, Ordering
, SSID
);
7001 return AteExtraComma
? InstExtraComma
: InstNormal
;
7005 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7006 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
7007 int LLParser::ParseCmpXchg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7008 Value
*Ptr
, *Cmp
, *New
; LocTy PtrLoc
, CmpLoc
, NewLoc
;
7009 bool AteExtraComma
= false;
7010 AtomicOrdering SuccessOrdering
= AtomicOrdering::NotAtomic
;
7011 AtomicOrdering FailureOrdering
= AtomicOrdering::NotAtomic
;
7012 SyncScope::ID SSID
= SyncScope::System
;
7013 bool isVolatile
= false;
7014 bool isWeak
= false;
7016 if (EatIfPresent(lltok::kw_weak
))
7019 if (EatIfPresent(lltok::kw_volatile
))
7022 if (ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
7023 ParseToken(lltok::comma
, "expected ',' after cmpxchg address") ||
7024 ParseTypeAndValue(Cmp
, CmpLoc
, PFS
) ||
7025 ParseToken(lltok::comma
, "expected ',' after cmpxchg cmp operand") ||
7026 ParseTypeAndValue(New
, NewLoc
, PFS
) ||
7027 ParseScopeAndOrdering(true /*Always atomic*/, SSID
, SuccessOrdering
) ||
7028 ParseOrdering(FailureOrdering
))
7031 if (SuccessOrdering
== AtomicOrdering::Unordered
||
7032 FailureOrdering
== AtomicOrdering::Unordered
)
7033 return TokError("cmpxchg cannot be unordered");
7034 if (isStrongerThan(FailureOrdering
, SuccessOrdering
))
7035 return TokError("cmpxchg failure argument shall be no stronger than the "
7036 "success argument");
7037 if (FailureOrdering
== AtomicOrdering::Release
||
7038 FailureOrdering
== AtomicOrdering::AcquireRelease
)
7040 "cmpxchg failure ordering cannot include release semantics");
7041 if (!Ptr
->getType()->isPointerTy())
7042 return Error(PtrLoc
, "cmpxchg operand must be a pointer");
7043 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Cmp
->getType())
7044 return Error(CmpLoc
, "compare value and pointer type do not match");
7045 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != New
->getType())
7046 return Error(NewLoc
, "new value and pointer type do not match");
7047 if (!New
->getType()->isFirstClassType())
7048 return Error(NewLoc
, "cmpxchg operand must be a first class value");
7049 AtomicCmpXchgInst
*CXI
= new AtomicCmpXchgInst(
7050 Ptr
, Cmp
, New
, SuccessOrdering
, FailureOrdering
, SSID
);
7051 CXI
->setVolatile(isVolatile
);
7052 CXI
->setWeak(isWeak
);
7054 return AteExtraComma
? InstExtraComma
: InstNormal
;
7058 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7059 /// 'singlethread'? AtomicOrdering
7060 int LLParser::ParseAtomicRMW(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7061 Value
*Ptr
, *Val
; LocTy PtrLoc
, ValLoc
;
7062 bool AteExtraComma
= false;
7063 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7064 SyncScope::ID SSID
= SyncScope::System
;
7065 bool isVolatile
= false;
7067 AtomicRMWInst::BinOp Operation
;
7069 if (EatIfPresent(lltok::kw_volatile
))
7072 switch (Lex
.getKind()) {
7073 default: return TokError("expected binary operation in atomicrmw");
7074 case lltok::kw_xchg
: Operation
= AtomicRMWInst::Xchg
; break;
7075 case lltok::kw_add
: Operation
= AtomicRMWInst::Add
; break;
7076 case lltok::kw_sub
: Operation
= AtomicRMWInst::Sub
; break;
7077 case lltok::kw_and
: Operation
= AtomicRMWInst::And
; break;
7078 case lltok::kw_nand
: Operation
= AtomicRMWInst::Nand
; break;
7079 case lltok::kw_or
: Operation
= AtomicRMWInst::Or
; break;
7080 case lltok::kw_xor
: Operation
= AtomicRMWInst::Xor
; break;
7081 case lltok::kw_max
: Operation
= AtomicRMWInst::Max
; break;
7082 case lltok::kw_min
: Operation
= AtomicRMWInst::Min
; break;
7083 case lltok::kw_umax
: Operation
= AtomicRMWInst::UMax
; break;
7084 case lltok::kw_umin
: Operation
= AtomicRMWInst::UMin
; break;
7085 case lltok::kw_fadd
:
7086 Operation
= AtomicRMWInst::FAdd
;
7089 case lltok::kw_fsub
:
7090 Operation
= AtomicRMWInst::FSub
;
7094 Lex
.Lex(); // Eat the operation.
7096 if (ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
7097 ParseToken(lltok::comma
, "expected ',' after atomicrmw address") ||
7098 ParseTypeAndValue(Val
, ValLoc
, PFS
) ||
7099 ParseScopeAndOrdering(true /*Always atomic*/, SSID
, Ordering
))
7102 if (Ordering
== AtomicOrdering::Unordered
)
7103 return TokError("atomicrmw cannot be unordered");
7104 if (!Ptr
->getType()->isPointerTy())
7105 return Error(PtrLoc
, "atomicrmw operand must be a pointer");
7106 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Val
->getType())
7107 return Error(ValLoc
, "atomicrmw value and pointer type do not match");
7109 if (Operation
== AtomicRMWInst::Xchg
) {
7110 if (!Val
->getType()->isIntegerTy() &&
7111 !Val
->getType()->isFloatingPointTy()) {
7112 return Error(ValLoc
, "atomicrmw " +
7113 AtomicRMWInst::getOperationName(Operation
) +
7114 " operand must be an integer or floating point type");
7117 if (!Val
->getType()->isFloatingPointTy()) {
7118 return Error(ValLoc
, "atomicrmw " +
7119 AtomicRMWInst::getOperationName(Operation
) +
7120 " operand must be a floating point type");
7123 if (!Val
->getType()->isIntegerTy()) {
7124 return Error(ValLoc
, "atomicrmw " +
7125 AtomicRMWInst::getOperationName(Operation
) +
7126 " operand must be an integer");
7130 unsigned Size
= Val
->getType()->getPrimitiveSizeInBits();
7131 if (Size
< 8 || (Size
& (Size
- 1)))
7132 return Error(ValLoc
, "atomicrmw operand must be power-of-two byte-sized"
7135 AtomicRMWInst
*RMWI
=
7136 new AtomicRMWInst(Operation
, Ptr
, Val
, Ordering
, SSID
);
7137 RMWI
->setVolatile(isVolatile
);
7139 return AteExtraComma
? InstExtraComma
: InstNormal
;
7143 /// ::= 'fence' 'singlethread'? AtomicOrdering
7144 int LLParser::ParseFence(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7145 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7146 SyncScope::ID SSID
= SyncScope::System
;
7147 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID
, Ordering
))
7150 if (Ordering
== AtomicOrdering::Unordered
)
7151 return TokError("fence cannot be unordered");
7152 if (Ordering
== AtomicOrdering::Monotonic
)
7153 return TokError("fence cannot be monotonic");
7155 Inst
= new FenceInst(Context
, Ordering
, SSID
);
7159 /// ParseGetElementPtr
7160 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7161 int LLParser::ParseGetElementPtr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7162 Value
*Ptr
= nullptr;
7163 Value
*Val
= nullptr;
7166 bool InBounds
= EatIfPresent(lltok::kw_inbounds
);
7169 LocTy ExplicitTypeLoc
= Lex
.getLoc();
7170 if (ParseType(Ty
) ||
7171 ParseToken(lltok::comma
, "expected comma after getelementptr's type") ||
7172 ParseTypeAndValue(Ptr
, Loc
, PFS
))
7175 Type
*BaseType
= Ptr
->getType();
7176 PointerType
*BasePointerType
= dyn_cast
<PointerType
>(BaseType
->getScalarType());
7177 if (!BasePointerType
)
7178 return Error(Loc
, "base of getelementptr must be a pointer");
7180 if (Ty
!= BasePointerType
->getElementType())
7181 return Error(ExplicitTypeLoc
,
7182 "explicit pointee type doesn't match operand's pointee type");
7184 SmallVector
<Value
*, 16> Indices
;
7185 bool AteExtraComma
= false;
7186 // GEP returns a vector of pointers if at least one of parameters is a vector.
7187 // All vector parameters should have the same vector width.
7188 unsigned GEPWidth
= BaseType
->isVectorTy() ?
7189 BaseType
->getVectorNumElements() : 0;
7191 while (EatIfPresent(lltok::comma
)) {
7192 if (Lex
.getKind() == lltok::MetadataVar
) {
7193 AteExtraComma
= true;
7196 if (ParseTypeAndValue(Val
, EltLoc
, PFS
)) return true;
7197 if (!Val
->getType()->isIntOrIntVectorTy())
7198 return Error(EltLoc
, "getelementptr index must be an integer");
7200 if (Val
->getType()->isVectorTy()) {
7201 unsigned ValNumEl
= Val
->getType()->getVectorNumElements();
7202 if (GEPWidth
&& GEPWidth
!= ValNumEl
)
7203 return Error(EltLoc
,
7204 "getelementptr vector index has a wrong number of elements");
7205 GEPWidth
= ValNumEl
;
7207 Indices
.push_back(Val
);
7210 SmallPtrSet
<Type
*, 4> Visited
;
7211 if (!Indices
.empty() && !Ty
->isSized(&Visited
))
7212 return Error(Loc
, "base element of getelementptr must be sized");
7214 if (!GetElementPtrInst::getIndexedType(Ty
, Indices
))
7215 return Error(Loc
, "invalid getelementptr indices");
7216 Inst
= GetElementPtrInst::Create(Ty
, Ptr
, Indices
);
7218 cast
<GetElementPtrInst
>(Inst
)->setIsInBounds(true);
7219 return AteExtraComma
? InstExtraComma
: InstNormal
;
7222 /// ParseExtractValue
7223 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
7224 int LLParser::ParseExtractValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7225 Value
*Val
; LocTy Loc
;
7226 SmallVector
<unsigned, 4> Indices
;
7228 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
7229 ParseIndexList(Indices
, AteExtraComma
))
7232 if (!Val
->getType()->isAggregateType())
7233 return Error(Loc
, "extractvalue operand must be aggregate type");
7235 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
))
7236 return Error(Loc
, "invalid indices for extractvalue");
7237 Inst
= ExtractValueInst::Create(Val
, Indices
);
7238 return AteExtraComma
? InstExtraComma
: InstNormal
;
7241 /// ParseInsertValue
7242 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7243 int LLParser::ParseInsertValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7244 Value
*Val0
, *Val1
; LocTy Loc0
, Loc1
;
7245 SmallVector
<unsigned, 4> Indices
;
7247 if (ParseTypeAndValue(Val0
, Loc0
, PFS
) ||
7248 ParseToken(lltok::comma
, "expected comma after insertvalue operand") ||
7249 ParseTypeAndValue(Val1
, Loc1
, PFS
) ||
7250 ParseIndexList(Indices
, AteExtraComma
))
7253 if (!Val0
->getType()->isAggregateType())
7254 return Error(Loc0
, "insertvalue operand must be aggregate type");
7256 Type
*IndexedType
= ExtractValueInst::getIndexedType(Val0
->getType(), Indices
);
7258 return Error(Loc0
, "invalid indices for insertvalue");
7259 if (IndexedType
!= Val1
->getType())
7260 return Error(Loc1
, "insertvalue operand and field disagree in type: '" +
7261 getTypeString(Val1
->getType()) + "' instead of '" +
7262 getTypeString(IndexedType
) + "'");
7263 Inst
= InsertValueInst::Create(Val0
, Val1
, Indices
);
7264 return AteExtraComma
? InstExtraComma
: InstNormal
;
7267 //===----------------------------------------------------------------------===//
7268 // Embedded metadata.
7269 //===----------------------------------------------------------------------===//
7271 /// ParseMDNodeVector
7272 /// ::= { Element (',' Element)* }
7274 /// ::= 'null' | TypeAndValue
7275 bool LLParser::ParseMDNodeVector(SmallVectorImpl
<Metadata
*> &Elts
) {
7276 if (ParseToken(lltok::lbrace
, "expected '{' here"))
7279 // Check for an empty list.
7280 if (EatIfPresent(lltok::rbrace
))
7284 // Null is a special case since it is typeless.
7285 if (EatIfPresent(lltok::kw_null
)) {
7286 Elts
.push_back(nullptr);
7291 if (ParseMetadata(MD
, nullptr))
7294 } while (EatIfPresent(lltok::comma
));
7296 return ParseToken(lltok::rbrace
, "expected end of metadata node");
7299 //===----------------------------------------------------------------------===//
7300 // Use-list order directives.
7301 //===----------------------------------------------------------------------===//
7302 bool LLParser::sortUseListOrder(Value
*V
, ArrayRef
<unsigned> Indexes
,
7305 return Error(Loc
, "value has no uses");
7307 unsigned NumUses
= 0;
7308 SmallDenseMap
<const Use
*, unsigned, 16> Order
;
7309 for (const Use
&U
: V
->uses()) {
7310 if (++NumUses
> Indexes
.size())
7312 Order
[&U
] = Indexes
[NumUses
- 1];
7315 return Error(Loc
, "value only has one use");
7316 if (Order
.size() != Indexes
.size() || NumUses
> Indexes
.size())
7318 "wrong number of indexes, expected " + Twine(V
->getNumUses()));
7320 V
->sortUseList([&](const Use
&L
, const Use
&R
) {
7321 return Order
.lookup(&L
) < Order
.lookup(&R
);
7326 /// ParseUseListOrderIndexes
7327 /// ::= '{' uint32 (',' uint32)+ '}'
7328 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl
<unsigned> &Indexes
) {
7329 SMLoc Loc
= Lex
.getLoc();
7330 if (ParseToken(lltok::lbrace
, "expected '{' here"))
7332 if (Lex
.getKind() == lltok::rbrace
)
7333 return Lex
.Error("expected non-empty list of uselistorder indexes");
7335 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7336 // indexes should be distinct numbers in the range [0, size-1], and should
7338 unsigned Offset
= 0;
7340 bool IsOrdered
= true;
7341 assert(Indexes
.empty() && "Expected empty order vector");
7344 if (ParseUInt32(Index
))
7347 // Update consistency checks.
7348 Offset
+= Index
- Indexes
.size();
7349 Max
= std::max(Max
, Index
);
7350 IsOrdered
&= Index
== Indexes
.size();
7352 Indexes
.push_back(Index
);
7353 } while (EatIfPresent(lltok::comma
));
7355 if (ParseToken(lltok::rbrace
, "expected '}' here"))
7358 if (Indexes
.size() < 2)
7359 return Error(Loc
, "expected >= 2 uselistorder indexes");
7360 if (Offset
!= 0 || Max
>= Indexes
.size())
7361 return Error(Loc
, "expected distinct uselistorder indexes in range [0, size)");
7363 return Error(Loc
, "expected uselistorder indexes to change the order");
7368 /// ParseUseListOrder
7369 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7370 bool LLParser::ParseUseListOrder(PerFunctionState
*PFS
) {
7371 SMLoc Loc
= Lex
.getLoc();
7372 if (ParseToken(lltok::kw_uselistorder
, "expected uselistorder directive"))
7376 SmallVector
<unsigned, 16> Indexes
;
7377 if (ParseTypeAndValue(V
, PFS
) ||
7378 ParseToken(lltok::comma
, "expected comma in uselistorder directive") ||
7379 ParseUseListOrderIndexes(Indexes
))
7382 return sortUseListOrder(V
, Indexes
, Loc
);
7385 /// ParseUseListOrderBB
7386 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7387 bool LLParser::ParseUseListOrderBB() {
7388 assert(Lex
.getKind() == lltok::kw_uselistorder_bb
);
7389 SMLoc Loc
= Lex
.getLoc();
7393 SmallVector
<unsigned, 16> Indexes
;
7394 if (ParseValID(Fn
) ||
7395 ParseToken(lltok::comma
, "expected comma in uselistorder_bb directive") ||
7396 ParseValID(Label
) ||
7397 ParseToken(lltok::comma
, "expected comma in uselistorder_bb directive") ||
7398 ParseUseListOrderIndexes(Indexes
))
7401 // Check the function.
7403 if (Fn
.Kind
== ValID::t_GlobalName
)
7404 GV
= M
->getNamedValue(Fn
.StrVal
);
7405 else if (Fn
.Kind
== ValID::t_GlobalID
)
7406 GV
= Fn
.UIntVal
< NumberedVals
.size() ? NumberedVals
[Fn
.UIntVal
] : nullptr;
7408 return Error(Fn
.Loc
, "expected function name in uselistorder_bb");
7410 return Error(Fn
.Loc
, "invalid function forward reference in uselistorder_bb");
7411 auto *F
= dyn_cast
<Function
>(GV
);
7413 return Error(Fn
.Loc
, "expected function name in uselistorder_bb");
7414 if (F
->isDeclaration())
7415 return Error(Fn
.Loc
, "invalid declaration in uselistorder_bb");
7417 // Check the basic block.
7418 if (Label
.Kind
== ValID::t_LocalID
)
7419 return Error(Label
.Loc
, "invalid numeric label in uselistorder_bb");
7420 if (Label
.Kind
!= ValID::t_LocalName
)
7421 return Error(Label
.Loc
, "expected basic block name in uselistorder_bb");
7422 Value
*V
= F
->getValueSymbolTable()->lookup(Label
.StrVal
);
7424 return Error(Label
.Loc
, "invalid basic block in uselistorder_bb");
7425 if (!isa
<BasicBlock
>(V
))
7426 return Error(Label
.Loc
, "expected basic block in uselistorder_bb");
7428 return sortUseListOrder(V
, Indexes
, Loc
);
7432 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7433 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7434 bool LLParser::ParseModuleEntry(unsigned ID
) {
7435 assert(Lex
.getKind() == lltok::kw_module
);
7439 if (ParseToken(lltok::colon
, "expected ':' here") ||
7440 ParseToken(lltok::lparen
, "expected '(' here") ||
7441 ParseToken(lltok::kw_path
, "expected 'path' here") ||
7442 ParseToken(lltok::colon
, "expected ':' here") ||
7443 ParseStringConstant(Path
) ||
7444 ParseToken(lltok::comma
, "expected ',' here") ||
7445 ParseToken(lltok::kw_hash
, "expected 'hash' here") ||
7446 ParseToken(lltok::colon
, "expected ':' here") ||
7447 ParseToken(lltok::lparen
, "expected '(' here"))
7451 if (ParseUInt32(Hash
[0]) || ParseToken(lltok::comma
, "expected ',' here") ||
7452 ParseUInt32(Hash
[1]) || ParseToken(lltok::comma
, "expected ',' here") ||
7453 ParseUInt32(Hash
[2]) || ParseToken(lltok::comma
, "expected ',' here") ||
7454 ParseUInt32(Hash
[3]) || ParseToken(lltok::comma
, "expected ',' here") ||
7455 ParseUInt32(Hash
[4]))
7458 if (ParseToken(lltok::rparen
, "expected ')' here") ||
7459 ParseToken(lltok::rparen
, "expected ')' here"))
7462 auto ModuleEntry
= Index
->addModule(Path
, ID
, Hash
);
7463 ModuleIdMap
[ID
] = ModuleEntry
->first();
7469 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7470 bool LLParser::ParseTypeIdEntry(unsigned ID
) {
7471 assert(Lex
.getKind() == lltok::kw_typeid
);
7475 if (ParseToken(lltok::colon
, "expected ':' here") ||
7476 ParseToken(lltok::lparen
, "expected '(' here") ||
7477 ParseToken(lltok::kw_name
, "expected 'name' here") ||
7478 ParseToken(lltok::colon
, "expected ':' here") ||
7479 ParseStringConstant(Name
))
7482 TypeIdSummary
&TIS
= Index
->getOrInsertTypeIdSummary(Name
);
7483 if (ParseToken(lltok::comma
, "expected ',' here") ||
7484 ParseTypeIdSummary(TIS
) || ParseToken(lltok::rparen
, "expected ')' here"))
7487 // Check if this ID was forward referenced, and if so, update the
7488 // corresponding GUIDs.
7489 auto FwdRefTIDs
= ForwardRefTypeIds
.find(ID
);
7490 if (FwdRefTIDs
!= ForwardRefTypeIds
.end()) {
7491 for (auto TIDRef
: FwdRefTIDs
->second
) {
7492 assert(!*TIDRef
.first
&&
7493 "Forward referenced type id GUID expected to be 0");
7494 *TIDRef
.first
= GlobalValue::getGUID(Name
);
7496 ForwardRefTypeIds
.erase(FwdRefTIDs
);
7503 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7504 bool LLParser::ParseTypeIdSummary(TypeIdSummary
&TIS
) {
7505 if (ParseToken(lltok::kw_summary
, "expected 'summary' here") ||
7506 ParseToken(lltok::colon
, "expected ':' here") ||
7507 ParseToken(lltok::lparen
, "expected '(' here") ||
7508 ParseTypeTestResolution(TIS
.TTRes
))
7511 if (EatIfPresent(lltok::comma
)) {
7512 // Expect optional wpdResolutions field
7513 if (ParseOptionalWpdResolutions(TIS
.WPDRes
))
7517 if (ParseToken(lltok::rparen
, "expected ')' here"))
7523 static ValueInfo EmptyVI
=
7524 ValueInfo(false, (GlobalValueSummaryMapTy::value_type
*)-8);
7526 /// TypeIdCompatibleVtableEntry
7527 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
7528 /// TypeIdCompatibleVtableInfo
7530 bool LLParser::ParseTypeIdCompatibleVtableEntry(unsigned ID
) {
7531 assert(Lex
.getKind() == lltok::kw_typeidCompatibleVTable
);
7535 if (ParseToken(lltok::colon
, "expected ':' here") ||
7536 ParseToken(lltok::lparen
, "expected '(' here") ||
7537 ParseToken(lltok::kw_name
, "expected 'name' here") ||
7538 ParseToken(lltok::colon
, "expected ':' here") ||
7539 ParseStringConstant(Name
))
7542 TypeIdCompatibleVtableInfo
&TI
=
7543 Index
->getOrInsertTypeIdCompatibleVtableSummary(Name
);
7544 if (ParseToken(lltok::comma
, "expected ',' here") ||
7545 ParseToken(lltok::kw_summary
, "expected 'summary' here") ||
7546 ParseToken(lltok::colon
, "expected ':' here") ||
7547 ParseToken(lltok::lparen
, "expected '(' here"))
7550 IdToIndexMapType IdToIndexMap
;
7551 // Parse each call edge
7554 if (ParseToken(lltok::lparen
, "expected '(' here") ||
7555 ParseToken(lltok::kw_offset
, "expected 'offset' here") ||
7556 ParseToken(lltok::colon
, "expected ':' here") || ParseUInt64(Offset
) ||
7557 ParseToken(lltok::comma
, "expected ',' here"))
7560 LocTy Loc
= Lex
.getLoc();
7563 if (ParseGVReference(VI
, GVId
))
7566 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
7567 // forward reference. We will save the location of the ValueInfo needing an
7568 // update, but can only do so once the std::vector is finalized.
7570 IdToIndexMap
[GVId
].push_back(std::make_pair(TI
.size(), Loc
));
7571 TI
.push_back({Offset
, VI
});
7573 if (ParseToken(lltok::rparen
, "expected ')' in call"))
7575 } while (EatIfPresent(lltok::comma
));
7577 // Now that the TI vector is finalized, it is safe to save the locations
7578 // of any forward GV references that need updating later.
7579 for (auto I
: IdToIndexMap
) {
7580 for (auto P
: I
.second
) {
7581 assert(TI
[P
.first
].VTableVI
== EmptyVI
&&
7582 "Forward referenced ValueInfo expected to be empty");
7583 auto FwdRef
= ForwardRefValueInfos
.insert(std::make_pair(
7584 I
.first
, std::vector
<std::pair
<ValueInfo
*, LocTy
>>()));
7585 FwdRef
.first
->second
.push_back(
7586 std::make_pair(&TI
[P
.first
].VTableVI
, P
.second
));
7590 if (ParseToken(lltok::rparen
, "expected ')' here") ||
7591 ParseToken(lltok::rparen
, "expected ')' here"))
7594 // Check if this ID was forward referenced, and if so, update the
7595 // corresponding GUIDs.
7596 auto FwdRefTIDs
= ForwardRefTypeIds
.find(ID
);
7597 if (FwdRefTIDs
!= ForwardRefTypeIds
.end()) {
7598 for (auto TIDRef
: FwdRefTIDs
->second
) {
7599 assert(!*TIDRef
.first
&&
7600 "Forward referenced type id GUID expected to be 0");
7601 *TIDRef
.first
= GlobalValue::getGUID(Name
);
7603 ForwardRefTypeIds
.erase(FwdRefTIDs
);
7609 /// TypeTestResolution
7610 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
7611 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7612 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7613 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7614 /// [',' 'inlinesBits' ':' UInt64]? ')'
7615 bool LLParser::ParseTypeTestResolution(TypeTestResolution
&TTRes
) {
7616 if (ParseToken(lltok::kw_typeTestRes
, "expected 'typeTestRes' here") ||
7617 ParseToken(lltok::colon
, "expected ':' here") ||
7618 ParseToken(lltok::lparen
, "expected '(' here") ||
7619 ParseToken(lltok::kw_kind
, "expected 'kind' here") ||
7620 ParseToken(lltok::colon
, "expected ':' here"))
7623 switch (Lex
.getKind()) {
7624 case lltok::kw_unsat
:
7625 TTRes
.TheKind
= TypeTestResolution::Unsat
;
7627 case lltok::kw_byteArray
:
7628 TTRes
.TheKind
= TypeTestResolution::ByteArray
;
7630 case lltok::kw_inline
:
7631 TTRes
.TheKind
= TypeTestResolution::Inline
;
7633 case lltok::kw_single
:
7634 TTRes
.TheKind
= TypeTestResolution::Single
;
7636 case lltok::kw_allOnes
:
7637 TTRes
.TheKind
= TypeTestResolution::AllOnes
;
7640 return Error(Lex
.getLoc(), "unexpected TypeTestResolution kind");
7644 if (ParseToken(lltok::comma
, "expected ',' here") ||
7645 ParseToken(lltok::kw_sizeM1BitWidth
, "expected 'sizeM1BitWidth' here") ||
7646 ParseToken(lltok::colon
, "expected ':' here") ||
7647 ParseUInt32(TTRes
.SizeM1BitWidth
))
7650 // Parse optional fields
7651 while (EatIfPresent(lltok::comma
)) {
7652 switch (Lex
.getKind()) {
7653 case lltok::kw_alignLog2
:
7655 if (ParseToken(lltok::colon
, "expected ':'") ||
7656 ParseUInt64(TTRes
.AlignLog2
))
7659 case lltok::kw_sizeM1
:
7661 if (ParseToken(lltok::colon
, "expected ':'") || ParseUInt64(TTRes
.SizeM1
))
7664 case lltok::kw_bitMask
: {
7667 if (ParseToken(lltok::colon
, "expected ':'") || ParseUInt32(Val
))
7669 assert(Val
<= 0xff);
7670 TTRes
.BitMask
= (uint8_t)Val
;
7673 case lltok::kw_inlineBits
:
7675 if (ParseToken(lltok::colon
, "expected ':'") ||
7676 ParseUInt64(TTRes
.InlineBits
))
7680 return Error(Lex
.getLoc(), "expected optional TypeTestResolution field");
7684 if (ParseToken(lltok::rparen
, "expected ')' here"))
7690 /// OptionalWpdResolutions
7691 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7692 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7693 bool LLParser::ParseOptionalWpdResolutions(
7694 std::map
<uint64_t, WholeProgramDevirtResolution
> &WPDResMap
) {
7695 if (ParseToken(lltok::kw_wpdResolutions
, "expected 'wpdResolutions' here") ||
7696 ParseToken(lltok::colon
, "expected ':' here") ||
7697 ParseToken(lltok::lparen
, "expected '(' here"))
7702 WholeProgramDevirtResolution WPDRes
;
7703 if (ParseToken(lltok::lparen
, "expected '(' here") ||
7704 ParseToken(lltok::kw_offset
, "expected 'offset' here") ||
7705 ParseToken(lltok::colon
, "expected ':' here") || ParseUInt64(Offset
) ||
7706 ParseToken(lltok::comma
, "expected ',' here") || ParseWpdRes(WPDRes
) ||
7707 ParseToken(lltok::rparen
, "expected ')' here"))
7709 WPDResMap
[Offset
] = WPDRes
;
7710 } while (EatIfPresent(lltok::comma
));
7712 if (ParseToken(lltok::rparen
, "expected ')' here"))
7719 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7720 /// [',' OptionalResByArg]? ')'
7721 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7722 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
7723 /// [',' OptionalResByArg]? ')'
7724 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7725 /// [',' OptionalResByArg]? ')'
7726 bool LLParser::ParseWpdRes(WholeProgramDevirtResolution
&WPDRes
) {
7727 if (ParseToken(lltok::kw_wpdRes
, "expected 'wpdRes' here") ||
7728 ParseToken(lltok::colon
, "expected ':' here") ||
7729 ParseToken(lltok::lparen
, "expected '(' here") ||
7730 ParseToken(lltok::kw_kind
, "expected 'kind' here") ||
7731 ParseToken(lltok::colon
, "expected ':' here"))
7734 switch (Lex
.getKind()) {
7735 case lltok::kw_indir
:
7736 WPDRes
.TheKind
= WholeProgramDevirtResolution::Indir
;
7738 case lltok::kw_singleImpl
:
7739 WPDRes
.TheKind
= WholeProgramDevirtResolution::SingleImpl
;
7741 case lltok::kw_branchFunnel
:
7742 WPDRes
.TheKind
= WholeProgramDevirtResolution::BranchFunnel
;
7745 return Error(Lex
.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7749 // Parse optional fields
7750 while (EatIfPresent(lltok::comma
)) {
7751 switch (Lex
.getKind()) {
7752 case lltok::kw_singleImplName
:
7754 if (ParseToken(lltok::colon
, "expected ':' here") ||
7755 ParseStringConstant(WPDRes
.SingleImplName
))
7758 case lltok::kw_resByArg
:
7759 if (ParseOptionalResByArg(WPDRes
.ResByArg
))
7763 return Error(Lex
.getLoc(),
7764 "expected optional WholeProgramDevirtResolution field");
7768 if (ParseToken(lltok::rparen
, "expected ')' here"))
7774 /// OptionalResByArg
7775 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7776 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7777 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7778 /// 'virtualConstProp' )
7779 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7780 /// [',' 'bit' ':' UInt32]? ')'
7781 bool LLParser::ParseOptionalResByArg(
7782 std::map
<std::vector
<uint64_t>, WholeProgramDevirtResolution::ByArg
>
7784 if (ParseToken(lltok::kw_resByArg
, "expected 'resByArg' here") ||
7785 ParseToken(lltok::colon
, "expected ':' here") ||
7786 ParseToken(lltok::lparen
, "expected '(' here"))
7790 std::vector
<uint64_t> Args
;
7791 if (ParseArgs(Args
) || ParseToken(lltok::comma
, "expected ',' here") ||
7792 ParseToken(lltok::kw_byArg
, "expected 'byArg here") ||
7793 ParseToken(lltok::colon
, "expected ':' here") ||
7794 ParseToken(lltok::lparen
, "expected '(' here") ||
7795 ParseToken(lltok::kw_kind
, "expected 'kind' here") ||
7796 ParseToken(lltok::colon
, "expected ':' here"))
7799 WholeProgramDevirtResolution::ByArg ByArg
;
7800 switch (Lex
.getKind()) {
7801 case lltok::kw_indir
:
7802 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::Indir
;
7804 case lltok::kw_uniformRetVal
:
7805 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::UniformRetVal
;
7807 case lltok::kw_uniqueRetVal
:
7808 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::UniqueRetVal
;
7810 case lltok::kw_virtualConstProp
:
7811 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::VirtualConstProp
;
7814 return Error(Lex
.getLoc(),
7815 "unexpected WholeProgramDevirtResolution::ByArg kind");
7819 // Parse optional fields
7820 while (EatIfPresent(lltok::comma
)) {
7821 switch (Lex
.getKind()) {
7822 case lltok::kw_info
:
7824 if (ParseToken(lltok::colon
, "expected ':' here") ||
7825 ParseUInt64(ByArg
.Info
))
7828 case lltok::kw_byte
:
7830 if (ParseToken(lltok::colon
, "expected ':' here") ||
7831 ParseUInt32(ByArg
.Byte
))
7836 if (ParseToken(lltok::colon
, "expected ':' here") ||
7837 ParseUInt32(ByArg
.Bit
))
7841 return Error(Lex
.getLoc(),
7842 "expected optional whole program devirt field");
7846 if (ParseToken(lltok::rparen
, "expected ')' here"))
7849 ResByArg
[Args
] = ByArg
;
7850 } while (EatIfPresent(lltok::comma
));
7852 if (ParseToken(lltok::rparen
, "expected ')' here"))
7858 /// OptionalResByArg
7859 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7860 bool LLParser::ParseArgs(std::vector
<uint64_t> &Args
) {
7861 if (ParseToken(lltok::kw_args
, "expected 'args' here") ||
7862 ParseToken(lltok::colon
, "expected ':' here") ||
7863 ParseToken(lltok::lparen
, "expected '(' here"))
7868 if (ParseUInt64(Val
))
7870 Args
.push_back(Val
);
7871 } while (EatIfPresent(lltok::comma
));
7873 if (ParseToken(lltok::rparen
, "expected ')' here"))
7879 static const auto FwdVIRef
= (GlobalValueSummaryMapTy::value_type
*)-8;
7881 static void resolveFwdRef(ValueInfo
*Fwd
, ValueInfo
&Resolved
) {
7882 bool ReadOnly
= Fwd
->isReadOnly();
7883 bool WriteOnly
= Fwd
->isWriteOnly();
7884 assert(!(ReadOnly
&& WriteOnly
));
7889 Fwd
->setWriteOnly();
7892 /// Stores the given Name/GUID and associated summary into the Index.
7893 /// Also updates any forward references to the associated entry ID.
7894 void LLParser::AddGlobalValueToIndex(
7895 std::string Name
, GlobalValue::GUID GUID
, GlobalValue::LinkageTypes Linkage
,
7896 unsigned ID
, std::unique_ptr
<GlobalValueSummary
> Summary
) {
7897 // First create the ValueInfo utilizing the Name or GUID.
7900 assert(Name
.empty());
7901 VI
= Index
->getOrInsertValueInfo(GUID
);
7903 assert(!Name
.empty());
7905 auto *GV
= M
->getNamedValue(Name
);
7907 VI
= Index
->getOrInsertValueInfo(GV
);
7910 (!GlobalValue::isLocalLinkage(Linkage
) || !SourceFileName
.empty()) &&
7911 "Need a source_filename to compute GUID for local");
7912 GUID
= GlobalValue::getGUID(
7913 GlobalValue::getGlobalIdentifier(Name
, Linkage
, SourceFileName
));
7914 VI
= Index
->getOrInsertValueInfo(GUID
, Index
->saveString(Name
));
7918 // Resolve forward references from calls/refs
7919 auto FwdRefVIs
= ForwardRefValueInfos
.find(ID
);
7920 if (FwdRefVIs
!= ForwardRefValueInfos
.end()) {
7921 for (auto VIRef
: FwdRefVIs
->second
) {
7922 assert(VIRef
.first
->getRef() == FwdVIRef
&&
7923 "Forward referenced ValueInfo expected to be empty");
7924 resolveFwdRef(VIRef
.first
, VI
);
7926 ForwardRefValueInfos
.erase(FwdRefVIs
);
7929 // Resolve forward references from aliases
7930 auto FwdRefAliasees
= ForwardRefAliasees
.find(ID
);
7931 if (FwdRefAliasees
!= ForwardRefAliasees
.end()) {
7932 for (auto AliaseeRef
: FwdRefAliasees
->second
) {
7933 assert(!AliaseeRef
.first
->hasAliasee() &&
7934 "Forward referencing alias already has aliasee");
7935 assert(Summary
&& "Aliasee must be a definition");
7936 AliaseeRef
.first
->setAliasee(VI
, Summary
.get());
7938 ForwardRefAliasees
.erase(FwdRefAliasees
);
7941 // Add the summary if one was provided.
7943 Index
->addGlobalValueSummary(VI
, std::move(Summary
));
7945 // Save the associated ValueInfo for use in later references by ID.
7946 if (ID
== NumberedValueInfos
.size())
7947 NumberedValueInfos
.push_back(VI
);
7949 // Handle non-continuous numbers (to make test simplification easier).
7950 if (ID
> NumberedValueInfos
.size())
7951 NumberedValueInfos
.resize(ID
+ 1);
7952 NumberedValueInfos
[ID
] = VI
;
7957 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7958 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7959 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7960 bool LLParser::ParseGVEntry(unsigned ID
) {
7961 assert(Lex
.getKind() == lltok::kw_gv
);
7964 if (ParseToken(lltok::colon
, "expected ':' here") ||
7965 ParseToken(lltok::lparen
, "expected '(' here"))
7969 GlobalValue::GUID GUID
= 0;
7970 switch (Lex
.getKind()) {
7971 case lltok::kw_name
:
7973 if (ParseToken(lltok::colon
, "expected ':' here") ||
7974 ParseStringConstant(Name
))
7976 // Can't create GUID/ValueInfo until we have the linkage.
7978 case lltok::kw_guid
:
7980 if (ParseToken(lltok::colon
, "expected ':' here") || ParseUInt64(GUID
))
7984 return Error(Lex
.getLoc(), "expected name or guid tag");
7987 if (!EatIfPresent(lltok::comma
)) {
7988 // No summaries. Wrap up.
7989 if (ParseToken(lltok::rparen
, "expected ')' here"))
7991 // This was created for a call to an external or indirect target.
7992 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
7993 // created for indirect calls with VP. A Name with no GUID came from
7994 // an external definition. We pass ExternalLinkage since that is only
7995 // used when the GUID must be computed from Name, and in that case
7996 // the symbol must have external linkage.
7997 AddGlobalValueToIndex(Name
, GUID
, GlobalValue::ExternalLinkage
, ID
,
8002 // Have a list of summaries
8003 if (ParseToken(lltok::kw_summaries
, "expected 'summaries' here") ||
8004 ParseToken(lltok::colon
, "expected ':' here"))
8008 if (ParseToken(lltok::lparen
, "expected '(' here"))
8010 switch (Lex
.getKind()) {
8011 case lltok::kw_function
:
8012 if (ParseFunctionSummary(Name
, GUID
, ID
))
8015 case lltok::kw_variable
:
8016 if (ParseVariableSummary(Name
, GUID
, ID
))
8019 case lltok::kw_alias
:
8020 if (ParseAliasSummary(Name
, GUID
, ID
))
8024 return Error(Lex
.getLoc(), "expected summary type");
8026 if (ParseToken(lltok::rparen
, "expected ')' here"))
8028 } while (EatIfPresent(lltok::comma
));
8030 if (ParseToken(lltok::rparen
, "expected ')' here"))
8037 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8038 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8039 /// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
8040 bool LLParser::ParseFunctionSummary(std::string Name
, GlobalValue::GUID GUID
,
8042 assert(Lex
.getKind() == lltok::kw_function
);
8045 StringRef ModulePath
;
8046 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
8047 /*Linkage=*/GlobalValue::ExternalLinkage
, /*NotEligibleToImport=*/false,
8048 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8050 std::vector
<FunctionSummary::EdgeTy
> Calls
;
8051 FunctionSummary::TypeIdInfo TypeIdInfo
;
8052 std::vector
<ValueInfo
> Refs
;
8053 // Default is all-zeros (conservative values).
8054 FunctionSummary::FFlags FFlags
= {};
8055 if (ParseToken(lltok::colon
, "expected ':' here") ||
8056 ParseToken(lltok::lparen
, "expected '(' here") ||
8057 ParseModuleReference(ModulePath
) ||
8058 ParseToken(lltok::comma
, "expected ',' here") || ParseGVFlags(GVFlags
) ||
8059 ParseToken(lltok::comma
, "expected ',' here") ||
8060 ParseToken(lltok::kw_insts
, "expected 'insts' here") ||
8061 ParseToken(lltok::colon
, "expected ':' here") || ParseUInt32(InstCount
))
8064 // Parse optional fields
8065 while (EatIfPresent(lltok::comma
)) {
8066 switch (Lex
.getKind()) {
8067 case lltok::kw_funcFlags
:
8068 if (ParseOptionalFFlags(FFlags
))
8071 case lltok::kw_calls
:
8072 if (ParseOptionalCalls(Calls
))
8075 case lltok::kw_typeIdInfo
:
8076 if (ParseOptionalTypeIdInfo(TypeIdInfo
))
8079 case lltok::kw_refs
:
8080 if (ParseOptionalRefs(Refs
))
8084 return Error(Lex
.getLoc(), "expected optional function summary field");
8088 if (ParseToken(lltok::rparen
, "expected ')' here"))
8091 auto FS
= std::make_unique
<FunctionSummary
>(
8092 GVFlags
, InstCount
, FFlags
, /*EntryCount=*/0, std::move(Refs
),
8093 std::move(Calls
), std::move(TypeIdInfo
.TypeTests
),
8094 std::move(TypeIdInfo
.TypeTestAssumeVCalls
),
8095 std::move(TypeIdInfo
.TypeCheckedLoadVCalls
),
8096 std::move(TypeIdInfo
.TypeTestAssumeConstVCalls
),
8097 std::move(TypeIdInfo
.TypeCheckedLoadConstVCalls
));
8099 FS
->setModulePath(ModulePath
);
8101 AddGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
8108 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8109 /// [',' OptionalRefs]? ')'
8110 bool LLParser::ParseVariableSummary(std::string Name
, GlobalValue::GUID GUID
,
8112 assert(Lex
.getKind() == lltok::kw_variable
);
8115 StringRef ModulePath
;
8116 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
8117 /*Linkage=*/GlobalValue::ExternalLinkage
, /*NotEligibleToImport=*/false,
8118 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8119 GlobalVarSummary::GVarFlags
GVarFlags(/*ReadOnly*/ false,
8120 /* WriteOnly */ false);
8121 std::vector
<ValueInfo
> Refs
;
8122 VTableFuncList VTableFuncs
;
8123 if (ParseToken(lltok::colon
, "expected ':' here") ||
8124 ParseToken(lltok::lparen
, "expected '(' here") ||
8125 ParseModuleReference(ModulePath
) ||
8126 ParseToken(lltok::comma
, "expected ',' here") || ParseGVFlags(GVFlags
) ||
8127 ParseToken(lltok::comma
, "expected ',' here") ||
8128 ParseGVarFlags(GVarFlags
))
8131 // Parse optional fields
8132 while (EatIfPresent(lltok::comma
)) {
8133 switch (Lex
.getKind()) {
8134 case lltok::kw_vTableFuncs
:
8135 if (ParseOptionalVTableFuncs(VTableFuncs
))
8138 case lltok::kw_refs
:
8139 if (ParseOptionalRefs(Refs
))
8143 return Error(Lex
.getLoc(), "expected optional variable summary field");
8147 if (ParseToken(lltok::rparen
, "expected ')' here"))
8151 std::make_unique
<GlobalVarSummary
>(GVFlags
, GVarFlags
, std::move(Refs
));
8153 GS
->setModulePath(ModulePath
);
8154 GS
->setVTableFuncs(std::move(VTableFuncs
));
8156 AddGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
8163 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8164 /// 'aliasee' ':' GVReference ')'
8165 bool LLParser::ParseAliasSummary(std::string Name
, GlobalValue::GUID GUID
,
8167 assert(Lex
.getKind() == lltok::kw_alias
);
8168 LocTy Loc
= Lex
.getLoc();
8171 StringRef ModulePath
;
8172 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
8173 /*Linkage=*/GlobalValue::ExternalLinkage
, /*NotEligibleToImport=*/false,
8174 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8175 if (ParseToken(lltok::colon
, "expected ':' here") ||
8176 ParseToken(lltok::lparen
, "expected '(' here") ||
8177 ParseModuleReference(ModulePath
) ||
8178 ParseToken(lltok::comma
, "expected ',' here") || ParseGVFlags(GVFlags
) ||
8179 ParseToken(lltok::comma
, "expected ',' here") ||
8180 ParseToken(lltok::kw_aliasee
, "expected 'aliasee' here") ||
8181 ParseToken(lltok::colon
, "expected ':' here"))
8184 ValueInfo AliaseeVI
;
8186 if (ParseGVReference(AliaseeVI
, GVId
))
8189 if (ParseToken(lltok::rparen
, "expected ')' here"))
8192 auto AS
= std::make_unique
<AliasSummary
>(GVFlags
);
8194 AS
->setModulePath(ModulePath
);
8196 // Record forward reference if the aliasee is not parsed yet.
8197 if (AliaseeVI
.getRef() == FwdVIRef
) {
8198 auto FwdRef
= ForwardRefAliasees
.insert(
8199 std::make_pair(GVId
, std::vector
<std::pair
<AliasSummary
*, LocTy
>>()));
8200 FwdRef
.first
->second
.push_back(std::make_pair(AS
.get(), Loc
));
8202 auto Summary
= Index
->findSummaryInModule(AliaseeVI
, ModulePath
);
8203 assert(Summary
&& "Aliasee must be a definition");
8204 AS
->setAliasee(AliaseeVI
, Summary
);
8207 AddGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
8215 bool LLParser::ParseFlag(unsigned &Val
) {
8216 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
8217 return TokError("expected integer");
8218 Val
= (unsigned)Lex
.getAPSIntVal().getBoolValue();
8224 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8225 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8226 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
8227 /// [',' 'noInline' ':' Flag]? ')'
8228 bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags
&FFlags
) {
8229 assert(Lex
.getKind() == lltok::kw_funcFlags
);
8232 if (ParseToken(lltok::colon
, "expected ':' in funcFlags") |
8233 ParseToken(lltok::lparen
, "expected '(' in funcFlags"))
8238 switch (Lex
.getKind()) {
8239 case lltok::kw_readNone
:
8241 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
8243 FFlags
.ReadNone
= Val
;
8245 case lltok::kw_readOnly
:
8247 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
8249 FFlags
.ReadOnly
= Val
;
8251 case lltok::kw_noRecurse
:
8253 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
8255 FFlags
.NoRecurse
= Val
;
8257 case lltok::kw_returnDoesNotAlias
:
8259 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
8261 FFlags
.ReturnDoesNotAlias
= Val
;
8263 case lltok::kw_noInline
:
8265 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
8267 FFlags
.NoInline
= Val
;
8270 return Error(Lex
.getLoc(), "expected function flag type");
8272 } while (EatIfPresent(lltok::comma
));
8274 if (ParseToken(lltok::rparen
, "expected ')' in funcFlags"))
8281 /// := 'calls' ':' '(' Call [',' Call]* ')'
8282 /// Call ::= '(' 'callee' ':' GVReference
8283 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8284 bool LLParser::ParseOptionalCalls(std::vector
<FunctionSummary::EdgeTy
> &Calls
) {
8285 assert(Lex
.getKind() == lltok::kw_calls
);
8288 if (ParseToken(lltok::colon
, "expected ':' in calls") |
8289 ParseToken(lltok::lparen
, "expected '(' in calls"))
8292 IdToIndexMapType IdToIndexMap
;
8293 // Parse each call edge
8296 if (ParseToken(lltok::lparen
, "expected '(' in call") ||
8297 ParseToken(lltok::kw_callee
, "expected 'callee' in call") ||
8298 ParseToken(lltok::colon
, "expected ':'"))
8301 LocTy Loc
= Lex
.getLoc();
8303 if (ParseGVReference(VI
, GVId
))
8306 CalleeInfo::HotnessType Hotness
= CalleeInfo::HotnessType::Unknown
;
8308 if (EatIfPresent(lltok::comma
)) {
8309 // Expect either hotness or relbf
8310 if (EatIfPresent(lltok::kw_hotness
)) {
8311 if (ParseToken(lltok::colon
, "expected ':'") || ParseHotness(Hotness
))
8314 if (ParseToken(lltok::kw_relbf
, "expected relbf") ||
8315 ParseToken(lltok::colon
, "expected ':'") || ParseUInt32(RelBF
))
8319 // Keep track of the Call array index needing a forward reference.
8320 // We will save the location of the ValueInfo needing an update, but
8321 // can only do so once the std::vector is finalized.
8322 if (VI
.getRef() == FwdVIRef
)
8323 IdToIndexMap
[GVId
].push_back(std::make_pair(Calls
.size(), Loc
));
8324 Calls
.push_back(FunctionSummary::EdgeTy
{VI
, CalleeInfo(Hotness
, RelBF
)});
8326 if (ParseToken(lltok::rparen
, "expected ')' in call"))
8328 } while (EatIfPresent(lltok::comma
));
8330 // Now that the Calls vector is finalized, it is safe to save the locations
8331 // of any forward GV references that need updating later.
8332 for (auto I
: IdToIndexMap
) {
8333 for (auto P
: I
.second
) {
8334 assert(Calls
[P
.first
].first
.getRef() == FwdVIRef
&&
8335 "Forward referenced ValueInfo expected to be empty");
8336 auto FwdRef
= ForwardRefValueInfos
.insert(std::make_pair(
8337 I
.first
, std::vector
<std::pair
<ValueInfo
*, LocTy
>>()));
8338 FwdRef
.first
->second
.push_back(
8339 std::make_pair(&Calls
[P
.first
].first
, P
.second
));
8343 if (ParseToken(lltok::rparen
, "expected ')' in calls"))
8350 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
8351 bool LLParser::ParseHotness(CalleeInfo::HotnessType
&Hotness
) {
8352 switch (Lex
.getKind()) {
8353 case lltok::kw_unknown
:
8354 Hotness
= CalleeInfo::HotnessType::Unknown
;
8356 case lltok::kw_cold
:
8357 Hotness
= CalleeInfo::HotnessType::Cold
;
8359 case lltok::kw_none
:
8360 Hotness
= CalleeInfo::HotnessType::None
;
8363 Hotness
= CalleeInfo::HotnessType::Hot
;
8365 case lltok::kw_critical
:
8366 Hotness
= CalleeInfo::HotnessType::Critical
;
8369 return Error(Lex
.getLoc(), "invalid call edge hotness");
8375 /// OptionalVTableFuncs
8376 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8377 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8378 bool LLParser::ParseOptionalVTableFuncs(VTableFuncList
&VTableFuncs
) {
8379 assert(Lex
.getKind() == lltok::kw_vTableFuncs
);
8382 if (ParseToken(lltok::colon
, "expected ':' in vTableFuncs") |
8383 ParseToken(lltok::lparen
, "expected '(' in vTableFuncs"))
8386 IdToIndexMapType IdToIndexMap
;
8387 // Parse each virtual function pair
8390 if (ParseToken(lltok::lparen
, "expected '(' in vTableFunc") ||
8391 ParseToken(lltok::kw_virtFunc
, "expected 'callee' in vTableFunc") ||
8392 ParseToken(lltok::colon
, "expected ':'"))
8395 LocTy Loc
= Lex
.getLoc();
8397 if (ParseGVReference(VI
, GVId
))
8401 if (ParseToken(lltok::comma
, "expected comma") ||
8402 ParseToken(lltok::kw_offset
, "expected offset") ||
8403 ParseToken(lltok::colon
, "expected ':'") || ParseUInt64(Offset
))
8406 // Keep track of the VTableFuncs array index needing a forward reference.
8407 // We will save the location of the ValueInfo needing an update, but
8408 // can only do so once the std::vector is finalized.
8410 IdToIndexMap
[GVId
].push_back(std::make_pair(VTableFuncs
.size(), Loc
));
8411 VTableFuncs
.push_back({VI
, Offset
});
8413 if (ParseToken(lltok::rparen
, "expected ')' in vTableFunc"))
8415 } while (EatIfPresent(lltok::comma
));
8417 // Now that the VTableFuncs vector is finalized, it is safe to save the
8418 // locations of any forward GV references that need updating later.
8419 for (auto I
: IdToIndexMap
) {
8420 for (auto P
: I
.second
) {
8421 assert(VTableFuncs
[P
.first
].FuncVI
== EmptyVI
&&
8422 "Forward referenced ValueInfo expected to be empty");
8423 auto FwdRef
= ForwardRefValueInfos
.insert(std::make_pair(
8424 I
.first
, std::vector
<std::pair
<ValueInfo
*, LocTy
>>()));
8425 FwdRef
.first
->second
.push_back(
8426 std::make_pair(&VTableFuncs
[P
.first
].FuncVI
, P
.second
));
8430 if (ParseToken(lltok::rparen
, "expected ')' in vTableFuncs"))
8437 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8438 bool LLParser::ParseOptionalRefs(std::vector
<ValueInfo
> &Refs
) {
8439 assert(Lex
.getKind() == lltok::kw_refs
);
8442 if (ParseToken(lltok::colon
, "expected ':' in refs") |
8443 ParseToken(lltok::lparen
, "expected '(' in refs"))
8446 struct ValueContext
{
8451 std::vector
<ValueContext
> VContexts
;
8452 // Parse each ref edge
8455 VC
.Loc
= Lex
.getLoc();
8456 if (ParseGVReference(VC
.VI
, VC
.GVId
))
8458 VContexts
.push_back(VC
);
8459 } while (EatIfPresent(lltok::comma
));
8461 // Sort value contexts so that ones with writeonly
8462 // and readonly ValueInfo are at the end of VContexts vector.
8463 // See FunctionSummary::specialRefCounts()
8464 llvm::sort(VContexts
, [](const ValueContext
&VC1
, const ValueContext
&VC2
) {
8465 return VC1
.VI
.getAccessSpecifier() < VC2
.VI
.getAccessSpecifier();
8468 IdToIndexMapType IdToIndexMap
;
8469 for (auto &VC
: VContexts
) {
8470 // Keep track of the Refs array index needing a forward reference.
8471 // We will save the location of the ValueInfo needing an update, but
8472 // can only do so once the std::vector is finalized.
8473 if (VC
.VI
.getRef() == FwdVIRef
)
8474 IdToIndexMap
[VC
.GVId
].push_back(std::make_pair(Refs
.size(), VC
.Loc
));
8475 Refs
.push_back(VC
.VI
);
8478 // Now that the Refs vector is finalized, it is safe to save the locations
8479 // of any forward GV references that need updating later.
8480 for (auto I
: IdToIndexMap
) {
8481 for (auto P
: I
.second
) {
8482 assert(Refs
[P
.first
].getRef() == FwdVIRef
&&
8483 "Forward referenced ValueInfo expected to be empty");
8484 auto FwdRef
= ForwardRefValueInfos
.insert(std::make_pair(
8485 I
.first
, std::vector
<std::pair
<ValueInfo
*, LocTy
>>()));
8486 FwdRef
.first
->second
.push_back(std::make_pair(&Refs
[P
.first
], P
.second
));
8490 if (ParseToken(lltok::rparen
, "expected ')' in refs"))
8496 /// OptionalTypeIdInfo
8497 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8498 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8499 /// [',' TypeCheckedLoadConstVCalls]? ')'
8500 bool LLParser::ParseOptionalTypeIdInfo(
8501 FunctionSummary::TypeIdInfo
&TypeIdInfo
) {
8502 assert(Lex
.getKind() == lltok::kw_typeIdInfo
);
8505 if (ParseToken(lltok::colon
, "expected ':' here") ||
8506 ParseToken(lltok::lparen
, "expected '(' in typeIdInfo"))
8510 switch (Lex
.getKind()) {
8511 case lltok::kw_typeTests
:
8512 if (ParseTypeTests(TypeIdInfo
.TypeTests
))
8515 case lltok::kw_typeTestAssumeVCalls
:
8516 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls
,
8517 TypeIdInfo
.TypeTestAssumeVCalls
))
8520 case lltok::kw_typeCheckedLoadVCalls
:
8521 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls
,
8522 TypeIdInfo
.TypeCheckedLoadVCalls
))
8525 case lltok::kw_typeTestAssumeConstVCalls
:
8526 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls
,
8527 TypeIdInfo
.TypeTestAssumeConstVCalls
))
8530 case lltok::kw_typeCheckedLoadConstVCalls
:
8531 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls
,
8532 TypeIdInfo
.TypeCheckedLoadConstVCalls
))
8536 return Error(Lex
.getLoc(), "invalid typeIdInfo list type");
8538 } while (EatIfPresent(lltok::comma
));
8540 if (ParseToken(lltok::rparen
, "expected ')' in typeIdInfo"))
8547 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8548 /// [',' (SummaryID | UInt64)]* ')'
8549 bool LLParser::ParseTypeTests(std::vector
<GlobalValue::GUID
> &TypeTests
) {
8550 assert(Lex
.getKind() == lltok::kw_typeTests
);
8553 if (ParseToken(lltok::colon
, "expected ':' here") ||
8554 ParseToken(lltok::lparen
, "expected '(' in typeIdInfo"))
8557 IdToIndexMapType IdToIndexMap
;
8559 GlobalValue::GUID GUID
= 0;
8560 if (Lex
.getKind() == lltok::SummaryID
) {
8561 unsigned ID
= Lex
.getUIntVal();
8562 LocTy Loc
= Lex
.getLoc();
8563 // Keep track of the TypeTests array index needing a forward reference.
8564 // We will save the location of the GUID needing an update, but
8565 // can only do so once the std::vector is finalized.
8566 IdToIndexMap
[ID
].push_back(std::make_pair(TypeTests
.size(), Loc
));
8568 } else if (ParseUInt64(GUID
))
8570 TypeTests
.push_back(GUID
);
8571 } while (EatIfPresent(lltok::comma
));
8573 // Now that the TypeTests vector is finalized, it is safe to save the
8574 // locations of any forward GV references that need updating later.
8575 for (auto I
: IdToIndexMap
) {
8576 for (auto P
: I
.second
) {
8577 assert(TypeTests
[P
.first
] == 0 &&
8578 "Forward referenced type id GUID expected to be 0");
8579 auto FwdRef
= ForwardRefTypeIds
.insert(std::make_pair(
8580 I
.first
, std::vector
<std::pair
<GlobalValue::GUID
*, LocTy
>>()));
8581 FwdRef
.first
->second
.push_back(
8582 std::make_pair(&TypeTests
[P
.first
], P
.second
));
8586 if (ParseToken(lltok::rparen
, "expected ')' in typeIdInfo"))
8593 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
8594 bool LLParser::ParseVFuncIdList(
8595 lltok::Kind Kind
, std::vector
<FunctionSummary::VFuncId
> &VFuncIdList
) {
8596 assert(Lex
.getKind() == Kind
);
8599 if (ParseToken(lltok::colon
, "expected ':' here") ||
8600 ParseToken(lltok::lparen
, "expected '(' here"))
8603 IdToIndexMapType IdToIndexMap
;
8605 FunctionSummary::VFuncId VFuncId
;
8606 if (ParseVFuncId(VFuncId
, IdToIndexMap
, VFuncIdList
.size()))
8608 VFuncIdList
.push_back(VFuncId
);
8609 } while (EatIfPresent(lltok::comma
));
8611 if (ParseToken(lltok::rparen
, "expected ')' here"))
8614 // Now that the VFuncIdList vector is finalized, it is safe to save the
8615 // locations of any forward GV references that need updating later.
8616 for (auto I
: IdToIndexMap
) {
8617 for (auto P
: I
.second
) {
8618 assert(VFuncIdList
[P
.first
].GUID
== 0 &&
8619 "Forward referenced type id GUID expected to be 0");
8620 auto FwdRef
= ForwardRefTypeIds
.insert(std::make_pair(
8621 I
.first
, std::vector
<std::pair
<GlobalValue::GUID
*, LocTy
>>()));
8622 FwdRef
.first
->second
.push_back(
8623 std::make_pair(&VFuncIdList
[P
.first
].GUID
, P
.second
));
8631 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8632 bool LLParser::ParseConstVCallList(
8634 std::vector
<FunctionSummary::ConstVCall
> &ConstVCallList
) {
8635 assert(Lex
.getKind() == Kind
);
8638 if (ParseToken(lltok::colon
, "expected ':' here") ||
8639 ParseToken(lltok::lparen
, "expected '(' here"))
8642 IdToIndexMapType IdToIndexMap
;
8644 FunctionSummary::ConstVCall ConstVCall
;
8645 if (ParseConstVCall(ConstVCall
, IdToIndexMap
, ConstVCallList
.size()))
8647 ConstVCallList
.push_back(ConstVCall
);
8648 } while (EatIfPresent(lltok::comma
));
8650 if (ParseToken(lltok::rparen
, "expected ')' here"))
8653 // Now that the ConstVCallList vector is finalized, it is safe to save the
8654 // locations of any forward GV references that need updating later.
8655 for (auto I
: IdToIndexMap
) {
8656 for (auto P
: I
.second
) {
8657 assert(ConstVCallList
[P
.first
].VFunc
.GUID
== 0 &&
8658 "Forward referenced type id GUID expected to be 0");
8659 auto FwdRef
= ForwardRefTypeIds
.insert(std::make_pair(
8660 I
.first
, std::vector
<std::pair
<GlobalValue::GUID
*, LocTy
>>()));
8661 FwdRef
.first
->second
.push_back(
8662 std::make_pair(&ConstVCallList
[P
.first
].VFunc
.GUID
, P
.second
));
8670 /// ::= '(' VFuncId ',' Args ')'
8671 bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall
&ConstVCall
,
8672 IdToIndexMapType
&IdToIndexMap
, unsigned Index
) {
8673 if (ParseToken(lltok::lparen
, "expected '(' here") ||
8674 ParseVFuncId(ConstVCall
.VFunc
, IdToIndexMap
, Index
))
8677 if (EatIfPresent(lltok::comma
))
8678 if (ParseArgs(ConstVCall
.Args
))
8681 if (ParseToken(lltok::rparen
, "expected ')' here"))
8688 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8689 /// 'offset' ':' UInt64 ')'
8690 bool LLParser::ParseVFuncId(FunctionSummary::VFuncId
&VFuncId
,
8691 IdToIndexMapType
&IdToIndexMap
, unsigned Index
) {
8692 assert(Lex
.getKind() == lltok::kw_vFuncId
);
8695 if (ParseToken(lltok::colon
, "expected ':' here") ||
8696 ParseToken(lltok::lparen
, "expected '(' here"))
8699 if (Lex
.getKind() == lltok::SummaryID
) {
8701 unsigned ID
= Lex
.getUIntVal();
8702 LocTy Loc
= Lex
.getLoc();
8703 // Keep track of the array index needing a forward reference.
8704 // We will save the location of the GUID needing an update, but
8705 // can only do so once the caller's std::vector is finalized.
8706 IdToIndexMap
[ID
].push_back(std::make_pair(Index
, Loc
));
8708 } else if (ParseToken(lltok::kw_guid
, "expected 'guid' here") ||
8709 ParseToken(lltok::colon
, "expected ':' here") ||
8710 ParseUInt64(VFuncId
.GUID
))
8713 if (ParseToken(lltok::comma
, "expected ',' here") ||
8714 ParseToken(lltok::kw_offset
, "expected 'offset' here") ||
8715 ParseToken(lltok::colon
, "expected ':' here") ||
8716 ParseUInt64(VFuncId
.Offset
) ||
8717 ParseToken(lltok::rparen
, "expected ')' here"))
8724 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8725 /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8726 /// 'dsoLocal' ':' Flag ',' 'canAutoHide' ':' Flag ')'
8727 bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags
&GVFlags
) {
8728 assert(Lex
.getKind() == lltok::kw_flags
);
8731 if (ParseToken(lltok::colon
, "expected ':' here") ||
8732 ParseToken(lltok::lparen
, "expected '(' here"))
8737 switch (Lex
.getKind()) {
8738 case lltok::kw_linkage
:
8740 if (ParseToken(lltok::colon
, "expected ':'"))
8743 GVFlags
.Linkage
= parseOptionalLinkageAux(Lex
.getKind(), HasLinkage
);
8744 assert(HasLinkage
&& "Linkage not optional in summary entry");
8747 case lltok::kw_notEligibleToImport
:
8749 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Flag
))
8751 GVFlags
.NotEligibleToImport
= Flag
;
8753 case lltok::kw_live
:
8755 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Flag
))
8757 GVFlags
.Live
= Flag
;
8759 case lltok::kw_dsoLocal
:
8761 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Flag
))
8763 GVFlags
.DSOLocal
= Flag
;
8765 case lltok::kw_canAutoHide
:
8767 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Flag
))
8769 GVFlags
.CanAutoHide
= Flag
;
8772 return Error(Lex
.getLoc(), "expected gv flag type");
8774 } while (EatIfPresent(lltok::comma
));
8776 if (ParseToken(lltok::rparen
, "expected ')' here"))
8783 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
8784 /// ',' 'writeonly' ':' Flag ')'
8785 bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags
&GVarFlags
) {
8786 assert(Lex
.getKind() == lltok::kw_varFlags
);
8789 if (ParseToken(lltok::colon
, "expected ':' here") ||
8790 ParseToken(lltok::lparen
, "expected '(' here"))
8793 auto ParseRest
= [this](unsigned int &Val
) {
8795 if (ParseToken(lltok::colon
, "expected ':'"))
8797 return ParseFlag(Val
);
8802 switch (Lex
.getKind()) {
8803 case lltok::kw_readonly
:
8804 if (ParseRest(Flag
))
8806 GVarFlags
.MaybeReadOnly
= Flag
;
8808 case lltok::kw_writeonly
:
8809 if (ParseRest(Flag
))
8811 GVarFlags
.MaybeWriteOnly
= Flag
;
8814 return Error(Lex
.getLoc(), "expected gvar flag type");
8816 } while (EatIfPresent(lltok::comma
));
8817 return ParseToken(lltok::rparen
, "expected ')' here");
8821 /// ::= 'module' ':' UInt
8822 bool LLParser::ParseModuleReference(StringRef
&ModulePath
) {
8824 if (ParseToken(lltok::kw_module
, "expected 'module' here") ||
8825 ParseToken(lltok::colon
, "expected ':' here") ||
8826 ParseToken(lltok::SummaryID
, "expected module ID"))
8829 unsigned ModuleID
= Lex
.getUIntVal();
8830 auto I
= ModuleIdMap
.find(ModuleID
);
8831 // We should have already parsed all module IDs
8832 assert(I
!= ModuleIdMap
.end());
8833 ModulePath
= I
->second
;
8839 bool LLParser::ParseGVReference(ValueInfo
&VI
, unsigned &GVId
) {
8840 bool WriteOnly
= false, ReadOnly
= EatIfPresent(lltok::kw_readonly
);
8842 WriteOnly
= EatIfPresent(lltok::kw_writeonly
);
8843 if (ParseToken(lltok::SummaryID
, "expected GV ID"))
8846 GVId
= Lex
.getUIntVal();
8847 // Check if we already have a VI for this GV
8848 if (GVId
< NumberedValueInfos
.size()) {
8849 assert(NumberedValueInfos
[GVId
].getRef() != FwdVIRef
);
8850 VI
= NumberedValueInfos
[GVId
];
8852 // We will create a forward reference to the stored location.
8853 VI
= ValueInfo(false, FwdVIRef
);