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 (auto *GV
= dyn_cast
<GlobalVariable
>(V
)) {
167 AttrBuilder
Attrs(GV
->getAttributes());
169 GV
->setAttributes(AttributeSet::get(Context
,Attrs
));
171 llvm_unreachable("invalid object with forward attribute group reference");
175 // If there are entries in ForwardRefBlockAddresses at this point, the
176 // function was never defined.
177 if (!ForwardRefBlockAddresses
.empty())
178 return Error(ForwardRefBlockAddresses
.begin()->first
.Loc
,
179 "expected function name in blockaddress");
181 for (const auto &NT
: NumberedTypes
)
182 if (NT
.second
.second
.isValid())
183 return Error(NT
.second
.second
,
184 "use of undefined type '%" + Twine(NT
.first
) + "'");
186 for (StringMap
<std::pair
<Type
*, LocTy
> >::iterator I
=
187 NamedTypes
.begin(), E
= NamedTypes
.end(); I
!= E
; ++I
)
188 if (I
->second
.second
.isValid())
189 return Error(I
->second
.second
,
190 "use of undefined type named '" + I
->getKey() + "'");
192 if (!ForwardRefComdats
.empty())
193 return Error(ForwardRefComdats
.begin()->second
,
194 "use of undefined comdat '$" +
195 ForwardRefComdats
.begin()->first
+ "'");
197 if (!ForwardRefVals
.empty())
198 return Error(ForwardRefVals
.begin()->second
.second
,
199 "use of undefined value '@" + ForwardRefVals
.begin()->first
+
202 if (!ForwardRefValIDs
.empty())
203 return Error(ForwardRefValIDs
.begin()->second
.second
,
204 "use of undefined value '@" +
205 Twine(ForwardRefValIDs
.begin()->first
) + "'");
207 if (!ForwardRefMDNodes
.empty())
208 return Error(ForwardRefMDNodes
.begin()->second
.second
,
209 "use of undefined metadata '!" +
210 Twine(ForwardRefMDNodes
.begin()->first
) + "'");
212 // Resolve metadata cycles.
213 for (auto &N
: NumberedMetadata
) {
214 if (N
.second
&& !N
.second
->isResolved())
215 N
.second
->resolveCycles();
218 for (auto *Inst
: InstsWithTBAATag
) {
219 MDNode
*MD
= Inst
->getMetadata(LLVMContext::MD_tbaa
);
220 assert(MD
&& "UpgradeInstWithTBAATag should have a TBAA tag");
221 auto *UpgradedMD
= UpgradeTBAANode(*MD
);
222 if (MD
!= UpgradedMD
)
223 Inst
->setMetadata(LLVMContext::MD_tbaa
, UpgradedMD
);
226 // Look for intrinsic functions and CallInst that need to be upgraded
227 for (Module::iterator FI
= M
->begin(), FE
= M
->end(); FI
!= FE
; )
228 UpgradeCallsToIntrinsic(&*FI
++); // must be post-increment, as we remove
230 // Some types could be renamed during loading if several modules are
231 // loaded in the same LLVMContext (LTO scenario). In this case we should
232 // remangle intrinsics names as well.
233 for (Module::iterator FI
= M
->begin(), FE
= M
->end(); FI
!= FE
; ) {
234 Function
*F
= &*FI
++;
235 if (auto Remangled
= Intrinsic::remangleIntrinsicFunction(F
)) {
236 F
->replaceAllUsesWith(Remangled
.getValue());
237 F
->eraseFromParent();
241 if (UpgradeDebugInfo
)
242 llvm::UpgradeDebugInfo(*M
);
244 UpgradeModuleFlags(*M
);
245 UpgradeSectionAttributes(*M
);
249 // Initialize the slot mapping.
250 // Because by this point we've parsed and validated everything, we can "steal"
251 // the mapping from LLParser as it doesn't need it anymore.
252 Slots
->GlobalValues
= std::move(NumberedVals
);
253 Slots
->MetadataNodes
= std::move(NumberedMetadata
);
254 for (const auto &I
: NamedTypes
)
255 Slots
->NamedTypes
.insert(std::make_pair(I
.getKey(), I
.second
.first
));
256 for (const auto &I
: NumberedTypes
)
257 Slots
->Types
.insert(std::make_pair(I
.first
, I
.second
.first
));
262 /// Do final validity and sanity checks at the end of the index.
263 bool LLParser::ValidateEndOfIndex() {
267 if (!ForwardRefValueInfos
.empty())
268 return Error(ForwardRefValueInfos
.begin()->second
.front().second
,
269 "use of undefined summary '^" +
270 Twine(ForwardRefValueInfos
.begin()->first
) + "'");
272 if (!ForwardRefAliasees
.empty())
273 return Error(ForwardRefAliasees
.begin()->second
.front().second
,
274 "use of undefined summary '^" +
275 Twine(ForwardRefAliasees
.begin()->first
) + "'");
277 if (!ForwardRefTypeIds
.empty())
278 return Error(ForwardRefTypeIds
.begin()->second
.front().second
,
279 "use of undefined type id summary '^" +
280 Twine(ForwardRefTypeIds
.begin()->first
) + "'");
285 //===----------------------------------------------------------------------===//
286 // Top-Level Entities
287 //===----------------------------------------------------------------------===//
289 bool LLParser::ParseTopLevelEntities() {
290 // If there is no Module, then parse just the summary index entries.
293 switch (Lex
.getKind()) {
296 case lltok::SummaryID
:
297 if (ParseSummaryEntry())
300 case lltok::kw_source_filename
:
301 if (ParseSourceFileName())
305 // Skip everything else
311 switch (Lex
.getKind()) {
312 default: return TokError("expected top-level entity");
313 case lltok::Eof
: return false;
314 case lltok::kw_declare
: if (ParseDeclare()) return true; break;
315 case lltok::kw_define
: if (ParseDefine()) return true; break;
316 case lltok::kw_module
: if (ParseModuleAsm()) return true; break;
317 case lltok::kw_target
: if (ParseTargetDefinition()) return true; break;
318 case lltok::kw_source_filename
:
319 if (ParseSourceFileName())
322 case lltok::kw_deplibs
: if (ParseDepLibs()) return true; break;
323 case lltok::LocalVarID
: if (ParseUnnamedType()) return true; break;
324 case lltok::LocalVar
: if (ParseNamedType()) return true; break;
325 case lltok::GlobalID
: if (ParseUnnamedGlobal()) return true; break;
326 case lltok::GlobalVar
: if (ParseNamedGlobal()) return true; break;
327 case lltok::ComdatVar
: if (parseComdat()) return true; break;
328 case lltok::exclaim
: if (ParseStandaloneMetadata()) return true; break;
329 case lltok::SummaryID
:
330 if (ParseSummaryEntry())
333 case lltok::MetadataVar
:if (ParseNamedMetadata()) return true; break;
334 case lltok::kw_attributes
: if (ParseUnnamedAttrGrp()) return true; break;
335 case lltok::kw_uselistorder
: if (ParseUseListOrder()) return true; break;
336 case lltok::kw_uselistorder_bb
:
337 if (ParseUseListOrderBB())
345 /// ::= 'module' 'asm' STRINGCONSTANT
346 bool LLParser::ParseModuleAsm() {
347 assert(Lex
.getKind() == lltok::kw_module
);
351 if (ParseToken(lltok::kw_asm
, "expected 'module asm'") ||
352 ParseStringConstant(AsmStr
)) return true;
354 M
->appendModuleInlineAsm(AsmStr
);
359 /// ::= 'target' 'triple' '=' STRINGCONSTANT
360 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
361 bool LLParser::ParseTargetDefinition() {
362 assert(Lex
.getKind() == lltok::kw_target
);
365 default: return TokError("unknown target property");
366 case lltok::kw_triple
:
368 if (ParseToken(lltok::equal
, "expected '=' after target triple") ||
369 ParseStringConstant(Str
))
371 M
->setTargetTriple(Str
);
373 case lltok::kw_datalayout
:
375 if (ParseToken(lltok::equal
, "expected '=' after target datalayout") ||
376 ParseStringConstant(Str
))
378 if (DataLayoutStr
.empty())
379 M
->setDataLayout(Str
);
385 /// ::= 'source_filename' '=' STRINGCONSTANT
386 bool LLParser::ParseSourceFileName() {
387 assert(Lex
.getKind() == lltok::kw_source_filename
);
389 if (ParseToken(lltok::equal
, "expected '=' after source_filename") ||
390 ParseStringConstant(SourceFileName
))
393 M
->setSourceFileName(SourceFileName
);
398 /// ::= 'deplibs' '=' '[' ']'
399 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
400 /// FIXME: Remove in 4.0. Currently parse, but ignore.
401 bool LLParser::ParseDepLibs() {
402 assert(Lex
.getKind() == lltok::kw_deplibs
);
404 if (ParseToken(lltok::equal
, "expected '=' after deplibs") ||
405 ParseToken(lltok::lsquare
, "expected '=' after deplibs"))
408 if (EatIfPresent(lltok::rsquare
))
413 if (ParseStringConstant(Str
)) return true;
414 } while (EatIfPresent(lltok::comma
));
416 return ParseToken(lltok::rsquare
, "expected ']' at end of list");
419 /// ParseUnnamedType:
420 /// ::= LocalVarID '=' 'type' type
421 bool LLParser::ParseUnnamedType() {
422 LocTy TypeLoc
= Lex
.getLoc();
423 unsigned TypeID
= Lex
.getUIntVal();
424 Lex
.Lex(); // eat LocalVarID;
426 if (ParseToken(lltok::equal
, "expected '=' after name") ||
427 ParseToken(lltok::kw_type
, "expected 'type' after '='"))
430 Type
*Result
= nullptr;
431 if (ParseStructDefinition(TypeLoc
, "",
432 NumberedTypes
[TypeID
], Result
)) return true;
434 if (!isa
<StructType
>(Result
)) {
435 std::pair
<Type
*, LocTy
> &Entry
= NumberedTypes
[TypeID
];
437 return Error(TypeLoc
, "non-struct types may not be recursive");
438 Entry
.first
= Result
;
439 Entry
.second
= SMLoc();
446 /// ::= LocalVar '=' 'type' type
447 bool LLParser::ParseNamedType() {
448 std::string Name
= Lex
.getStrVal();
449 LocTy NameLoc
= Lex
.getLoc();
450 Lex
.Lex(); // eat LocalVar.
452 if (ParseToken(lltok::equal
, "expected '=' after name") ||
453 ParseToken(lltok::kw_type
, "expected 'type' after name"))
456 Type
*Result
= nullptr;
457 if (ParseStructDefinition(NameLoc
, Name
,
458 NamedTypes
[Name
], Result
)) return true;
460 if (!isa
<StructType
>(Result
)) {
461 std::pair
<Type
*, LocTy
> &Entry
= NamedTypes
[Name
];
463 return Error(NameLoc
, "non-struct types may not be recursive");
464 Entry
.first
= Result
;
465 Entry
.second
= SMLoc();
472 /// ::= 'declare' FunctionHeader
473 bool LLParser::ParseDeclare() {
474 assert(Lex
.getKind() == lltok::kw_declare
);
477 std::vector
<std::pair
<unsigned, MDNode
*>> MDs
;
478 while (Lex
.getKind() == lltok::MetadataVar
) {
481 if (ParseMetadataAttachment(MDK
, N
))
483 MDs
.push_back({MDK
, N
});
487 if (ParseFunctionHeader(F
, false))
490 F
->addMetadata(MD
.first
, *MD
.second
);
495 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
496 bool LLParser::ParseDefine() {
497 assert(Lex
.getKind() == lltok::kw_define
);
501 return ParseFunctionHeader(F
, true) ||
502 ParseOptionalFunctionMetadata(*F
) ||
503 ParseFunctionBody(*F
);
509 bool LLParser::ParseGlobalType(bool &IsConstant
) {
510 if (Lex
.getKind() == lltok::kw_constant
)
512 else if (Lex
.getKind() == lltok::kw_global
)
516 return TokError("expected 'global' or 'constant'");
522 bool LLParser::ParseOptionalUnnamedAddr(
523 GlobalVariable::UnnamedAddr
&UnnamedAddr
) {
524 if (EatIfPresent(lltok::kw_unnamed_addr
))
525 UnnamedAddr
= GlobalValue::UnnamedAddr::Global
;
526 else if (EatIfPresent(lltok::kw_local_unnamed_addr
))
527 UnnamedAddr
= GlobalValue::UnnamedAddr::Local
;
529 UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
533 /// ParseUnnamedGlobal:
534 /// OptionalVisibility (ALIAS | IFUNC) ...
535 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
536 /// OptionalDLLStorageClass
537 /// ... -> global variable
538 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
539 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
540 /// OptionalDLLStorageClass
541 /// ... -> global variable
542 bool LLParser::ParseUnnamedGlobal() {
543 unsigned VarID
= NumberedVals
.size();
545 LocTy NameLoc
= Lex
.getLoc();
547 // Handle the GlobalID form.
548 if (Lex
.getKind() == lltok::GlobalID
) {
549 if (Lex
.getUIntVal() != VarID
)
550 return Error(Lex
.getLoc(), "variable expected to be numbered '%" +
552 Lex
.Lex(); // eat GlobalID;
554 if (ParseToken(lltok::equal
, "expected '=' after name"))
559 unsigned Linkage
, Visibility
, DLLStorageClass
;
561 GlobalVariable::ThreadLocalMode TLM
;
562 GlobalVariable::UnnamedAddr UnnamedAddr
;
563 if (ParseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
565 ParseOptionalThreadLocal(TLM
) || ParseOptionalUnnamedAddr(UnnamedAddr
))
568 if (Lex
.getKind() != lltok::kw_alias
&& Lex
.getKind() != lltok::kw_ifunc
)
569 return ParseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
,
570 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
572 return parseIndirectSymbol(Name
, NameLoc
, Linkage
, Visibility
,
573 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
576 /// ParseNamedGlobal:
577 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
578 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
579 /// OptionalVisibility OptionalDLLStorageClass
580 /// ... -> global variable
581 bool LLParser::ParseNamedGlobal() {
582 assert(Lex
.getKind() == lltok::GlobalVar
);
583 LocTy NameLoc
= Lex
.getLoc();
584 std::string Name
= Lex
.getStrVal();
588 unsigned Linkage
, Visibility
, DLLStorageClass
;
590 GlobalVariable::ThreadLocalMode TLM
;
591 GlobalVariable::UnnamedAddr UnnamedAddr
;
592 if (ParseToken(lltok::equal
, "expected '=' in global variable") ||
593 ParseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
595 ParseOptionalThreadLocal(TLM
) || ParseOptionalUnnamedAddr(UnnamedAddr
))
598 if (Lex
.getKind() != lltok::kw_alias
&& Lex
.getKind() != lltok::kw_ifunc
)
599 return ParseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
,
600 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
602 return parseIndirectSymbol(Name
, NameLoc
, Linkage
, Visibility
,
603 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
606 bool LLParser::parseComdat() {
607 assert(Lex
.getKind() == lltok::ComdatVar
);
608 std::string Name
= Lex
.getStrVal();
609 LocTy NameLoc
= Lex
.getLoc();
612 if (ParseToken(lltok::equal
, "expected '=' here"))
615 if (ParseToken(lltok::kw_comdat
, "expected comdat keyword"))
616 return TokError("expected comdat type");
618 Comdat::SelectionKind SK
;
619 switch (Lex
.getKind()) {
621 return TokError("unknown selection kind");
625 case lltok::kw_exactmatch
:
626 SK
= Comdat::ExactMatch
;
628 case lltok::kw_largest
:
629 SK
= Comdat::Largest
;
631 case lltok::kw_noduplicates
:
632 SK
= Comdat::NoDuplicates
;
634 case lltok::kw_samesize
:
635 SK
= Comdat::SameSize
;
640 // See if the comdat was forward referenced, if so, use the comdat.
641 Module::ComdatSymTabType
&ComdatSymTab
= M
->getComdatSymbolTable();
642 Module::ComdatSymTabType::iterator I
= ComdatSymTab
.find(Name
);
643 if (I
!= ComdatSymTab
.end() && !ForwardRefComdats
.erase(Name
))
644 return Error(NameLoc
, "redefinition of comdat '$" + Name
+ "'");
647 if (I
!= ComdatSymTab
.end())
650 C
= M
->getOrInsertComdat(Name
);
651 C
->setSelectionKind(SK
);
657 // ::= '!' STRINGCONSTANT
658 bool LLParser::ParseMDString(MDString
*&Result
) {
660 if (ParseStringConstant(Str
)) return true;
661 Result
= MDString::get(Context
, Str
);
666 // ::= '!' MDNodeNumber
667 bool LLParser::ParseMDNodeID(MDNode
*&Result
) {
668 // !{ ..., !42, ... }
669 LocTy IDLoc
= Lex
.getLoc();
671 if (ParseUInt32(MID
))
674 // If not a forward reference, just return it now.
675 if (NumberedMetadata
.count(MID
)) {
676 Result
= NumberedMetadata
[MID
];
680 // Otherwise, create MDNode forward reference.
681 auto &FwdRef
= ForwardRefMDNodes
[MID
];
682 FwdRef
= std::make_pair(MDTuple::getTemporary(Context
, None
), IDLoc
);
684 Result
= FwdRef
.first
.get();
685 NumberedMetadata
[MID
].reset(Result
);
689 /// ParseNamedMetadata:
690 /// !foo = !{ !1, !2 }
691 bool LLParser::ParseNamedMetadata() {
692 assert(Lex
.getKind() == lltok::MetadataVar
);
693 std::string Name
= Lex
.getStrVal();
696 if (ParseToken(lltok::equal
, "expected '=' here") ||
697 ParseToken(lltok::exclaim
, "Expected '!' here") ||
698 ParseToken(lltok::lbrace
, "Expected '{' here"))
701 NamedMDNode
*NMD
= M
->getOrInsertNamedMetadata(Name
);
702 if (Lex
.getKind() != lltok::rbrace
)
705 // Parse DIExpressions inline as a special case. They are still MDNodes,
706 // so they can still appear in named metadata. Remove this logic if they
707 // become plain Metadata.
708 if (Lex
.getKind() == lltok::MetadataVar
&&
709 Lex
.getStrVal() == "DIExpression") {
710 if (ParseDIExpression(N
, /*IsDistinct=*/false))
712 } else if (ParseToken(lltok::exclaim
, "Expected '!' here") ||
717 } while (EatIfPresent(lltok::comma
));
719 return ParseToken(lltok::rbrace
, "expected end of metadata node");
722 /// ParseStandaloneMetadata:
724 bool LLParser::ParseStandaloneMetadata() {
725 assert(Lex
.getKind() == lltok::exclaim
);
727 unsigned MetadataID
= 0;
730 if (ParseUInt32(MetadataID
) ||
731 ParseToken(lltok::equal
, "expected '=' here"))
734 // Detect common error, from old metadata syntax.
735 if (Lex
.getKind() == lltok::Type
)
736 return TokError("unexpected type in metadata definition");
738 bool IsDistinct
= EatIfPresent(lltok::kw_distinct
);
739 if (Lex
.getKind() == lltok::MetadataVar
) {
740 if (ParseSpecializedMDNode(Init
, IsDistinct
))
742 } else if (ParseToken(lltok::exclaim
, "Expected '!' here") ||
743 ParseMDTuple(Init
, IsDistinct
))
746 // See if this was forward referenced, if so, handle it.
747 auto FI
= ForwardRefMDNodes
.find(MetadataID
);
748 if (FI
!= ForwardRefMDNodes
.end()) {
749 FI
->second
.first
->replaceAllUsesWith(Init
);
750 ForwardRefMDNodes
.erase(FI
);
752 assert(NumberedMetadata
[MetadataID
] == Init
&& "Tracking VH didn't work");
754 if (NumberedMetadata
.count(MetadataID
))
755 return TokError("Metadata id is already used");
756 NumberedMetadata
[MetadataID
].reset(Init
);
762 // Skips a single module summary entry.
763 bool LLParser::SkipModuleSummaryEntry() {
764 // Each module summary entry consists of a tag for the entry
765 // type, followed by a colon, then the fields surrounded by nested sets of
766 // parentheses. The "tag:" looks like a Label. Once parsing support is
767 // in place we will look for the tokens corresponding to the expected tags.
768 if (Lex
.getKind() != lltok::kw_gv
&& Lex
.getKind() != lltok::kw_module
&&
769 Lex
.getKind() != lltok::kw_typeid
)
771 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
773 if (ParseToken(lltok::colon
, "expected ':' at start of summary entry") ||
774 ParseToken(lltok::lparen
, "expected '(' at start of summary entry"))
776 // Now walk through the parenthesized entry, until the number of open
777 // parentheses goes back down to 0 (the first '(' was parsed above).
778 unsigned NumOpenParen
= 1;
780 switch (Lex
.getKind()) {
788 return TokError("found end of file while parsing summary entry");
790 // Skip everything in between parentheses.
794 } while (NumOpenParen
> 0);
799 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
800 bool LLParser::ParseSummaryEntry() {
801 assert(Lex
.getKind() == lltok::SummaryID
);
802 unsigned SummaryID
= Lex
.getUIntVal();
804 // For summary entries, colons should be treated as distinct tokens,
805 // not an indication of the end of a label token.
806 Lex
.setIgnoreColonInIdentifiers(true);
809 if (ParseToken(lltok::equal
, "expected '=' here"))
812 // If we don't have an index object, skip the summary entry.
814 return SkipModuleSummaryEntry();
816 switch (Lex
.getKind()) {
818 return ParseGVEntry(SummaryID
);
819 case lltok::kw_module
:
820 return ParseModuleEntry(SummaryID
);
821 case lltok::kw_typeid
:
822 return ParseTypeIdEntry(SummaryID
);
825 return Error(Lex
.getLoc(), "unexpected summary kind");
827 Lex
.setIgnoreColonInIdentifiers(false);
831 static bool isValidVisibilityForLinkage(unsigned V
, unsigned L
) {
832 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes
)L
) ||
833 (GlobalValue::VisibilityTypes
)V
== GlobalValue::DefaultVisibility
;
836 // If there was an explicit dso_local, update GV. In the absence of an explicit
837 // dso_local we keep the default value.
838 static void maybeSetDSOLocal(bool DSOLocal
, GlobalValue
&GV
) {
840 GV
.setDSOLocal(true);
843 /// parseIndirectSymbol:
844 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
845 /// OptionalVisibility OptionalDLLStorageClass
846 /// OptionalThreadLocal OptionalUnnamedAddr
847 // 'alias|ifunc' IndirectSymbol
852 /// Everything through OptionalUnnamedAddr has already been parsed.
854 bool LLParser::parseIndirectSymbol(const std::string
&Name
, LocTy NameLoc
,
855 unsigned L
, unsigned Visibility
,
856 unsigned DLLStorageClass
, bool DSOLocal
,
857 GlobalVariable::ThreadLocalMode TLM
,
858 GlobalVariable::UnnamedAddr UnnamedAddr
) {
860 if (Lex
.getKind() == lltok::kw_alias
)
862 else if (Lex
.getKind() == lltok::kw_ifunc
)
865 llvm_unreachable("Not an alias or ifunc!");
868 GlobalValue::LinkageTypes Linkage
= (GlobalValue::LinkageTypes
) L
;
870 if(IsAlias
&& !GlobalAlias::isValidLinkage(Linkage
))
871 return Error(NameLoc
, "invalid linkage type for alias");
873 if (!isValidVisibilityForLinkage(Visibility
, L
))
874 return Error(NameLoc
,
875 "symbol with local linkage must have default visibility");
878 LocTy ExplicitTypeLoc
= Lex
.getLoc();
880 ParseToken(lltok::comma
, "expected comma after alias or ifunc's type"))
884 LocTy AliaseeLoc
= Lex
.getLoc();
885 if (Lex
.getKind() != lltok::kw_bitcast
&&
886 Lex
.getKind() != lltok::kw_getelementptr
&&
887 Lex
.getKind() != lltok::kw_addrspacecast
&&
888 Lex
.getKind() != lltok::kw_inttoptr
) {
889 if (ParseGlobalTypeAndValue(Aliasee
))
892 // The bitcast dest type is not present, it is implied by the dest type.
896 if (ID
.Kind
!= ValID::t_Constant
)
897 return Error(AliaseeLoc
, "invalid aliasee");
898 Aliasee
= ID
.ConstantVal
;
901 Type
*AliaseeType
= Aliasee
->getType();
902 auto *PTy
= dyn_cast
<PointerType
>(AliaseeType
);
904 return Error(AliaseeLoc
, "An alias or ifunc must have pointer type");
905 unsigned AddrSpace
= PTy
->getAddressSpace();
907 if (IsAlias
&& Ty
!= PTy
->getElementType())
910 "explicit pointee type doesn't match operand's pointee type");
912 if (!IsAlias
&& !PTy
->getElementType()->isFunctionTy())
915 "explicit pointee type should be a function type");
917 GlobalValue
*GVal
= nullptr;
919 // See if the alias was forward referenced, if so, prepare to replace the
920 // forward reference.
922 GVal
= M
->getNamedValue(Name
);
924 if (!ForwardRefVals
.erase(Name
))
925 return Error(NameLoc
, "redefinition of global '@" + Name
+ "'");
928 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
929 if (I
!= ForwardRefValIDs
.end()) {
930 GVal
= I
->second
.first
;
931 ForwardRefValIDs
.erase(I
);
935 // Okay, create the alias but do not insert it into the module yet.
936 std::unique_ptr
<GlobalIndirectSymbol
> GA
;
938 GA
.reset(GlobalAlias::create(Ty
, AddrSpace
,
939 (GlobalValue::LinkageTypes
)Linkage
, Name
,
940 Aliasee
, /*Parent*/ nullptr));
942 GA
.reset(GlobalIFunc::create(Ty
, AddrSpace
,
943 (GlobalValue::LinkageTypes
)Linkage
, Name
,
944 Aliasee
, /*Parent*/ nullptr));
945 GA
->setThreadLocalMode(TLM
);
946 GA
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
947 GA
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
948 GA
->setUnnamedAddr(UnnamedAddr
);
949 maybeSetDSOLocal(DSOLocal
, *GA
);
952 NumberedVals
.push_back(GA
.get());
955 // Verify that types agree.
956 if (GVal
->getType() != GA
->getType())
959 "forward reference and definition of alias have different types");
961 // If they agree, just RAUW the old value with the alias and remove the
963 GVal
->replaceAllUsesWith(GA
.get());
964 GVal
->eraseFromParent();
967 // Insert into the module, we know its name won't collide now.
969 M
->getAliasList().push_back(cast
<GlobalAlias
>(GA
.get()));
971 M
->getIFuncList().push_back(cast
<GlobalIFunc
>(GA
.get()));
972 assert(GA
->getName() == Name
&& "Should not be a name conflict!");
974 // The module owns this now
981 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
982 /// OptionalVisibility OptionalDLLStorageClass
983 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
984 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
985 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
986 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
987 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
988 /// Const OptionalAttrs
990 /// Everything up to and including OptionalUnnamedAddr has been parsed
993 bool LLParser::ParseGlobal(const std::string
&Name
, LocTy NameLoc
,
994 unsigned Linkage
, bool HasLinkage
,
995 unsigned Visibility
, unsigned DLLStorageClass
,
996 bool DSOLocal
, GlobalVariable::ThreadLocalMode TLM
,
997 GlobalVariable::UnnamedAddr UnnamedAddr
) {
998 if (!isValidVisibilityForLinkage(Visibility
, Linkage
))
999 return Error(NameLoc
,
1000 "symbol with local linkage must have default visibility");
1003 bool IsConstant
, IsExternallyInitialized
;
1004 LocTy IsExternallyInitializedLoc
;
1008 if (ParseOptionalAddrSpace(AddrSpace
) ||
1009 ParseOptionalToken(lltok::kw_externally_initialized
,
1010 IsExternallyInitialized
,
1011 &IsExternallyInitializedLoc
) ||
1012 ParseGlobalType(IsConstant
) ||
1013 ParseType(Ty
, TyLoc
))
1016 // If the linkage is specified and is external, then no initializer is
1018 Constant
*Init
= nullptr;
1020 !GlobalValue::isValidDeclarationLinkage(
1021 (GlobalValue::LinkageTypes
)Linkage
)) {
1022 if (ParseGlobalValue(Ty
, Init
))
1026 if (Ty
->isFunctionTy() || !PointerType::isValidElementType(Ty
))
1027 return Error(TyLoc
, "invalid type for global variable");
1029 GlobalValue
*GVal
= nullptr;
1031 // See if the global was forward referenced, if so, use the global.
1032 if (!Name
.empty()) {
1033 GVal
= M
->getNamedValue(Name
);
1035 if (!ForwardRefVals
.erase(Name
))
1036 return Error(NameLoc
, "redefinition of global '@" + Name
+ "'");
1039 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
1040 if (I
!= ForwardRefValIDs
.end()) {
1041 GVal
= I
->second
.first
;
1042 ForwardRefValIDs
.erase(I
);
1048 GV
= new GlobalVariable(*M
, Ty
, false, GlobalValue::ExternalLinkage
, nullptr,
1049 Name
, nullptr, GlobalVariable::NotThreadLocal
,
1052 if (GVal
->getValueType() != Ty
)
1054 "forward reference and definition of global have different types");
1056 GV
= cast
<GlobalVariable
>(GVal
);
1058 // Move the forward-reference to the correct spot in the module.
1059 M
->getGlobalList().splice(M
->global_end(), M
->getGlobalList(), GV
);
1063 NumberedVals
.push_back(GV
);
1065 // Set the parsed properties on the global.
1067 GV
->setInitializer(Init
);
1068 GV
->setConstant(IsConstant
);
1069 GV
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
1070 maybeSetDSOLocal(DSOLocal
, *GV
);
1071 GV
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
1072 GV
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
1073 GV
->setExternallyInitialized(IsExternallyInitialized
);
1074 GV
->setThreadLocalMode(TLM
);
1075 GV
->setUnnamedAddr(UnnamedAddr
);
1077 // Parse attributes on the global.
1078 while (Lex
.getKind() == lltok::comma
) {
1081 if (Lex
.getKind() == lltok::kw_section
) {
1083 GV
->setSection(Lex
.getStrVal());
1084 if (ParseToken(lltok::StringConstant
, "expected global section string"))
1086 } else if (Lex
.getKind() == lltok::kw_align
) {
1088 if (ParseOptionalAlignment(Alignment
)) return true;
1089 GV
->setAlignment(Alignment
);
1090 } else if (Lex
.getKind() == lltok::MetadataVar
) {
1091 if (ParseGlobalObjectMetadataAttachment(*GV
))
1095 if (parseOptionalComdat(Name
, C
))
1100 return TokError("unknown global variable property!");
1106 std::vector
<unsigned> FwdRefAttrGrps
;
1107 if (ParseFnAttributeValuePairs(Attrs
, FwdRefAttrGrps
, false, BuiltinLoc
))
1109 if (Attrs
.hasAttributes() || !FwdRefAttrGrps
.empty()) {
1110 GV
->setAttributes(AttributeSet::get(Context
, Attrs
));
1111 ForwardRefAttrGroups
[GV
] = FwdRefAttrGrps
;
1117 /// ParseUnnamedAttrGrp
1118 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1119 bool LLParser::ParseUnnamedAttrGrp() {
1120 assert(Lex
.getKind() == lltok::kw_attributes
);
1121 LocTy AttrGrpLoc
= Lex
.getLoc();
1124 if (Lex
.getKind() != lltok::AttrGrpID
)
1125 return TokError("expected attribute group id");
1127 unsigned VarID
= Lex
.getUIntVal();
1128 std::vector
<unsigned> unused
;
1132 if (ParseToken(lltok::equal
, "expected '=' here") ||
1133 ParseToken(lltok::lbrace
, "expected '{' here") ||
1134 ParseFnAttributeValuePairs(NumberedAttrBuilders
[VarID
], unused
, true,
1136 ParseToken(lltok::rbrace
, "expected end of attribute group"))
1139 if (!NumberedAttrBuilders
[VarID
].hasAttributes())
1140 return Error(AttrGrpLoc
, "attribute group has no attributes");
1145 /// ParseFnAttributeValuePairs
1146 /// ::= <attr> | <attr> '=' <value>
1147 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder
&B
,
1148 std::vector
<unsigned> &FwdRefAttrGrps
,
1149 bool inAttrGrp
, LocTy
&BuiltinLoc
) {
1150 bool HaveError
= false;
1155 lltok::Kind Token
= Lex
.getKind();
1156 if (Token
== lltok::kw_builtin
)
1157 BuiltinLoc
= Lex
.getLoc();
1160 if (!inAttrGrp
) return HaveError
;
1161 return Error(Lex
.getLoc(), "unterminated attribute group");
1166 case lltok::AttrGrpID
: {
1167 // Allow a function to reference an attribute group:
1169 // define void @foo() #1 { ... }
1173 "cannot have an attribute group reference in an attribute group");
1175 unsigned AttrGrpNum
= Lex
.getUIntVal();
1176 if (inAttrGrp
) break;
1178 // Save the reference to the attribute group. We'll fill it in later.
1179 FwdRefAttrGrps
.push_back(AttrGrpNum
);
1182 // Target-dependent attributes:
1183 case lltok::StringConstant
: {
1184 if (ParseStringAttribute(B
))
1189 // Target-independent attributes:
1190 case lltok::kw_align
: {
1191 // As a hack, we allow function alignment to be initially parsed as an
1192 // attribute on a function declaration/definition or added to an attribute
1193 // group and later moved to the alignment field.
1197 if (ParseToken(lltok::equal
, "expected '=' here") ||
1198 ParseUInt32(Alignment
))
1201 if (ParseOptionalAlignment(Alignment
))
1204 B
.addAlignmentAttr(Alignment
);
1207 case lltok::kw_alignstack
: {
1211 if (ParseToken(lltok::equal
, "expected '=' here") ||
1212 ParseUInt32(Alignment
))
1215 if (ParseOptionalStackAlignment(Alignment
))
1218 B
.addStackAlignmentAttr(Alignment
);
1221 case lltok::kw_allocsize
: {
1222 unsigned ElemSizeArg
;
1223 Optional
<unsigned> NumElemsArg
;
1224 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1225 if (parseAllocSizeArguments(ElemSizeArg
, NumElemsArg
))
1227 B
.addAllocSizeAttr(ElemSizeArg
, NumElemsArg
);
1230 case lltok::kw_alwaysinline
: B
.addAttribute(Attribute::AlwaysInline
); break;
1231 case lltok::kw_argmemonly
: B
.addAttribute(Attribute::ArgMemOnly
); break;
1232 case lltok::kw_builtin
: B
.addAttribute(Attribute::Builtin
); break;
1233 case lltok::kw_cold
: B
.addAttribute(Attribute::Cold
); break;
1234 case lltok::kw_convergent
: B
.addAttribute(Attribute::Convergent
); break;
1235 case lltok::kw_inaccessiblememonly
:
1236 B
.addAttribute(Attribute::InaccessibleMemOnly
); break;
1237 case lltok::kw_inaccessiblemem_or_argmemonly
:
1238 B
.addAttribute(Attribute::InaccessibleMemOrArgMemOnly
); break;
1239 case lltok::kw_inlinehint
: B
.addAttribute(Attribute::InlineHint
); break;
1240 case lltok::kw_jumptable
: B
.addAttribute(Attribute::JumpTable
); break;
1241 case lltok::kw_minsize
: B
.addAttribute(Attribute::MinSize
); break;
1242 case lltok::kw_naked
: B
.addAttribute(Attribute::Naked
); break;
1243 case lltok::kw_nobuiltin
: B
.addAttribute(Attribute::NoBuiltin
); break;
1244 case lltok::kw_noduplicate
: B
.addAttribute(Attribute::NoDuplicate
); break;
1245 case lltok::kw_noimplicitfloat
:
1246 B
.addAttribute(Attribute::NoImplicitFloat
); break;
1247 case lltok::kw_noinline
: B
.addAttribute(Attribute::NoInline
); break;
1248 case lltok::kw_nonlazybind
: B
.addAttribute(Attribute::NonLazyBind
); break;
1249 case lltok::kw_noredzone
: B
.addAttribute(Attribute::NoRedZone
); break;
1250 case lltok::kw_noreturn
: B
.addAttribute(Attribute::NoReturn
); break;
1251 case lltok::kw_nocf_check
: B
.addAttribute(Attribute::NoCfCheck
); break;
1252 case lltok::kw_norecurse
: B
.addAttribute(Attribute::NoRecurse
); break;
1253 case lltok::kw_nounwind
: B
.addAttribute(Attribute::NoUnwind
); break;
1254 case lltok::kw_optforfuzzing
:
1255 B
.addAttribute(Attribute::OptForFuzzing
); break;
1256 case lltok::kw_optnone
: B
.addAttribute(Attribute::OptimizeNone
); break;
1257 case lltok::kw_optsize
: B
.addAttribute(Attribute::OptimizeForSize
); break;
1258 case lltok::kw_readnone
: B
.addAttribute(Attribute::ReadNone
); break;
1259 case lltok::kw_readonly
: B
.addAttribute(Attribute::ReadOnly
); break;
1260 case lltok::kw_returns_twice
:
1261 B
.addAttribute(Attribute::ReturnsTwice
); break;
1262 case lltok::kw_speculatable
: B
.addAttribute(Attribute::Speculatable
); break;
1263 case lltok::kw_ssp
: B
.addAttribute(Attribute::StackProtect
); break;
1264 case lltok::kw_sspreq
: B
.addAttribute(Attribute::StackProtectReq
); break;
1265 case lltok::kw_sspstrong
:
1266 B
.addAttribute(Attribute::StackProtectStrong
); break;
1267 case lltok::kw_safestack
: B
.addAttribute(Attribute::SafeStack
); break;
1268 case lltok::kw_shadowcallstack
:
1269 B
.addAttribute(Attribute::ShadowCallStack
); break;
1270 case lltok::kw_sanitize_address
:
1271 B
.addAttribute(Attribute::SanitizeAddress
); break;
1272 case lltok::kw_sanitize_hwaddress
:
1273 B
.addAttribute(Attribute::SanitizeHWAddress
); break;
1274 case lltok::kw_sanitize_thread
:
1275 B
.addAttribute(Attribute::SanitizeThread
); break;
1276 case lltok::kw_sanitize_memory
:
1277 B
.addAttribute(Attribute::SanitizeMemory
); break;
1278 case lltok::kw_speculative_load_hardening
:
1279 B
.addAttribute(Attribute::SpeculativeLoadHardening
);
1281 case lltok::kw_strictfp
: B
.addAttribute(Attribute::StrictFP
); break;
1282 case lltok::kw_uwtable
: B
.addAttribute(Attribute::UWTable
); break;
1283 case lltok::kw_writeonly
: B
.addAttribute(Attribute::WriteOnly
); break;
1286 case lltok::kw_inreg
:
1287 case lltok::kw_signext
:
1288 case lltok::kw_zeroext
:
1291 "invalid use of attribute on a function");
1293 case lltok::kw_byval
:
1294 case lltok::kw_dereferenceable
:
1295 case lltok::kw_dereferenceable_or_null
:
1296 case lltok::kw_inalloca
:
1297 case lltok::kw_nest
:
1298 case lltok::kw_noalias
:
1299 case lltok::kw_nocapture
:
1300 case lltok::kw_nonnull
:
1301 case lltok::kw_returned
:
1302 case lltok::kw_sret
:
1303 case lltok::kw_swifterror
:
1304 case lltok::kw_swiftself
:
1307 "invalid use of parameter-only attribute on a function");
1315 //===----------------------------------------------------------------------===//
1316 // GlobalValue Reference/Resolution Routines.
1317 //===----------------------------------------------------------------------===//
1319 static inline GlobalValue
*createGlobalFwdRef(Module
*M
, PointerType
*PTy
,
1320 const std::string
&Name
) {
1321 if (auto *FT
= dyn_cast
<FunctionType
>(PTy
->getElementType()))
1322 return Function::Create(FT
, GlobalValue::ExternalWeakLinkage
,
1323 PTy
->getAddressSpace(), Name
, M
);
1325 return new GlobalVariable(*M
, PTy
->getElementType(), false,
1326 GlobalValue::ExternalWeakLinkage
, nullptr, Name
,
1327 nullptr, GlobalVariable::NotThreadLocal
,
1328 PTy
->getAddressSpace());
1331 Value
*LLParser::checkValidVariableType(LocTy Loc
, const Twine
&Name
, Type
*Ty
,
1332 Value
*Val
, bool IsCall
) {
1333 if (Val
->getType() == Ty
)
1335 // For calls we also accept variables in the program address space.
1336 Type
*SuggestedTy
= Ty
;
1337 if (IsCall
&& isa
<PointerType
>(Ty
)) {
1338 Type
*TyInProgAS
= cast
<PointerType
>(Ty
)->getElementType()->getPointerTo(
1339 M
->getDataLayout().getProgramAddressSpace());
1340 SuggestedTy
= TyInProgAS
;
1341 if (Val
->getType() == TyInProgAS
)
1344 if (Ty
->isLabelTy())
1345 Error(Loc
, "'" + Name
+ "' is not a basic block");
1347 Error(Loc
, "'" + Name
+ "' defined with type '" +
1348 getTypeString(Val
->getType()) + "' but expected '" +
1349 getTypeString(SuggestedTy
) + "'");
1353 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1354 /// forward reference record if needed. This can return null if the value
1355 /// exists but does not have the right type.
1356 GlobalValue
*LLParser::GetGlobalVal(const std::string
&Name
, Type
*Ty
,
1357 LocTy Loc
, bool IsCall
) {
1358 PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
1360 Error(Loc
, "global variable reference must have pointer type");
1364 // Look this name up in the normal function symbol table.
1366 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
));
1368 // If this is a forward reference for the value, see if we already created a
1369 // forward ref record.
1371 auto I
= ForwardRefVals
.find(Name
);
1372 if (I
!= ForwardRefVals
.end())
1373 Val
= I
->second
.first
;
1376 // If we have the value in the symbol table or fwd-ref table, return it.
1378 return cast_or_null
<GlobalValue
>(
1379 checkValidVariableType(Loc
, "@" + Name
, Ty
, Val
, IsCall
));
1381 // Otherwise, create a new forward reference for this value and remember it.
1382 GlobalValue
*FwdVal
= createGlobalFwdRef(M
, PTy
, Name
);
1383 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
1387 GlobalValue
*LLParser::GetGlobalVal(unsigned ID
, Type
*Ty
, LocTy Loc
,
1389 PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
1391 Error(Loc
, "global variable reference must have pointer type");
1395 GlobalValue
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : nullptr;
1397 // If this is a forward reference for the value, see if we already created a
1398 // forward ref record.
1400 auto I
= ForwardRefValIDs
.find(ID
);
1401 if (I
!= ForwardRefValIDs
.end())
1402 Val
= I
->second
.first
;
1405 // If we have the value in the symbol table or fwd-ref table, return it.
1407 return cast_or_null
<GlobalValue
>(
1408 checkValidVariableType(Loc
, "@" + Twine(ID
), Ty
, Val
, IsCall
));
1410 // Otherwise, create a new forward reference for this value and remember it.
1411 GlobalValue
*FwdVal
= createGlobalFwdRef(M
, PTy
, "");
1412 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
1416 //===----------------------------------------------------------------------===//
1417 // Comdat Reference/Resolution Routines.
1418 //===----------------------------------------------------------------------===//
1420 Comdat
*LLParser::getComdat(const std::string
&Name
, LocTy Loc
) {
1421 // Look this name up in the comdat symbol table.
1422 Module::ComdatSymTabType
&ComdatSymTab
= M
->getComdatSymbolTable();
1423 Module::ComdatSymTabType::iterator I
= ComdatSymTab
.find(Name
);
1424 if (I
!= ComdatSymTab
.end())
1427 // Otherwise, create a new forward reference for this value and remember it.
1428 Comdat
*C
= M
->getOrInsertComdat(Name
);
1429 ForwardRefComdats
[Name
] = Loc
;
1433 //===----------------------------------------------------------------------===//
1435 //===----------------------------------------------------------------------===//
1437 /// ParseToken - If the current token has the specified kind, eat it and return
1438 /// success. Otherwise, emit the specified error and return failure.
1439 bool LLParser::ParseToken(lltok::Kind T
, const char *ErrMsg
) {
1440 if (Lex
.getKind() != T
)
1441 return TokError(ErrMsg
);
1446 /// ParseStringConstant
1447 /// ::= StringConstant
1448 bool LLParser::ParseStringConstant(std::string
&Result
) {
1449 if (Lex
.getKind() != lltok::StringConstant
)
1450 return TokError("expected string constant");
1451 Result
= Lex
.getStrVal();
1458 bool LLParser::ParseUInt32(uint32_t &Val
) {
1459 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
1460 return TokError("expected integer");
1461 uint64_t Val64
= Lex
.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL
+1);
1462 if (Val64
!= unsigned(Val64
))
1463 return TokError("expected 32-bit integer (too large)");
1471 bool LLParser::ParseUInt64(uint64_t &Val
) {
1472 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
1473 return TokError("expected integer");
1474 Val
= Lex
.getAPSIntVal().getLimitedValue();
1480 /// := 'localdynamic'
1481 /// := 'initialexec'
1483 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode
&TLM
) {
1484 switch (Lex
.getKind()) {
1486 return TokError("expected localdynamic, initialexec or localexec");
1487 case lltok::kw_localdynamic
:
1488 TLM
= GlobalVariable::LocalDynamicTLSModel
;
1490 case lltok::kw_initialexec
:
1491 TLM
= GlobalVariable::InitialExecTLSModel
;
1493 case lltok::kw_localexec
:
1494 TLM
= GlobalVariable::LocalExecTLSModel
;
1502 /// ParseOptionalThreadLocal
1504 /// := 'thread_local'
1505 /// := 'thread_local' '(' tlsmodel ')'
1506 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode
&TLM
) {
1507 TLM
= GlobalVariable::NotThreadLocal
;
1508 if (!EatIfPresent(lltok::kw_thread_local
))
1511 TLM
= GlobalVariable::GeneralDynamicTLSModel
;
1512 if (Lex
.getKind() == lltok::lparen
) {
1514 return ParseTLSModel(TLM
) ||
1515 ParseToken(lltok::rparen
, "expected ')' after thread local model");
1520 /// ParseOptionalAddrSpace
1522 /// := 'addrspace' '(' uint32 ')'
1523 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace
, unsigned DefaultAS
) {
1524 AddrSpace
= DefaultAS
;
1525 if (!EatIfPresent(lltok::kw_addrspace
))
1527 return ParseToken(lltok::lparen
, "expected '(' in address space") ||
1528 ParseUInt32(AddrSpace
) ||
1529 ParseToken(lltok::rparen
, "expected ')' in address space");
1532 /// ParseStringAttribute
1533 /// := StringConstant
1534 /// := StringConstant '=' StringConstant
1535 bool LLParser::ParseStringAttribute(AttrBuilder
&B
) {
1536 std::string Attr
= Lex
.getStrVal();
1539 if (EatIfPresent(lltok::equal
) && ParseStringConstant(Val
))
1541 B
.addAttribute(Attr
, Val
);
1545 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1546 bool LLParser::ParseOptionalParamAttrs(AttrBuilder
&B
) {
1547 bool HaveError
= false;
1552 lltok::Kind Token
= Lex
.getKind();
1554 default: // End of attributes.
1556 case lltok::StringConstant
: {
1557 if (ParseStringAttribute(B
))
1561 case lltok::kw_align
: {
1563 if (ParseOptionalAlignment(Alignment
))
1565 B
.addAlignmentAttr(Alignment
);
1568 case lltok::kw_byval
: B
.addAttribute(Attribute::ByVal
); break;
1569 case lltok::kw_dereferenceable
: {
1571 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable
, Bytes
))
1573 B
.addDereferenceableAttr(Bytes
);
1576 case lltok::kw_dereferenceable_or_null
: {
1578 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null
, Bytes
))
1580 B
.addDereferenceableOrNullAttr(Bytes
);
1583 case lltok::kw_inalloca
: B
.addAttribute(Attribute::InAlloca
); break;
1584 case lltok::kw_inreg
: B
.addAttribute(Attribute::InReg
); break;
1585 case lltok::kw_nest
: B
.addAttribute(Attribute::Nest
); break;
1586 case lltok::kw_noalias
: B
.addAttribute(Attribute::NoAlias
); break;
1587 case lltok::kw_nocapture
: B
.addAttribute(Attribute::NoCapture
); break;
1588 case lltok::kw_nonnull
: B
.addAttribute(Attribute::NonNull
); break;
1589 case lltok::kw_readnone
: B
.addAttribute(Attribute::ReadNone
); break;
1590 case lltok::kw_readonly
: B
.addAttribute(Attribute::ReadOnly
); break;
1591 case lltok::kw_returned
: B
.addAttribute(Attribute::Returned
); break;
1592 case lltok::kw_signext
: B
.addAttribute(Attribute::SExt
); break;
1593 case lltok::kw_sret
: B
.addAttribute(Attribute::StructRet
); break;
1594 case lltok::kw_swifterror
: B
.addAttribute(Attribute::SwiftError
); break;
1595 case lltok::kw_swiftself
: B
.addAttribute(Attribute::SwiftSelf
); break;
1596 case lltok::kw_writeonly
: B
.addAttribute(Attribute::WriteOnly
); break;
1597 case lltok::kw_zeroext
: B
.addAttribute(Attribute::ZExt
); break;
1599 case lltok::kw_alignstack
:
1600 case lltok::kw_alwaysinline
:
1601 case lltok::kw_argmemonly
:
1602 case lltok::kw_builtin
:
1603 case lltok::kw_inlinehint
:
1604 case lltok::kw_jumptable
:
1605 case lltok::kw_minsize
:
1606 case lltok::kw_naked
:
1607 case lltok::kw_nobuiltin
:
1608 case lltok::kw_noduplicate
:
1609 case lltok::kw_noimplicitfloat
:
1610 case lltok::kw_noinline
:
1611 case lltok::kw_nonlazybind
:
1612 case lltok::kw_noredzone
:
1613 case lltok::kw_noreturn
:
1614 case lltok::kw_nocf_check
:
1615 case lltok::kw_nounwind
:
1616 case lltok::kw_optforfuzzing
:
1617 case lltok::kw_optnone
:
1618 case lltok::kw_optsize
:
1619 case lltok::kw_returns_twice
:
1620 case lltok::kw_sanitize_address
:
1621 case lltok::kw_sanitize_hwaddress
:
1622 case lltok::kw_sanitize_memory
:
1623 case lltok::kw_sanitize_thread
:
1624 case lltok::kw_speculative_load_hardening
:
1626 case lltok::kw_sspreq
:
1627 case lltok::kw_sspstrong
:
1628 case lltok::kw_safestack
:
1629 case lltok::kw_shadowcallstack
:
1630 case lltok::kw_strictfp
:
1631 case lltok::kw_uwtable
:
1632 HaveError
|= Error(Lex
.getLoc(), "invalid use of function-only attribute");
1640 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1641 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder
&B
) {
1642 bool HaveError
= false;
1647 lltok::Kind Token
= Lex
.getKind();
1649 default: // End of attributes.
1651 case lltok::StringConstant
: {
1652 if (ParseStringAttribute(B
))
1656 case lltok::kw_dereferenceable
: {
1658 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable
, Bytes
))
1660 B
.addDereferenceableAttr(Bytes
);
1663 case lltok::kw_dereferenceable_or_null
: {
1665 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null
, Bytes
))
1667 B
.addDereferenceableOrNullAttr(Bytes
);
1670 case lltok::kw_align
: {
1672 if (ParseOptionalAlignment(Alignment
))
1674 B
.addAlignmentAttr(Alignment
);
1677 case lltok::kw_inreg
: B
.addAttribute(Attribute::InReg
); break;
1678 case lltok::kw_noalias
: B
.addAttribute(Attribute::NoAlias
); break;
1679 case lltok::kw_nonnull
: B
.addAttribute(Attribute::NonNull
); break;
1680 case lltok::kw_signext
: B
.addAttribute(Attribute::SExt
); break;
1681 case lltok::kw_zeroext
: B
.addAttribute(Attribute::ZExt
); break;
1684 case lltok::kw_byval
:
1685 case lltok::kw_inalloca
:
1686 case lltok::kw_nest
:
1687 case lltok::kw_nocapture
:
1688 case lltok::kw_returned
:
1689 case lltok::kw_sret
:
1690 case lltok::kw_swifterror
:
1691 case lltok::kw_swiftself
:
1692 HaveError
|= Error(Lex
.getLoc(), "invalid use of parameter-only attribute");
1695 case lltok::kw_alignstack
:
1696 case lltok::kw_alwaysinline
:
1697 case lltok::kw_argmemonly
:
1698 case lltok::kw_builtin
:
1699 case lltok::kw_cold
:
1700 case lltok::kw_inlinehint
:
1701 case lltok::kw_jumptable
:
1702 case lltok::kw_minsize
:
1703 case lltok::kw_naked
:
1704 case lltok::kw_nobuiltin
:
1705 case lltok::kw_noduplicate
:
1706 case lltok::kw_noimplicitfloat
:
1707 case lltok::kw_noinline
:
1708 case lltok::kw_nonlazybind
:
1709 case lltok::kw_noredzone
:
1710 case lltok::kw_noreturn
:
1711 case lltok::kw_nocf_check
:
1712 case lltok::kw_nounwind
:
1713 case lltok::kw_optforfuzzing
:
1714 case lltok::kw_optnone
:
1715 case lltok::kw_optsize
:
1716 case lltok::kw_returns_twice
:
1717 case lltok::kw_sanitize_address
:
1718 case lltok::kw_sanitize_hwaddress
:
1719 case lltok::kw_sanitize_memory
:
1720 case lltok::kw_sanitize_thread
:
1721 case lltok::kw_speculative_load_hardening
:
1723 case lltok::kw_sspreq
:
1724 case lltok::kw_sspstrong
:
1725 case lltok::kw_safestack
:
1726 case lltok::kw_shadowcallstack
:
1727 case lltok::kw_strictfp
:
1728 case lltok::kw_uwtable
:
1729 HaveError
|= Error(Lex
.getLoc(), "invalid use of function-only attribute");
1732 case lltok::kw_readnone
:
1733 case lltok::kw_readonly
:
1734 HaveError
|= Error(Lex
.getLoc(), "invalid use of attribute on return type");
1741 static unsigned parseOptionalLinkageAux(lltok::Kind Kind
, bool &HasLinkage
) {
1746 return GlobalValue::ExternalLinkage
;
1747 case lltok::kw_private
:
1748 return GlobalValue::PrivateLinkage
;
1749 case lltok::kw_internal
:
1750 return GlobalValue::InternalLinkage
;
1751 case lltok::kw_weak
:
1752 return GlobalValue::WeakAnyLinkage
;
1753 case lltok::kw_weak_odr
:
1754 return GlobalValue::WeakODRLinkage
;
1755 case lltok::kw_linkonce
:
1756 return GlobalValue::LinkOnceAnyLinkage
;
1757 case lltok::kw_linkonce_odr
:
1758 return GlobalValue::LinkOnceODRLinkage
;
1759 case lltok::kw_available_externally
:
1760 return GlobalValue::AvailableExternallyLinkage
;
1761 case lltok::kw_appending
:
1762 return GlobalValue::AppendingLinkage
;
1763 case lltok::kw_common
:
1764 return GlobalValue::CommonLinkage
;
1765 case lltok::kw_extern_weak
:
1766 return GlobalValue::ExternalWeakLinkage
;
1767 case lltok::kw_external
:
1768 return GlobalValue::ExternalLinkage
;
1772 /// ParseOptionalLinkage
1779 /// ::= 'linkonce_odr'
1780 /// ::= 'available_externally'
1783 /// ::= 'extern_weak'
1785 bool LLParser::ParseOptionalLinkage(unsigned &Res
, bool &HasLinkage
,
1786 unsigned &Visibility
,
1787 unsigned &DLLStorageClass
,
1789 Res
= parseOptionalLinkageAux(Lex
.getKind(), HasLinkage
);
1792 ParseOptionalDSOLocal(DSOLocal
);
1793 ParseOptionalVisibility(Visibility
);
1794 ParseOptionalDLLStorageClass(DLLStorageClass
);
1796 if (DSOLocal
&& DLLStorageClass
== GlobalValue::DLLImportStorageClass
) {
1797 return Error(Lex
.getLoc(), "dso_location and DLL-StorageClass mismatch");
1803 void LLParser::ParseOptionalDSOLocal(bool &DSOLocal
) {
1804 switch (Lex
.getKind()) {
1808 case lltok::kw_dso_local
:
1812 case lltok::kw_dso_preemptable
:
1819 /// ParseOptionalVisibility
1825 void LLParser::ParseOptionalVisibility(unsigned &Res
) {
1826 switch (Lex
.getKind()) {
1828 Res
= GlobalValue::DefaultVisibility
;
1830 case lltok::kw_default
:
1831 Res
= GlobalValue::DefaultVisibility
;
1833 case lltok::kw_hidden
:
1834 Res
= GlobalValue::HiddenVisibility
;
1836 case lltok::kw_protected
:
1837 Res
= GlobalValue::ProtectedVisibility
;
1843 /// ParseOptionalDLLStorageClass
1848 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res
) {
1849 switch (Lex
.getKind()) {
1851 Res
= GlobalValue::DefaultStorageClass
;
1853 case lltok::kw_dllimport
:
1854 Res
= GlobalValue::DLLImportStorageClass
;
1856 case lltok::kw_dllexport
:
1857 Res
= GlobalValue::DLLExportStorageClass
;
1863 /// ParseOptionalCallingConv
1867 /// ::= 'intel_ocl_bicc'
1869 /// ::= 'x86_stdcallcc'
1870 /// ::= 'x86_fastcallcc'
1871 /// ::= 'x86_thiscallcc'
1872 /// ::= 'x86_vectorcallcc'
1873 /// ::= 'arm_apcscc'
1874 /// ::= 'arm_aapcscc'
1875 /// ::= 'arm_aapcs_vfpcc'
1876 /// ::= 'aarch64_vector_pcs'
1877 /// ::= 'msp430_intrcc'
1878 /// ::= 'avr_intrcc'
1879 /// ::= 'avr_signalcc'
1880 /// ::= 'ptx_kernel'
1881 /// ::= 'ptx_device'
1883 /// ::= 'spir_kernel'
1884 /// ::= 'x86_64_sysvcc'
1886 /// ::= 'webkit_jscc'
1888 /// ::= 'preserve_mostcc'
1889 /// ::= 'preserve_allcc'
1892 /// ::= 'x86_intrcc'
1895 /// ::= 'cxx_fast_tlscc'
1903 /// ::= 'amdgpu_kernel'
1906 bool LLParser::ParseOptionalCallingConv(unsigned &CC
) {
1907 switch (Lex
.getKind()) {
1908 default: CC
= CallingConv::C
; return false;
1909 case lltok::kw_ccc
: CC
= CallingConv::C
; break;
1910 case lltok::kw_fastcc
: CC
= CallingConv::Fast
; break;
1911 case lltok::kw_coldcc
: CC
= CallingConv::Cold
; break;
1912 case lltok::kw_x86_stdcallcc
: CC
= CallingConv::X86_StdCall
; break;
1913 case lltok::kw_x86_fastcallcc
: CC
= CallingConv::X86_FastCall
; break;
1914 case lltok::kw_x86_regcallcc
: CC
= CallingConv::X86_RegCall
; break;
1915 case lltok::kw_x86_thiscallcc
: CC
= CallingConv::X86_ThisCall
; break;
1916 case lltok::kw_x86_vectorcallcc
:CC
= CallingConv::X86_VectorCall
; break;
1917 case lltok::kw_arm_apcscc
: CC
= CallingConv::ARM_APCS
; break;
1918 case lltok::kw_arm_aapcscc
: CC
= CallingConv::ARM_AAPCS
; break;
1919 case lltok::kw_arm_aapcs_vfpcc
:CC
= CallingConv::ARM_AAPCS_VFP
; break;
1920 case lltok::kw_aarch64_vector_pcs
:CC
= CallingConv::AArch64_VectorCall
; break;
1921 case lltok::kw_msp430_intrcc
: CC
= CallingConv::MSP430_INTR
; break;
1922 case lltok::kw_avr_intrcc
: CC
= CallingConv::AVR_INTR
; break;
1923 case lltok::kw_avr_signalcc
: CC
= CallingConv::AVR_SIGNAL
; break;
1924 case lltok::kw_ptx_kernel
: CC
= CallingConv::PTX_Kernel
; break;
1925 case lltok::kw_ptx_device
: CC
= CallingConv::PTX_Device
; break;
1926 case lltok::kw_spir_kernel
: CC
= CallingConv::SPIR_KERNEL
; break;
1927 case lltok::kw_spir_func
: CC
= CallingConv::SPIR_FUNC
; break;
1928 case lltok::kw_intel_ocl_bicc
: CC
= CallingConv::Intel_OCL_BI
; break;
1929 case lltok::kw_x86_64_sysvcc
: CC
= CallingConv::X86_64_SysV
; break;
1930 case lltok::kw_win64cc
: CC
= CallingConv::Win64
; break;
1931 case lltok::kw_webkit_jscc
: CC
= CallingConv::WebKit_JS
; break;
1932 case lltok::kw_anyregcc
: CC
= CallingConv::AnyReg
; break;
1933 case lltok::kw_preserve_mostcc
:CC
= CallingConv::PreserveMost
; break;
1934 case lltok::kw_preserve_allcc
: CC
= CallingConv::PreserveAll
; break;
1935 case lltok::kw_ghccc
: CC
= CallingConv::GHC
; break;
1936 case lltok::kw_swiftcc
: CC
= CallingConv::Swift
; break;
1937 case lltok::kw_x86_intrcc
: CC
= CallingConv::X86_INTR
; break;
1938 case lltok::kw_hhvmcc
: CC
= CallingConv::HHVM
; break;
1939 case lltok::kw_hhvm_ccc
: CC
= CallingConv::HHVM_C
; break;
1940 case lltok::kw_cxx_fast_tlscc
: CC
= CallingConv::CXX_FAST_TLS
; break;
1941 case lltok::kw_amdgpu_vs
: CC
= CallingConv::AMDGPU_VS
; break;
1942 case lltok::kw_amdgpu_ls
: CC
= CallingConv::AMDGPU_LS
; break;
1943 case lltok::kw_amdgpu_hs
: CC
= CallingConv::AMDGPU_HS
; break;
1944 case lltok::kw_amdgpu_es
: CC
= CallingConv::AMDGPU_ES
; break;
1945 case lltok::kw_amdgpu_gs
: CC
= CallingConv::AMDGPU_GS
; break;
1946 case lltok::kw_amdgpu_ps
: CC
= CallingConv::AMDGPU_PS
; break;
1947 case lltok::kw_amdgpu_cs
: CC
= CallingConv::AMDGPU_CS
; break;
1948 case lltok::kw_amdgpu_kernel
: CC
= CallingConv::AMDGPU_KERNEL
; break;
1949 case lltok::kw_cc
: {
1951 return ParseUInt32(CC
);
1959 /// ParseMetadataAttachment
1961 bool LLParser::ParseMetadataAttachment(unsigned &Kind
, MDNode
*&MD
) {
1962 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata attachment");
1964 std::string Name
= Lex
.getStrVal();
1965 Kind
= M
->getMDKindID(Name
);
1968 return ParseMDNode(MD
);
1971 /// ParseInstructionMetadata
1972 /// ::= !dbg !42 (',' !dbg !57)*
1973 bool LLParser::ParseInstructionMetadata(Instruction
&Inst
) {
1975 if (Lex
.getKind() != lltok::MetadataVar
)
1976 return TokError("expected metadata after comma");
1980 if (ParseMetadataAttachment(MDK
, N
))
1983 Inst
.setMetadata(MDK
, N
);
1984 if (MDK
== LLVMContext::MD_tbaa
)
1985 InstsWithTBAATag
.push_back(&Inst
);
1987 // If this is the end of the list, we're done.
1988 } while (EatIfPresent(lltok::comma
));
1992 /// ParseGlobalObjectMetadataAttachment
1994 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject
&GO
) {
1997 if (ParseMetadataAttachment(MDK
, N
))
2000 GO
.addMetadata(MDK
, *N
);
2004 /// ParseOptionalFunctionMetadata
2006 bool LLParser::ParseOptionalFunctionMetadata(Function
&F
) {
2007 while (Lex
.getKind() == lltok::MetadataVar
)
2008 if (ParseGlobalObjectMetadataAttachment(F
))
2013 /// ParseOptionalAlignment
2016 bool LLParser::ParseOptionalAlignment(unsigned &Alignment
) {
2018 if (!EatIfPresent(lltok::kw_align
))
2020 LocTy AlignLoc
= Lex
.getLoc();
2021 if (ParseUInt32(Alignment
)) return true;
2022 if (!isPowerOf2_32(Alignment
))
2023 return Error(AlignLoc
, "alignment is not a power of two");
2024 if (Alignment
> Value::MaximumAlignment
)
2025 return Error(AlignLoc
, "huge alignments are not supported yet");
2029 /// ParseOptionalDerefAttrBytes
2031 /// ::= AttrKind '(' 4 ')'
2033 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2034 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind
,
2036 assert((AttrKind
== lltok::kw_dereferenceable
||
2037 AttrKind
== lltok::kw_dereferenceable_or_null
) &&
2041 if (!EatIfPresent(AttrKind
))
2043 LocTy ParenLoc
= Lex
.getLoc();
2044 if (!EatIfPresent(lltok::lparen
))
2045 return Error(ParenLoc
, "expected '('");
2046 LocTy DerefLoc
= Lex
.getLoc();
2047 if (ParseUInt64(Bytes
)) return true;
2048 ParenLoc
= Lex
.getLoc();
2049 if (!EatIfPresent(lltok::rparen
))
2050 return Error(ParenLoc
, "expected ')'");
2052 return Error(DerefLoc
, "dereferenceable bytes must be non-zero");
2056 /// ParseOptionalCommaAlign
2060 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2062 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment
,
2063 bool &AteExtraComma
) {
2064 AteExtraComma
= false;
2065 while (EatIfPresent(lltok::comma
)) {
2066 // Metadata at the end is an early exit.
2067 if (Lex
.getKind() == lltok::MetadataVar
) {
2068 AteExtraComma
= true;
2072 if (Lex
.getKind() != lltok::kw_align
)
2073 return Error(Lex
.getLoc(), "expected metadata or 'align'");
2075 if (ParseOptionalAlignment(Alignment
)) return true;
2081 /// ParseOptionalCommaAddrSpace
2083 /// ::= ',' addrspace(1)
2085 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2087 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace
,
2089 bool &AteExtraComma
) {
2090 AteExtraComma
= false;
2091 while (EatIfPresent(lltok::comma
)) {
2092 // Metadata at the end is an early exit.
2093 if (Lex
.getKind() == lltok::MetadataVar
) {
2094 AteExtraComma
= true;
2099 if (Lex
.getKind() != lltok::kw_addrspace
)
2100 return Error(Lex
.getLoc(), "expected metadata or 'addrspace'");
2102 if (ParseOptionalAddrSpace(AddrSpace
))
2109 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg
,
2110 Optional
<unsigned> &HowManyArg
) {
2113 auto StartParen
= Lex
.getLoc();
2114 if (!EatIfPresent(lltok::lparen
))
2115 return Error(StartParen
, "expected '('");
2117 if (ParseUInt32(BaseSizeArg
))
2120 if (EatIfPresent(lltok::comma
)) {
2121 auto HowManyAt
= Lex
.getLoc();
2123 if (ParseUInt32(HowMany
))
2125 if (HowMany
== BaseSizeArg
)
2126 return Error(HowManyAt
,
2127 "'allocsize' indices can't refer to the same parameter");
2128 HowManyArg
= HowMany
;
2132 auto EndParen
= Lex
.getLoc();
2133 if (!EatIfPresent(lltok::rparen
))
2134 return Error(EndParen
, "expected ')'");
2138 /// ParseScopeAndOrdering
2139 /// if isAtomic: ::= SyncScope? AtomicOrdering
2142 /// This sets Scope and Ordering to the parsed values.
2143 bool LLParser::ParseScopeAndOrdering(bool isAtomic
, SyncScope::ID
&SSID
,
2144 AtomicOrdering
&Ordering
) {
2148 return ParseScope(SSID
) || ParseOrdering(Ordering
);
2152 /// ::= syncscope("singlethread" | "<target scope>")?
2154 /// This sets synchronization scope ID to the ID of the parsed value.
2155 bool LLParser::ParseScope(SyncScope::ID
&SSID
) {
2156 SSID
= SyncScope::System
;
2157 if (EatIfPresent(lltok::kw_syncscope
)) {
2158 auto StartParenAt
= Lex
.getLoc();
2159 if (!EatIfPresent(lltok::lparen
))
2160 return Error(StartParenAt
, "Expected '(' in syncscope");
2163 auto SSNAt
= Lex
.getLoc();
2164 if (ParseStringConstant(SSN
))
2165 return Error(SSNAt
, "Expected synchronization scope name");
2167 auto EndParenAt
= Lex
.getLoc();
2168 if (!EatIfPresent(lltok::rparen
))
2169 return Error(EndParenAt
, "Expected ')' in syncscope");
2171 SSID
= Context
.getOrInsertSyncScopeID(SSN
);
2178 /// ::= AtomicOrdering
2180 /// This sets Ordering to the parsed value.
2181 bool LLParser::ParseOrdering(AtomicOrdering
&Ordering
) {
2182 switch (Lex
.getKind()) {
2183 default: return TokError("Expected ordering on atomic instruction");
2184 case lltok::kw_unordered
: Ordering
= AtomicOrdering::Unordered
; break;
2185 case lltok::kw_monotonic
: Ordering
= AtomicOrdering::Monotonic
; break;
2186 // Not specified yet:
2187 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2188 case lltok::kw_acquire
: Ordering
= AtomicOrdering::Acquire
; break;
2189 case lltok::kw_release
: Ordering
= AtomicOrdering::Release
; break;
2190 case lltok::kw_acq_rel
: Ordering
= AtomicOrdering::AcquireRelease
; break;
2191 case lltok::kw_seq_cst
:
2192 Ordering
= AtomicOrdering::SequentiallyConsistent
;
2199 /// ParseOptionalStackAlignment
2201 /// ::= 'alignstack' '(' 4 ')'
2202 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment
) {
2204 if (!EatIfPresent(lltok::kw_alignstack
))
2206 LocTy ParenLoc
= Lex
.getLoc();
2207 if (!EatIfPresent(lltok::lparen
))
2208 return Error(ParenLoc
, "expected '('");
2209 LocTy AlignLoc
= Lex
.getLoc();
2210 if (ParseUInt32(Alignment
)) return true;
2211 ParenLoc
= Lex
.getLoc();
2212 if (!EatIfPresent(lltok::rparen
))
2213 return Error(ParenLoc
, "expected ')'");
2214 if (!isPowerOf2_32(Alignment
))
2215 return Error(AlignLoc
, "stack alignment is not a power of two");
2219 /// ParseIndexList - This parses the index list for an insert/extractvalue
2220 /// instruction. This sets AteExtraComma in the case where we eat an extra
2221 /// comma at the end of the line and find that it is followed by metadata.
2222 /// Clients that don't allow metadata can call the version of this function that
2223 /// only takes one argument.
2226 /// ::= (',' uint32)+
2228 bool LLParser::ParseIndexList(SmallVectorImpl
<unsigned> &Indices
,
2229 bool &AteExtraComma
) {
2230 AteExtraComma
= false;
2232 if (Lex
.getKind() != lltok::comma
)
2233 return TokError("expected ',' as start of index list");
2235 while (EatIfPresent(lltok::comma
)) {
2236 if (Lex
.getKind() == lltok::MetadataVar
) {
2237 if (Indices
.empty()) return TokError("expected index");
2238 AteExtraComma
= true;
2242 if (ParseUInt32(Idx
)) return true;
2243 Indices
.push_back(Idx
);
2249 //===----------------------------------------------------------------------===//
2251 //===----------------------------------------------------------------------===//
2253 /// ParseType - Parse a type.
2254 bool LLParser::ParseType(Type
*&Result
, const Twine
&Msg
, bool AllowVoid
) {
2255 SMLoc TypeLoc
= Lex
.getLoc();
2256 switch (Lex
.getKind()) {
2258 return TokError(Msg
);
2260 // Type ::= 'float' | 'void' (etc)
2261 Result
= Lex
.getTyVal();
2265 // Type ::= StructType
2266 if (ParseAnonStructType(Result
, false))
2269 case lltok::lsquare
:
2270 // Type ::= '[' ... ']'
2271 Lex
.Lex(); // eat the lsquare.
2272 if (ParseArrayVectorType(Result
, false))
2275 case lltok::less
: // Either vector or packed struct.
2276 // Type ::= '<' ... '>'
2278 if (Lex
.getKind() == lltok::lbrace
) {
2279 if (ParseAnonStructType(Result
, true) ||
2280 ParseToken(lltok::greater
, "expected '>' at end of packed struct"))
2282 } else if (ParseArrayVectorType(Result
, true))
2285 case lltok::LocalVar
: {
2287 std::pair
<Type
*, LocTy
> &Entry
= NamedTypes
[Lex
.getStrVal()];
2289 // If the type hasn't been defined yet, create a forward definition and
2290 // remember where that forward def'n was seen (in case it never is defined).
2292 Entry
.first
= StructType::create(Context
, Lex
.getStrVal());
2293 Entry
.second
= Lex
.getLoc();
2295 Result
= Entry
.first
;
2300 case lltok::LocalVarID
: {
2302 std::pair
<Type
*, LocTy
> &Entry
= NumberedTypes
[Lex
.getUIntVal()];
2304 // If the type hasn't been defined yet, create a forward definition and
2305 // remember where that forward def'n was seen (in case it never is defined).
2307 Entry
.first
= StructType::create(Context
);
2308 Entry
.second
= Lex
.getLoc();
2310 Result
= Entry
.first
;
2316 // Parse the type suffixes.
2318 switch (Lex
.getKind()) {
2321 if (!AllowVoid
&& Result
->isVoidTy())
2322 return Error(TypeLoc
, "void type only allowed for function results");
2325 // Type ::= Type '*'
2327 if (Result
->isLabelTy())
2328 return TokError("basic block pointers are invalid");
2329 if (Result
->isVoidTy())
2330 return TokError("pointers to void are invalid - use i8* instead");
2331 if (!PointerType::isValidElementType(Result
))
2332 return TokError("pointer to this type is invalid");
2333 Result
= PointerType::getUnqual(Result
);
2337 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2338 case lltok::kw_addrspace
: {
2339 if (Result
->isLabelTy())
2340 return TokError("basic block pointers are invalid");
2341 if (Result
->isVoidTy())
2342 return TokError("pointers to void are invalid; use i8* instead");
2343 if (!PointerType::isValidElementType(Result
))
2344 return TokError("pointer to this type is invalid");
2346 if (ParseOptionalAddrSpace(AddrSpace
) ||
2347 ParseToken(lltok::star
, "expected '*' in address space"))
2350 Result
= PointerType::get(Result
, AddrSpace
);
2354 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2356 if (ParseFunctionType(Result
))
2363 /// ParseParameterList
2365 /// ::= '(' Arg (',' Arg)* ')'
2367 /// ::= Type OptionalAttributes Value OptionalAttributes
2368 bool LLParser::ParseParameterList(SmallVectorImpl
<ParamInfo
> &ArgList
,
2369 PerFunctionState
&PFS
, bool IsMustTailCall
,
2370 bool InVarArgsFunc
) {
2371 if (ParseToken(lltok::lparen
, "expected '(' in call"))
2374 while (Lex
.getKind() != lltok::rparen
) {
2375 // If this isn't the first argument, we need a comma.
2376 if (!ArgList
.empty() &&
2377 ParseToken(lltok::comma
, "expected ',' in argument list"))
2380 // Parse an ellipsis if this is a musttail call in a variadic function.
2381 if (Lex
.getKind() == lltok::dotdotdot
) {
2382 const char *Msg
= "unexpected ellipsis in argument list for ";
2383 if (!IsMustTailCall
)
2384 return TokError(Twine(Msg
) + "non-musttail call");
2386 return TokError(Twine(Msg
) + "musttail call in non-varargs function");
2387 Lex
.Lex(); // Lex the '...', it is purely for readability.
2388 return ParseToken(lltok::rparen
, "expected ')' at end of argument list");
2391 // Parse the argument.
2393 Type
*ArgTy
= nullptr;
2394 AttrBuilder ArgAttrs
;
2396 if (ParseType(ArgTy
, ArgLoc
))
2399 if (ArgTy
->isMetadataTy()) {
2400 if (ParseMetadataAsValue(V
, PFS
))
2403 // Otherwise, handle normal operands.
2404 if (ParseOptionalParamAttrs(ArgAttrs
) || ParseValue(ArgTy
, V
, PFS
))
2407 ArgList
.push_back(ParamInfo(
2408 ArgLoc
, V
, AttributeSet::get(V
->getContext(), ArgAttrs
)));
2411 if (IsMustTailCall
&& InVarArgsFunc
)
2412 return TokError("expected '...' at end of argument list for musttail call "
2413 "in varargs function");
2415 Lex
.Lex(); // Lex the ')'.
2419 /// ParseOptionalOperandBundles
2421 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2424 /// ::= bundle-tag '(' ')'
2425 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2427 /// bundle-tag ::= String Constant
2428 bool LLParser::ParseOptionalOperandBundles(
2429 SmallVectorImpl
<OperandBundleDef
> &BundleList
, PerFunctionState
&PFS
) {
2430 LocTy BeginLoc
= Lex
.getLoc();
2431 if (!EatIfPresent(lltok::lsquare
))
2434 while (Lex
.getKind() != lltok::rsquare
) {
2435 // If this isn't the first operand bundle, we need a comma.
2436 if (!BundleList
.empty() &&
2437 ParseToken(lltok::comma
, "expected ',' in input list"))
2441 if (ParseStringConstant(Tag
))
2444 if (ParseToken(lltok::lparen
, "expected '(' in operand bundle"))
2447 std::vector
<Value
*> Inputs
;
2448 while (Lex
.getKind() != lltok::rparen
) {
2449 // If this isn't the first input, we need a comma.
2450 if (!Inputs
.empty() &&
2451 ParseToken(lltok::comma
, "expected ',' in input list"))
2455 Value
*Input
= nullptr;
2456 if (ParseType(Ty
) || ParseValue(Ty
, Input
, PFS
))
2458 Inputs
.push_back(Input
);
2461 BundleList
.emplace_back(std::move(Tag
), std::move(Inputs
));
2463 Lex
.Lex(); // Lex the ')'.
2466 if (BundleList
.empty())
2467 return Error(BeginLoc
, "operand bundle set must not be empty");
2469 Lex
.Lex(); // Lex the ']'.
2473 /// ParseArgumentList - Parse the argument list for a function type or function
2475 /// ::= '(' ArgTypeListI ')'
2479 /// ::= ArgTypeList ',' '...'
2480 /// ::= ArgType (',' ArgType)*
2482 bool LLParser::ParseArgumentList(SmallVectorImpl
<ArgInfo
> &ArgList
,
2485 assert(Lex
.getKind() == lltok::lparen
);
2486 Lex
.Lex(); // eat the (.
2488 if (Lex
.getKind() == lltok::rparen
) {
2490 } else if (Lex
.getKind() == lltok::dotdotdot
) {
2494 LocTy TypeLoc
= Lex
.getLoc();
2495 Type
*ArgTy
= nullptr;
2499 if (ParseType(ArgTy
) ||
2500 ParseOptionalParamAttrs(Attrs
)) return true;
2502 if (ArgTy
->isVoidTy())
2503 return Error(TypeLoc
, "argument can not have void type");
2505 if (Lex
.getKind() == lltok::LocalVar
) {
2506 Name
= Lex
.getStrVal();
2510 if (!FunctionType::isValidArgumentType(ArgTy
))
2511 return Error(TypeLoc
, "invalid type for function argument");
2513 ArgList
.emplace_back(TypeLoc
, ArgTy
,
2514 AttributeSet::get(ArgTy
->getContext(), Attrs
),
2517 while (EatIfPresent(lltok::comma
)) {
2518 // Handle ... at end of arg list.
2519 if (EatIfPresent(lltok::dotdotdot
)) {
2524 // Otherwise must be an argument type.
2525 TypeLoc
= Lex
.getLoc();
2526 if (ParseType(ArgTy
) || ParseOptionalParamAttrs(Attrs
)) return true;
2528 if (ArgTy
->isVoidTy())
2529 return Error(TypeLoc
, "argument can not have void type");
2531 if (Lex
.getKind() == lltok::LocalVar
) {
2532 Name
= Lex
.getStrVal();
2538 if (!ArgTy
->isFirstClassType())
2539 return Error(TypeLoc
, "invalid type for function argument");
2541 ArgList
.emplace_back(TypeLoc
, ArgTy
,
2542 AttributeSet::get(ArgTy
->getContext(), Attrs
),
2547 return ParseToken(lltok::rparen
, "expected ')' at end of argument list");
2550 /// ParseFunctionType
2551 /// ::= Type ArgumentList OptionalAttrs
2552 bool LLParser::ParseFunctionType(Type
*&Result
) {
2553 assert(Lex
.getKind() == lltok::lparen
);
2555 if (!FunctionType::isValidReturnType(Result
))
2556 return TokError("invalid function return type");
2558 SmallVector
<ArgInfo
, 8> ArgList
;
2560 if (ParseArgumentList(ArgList
, isVarArg
))
2563 // Reject names on the arguments lists.
2564 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
2565 if (!ArgList
[i
].Name
.empty())
2566 return Error(ArgList
[i
].Loc
, "argument name invalid in function type");
2567 if (ArgList
[i
].Attrs
.hasAttributes())
2568 return Error(ArgList
[i
].Loc
,
2569 "argument attributes invalid in function type");
2572 SmallVector
<Type
*, 16> ArgListTy
;
2573 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
2574 ArgListTy
.push_back(ArgList
[i
].Ty
);
2576 Result
= FunctionType::get(Result
, ArgListTy
, isVarArg
);
2580 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2582 bool LLParser::ParseAnonStructType(Type
*&Result
, bool Packed
) {
2583 SmallVector
<Type
*, 8> Elts
;
2584 if (ParseStructBody(Elts
)) return true;
2586 Result
= StructType::get(Context
, Elts
, Packed
);
2590 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2591 bool LLParser::ParseStructDefinition(SMLoc TypeLoc
, StringRef Name
,
2592 std::pair
<Type
*, LocTy
> &Entry
,
2594 // If the type was already defined, diagnose the redefinition.
2595 if (Entry
.first
&& !Entry
.second
.isValid())
2596 return Error(TypeLoc
, "redefinition of type");
2598 // If we have opaque, just return without filling in the definition for the
2599 // struct. This counts as a definition as far as the .ll file goes.
2600 if (EatIfPresent(lltok::kw_opaque
)) {
2601 // This type is being defined, so clear the location to indicate this.
2602 Entry
.second
= SMLoc();
2604 // If this type number has never been uttered, create it.
2606 Entry
.first
= StructType::create(Context
, Name
);
2607 ResultTy
= Entry
.first
;
2611 // If the type starts with '<', then it is either a packed struct or a vector.
2612 bool isPacked
= EatIfPresent(lltok::less
);
2614 // If we don't have a struct, then we have a random type alias, which we
2615 // accept for compatibility with old files. These types are not allowed to be
2616 // forward referenced and not allowed to be recursive.
2617 if (Lex
.getKind() != lltok::lbrace
) {
2619 return Error(TypeLoc
, "forward references to non-struct type");
2623 return ParseArrayVectorType(ResultTy
, true);
2624 return ParseType(ResultTy
);
2627 // This type is being defined, so clear the location to indicate this.
2628 Entry
.second
= SMLoc();
2630 // If this type number has never been uttered, create it.
2632 Entry
.first
= StructType::create(Context
, Name
);
2634 StructType
*STy
= cast
<StructType
>(Entry
.first
);
2636 SmallVector
<Type
*, 8> Body
;
2637 if (ParseStructBody(Body
) ||
2638 (isPacked
&& ParseToken(lltok::greater
, "expected '>' in packed struct")))
2641 STy
->setBody(Body
, isPacked
);
2646 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2649 /// ::= '{' Type (',' Type)* '}'
2650 /// ::= '<' '{' '}' '>'
2651 /// ::= '<' '{' Type (',' Type)* '}' '>'
2652 bool LLParser::ParseStructBody(SmallVectorImpl
<Type
*> &Body
) {
2653 assert(Lex
.getKind() == lltok::lbrace
);
2654 Lex
.Lex(); // Consume the '{'
2656 // Handle the empty struct.
2657 if (EatIfPresent(lltok::rbrace
))
2660 LocTy EltTyLoc
= Lex
.getLoc();
2662 if (ParseType(Ty
)) return true;
2665 if (!StructType::isValidElementType(Ty
))
2666 return Error(EltTyLoc
, "invalid element type for struct");
2668 while (EatIfPresent(lltok::comma
)) {
2669 EltTyLoc
= Lex
.getLoc();
2670 if (ParseType(Ty
)) return true;
2672 if (!StructType::isValidElementType(Ty
))
2673 return Error(EltTyLoc
, "invalid element type for struct");
2678 return ParseToken(lltok::rbrace
, "expected '}' at end of struct");
2681 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2682 /// token has already been consumed.
2684 /// ::= '[' APSINTVAL 'x' Types ']'
2685 /// ::= '<' APSINTVAL 'x' Types '>'
2686 bool LLParser::ParseArrayVectorType(Type
*&Result
, bool isVector
) {
2687 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned() ||
2688 Lex
.getAPSIntVal().getBitWidth() > 64)
2689 return TokError("expected number in address space");
2691 LocTy SizeLoc
= Lex
.getLoc();
2692 uint64_t Size
= Lex
.getAPSIntVal().getZExtValue();
2695 if (ParseToken(lltok::kw_x
, "expected 'x' after element count"))
2698 LocTy TypeLoc
= Lex
.getLoc();
2699 Type
*EltTy
= nullptr;
2700 if (ParseType(EltTy
)) return true;
2702 if (ParseToken(isVector
? lltok::greater
: lltok::rsquare
,
2703 "expected end of sequential type"))
2708 return Error(SizeLoc
, "zero element vector is illegal");
2709 if ((unsigned)Size
!= Size
)
2710 return Error(SizeLoc
, "size too large for vector");
2711 if (!VectorType::isValidElementType(EltTy
))
2712 return Error(TypeLoc
, "invalid vector element type");
2713 Result
= VectorType::get(EltTy
, unsigned(Size
));
2715 if (!ArrayType::isValidElementType(EltTy
))
2716 return Error(TypeLoc
, "invalid array element type");
2717 Result
= ArrayType::get(EltTy
, Size
);
2722 //===----------------------------------------------------------------------===//
2723 // Function Semantic Analysis.
2724 //===----------------------------------------------------------------------===//
2726 LLParser::PerFunctionState::PerFunctionState(LLParser
&p
, Function
&f
,
2728 : P(p
), F(f
), FunctionNumber(functionNumber
) {
2730 // Insert unnamed arguments into the NumberedVals list.
2731 for (Argument
&A
: F
.args())
2733 NumberedVals
.push_back(&A
);
2736 LLParser::PerFunctionState::~PerFunctionState() {
2737 // If there were any forward referenced non-basicblock values, delete them.
2739 for (const auto &P
: ForwardRefVals
) {
2740 if (isa
<BasicBlock
>(P
.second
.first
))
2742 P
.second
.first
->replaceAllUsesWith(
2743 UndefValue::get(P
.second
.first
->getType()));
2744 P
.second
.first
->deleteValue();
2747 for (const auto &P
: ForwardRefValIDs
) {
2748 if (isa
<BasicBlock
>(P
.second
.first
))
2750 P
.second
.first
->replaceAllUsesWith(
2751 UndefValue::get(P
.second
.first
->getType()));
2752 P
.second
.first
->deleteValue();
2756 bool LLParser::PerFunctionState::FinishFunction() {
2757 if (!ForwardRefVals
.empty())
2758 return P
.Error(ForwardRefVals
.begin()->second
.second
,
2759 "use of undefined value '%" + ForwardRefVals
.begin()->first
+
2761 if (!ForwardRefValIDs
.empty())
2762 return P
.Error(ForwardRefValIDs
.begin()->second
.second
,
2763 "use of undefined value '%" +
2764 Twine(ForwardRefValIDs
.begin()->first
) + "'");
2768 /// GetVal - Get a value with the specified name or ID, creating a
2769 /// forward reference record if needed. This can return null if the value
2770 /// exists but does not have the right type.
2771 Value
*LLParser::PerFunctionState::GetVal(const std::string
&Name
, Type
*Ty
,
2772 LocTy Loc
, bool IsCall
) {
2773 // Look this name up in the normal function symbol table.
2774 Value
*Val
= F
.getValueSymbolTable()->lookup(Name
);
2776 // If this is a forward reference for the value, see if we already created a
2777 // forward ref record.
2779 auto I
= ForwardRefVals
.find(Name
);
2780 if (I
!= ForwardRefVals
.end())
2781 Val
= I
->second
.first
;
2784 // If we have the value in the symbol table or fwd-ref table, return it.
2786 return P
.checkValidVariableType(Loc
, "%" + Name
, Ty
, Val
, IsCall
);
2788 // Don't make placeholders with invalid type.
2789 if (!Ty
->isFirstClassType()) {
2790 P
.Error(Loc
, "invalid use of a non-first-class type");
2794 // Otherwise, create a new forward reference for this value and remember it.
2796 if (Ty
->isLabelTy()) {
2797 FwdVal
= BasicBlock::Create(F
.getContext(), Name
, &F
);
2799 FwdVal
= new Argument(Ty
, Name
);
2802 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
2806 Value
*LLParser::PerFunctionState::GetVal(unsigned ID
, Type
*Ty
, LocTy Loc
,
2808 // Look this name up in the normal function symbol table.
2809 Value
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : nullptr;
2811 // If this is a forward reference for the value, see if we already created a
2812 // forward ref record.
2814 auto I
= ForwardRefValIDs
.find(ID
);
2815 if (I
!= ForwardRefValIDs
.end())
2816 Val
= I
->second
.first
;
2819 // If we have the value in the symbol table or fwd-ref table, return it.
2821 return P
.checkValidVariableType(Loc
, "%" + Twine(ID
), Ty
, Val
, IsCall
);
2823 if (!Ty
->isFirstClassType()) {
2824 P
.Error(Loc
, "invalid use of a non-first-class type");
2828 // Otherwise, create a new forward reference for this value and remember it.
2830 if (Ty
->isLabelTy()) {
2831 FwdVal
= BasicBlock::Create(F
.getContext(), "", &F
);
2833 FwdVal
= new Argument(Ty
);
2836 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
2840 /// SetInstName - After an instruction is parsed and inserted into its
2841 /// basic block, this installs its name.
2842 bool LLParser::PerFunctionState::SetInstName(int NameID
,
2843 const std::string
&NameStr
,
2844 LocTy NameLoc
, Instruction
*Inst
) {
2845 // If this instruction has void type, it cannot have a name or ID specified.
2846 if (Inst
->getType()->isVoidTy()) {
2847 if (NameID
!= -1 || !NameStr
.empty())
2848 return P
.Error(NameLoc
, "instructions returning void cannot have a name");
2852 // If this was a numbered instruction, verify that the instruction is the
2853 // expected value and resolve any forward references.
2854 if (NameStr
.empty()) {
2855 // If neither a name nor an ID was specified, just use the next ID.
2857 NameID
= NumberedVals
.size();
2859 if (unsigned(NameID
) != NumberedVals
.size())
2860 return P
.Error(NameLoc
, "instruction expected to be numbered '%" +
2861 Twine(NumberedVals
.size()) + "'");
2863 auto FI
= ForwardRefValIDs
.find(NameID
);
2864 if (FI
!= ForwardRefValIDs
.end()) {
2865 Value
*Sentinel
= FI
->second
.first
;
2866 if (Sentinel
->getType() != Inst
->getType())
2867 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
2868 getTypeString(FI
->second
.first
->getType()) + "'");
2870 Sentinel
->replaceAllUsesWith(Inst
);
2871 Sentinel
->deleteValue();
2872 ForwardRefValIDs
.erase(FI
);
2875 NumberedVals
.push_back(Inst
);
2879 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2880 auto FI
= ForwardRefVals
.find(NameStr
);
2881 if (FI
!= ForwardRefVals
.end()) {
2882 Value
*Sentinel
= FI
->second
.first
;
2883 if (Sentinel
->getType() != Inst
->getType())
2884 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
2885 getTypeString(FI
->second
.first
->getType()) + "'");
2887 Sentinel
->replaceAllUsesWith(Inst
);
2888 Sentinel
->deleteValue();
2889 ForwardRefVals
.erase(FI
);
2892 // Set the name on the instruction.
2893 Inst
->setName(NameStr
);
2895 if (Inst
->getName() != NameStr
)
2896 return P
.Error(NameLoc
, "multiple definition of local value named '" +
2901 /// GetBB - Get a basic block with the specified name or ID, creating a
2902 /// forward reference record if needed.
2903 BasicBlock
*LLParser::PerFunctionState::GetBB(const std::string
&Name
,
2905 return dyn_cast_or_null
<BasicBlock
>(
2906 GetVal(Name
, Type::getLabelTy(F
.getContext()), Loc
, /*IsCall=*/false));
2909 BasicBlock
*LLParser::PerFunctionState::GetBB(unsigned ID
, LocTy Loc
) {
2910 return dyn_cast_or_null
<BasicBlock
>(
2911 GetVal(ID
, Type::getLabelTy(F
.getContext()), Loc
, /*IsCall=*/false));
2914 /// DefineBB - Define the specified basic block, which is either named or
2915 /// unnamed. If there is an error, this returns null otherwise it returns
2916 /// the block being defined.
2917 BasicBlock
*LLParser::PerFunctionState::DefineBB(const std::string
&Name
,
2921 BB
= GetBB(NumberedVals
.size(), Loc
);
2923 BB
= GetBB(Name
, Loc
);
2924 if (!BB
) return nullptr; // Already diagnosed error.
2926 // Move the block to the end of the function. Forward ref'd blocks are
2927 // inserted wherever they happen to be referenced.
2928 F
.getBasicBlockList().splice(F
.end(), F
.getBasicBlockList(), BB
);
2930 // Remove the block from forward ref sets.
2932 ForwardRefValIDs
.erase(NumberedVals
.size());
2933 NumberedVals
.push_back(BB
);
2935 // BB forward references are already in the function symbol table.
2936 ForwardRefVals
.erase(Name
);
2942 //===----------------------------------------------------------------------===//
2944 //===----------------------------------------------------------------------===//
2946 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2947 /// type implied. For example, if we parse "4" we don't know what integer type
2948 /// it has. The value will later be combined with its type and checked for
2949 /// sanity. PFS is used to convert function-local operands of metadata (since
2950 /// metadata operands are not just parsed here but also converted to values).
2951 /// PFS can be null when we are not parsing metadata values inside a function.
2952 bool LLParser::ParseValID(ValID
&ID
, PerFunctionState
*PFS
) {
2953 ID
.Loc
= Lex
.getLoc();
2954 switch (Lex
.getKind()) {
2955 default: return TokError("expected value token");
2956 case lltok::GlobalID
: // @42
2957 ID
.UIntVal
= Lex
.getUIntVal();
2958 ID
.Kind
= ValID::t_GlobalID
;
2960 case lltok::GlobalVar
: // @foo
2961 ID
.StrVal
= Lex
.getStrVal();
2962 ID
.Kind
= ValID::t_GlobalName
;
2964 case lltok::LocalVarID
: // %42
2965 ID
.UIntVal
= Lex
.getUIntVal();
2966 ID
.Kind
= ValID::t_LocalID
;
2968 case lltok::LocalVar
: // %foo
2969 ID
.StrVal
= Lex
.getStrVal();
2970 ID
.Kind
= ValID::t_LocalName
;
2973 ID
.APSIntVal
= Lex
.getAPSIntVal();
2974 ID
.Kind
= ValID::t_APSInt
;
2976 case lltok::APFloat
:
2977 ID
.APFloatVal
= Lex
.getAPFloatVal();
2978 ID
.Kind
= ValID::t_APFloat
;
2980 case lltok::kw_true
:
2981 ID
.ConstantVal
= ConstantInt::getTrue(Context
);
2982 ID
.Kind
= ValID::t_Constant
;
2984 case lltok::kw_false
:
2985 ID
.ConstantVal
= ConstantInt::getFalse(Context
);
2986 ID
.Kind
= ValID::t_Constant
;
2988 case lltok::kw_null
: ID
.Kind
= ValID::t_Null
; break;
2989 case lltok::kw_undef
: ID
.Kind
= ValID::t_Undef
; break;
2990 case lltok::kw_zeroinitializer
: ID
.Kind
= ValID::t_Zero
; break;
2991 case lltok::kw_none
: ID
.Kind
= ValID::t_None
; break;
2993 case lltok::lbrace
: {
2994 // ValID ::= '{' ConstVector '}'
2996 SmallVector
<Constant
*, 16> Elts
;
2997 if (ParseGlobalValueVector(Elts
) ||
2998 ParseToken(lltok::rbrace
, "expected end of struct constant"))
3001 ID
.ConstantStructElts
= make_unique
<Constant
*[]>(Elts
.size());
3002 ID
.UIntVal
= Elts
.size();
3003 memcpy(ID
.ConstantStructElts
.get(), Elts
.data(),
3004 Elts
.size() * sizeof(Elts
[0]));
3005 ID
.Kind
= ValID::t_ConstantStruct
;
3009 // ValID ::= '<' ConstVector '>' --> Vector.
3010 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3012 bool isPackedStruct
= EatIfPresent(lltok::lbrace
);
3014 SmallVector
<Constant
*, 16> Elts
;
3015 LocTy FirstEltLoc
= Lex
.getLoc();
3016 if (ParseGlobalValueVector(Elts
) ||
3018 ParseToken(lltok::rbrace
, "expected end of packed struct")) ||
3019 ParseToken(lltok::greater
, "expected end of constant"))
3022 if (isPackedStruct
) {
3023 ID
.ConstantStructElts
= make_unique
<Constant
*[]>(Elts
.size());
3024 memcpy(ID
.ConstantStructElts
.get(), Elts
.data(),
3025 Elts
.size() * sizeof(Elts
[0]));
3026 ID
.UIntVal
= Elts
.size();
3027 ID
.Kind
= ValID::t_PackedConstantStruct
;
3032 return Error(ID
.Loc
, "constant vector must not be empty");
3034 if (!Elts
[0]->getType()->isIntegerTy() &&
3035 !Elts
[0]->getType()->isFloatingPointTy() &&
3036 !Elts
[0]->getType()->isPointerTy())
3037 return Error(FirstEltLoc
,
3038 "vector elements must have integer, pointer or floating point type");
3040 // Verify that all the vector elements have the same type.
3041 for (unsigned i
= 1, e
= Elts
.size(); i
!= e
; ++i
)
3042 if (Elts
[i
]->getType() != Elts
[0]->getType())
3043 return Error(FirstEltLoc
,
3044 "vector element #" + Twine(i
) +
3045 " is not of type '" + getTypeString(Elts
[0]->getType()));
3047 ID
.ConstantVal
= ConstantVector::get(Elts
);
3048 ID
.Kind
= ValID::t_Constant
;
3051 case lltok::lsquare
: { // Array Constant
3053 SmallVector
<Constant
*, 16> Elts
;
3054 LocTy FirstEltLoc
= Lex
.getLoc();
3055 if (ParseGlobalValueVector(Elts
) ||
3056 ParseToken(lltok::rsquare
, "expected end of array constant"))
3059 // Handle empty element.
3061 // Use undef instead of an array because it's inconvenient to determine
3062 // the element type at this point, there being no elements to examine.
3063 ID
.Kind
= ValID::t_EmptyArray
;
3067 if (!Elts
[0]->getType()->isFirstClassType())
3068 return Error(FirstEltLoc
, "invalid array element type: " +
3069 getTypeString(Elts
[0]->getType()));
3071 ArrayType
*ATy
= ArrayType::get(Elts
[0]->getType(), Elts
.size());
3073 // Verify all elements are correct type!
3074 for (unsigned i
= 0, e
= Elts
.size(); i
!= e
; ++i
) {
3075 if (Elts
[i
]->getType() != Elts
[0]->getType())
3076 return Error(FirstEltLoc
,
3077 "array element #" + Twine(i
) +
3078 " is not of type '" + getTypeString(Elts
[0]->getType()));
3081 ID
.ConstantVal
= ConstantArray::get(ATy
, Elts
);
3082 ID
.Kind
= ValID::t_Constant
;
3085 case lltok::kw_c
: // c "foo"
3087 ID
.ConstantVal
= ConstantDataArray::getString(Context
, Lex
.getStrVal(),
3089 if (ParseToken(lltok::StringConstant
, "expected string")) return true;
3090 ID
.Kind
= ValID::t_Constant
;
3093 case lltok::kw_asm
: {
3094 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3096 bool HasSideEffect
, AlignStack
, AsmDialect
;
3098 if (ParseOptionalToken(lltok::kw_sideeffect
, HasSideEffect
) ||
3099 ParseOptionalToken(lltok::kw_alignstack
, AlignStack
) ||
3100 ParseOptionalToken(lltok::kw_inteldialect
, AsmDialect
) ||
3101 ParseStringConstant(ID
.StrVal
) ||
3102 ParseToken(lltok::comma
, "expected comma in inline asm expression") ||
3103 ParseToken(lltok::StringConstant
, "expected constraint string"))
3105 ID
.StrVal2
= Lex
.getStrVal();
3106 ID
.UIntVal
= unsigned(HasSideEffect
) | (unsigned(AlignStack
)<<1) |
3107 (unsigned(AsmDialect
)<<2);
3108 ID
.Kind
= ValID::t_InlineAsm
;
3112 case lltok::kw_blockaddress
: {
3113 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3118 if (ParseToken(lltok::lparen
, "expected '(' in block address expression") ||
3120 ParseToken(lltok::comma
, "expected comma in block address expression")||
3121 ParseValID(Label
) ||
3122 ParseToken(lltok::rparen
, "expected ')' in block address expression"))
3125 if (Fn
.Kind
!= ValID::t_GlobalID
&& Fn
.Kind
!= ValID::t_GlobalName
)
3126 return Error(Fn
.Loc
, "expected function name in blockaddress");
3127 if (Label
.Kind
!= ValID::t_LocalID
&& Label
.Kind
!= ValID::t_LocalName
)
3128 return Error(Label
.Loc
, "expected basic block name in blockaddress");
3130 // Try to find the function (but skip it if it's forward-referenced).
3131 GlobalValue
*GV
= nullptr;
3132 if (Fn
.Kind
== ValID::t_GlobalID
) {
3133 if (Fn
.UIntVal
< NumberedVals
.size())
3134 GV
= NumberedVals
[Fn
.UIntVal
];
3135 } else if (!ForwardRefVals
.count(Fn
.StrVal
)) {
3136 GV
= M
->getNamedValue(Fn
.StrVal
);
3138 Function
*F
= nullptr;
3140 // Confirm that it's actually a function with a definition.
3141 if (!isa
<Function
>(GV
))
3142 return Error(Fn
.Loc
, "expected function name in blockaddress");
3143 F
= cast
<Function
>(GV
);
3144 if (F
->isDeclaration())
3145 return Error(Fn
.Loc
, "cannot take blockaddress inside a declaration");
3149 // Make a global variable as a placeholder for this reference.
3150 GlobalValue
*&FwdRef
=
3151 ForwardRefBlockAddresses
.insert(std::make_pair(
3153 std::map
<ValID
, GlobalValue
*>()))
3154 .first
->second
.insert(std::make_pair(std::move(Label
), nullptr))
3157 FwdRef
= new GlobalVariable(*M
, Type::getInt8Ty(Context
), false,
3158 GlobalValue::InternalLinkage
, nullptr, "");
3159 ID
.ConstantVal
= FwdRef
;
3160 ID
.Kind
= ValID::t_Constant
;
3164 // We found the function; now find the basic block. Don't use PFS, since we
3165 // might be inside a constant expression.
3167 if (BlockAddressPFS
&& F
== &BlockAddressPFS
->getFunction()) {
3168 if (Label
.Kind
== ValID::t_LocalID
)
3169 BB
= BlockAddressPFS
->GetBB(Label
.UIntVal
, Label
.Loc
);
3171 BB
= BlockAddressPFS
->GetBB(Label
.StrVal
, Label
.Loc
);
3173 return Error(Label
.Loc
, "referenced value is not a basic block");
3175 if (Label
.Kind
== ValID::t_LocalID
)
3176 return Error(Label
.Loc
, "cannot take address of numeric label after "
3177 "the function is defined");
3178 BB
= dyn_cast_or_null
<BasicBlock
>(
3179 F
->getValueSymbolTable()->lookup(Label
.StrVal
));
3181 return Error(Label
.Loc
, "referenced value is not a basic block");
3184 ID
.ConstantVal
= BlockAddress::get(F
, BB
);
3185 ID
.Kind
= ValID::t_Constant
;
3189 case lltok::kw_trunc
:
3190 case lltok::kw_zext
:
3191 case lltok::kw_sext
:
3192 case lltok::kw_fptrunc
:
3193 case lltok::kw_fpext
:
3194 case lltok::kw_bitcast
:
3195 case lltok::kw_addrspacecast
:
3196 case lltok::kw_uitofp
:
3197 case lltok::kw_sitofp
:
3198 case lltok::kw_fptoui
:
3199 case lltok::kw_fptosi
:
3200 case lltok::kw_inttoptr
:
3201 case lltok::kw_ptrtoint
: {
3202 unsigned Opc
= Lex
.getUIntVal();
3203 Type
*DestTy
= nullptr;
3206 if (ParseToken(lltok::lparen
, "expected '(' after constantexpr cast") ||
3207 ParseGlobalTypeAndValue(SrcVal
) ||
3208 ParseToken(lltok::kw_to
, "expected 'to' in constantexpr cast") ||
3209 ParseType(DestTy
) ||
3210 ParseToken(lltok::rparen
, "expected ')' at end of constantexpr cast"))
3212 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, SrcVal
, DestTy
))
3213 return Error(ID
.Loc
, "invalid cast opcode for cast from '" +
3214 getTypeString(SrcVal
->getType()) + "' to '" +
3215 getTypeString(DestTy
) + "'");
3216 ID
.ConstantVal
= ConstantExpr::getCast((Instruction::CastOps
)Opc
,
3218 ID
.Kind
= ValID::t_Constant
;
3221 case lltok::kw_extractvalue
: {
3224 SmallVector
<unsigned, 4> Indices
;
3225 if (ParseToken(lltok::lparen
, "expected '(' in extractvalue constantexpr")||
3226 ParseGlobalTypeAndValue(Val
) ||
3227 ParseIndexList(Indices
) ||
3228 ParseToken(lltok::rparen
, "expected ')' in extractvalue constantexpr"))
3231 if (!Val
->getType()->isAggregateType())
3232 return Error(ID
.Loc
, "extractvalue operand must be aggregate type");
3233 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
))
3234 return Error(ID
.Loc
, "invalid indices for extractvalue");
3235 ID
.ConstantVal
= ConstantExpr::getExtractValue(Val
, Indices
);
3236 ID
.Kind
= ValID::t_Constant
;
3239 case lltok::kw_insertvalue
: {
3241 Constant
*Val0
, *Val1
;
3242 SmallVector
<unsigned, 4> Indices
;
3243 if (ParseToken(lltok::lparen
, "expected '(' in insertvalue constantexpr")||
3244 ParseGlobalTypeAndValue(Val0
) ||
3245 ParseToken(lltok::comma
, "expected comma in insertvalue constantexpr")||
3246 ParseGlobalTypeAndValue(Val1
) ||
3247 ParseIndexList(Indices
) ||
3248 ParseToken(lltok::rparen
, "expected ')' in insertvalue constantexpr"))
3250 if (!Val0
->getType()->isAggregateType())
3251 return Error(ID
.Loc
, "insertvalue operand must be aggregate type");
3253 ExtractValueInst::getIndexedType(Val0
->getType(), Indices
);
3255 return Error(ID
.Loc
, "invalid indices for insertvalue");
3256 if (IndexedType
!= Val1
->getType())
3257 return Error(ID
.Loc
, "insertvalue operand and field disagree in type: '" +
3258 getTypeString(Val1
->getType()) +
3259 "' instead of '" + getTypeString(IndexedType
) +
3261 ID
.ConstantVal
= ConstantExpr::getInsertValue(Val0
, Val1
, Indices
);
3262 ID
.Kind
= ValID::t_Constant
;
3265 case lltok::kw_icmp
:
3266 case lltok::kw_fcmp
: {
3267 unsigned PredVal
, Opc
= Lex
.getUIntVal();
3268 Constant
*Val0
, *Val1
;
3270 if (ParseCmpPredicate(PredVal
, Opc
) ||
3271 ParseToken(lltok::lparen
, "expected '(' in compare constantexpr") ||
3272 ParseGlobalTypeAndValue(Val0
) ||
3273 ParseToken(lltok::comma
, "expected comma in compare constantexpr") ||
3274 ParseGlobalTypeAndValue(Val1
) ||
3275 ParseToken(lltok::rparen
, "expected ')' in compare constantexpr"))
3278 if (Val0
->getType() != Val1
->getType())
3279 return Error(ID
.Loc
, "compare operands must have the same type");
3281 CmpInst::Predicate Pred
= (CmpInst::Predicate
)PredVal
;
3283 if (Opc
== Instruction::FCmp
) {
3284 if (!Val0
->getType()->isFPOrFPVectorTy())
3285 return Error(ID
.Loc
, "fcmp requires floating point operands");
3286 ID
.ConstantVal
= ConstantExpr::getFCmp(Pred
, Val0
, Val1
);
3288 assert(Opc
== Instruction::ICmp
&& "Unexpected opcode for CmpInst!");
3289 if (!Val0
->getType()->isIntOrIntVectorTy() &&
3290 !Val0
->getType()->isPtrOrPtrVectorTy())
3291 return Error(ID
.Loc
, "icmp requires pointer or integer operands");
3292 ID
.ConstantVal
= ConstantExpr::getICmp(Pred
, Val0
, Val1
);
3294 ID
.Kind
= ValID::t_Constant
;
3299 case lltok::kw_fneg
: {
3300 unsigned Opc
= Lex
.getUIntVal();
3303 if (ParseToken(lltok::lparen
, "expected '(' in unary constantexpr") ||
3304 ParseGlobalTypeAndValue(Val
) ||
3305 ParseToken(lltok::rparen
, "expected ')' in unary constantexpr"))
3308 // Check that the type is valid for the operator.
3310 case Instruction::FNeg
:
3311 if (!Val
->getType()->isFPOrFPVectorTy())
3312 return Error(ID
.Loc
, "constexpr requires fp operands");
3314 default: llvm_unreachable("Unknown unary operator!");
3317 Constant
*C
= ConstantExpr::get(Opc
, Val
, Flags
);
3319 ID
.Kind
= ValID::t_Constant
;
3322 // Binary Operators.
3324 case lltok::kw_fadd
:
3326 case lltok::kw_fsub
:
3328 case lltok::kw_fmul
:
3329 case lltok::kw_udiv
:
3330 case lltok::kw_sdiv
:
3331 case lltok::kw_fdiv
:
3332 case lltok::kw_urem
:
3333 case lltok::kw_srem
:
3334 case lltok::kw_frem
:
3336 case lltok::kw_lshr
:
3337 case lltok::kw_ashr
: {
3341 unsigned Opc
= Lex
.getUIntVal();
3342 Constant
*Val0
, *Val1
;
3344 LocTy ModifierLoc
= Lex
.getLoc();
3345 if (Opc
== Instruction::Add
|| Opc
== Instruction::Sub
||
3346 Opc
== Instruction::Mul
|| Opc
== Instruction::Shl
) {
3347 if (EatIfPresent(lltok::kw_nuw
))
3349 if (EatIfPresent(lltok::kw_nsw
)) {
3351 if (EatIfPresent(lltok::kw_nuw
))
3354 } else if (Opc
== Instruction::SDiv
|| Opc
== Instruction::UDiv
||
3355 Opc
== Instruction::LShr
|| Opc
== Instruction::AShr
) {
3356 if (EatIfPresent(lltok::kw_exact
))
3359 if (ParseToken(lltok::lparen
, "expected '(' in binary constantexpr") ||
3360 ParseGlobalTypeAndValue(Val0
) ||
3361 ParseToken(lltok::comma
, "expected comma in binary constantexpr") ||
3362 ParseGlobalTypeAndValue(Val1
) ||
3363 ParseToken(lltok::rparen
, "expected ')' in binary constantexpr"))
3365 if (Val0
->getType() != Val1
->getType())
3366 return Error(ID
.Loc
, "operands of constexpr must have same type");
3367 if (!Val0
->getType()->isIntOrIntVectorTy()) {
3369 return Error(ModifierLoc
, "nuw only applies to integer operations");
3371 return Error(ModifierLoc
, "nsw only applies to integer operations");
3373 // Check that the type is valid for the operator.
3375 case Instruction::Add
:
3376 case Instruction::Sub
:
3377 case Instruction::Mul
:
3378 case Instruction::UDiv
:
3379 case Instruction::SDiv
:
3380 case Instruction::URem
:
3381 case Instruction::SRem
:
3382 case Instruction::Shl
:
3383 case Instruction::AShr
:
3384 case Instruction::LShr
:
3385 if (!Val0
->getType()->isIntOrIntVectorTy())
3386 return Error(ID
.Loc
, "constexpr requires integer operands");
3388 case Instruction::FAdd
:
3389 case Instruction::FSub
:
3390 case Instruction::FMul
:
3391 case Instruction::FDiv
:
3392 case Instruction::FRem
:
3393 if (!Val0
->getType()->isFPOrFPVectorTy())
3394 return Error(ID
.Loc
, "constexpr requires fp operands");
3396 default: llvm_unreachable("Unknown binary operator!");
3399 if (NUW
) Flags
|= OverflowingBinaryOperator::NoUnsignedWrap
;
3400 if (NSW
) Flags
|= OverflowingBinaryOperator::NoSignedWrap
;
3401 if (Exact
) Flags
|= PossiblyExactOperator::IsExact
;
3402 Constant
*C
= ConstantExpr::get(Opc
, Val0
, Val1
, Flags
);
3404 ID
.Kind
= ValID::t_Constant
;
3408 // Logical Operations
3411 case lltok::kw_xor
: {
3412 unsigned Opc
= Lex
.getUIntVal();
3413 Constant
*Val0
, *Val1
;
3415 if (ParseToken(lltok::lparen
, "expected '(' in logical constantexpr") ||
3416 ParseGlobalTypeAndValue(Val0
) ||
3417 ParseToken(lltok::comma
, "expected comma in logical constantexpr") ||
3418 ParseGlobalTypeAndValue(Val1
) ||
3419 ParseToken(lltok::rparen
, "expected ')' in logical constantexpr"))
3421 if (Val0
->getType() != Val1
->getType())
3422 return Error(ID
.Loc
, "operands of constexpr must have same type");
3423 if (!Val0
->getType()->isIntOrIntVectorTy())
3424 return Error(ID
.Loc
,
3425 "constexpr requires integer or integer vector operands");
3426 ID
.ConstantVal
= ConstantExpr::get(Opc
, Val0
, Val1
);
3427 ID
.Kind
= ValID::t_Constant
;
3431 case lltok::kw_getelementptr
:
3432 case lltok::kw_shufflevector
:
3433 case lltok::kw_insertelement
:
3434 case lltok::kw_extractelement
:
3435 case lltok::kw_select
: {
3436 unsigned Opc
= Lex
.getUIntVal();
3437 SmallVector
<Constant
*, 16> Elts
;
3438 bool InBounds
= false;
3442 if (Opc
== Instruction::GetElementPtr
)
3443 InBounds
= EatIfPresent(lltok::kw_inbounds
);
3445 if (ParseToken(lltok::lparen
, "expected '(' in constantexpr"))
3448 LocTy ExplicitTypeLoc
= Lex
.getLoc();
3449 if (Opc
== Instruction::GetElementPtr
) {
3450 if (ParseType(Ty
) ||
3451 ParseToken(lltok::comma
, "expected comma after getelementptr's type"))
3455 Optional
<unsigned> InRangeOp
;
3456 if (ParseGlobalValueVector(
3457 Elts
, Opc
== Instruction::GetElementPtr
? &InRangeOp
: nullptr) ||
3458 ParseToken(lltok::rparen
, "expected ')' in constantexpr"))
3461 if (Opc
== Instruction::GetElementPtr
) {
3462 if (Elts
.size() == 0 ||
3463 !Elts
[0]->getType()->isPtrOrPtrVectorTy())
3464 return Error(ID
.Loc
, "base of getelementptr must be a pointer");
3466 Type
*BaseType
= Elts
[0]->getType();
3467 auto *BasePointerType
= cast
<PointerType
>(BaseType
->getScalarType());
3468 if (Ty
!= BasePointerType
->getElementType())
3471 "explicit pointee type doesn't match operand's pointee type");
3474 BaseType
->isVectorTy() ? BaseType
->getVectorNumElements() : 0;
3476 ArrayRef
<Constant
*> Indices(Elts
.begin() + 1, Elts
.end());
3477 for (Constant
*Val
: Indices
) {
3478 Type
*ValTy
= Val
->getType();
3479 if (!ValTy
->isIntOrIntVectorTy())
3480 return Error(ID
.Loc
, "getelementptr index must be an integer");
3481 if (ValTy
->isVectorTy()) {
3482 unsigned ValNumEl
= ValTy
->getVectorNumElements();
3483 if (GEPWidth
&& (ValNumEl
!= GEPWidth
))
3486 "getelementptr vector index has a wrong number of elements");
3487 // GEPWidth may have been unknown because the base is a scalar,
3488 // but it is known now.
3489 GEPWidth
= ValNumEl
;
3493 SmallPtrSet
<Type
*, 4> Visited
;
3494 if (!Indices
.empty() && !Ty
->isSized(&Visited
))
3495 return Error(ID
.Loc
, "base element of getelementptr must be sized");
3497 if (!GetElementPtrInst::getIndexedType(Ty
, Indices
))
3498 return Error(ID
.Loc
, "invalid getelementptr indices");
3501 if (*InRangeOp
== 0)
3502 return Error(ID
.Loc
,
3503 "inrange keyword may not appear on pointer operand");
3507 ID
.ConstantVal
= ConstantExpr::getGetElementPtr(Ty
, Elts
[0], Indices
,
3508 InBounds
, InRangeOp
);
3509 } else if (Opc
== Instruction::Select
) {
3510 if (Elts
.size() != 3)
3511 return Error(ID
.Loc
, "expected three operands to select");
3512 if (const char *Reason
= SelectInst::areInvalidOperands(Elts
[0], Elts
[1],
3514 return Error(ID
.Loc
, Reason
);
3515 ID
.ConstantVal
= ConstantExpr::getSelect(Elts
[0], Elts
[1], Elts
[2]);
3516 } else if (Opc
== Instruction::ShuffleVector
) {
3517 if (Elts
.size() != 3)
3518 return Error(ID
.Loc
, "expected three operands to shufflevector");
3519 if (!ShuffleVectorInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
3520 return Error(ID
.Loc
, "invalid operands to shufflevector");
3522 ConstantExpr::getShuffleVector(Elts
[0], Elts
[1],Elts
[2]);
3523 } else if (Opc
== Instruction::ExtractElement
) {
3524 if (Elts
.size() != 2)
3525 return Error(ID
.Loc
, "expected two operands to extractelement");
3526 if (!ExtractElementInst::isValidOperands(Elts
[0], Elts
[1]))
3527 return Error(ID
.Loc
, "invalid extractelement operands");
3528 ID
.ConstantVal
= ConstantExpr::getExtractElement(Elts
[0], Elts
[1]);
3530 assert(Opc
== Instruction::InsertElement
&& "Unknown opcode");
3531 if (Elts
.size() != 3)
3532 return Error(ID
.Loc
, "expected three operands to insertelement");
3533 if (!InsertElementInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
3534 return Error(ID
.Loc
, "invalid insertelement operands");
3536 ConstantExpr::getInsertElement(Elts
[0], Elts
[1],Elts
[2]);
3539 ID
.Kind
= ValID::t_Constant
;
3548 /// ParseGlobalValue - Parse a global value with the specified type.
3549 bool LLParser::ParseGlobalValue(Type
*Ty
, Constant
*&C
) {
3553 bool Parsed
= ParseValID(ID
) ||
3554 ConvertValIDToValue(Ty
, ID
, V
, nullptr, /*IsCall=*/false);
3555 if (V
&& !(C
= dyn_cast
<Constant
>(V
)))
3556 return Error(ID
.Loc
, "global values must be constants");
3560 bool LLParser::ParseGlobalTypeAndValue(Constant
*&V
) {
3562 return ParseType(Ty
) ||
3563 ParseGlobalValue(Ty
, V
);
3566 bool LLParser::parseOptionalComdat(StringRef GlobalName
, Comdat
*&C
) {
3569 LocTy KwLoc
= Lex
.getLoc();
3570 if (!EatIfPresent(lltok::kw_comdat
))
3573 if (EatIfPresent(lltok::lparen
)) {
3574 if (Lex
.getKind() != lltok::ComdatVar
)
3575 return TokError("expected comdat variable");
3576 C
= getComdat(Lex
.getStrVal(), Lex
.getLoc());
3578 if (ParseToken(lltok::rparen
, "expected ')' after comdat var"))
3581 if (GlobalName
.empty())
3582 return TokError("comdat cannot be unnamed");
3583 C
= getComdat(GlobalName
, KwLoc
);
3589 /// ParseGlobalValueVector
3591 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3592 bool LLParser::ParseGlobalValueVector(SmallVectorImpl
<Constant
*> &Elts
,
3593 Optional
<unsigned> *InRangeOp
) {
3595 if (Lex
.getKind() == lltok::rbrace
||
3596 Lex
.getKind() == lltok::rsquare
||
3597 Lex
.getKind() == lltok::greater
||
3598 Lex
.getKind() == lltok::rparen
)
3602 if (InRangeOp
&& !*InRangeOp
&& EatIfPresent(lltok::kw_inrange
))
3603 *InRangeOp
= Elts
.size();
3606 if (ParseGlobalTypeAndValue(C
)) return true;
3608 } while (EatIfPresent(lltok::comma
));
3613 bool LLParser::ParseMDTuple(MDNode
*&MD
, bool IsDistinct
) {
3614 SmallVector
<Metadata
*, 16> Elts
;
3615 if (ParseMDNodeVector(Elts
))
3618 MD
= (IsDistinct
? MDTuple::getDistinct
: MDTuple::get
)(Context
, Elts
);
3625 /// ::= !DILocation(...)
3626 bool LLParser::ParseMDNode(MDNode
*&N
) {
3627 if (Lex
.getKind() == lltok::MetadataVar
)
3628 return ParseSpecializedMDNode(N
);
3630 return ParseToken(lltok::exclaim
, "expected '!' here") ||
3634 bool LLParser::ParseMDNodeTail(MDNode
*&N
) {
3636 if (Lex
.getKind() == lltok::lbrace
)
3637 return ParseMDTuple(N
);
3640 return ParseMDNodeID(N
);
3645 /// Structure to represent an optional metadata field.
3646 template <class FieldTy
> struct MDFieldImpl
{
3647 typedef MDFieldImpl ImplTy
;
3651 void assign(FieldTy Val
) {
3653 this->Val
= std::move(Val
);
3656 explicit MDFieldImpl(FieldTy Default
)
3657 : Val(std::move(Default
)), Seen(false) {}
3660 /// Structure to represent an optional metadata field that
3661 /// can be of either type (A or B) and encapsulates the
3662 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3663 /// to reimplement the specifics for representing each Field.
3664 template <class FieldTypeA
, class FieldTypeB
> struct MDEitherFieldImpl
{
3665 typedef MDEitherFieldImpl
<FieldTypeA
, FieldTypeB
> ImplTy
;
3676 void assign(FieldTypeA A
) {
3678 this->A
= std::move(A
);
3682 void assign(FieldTypeB B
) {
3684 this->B
= std::move(B
);
3688 explicit MDEitherFieldImpl(FieldTypeA DefaultA
, FieldTypeB DefaultB
)
3689 : A(std::move(DefaultA
)), B(std::move(DefaultB
)), Seen(false),
3690 WhatIs(IsInvalid
) {}
3693 struct MDUnsignedField
: public MDFieldImpl
<uint64_t> {
3696 MDUnsignedField(uint64_t Default
= 0, uint64_t Max
= UINT64_MAX
)
3697 : ImplTy(Default
), Max(Max
) {}
3700 struct LineField
: public MDUnsignedField
{
3701 LineField() : MDUnsignedField(0, UINT32_MAX
) {}
3704 struct ColumnField
: public MDUnsignedField
{
3705 ColumnField() : MDUnsignedField(0, UINT16_MAX
) {}
3708 struct DwarfTagField
: public MDUnsignedField
{
3709 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user
) {}
3710 DwarfTagField(dwarf::Tag DefaultTag
)
3711 : MDUnsignedField(DefaultTag
, dwarf::DW_TAG_hi_user
) {}
3714 struct DwarfMacinfoTypeField
: public MDUnsignedField
{
3715 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext
) {}
3716 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType
)
3717 : MDUnsignedField(DefaultType
, dwarf::DW_MACINFO_vendor_ext
) {}
3720 struct DwarfAttEncodingField
: public MDUnsignedField
{
3721 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user
) {}
3724 struct DwarfVirtualityField
: public MDUnsignedField
{
3725 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max
) {}
3728 struct DwarfLangField
: public MDUnsignedField
{
3729 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user
) {}
3732 struct DwarfCCField
: public MDUnsignedField
{
3733 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user
) {}
3736 struct EmissionKindField
: public MDUnsignedField
{
3737 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind
) {}
3740 struct NameTableKindField
: public MDUnsignedField
{
3741 NameTableKindField()
3744 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind
) {}
3747 struct DIFlagField
: public MDFieldImpl
<DINode::DIFlags
> {
3748 DIFlagField() : MDFieldImpl(DINode::FlagZero
) {}
3751 struct DISPFlagField
: public MDFieldImpl
<DISubprogram::DISPFlags
> {
3752 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero
) {}
3755 struct MDSignedField
: public MDFieldImpl
<int64_t> {
3759 MDSignedField(int64_t Default
= 0)
3760 : ImplTy(Default
), Min(INT64_MIN
), Max(INT64_MAX
) {}
3761 MDSignedField(int64_t Default
, int64_t Min
, int64_t Max
)
3762 : ImplTy(Default
), Min(Min
), Max(Max
) {}
3765 struct MDBoolField
: public MDFieldImpl
<bool> {
3766 MDBoolField(bool Default
= false) : ImplTy(Default
) {}
3769 struct MDField
: public MDFieldImpl
<Metadata
*> {
3772 MDField(bool AllowNull
= true) : ImplTy(nullptr), AllowNull(AllowNull
) {}
3775 struct MDConstant
: public MDFieldImpl
<ConstantAsMetadata
*> {
3776 MDConstant() : ImplTy(nullptr) {}
3779 struct MDStringField
: public MDFieldImpl
<MDString
*> {
3781 MDStringField(bool AllowEmpty
= true)
3782 : ImplTy(nullptr), AllowEmpty(AllowEmpty
) {}
3785 struct MDFieldList
: public MDFieldImpl
<SmallVector
<Metadata
*, 4>> {
3786 MDFieldList() : ImplTy(SmallVector
<Metadata
*, 4>()) {}
3789 struct ChecksumKindField
: public MDFieldImpl
<DIFile::ChecksumKind
> {
3790 ChecksumKindField(DIFile::ChecksumKind CSKind
) : ImplTy(CSKind
) {}
3793 struct MDSignedOrMDField
: MDEitherFieldImpl
<MDSignedField
, MDField
> {
3794 MDSignedOrMDField(int64_t Default
= 0, bool AllowNull
= true)
3795 : ImplTy(MDSignedField(Default
), MDField(AllowNull
)) {}
3797 MDSignedOrMDField(int64_t Default
, int64_t Min
, int64_t Max
,
3798 bool AllowNull
= true)
3799 : ImplTy(MDSignedField(Default
, Min
, Max
), MDField(AllowNull
)) {}
3801 bool isMDSignedField() const { return WhatIs
== IsTypeA
; }
3802 bool isMDField() const { return WhatIs
== IsTypeB
; }
3803 int64_t getMDSignedValue() const {
3804 assert(isMDSignedField() && "Wrong field type");
3807 Metadata
*getMDFieldValue() const {
3808 assert(isMDField() && "Wrong field type");
3813 struct MDSignedOrUnsignedField
3814 : MDEitherFieldImpl
<MDSignedField
, MDUnsignedField
> {
3815 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3817 bool isMDSignedField() const { return WhatIs
== IsTypeA
; }
3818 bool isMDUnsignedField() const { return WhatIs
== IsTypeB
; }
3819 int64_t getMDSignedValue() const {
3820 assert(isMDSignedField() && "Wrong field type");
3823 uint64_t getMDUnsignedValue() const {
3824 assert(isMDUnsignedField() && "Wrong field type");
3829 } // end anonymous namespace
3834 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
3835 MDUnsignedField
&Result
) {
3836 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
3837 return TokError("expected unsigned integer");
3839 auto &U
= Lex
.getAPSIntVal();
3840 if (U
.ugt(Result
.Max
))
3841 return TokError("value for '" + Name
+ "' too large, limit is " +
3843 Result
.assign(U
.getZExtValue());
3844 assert(Result
.Val
<= Result
.Max
&& "Expected value in range");
3850 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, LineField
&Result
) {
3851 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3854 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, ColumnField
&Result
) {
3855 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3859 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DwarfTagField
&Result
) {
3860 if (Lex
.getKind() == lltok::APSInt
)
3861 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3863 if (Lex
.getKind() != lltok::DwarfTag
)
3864 return TokError("expected DWARF tag");
3866 unsigned Tag
= dwarf::getTag(Lex
.getStrVal());
3867 if (Tag
== dwarf::DW_TAG_invalid
)
3868 return TokError("invalid DWARF tag" + Twine(" '") + Lex
.getStrVal() + "'");
3869 assert(Tag
<= Result
.Max
&& "Expected valid DWARF tag");
3877 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
3878 DwarfMacinfoTypeField
&Result
) {
3879 if (Lex
.getKind() == lltok::APSInt
)
3880 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3882 if (Lex
.getKind() != lltok::DwarfMacinfo
)
3883 return TokError("expected DWARF macinfo type");
3885 unsigned Macinfo
= dwarf::getMacinfo(Lex
.getStrVal());
3886 if (Macinfo
== dwarf::DW_MACINFO_invalid
)
3888 "invalid DWARF macinfo type" + Twine(" '") + Lex
.getStrVal() + "'");
3889 assert(Macinfo
<= Result
.Max
&& "Expected valid DWARF macinfo type");
3891 Result
.assign(Macinfo
);
3897 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
3898 DwarfVirtualityField
&Result
) {
3899 if (Lex
.getKind() == lltok::APSInt
)
3900 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3902 if (Lex
.getKind() != lltok::DwarfVirtuality
)
3903 return TokError("expected DWARF virtuality code");
3905 unsigned Virtuality
= dwarf::getVirtuality(Lex
.getStrVal());
3906 if (Virtuality
== dwarf::DW_VIRTUALITY_invalid
)
3907 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3908 Lex
.getStrVal() + "'");
3909 assert(Virtuality
<= Result
.Max
&& "Expected valid DWARF virtuality code");
3910 Result
.assign(Virtuality
);
3916 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DwarfLangField
&Result
) {
3917 if (Lex
.getKind() == lltok::APSInt
)
3918 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3920 if (Lex
.getKind() != lltok::DwarfLang
)
3921 return TokError("expected DWARF language");
3923 unsigned Lang
= dwarf::getLanguage(Lex
.getStrVal());
3925 return TokError("invalid DWARF language" + Twine(" '") + Lex
.getStrVal() +
3927 assert(Lang
<= Result
.Max
&& "Expected valid DWARF language");
3928 Result
.assign(Lang
);
3934 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DwarfCCField
&Result
) {
3935 if (Lex
.getKind() == lltok::APSInt
)
3936 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3938 if (Lex
.getKind() != lltok::DwarfCC
)
3939 return TokError("expected DWARF calling convention");
3941 unsigned CC
= dwarf::getCallingConvention(Lex
.getStrVal());
3943 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex
.getStrVal() +
3945 assert(CC
<= Result
.Max
&& "Expected valid DWARF calling convention");
3952 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, EmissionKindField
&Result
) {
3953 if (Lex
.getKind() == lltok::APSInt
)
3954 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3956 if (Lex
.getKind() != lltok::EmissionKind
)
3957 return TokError("expected emission kind");
3959 auto Kind
= DICompileUnit::getEmissionKind(Lex
.getStrVal());
3961 return TokError("invalid emission kind" + Twine(" '") + Lex
.getStrVal() +
3963 assert(*Kind
<= Result
.Max
&& "Expected valid emission kind");
3964 Result
.assign(*Kind
);
3970 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
3971 NameTableKindField
&Result
) {
3972 if (Lex
.getKind() == lltok::APSInt
)
3973 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3975 if (Lex
.getKind() != lltok::NameTableKind
)
3976 return TokError("expected nameTable kind");
3978 auto Kind
= DICompileUnit::getNameTableKind(Lex
.getStrVal());
3980 return TokError("invalid nameTable kind" + Twine(" '") + Lex
.getStrVal() +
3982 assert(((unsigned)*Kind
) <= Result
.Max
&& "Expected valid nameTable kind");
3983 Result
.assign((unsigned)*Kind
);
3989 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
3990 DwarfAttEncodingField
&Result
) {
3991 if (Lex
.getKind() == lltok::APSInt
)
3992 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3994 if (Lex
.getKind() != lltok::DwarfAttEncoding
)
3995 return TokError("expected DWARF type attribute encoding");
3997 unsigned Encoding
= dwarf::getAttributeEncoding(Lex
.getStrVal());
3999 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4000 Lex
.getStrVal() + "'");
4001 assert(Encoding
<= Result
.Max
&& "Expected valid DWARF language");
4002 Result
.assign(Encoding
);
4009 /// ::= DIFlagVector
4010 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4012 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DIFlagField
&Result
) {
4014 // Parser for a single flag.
4015 auto parseFlag
= [&](DINode::DIFlags
&Val
) {
4016 if (Lex
.getKind() == lltok::APSInt
&& !Lex
.getAPSIntVal().isSigned()) {
4017 uint32_t TempVal
= static_cast<uint32_t>(Val
);
4018 bool Res
= ParseUInt32(TempVal
);
4019 Val
= static_cast<DINode::DIFlags
>(TempVal
);
4023 if (Lex
.getKind() != lltok::DIFlag
)
4024 return TokError("expected debug info flag");
4026 Val
= DINode::getFlag(Lex
.getStrVal());
4028 return TokError(Twine("invalid debug info flag flag '") +
4029 Lex
.getStrVal() + "'");
4034 // Parse the flags and combine them together.
4035 DINode::DIFlags Combined
= DINode::FlagZero
;
4037 DINode::DIFlags Val
;
4041 } while (EatIfPresent(lltok::bar
));
4043 Result
.assign(Combined
);
4049 /// ::= DISPFlagVector
4050 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4052 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DISPFlagField
&Result
) {
4054 // Parser for a single flag.
4055 auto parseFlag
= [&](DISubprogram::DISPFlags
&Val
) {
4056 if (Lex
.getKind() == lltok::APSInt
&& !Lex
.getAPSIntVal().isSigned()) {
4057 uint32_t TempVal
= static_cast<uint32_t>(Val
);
4058 bool Res
= ParseUInt32(TempVal
);
4059 Val
= static_cast<DISubprogram::DISPFlags
>(TempVal
);
4063 if (Lex
.getKind() != lltok::DISPFlag
)
4064 return TokError("expected debug info flag");
4066 Val
= DISubprogram::getFlag(Lex
.getStrVal());
4068 return TokError(Twine("invalid subprogram debug info flag '") +
4069 Lex
.getStrVal() + "'");
4074 // Parse the flags and combine them together.
4075 DISubprogram::DISPFlags Combined
= DISubprogram::SPFlagZero
;
4077 DISubprogram::DISPFlags Val
;
4081 } while (EatIfPresent(lltok::bar
));
4083 Result
.assign(Combined
);
4088 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4089 MDSignedField
&Result
) {
4090 if (Lex
.getKind() != lltok::APSInt
)
4091 return TokError("expected signed integer");
4093 auto &S
= Lex
.getAPSIntVal();
4095 return TokError("value for '" + Name
+ "' too small, limit is " +
4098 return TokError("value for '" + Name
+ "' too large, limit is " +
4100 Result
.assign(S
.getExtValue());
4101 assert(Result
.Val
>= Result
.Min
&& "Expected value in range");
4102 assert(Result
.Val
<= Result
.Max
&& "Expected value in range");
4108 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, MDBoolField
&Result
) {
4109 switch (Lex
.getKind()) {
4111 return TokError("expected 'true' or 'false'");
4112 case lltok::kw_true
:
4113 Result
.assign(true);
4115 case lltok::kw_false
:
4116 Result
.assign(false);
4124 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, MDField
&Result
) {
4125 if (Lex
.getKind() == lltok::kw_null
) {
4126 if (!Result
.AllowNull
)
4127 return TokError("'" + Name
+ "' cannot be null");
4129 Result
.assign(nullptr);
4134 if (ParseMetadata(MD
, nullptr))
4142 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4143 MDSignedOrMDField
&Result
) {
4144 // Try to parse a signed int.
4145 if (Lex
.getKind() == lltok::APSInt
) {
4146 MDSignedField Res
= Result
.A
;
4147 if (!ParseMDField(Loc
, Name
, Res
)) {
4154 // Otherwise, try to parse as an MDField.
4155 MDField Res
= Result
.B
;
4156 if (!ParseMDField(Loc
, Name
, Res
)) {
4165 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4166 MDSignedOrUnsignedField
&Result
) {
4167 if (Lex
.getKind() != lltok::APSInt
)
4170 if (Lex
.getAPSIntVal().isSigned()) {
4171 MDSignedField Res
= Result
.A
;
4172 if (ParseMDField(Loc
, Name
, Res
))
4178 MDUnsignedField Res
= Result
.B
;
4179 if (ParseMDField(Loc
, Name
, Res
))
4186 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, MDStringField
&Result
) {
4187 LocTy ValueLoc
= Lex
.getLoc();
4189 if (ParseStringConstant(S
))
4192 if (!Result
.AllowEmpty
&& S
.empty())
4193 return Error(ValueLoc
, "'" + Name
+ "' cannot be empty");
4195 Result
.assign(S
.empty() ? nullptr : MDString::get(Context
, S
));
4200 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, MDFieldList
&Result
) {
4201 SmallVector
<Metadata
*, 4> MDs
;
4202 if (ParseMDNodeVector(MDs
))
4205 Result
.assign(std::move(MDs
));
4210 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4211 ChecksumKindField
&Result
) {
4212 Optional
<DIFile::ChecksumKind
> CSKind
=
4213 DIFile::getChecksumKind(Lex
.getStrVal());
4215 if (Lex
.getKind() != lltok::ChecksumKind
|| !CSKind
)
4217 "invalid checksum kind" + Twine(" '") + Lex
.getStrVal() + "'");
4219 Result
.assign(*CSKind
);
4224 } // end namespace llvm
4226 template <class ParserTy
>
4227 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField
) {
4229 if (Lex
.getKind() != lltok::LabelStr
)
4230 return TokError("expected field label here");
4234 } while (EatIfPresent(lltok::comma
));
4239 template <class ParserTy
>
4240 bool LLParser::ParseMDFieldsImpl(ParserTy parseField
, LocTy
&ClosingLoc
) {
4241 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4244 if (ParseToken(lltok::lparen
, "expected '(' here"))
4246 if (Lex
.getKind() != lltok::rparen
)
4247 if (ParseMDFieldsImplBody(parseField
))
4250 ClosingLoc
= Lex
.getLoc();
4251 return ParseToken(lltok::rparen
, "expected ')' here");
4254 template <class FieldTy
>
4255 bool LLParser::ParseMDField(StringRef Name
, FieldTy
&Result
) {
4257 return TokError("field '" + Name
+ "' cannot be specified more than once");
4259 LocTy Loc
= Lex
.getLoc();
4261 return ParseMDField(Loc
, Name
, Result
);
4264 bool LLParser::ParseSpecializedMDNode(MDNode
*&N
, bool IsDistinct
) {
4265 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4267 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4268 if (Lex.getStrVal() == #CLASS) \
4269 return Parse##CLASS(N, IsDistinct);
4270 #include "llvm/IR/Metadata.def"
4272 return TokError("expected metadata type");
4275 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4276 #define NOP_FIELD(NAME, TYPE, INIT)
4277 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4279 return Error(ClosingLoc, "missing required field '" #NAME "'");
4280 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4281 if (Lex.getStrVal() == #NAME) \
4282 return ParseMDField(#NAME, NAME);
4283 #define PARSE_MD_FIELDS() \
4284 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4287 if (ParseMDFieldsImpl([&]() -> bool { \
4288 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4289 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4292 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4294 #define GET_OR_DISTINCT(CLASS, ARGS) \
4295 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4297 /// ParseDILocationFields:
4298 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4299 /// isImplicitCode: true)
4300 bool LLParser::ParseDILocation(MDNode
*&Result
, bool IsDistinct
) {
4301 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4302 OPTIONAL(line, LineField, ); \
4303 OPTIONAL(column, ColumnField, ); \
4304 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4305 OPTIONAL(inlinedAt, MDField, ); \
4306 OPTIONAL(isImplicitCode, MDBoolField, (false));
4308 #undef VISIT_MD_FIELDS
4311 GET_OR_DISTINCT(DILocation
, (Context
, line
.Val
, column
.Val
, scope
.Val
,
4312 inlinedAt
.Val
, isImplicitCode
.Val
));
4316 /// ParseGenericDINode:
4317 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4318 bool LLParser::ParseGenericDINode(MDNode
*&Result
, bool IsDistinct
) {
4319 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4320 REQUIRED(tag, DwarfTagField, ); \
4321 OPTIONAL(header, MDStringField, ); \
4322 OPTIONAL(operands, MDFieldList, );
4324 #undef VISIT_MD_FIELDS
4326 Result
= GET_OR_DISTINCT(GenericDINode
,
4327 (Context
, tag
.Val
, header
.Val
, operands
.Val
));
4331 /// ParseDISubrange:
4332 /// ::= !DISubrange(count: 30, lowerBound: 2)
4333 /// ::= !DISubrange(count: !node, lowerBound: 2)
4334 bool LLParser::ParseDISubrange(MDNode
*&Result
, bool IsDistinct
) {
4335 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4336 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4337 OPTIONAL(lowerBound, MDSignedField, );
4339 #undef VISIT_MD_FIELDS
4341 if (count
.isMDSignedField())
4342 Result
= GET_OR_DISTINCT(
4343 DISubrange
, (Context
, count
.getMDSignedValue(), lowerBound
.Val
));
4344 else if (count
.isMDField())
4345 Result
= GET_OR_DISTINCT(
4346 DISubrange
, (Context
, count
.getMDFieldValue(), lowerBound
.Val
));
4353 /// ParseDIEnumerator:
4354 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4355 bool LLParser::ParseDIEnumerator(MDNode
*&Result
, bool IsDistinct
) {
4356 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4357 REQUIRED(name, MDStringField, ); \
4358 REQUIRED(value, MDSignedOrUnsignedField, ); \
4359 OPTIONAL(isUnsigned, MDBoolField, (false));
4361 #undef VISIT_MD_FIELDS
4363 if (isUnsigned
.Val
&& value
.isMDSignedField())
4364 return TokError("unsigned enumerator with negative value");
4366 int64_t Value
= value
.isMDSignedField()
4367 ? value
.getMDSignedValue()
4368 : static_cast<int64_t>(value
.getMDUnsignedValue());
4370 GET_OR_DISTINCT(DIEnumerator
, (Context
, Value
, isUnsigned
.Val
, name
.Val
));
4375 /// ParseDIBasicType:
4376 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4377 /// encoding: DW_ATE_encoding, flags: 0)
4378 bool LLParser::ParseDIBasicType(MDNode
*&Result
, bool IsDistinct
) {
4379 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4380 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4381 OPTIONAL(name, MDStringField, ); \
4382 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4383 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4384 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4385 OPTIONAL(flags, DIFlagField, );
4387 #undef VISIT_MD_FIELDS
4389 Result
= GET_OR_DISTINCT(DIBasicType
, (Context
, tag
.Val
, name
.Val
, size
.Val
,
4390 align
.Val
, encoding
.Val
, flags
.Val
));
4394 /// ParseDIDerivedType:
4395 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4396 /// line: 7, scope: !1, baseType: !2, size: 32,
4397 /// align: 32, offset: 0, flags: 0, extraData: !3,
4398 /// dwarfAddressSpace: 3)
4399 bool LLParser::ParseDIDerivedType(MDNode
*&Result
, bool IsDistinct
) {
4400 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4401 REQUIRED(tag, DwarfTagField, ); \
4402 OPTIONAL(name, MDStringField, ); \
4403 OPTIONAL(file, MDField, ); \
4404 OPTIONAL(line, LineField, ); \
4405 OPTIONAL(scope, MDField, ); \
4406 REQUIRED(baseType, MDField, ); \
4407 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4408 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4409 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4410 OPTIONAL(flags, DIFlagField, ); \
4411 OPTIONAL(extraData, MDField, ); \
4412 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4414 #undef VISIT_MD_FIELDS
4416 Optional
<unsigned> DWARFAddressSpace
;
4417 if (dwarfAddressSpace
.Val
!= UINT32_MAX
)
4418 DWARFAddressSpace
= dwarfAddressSpace
.Val
;
4420 Result
= GET_OR_DISTINCT(DIDerivedType
,
4421 (Context
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
,
4422 scope
.Val
, baseType
.Val
, size
.Val
, align
.Val
,
4423 offset
.Val
, DWARFAddressSpace
, flags
.Val
,
4428 bool LLParser::ParseDICompositeType(MDNode
*&Result
, bool IsDistinct
) {
4429 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4430 REQUIRED(tag, DwarfTagField, ); \
4431 OPTIONAL(name, MDStringField, ); \
4432 OPTIONAL(file, MDField, ); \
4433 OPTIONAL(line, LineField, ); \
4434 OPTIONAL(scope, MDField, ); \
4435 OPTIONAL(baseType, MDField, ); \
4436 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4437 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4438 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4439 OPTIONAL(flags, DIFlagField, ); \
4440 OPTIONAL(elements, MDField, ); \
4441 OPTIONAL(runtimeLang, DwarfLangField, ); \
4442 OPTIONAL(vtableHolder, MDField, ); \
4443 OPTIONAL(templateParams, MDField, ); \
4444 OPTIONAL(identifier, MDStringField, ); \
4445 OPTIONAL(discriminator, MDField, );
4447 #undef VISIT_MD_FIELDS
4449 // If this has an identifier try to build an ODR type.
4451 if (auto *CT
= DICompositeType::buildODRType(
4452 Context
, *identifier
.Val
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
,
4453 scope
.Val
, baseType
.Val
, size
.Val
, align
.Val
, offset
.Val
, flags
.Val
,
4454 elements
.Val
, runtimeLang
.Val
, vtableHolder
.Val
,
4455 templateParams
.Val
, discriminator
.Val
)) {
4460 // Create a new node, and save it in the context if it belongs in the type
4462 Result
= GET_OR_DISTINCT(
4464 (Context
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
, scope
.Val
, baseType
.Val
,
4465 size
.Val
, align
.Val
, offset
.Val
, flags
.Val
, elements
.Val
,
4466 runtimeLang
.Val
, vtableHolder
.Val
, templateParams
.Val
, identifier
.Val
,
4467 discriminator
.Val
));
4471 bool LLParser::ParseDISubroutineType(MDNode
*&Result
, bool IsDistinct
) {
4472 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4473 OPTIONAL(flags, DIFlagField, ); \
4474 OPTIONAL(cc, DwarfCCField, ); \
4475 REQUIRED(types, MDField, );
4477 #undef VISIT_MD_FIELDS
4479 Result
= GET_OR_DISTINCT(DISubroutineType
,
4480 (Context
, flags
.Val
, cc
.Val
, types
.Val
));
4484 /// ParseDIFileType:
4485 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4486 /// checksumkind: CSK_MD5,
4487 /// checksum: "000102030405060708090a0b0c0d0e0f",
4488 /// source: "source file contents")
4489 bool LLParser::ParseDIFile(MDNode
*&Result
, bool IsDistinct
) {
4490 // The default constructed value for checksumkind is required, but will never
4491 // be used, as the parser checks if the field was actually Seen before using
4493 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4494 REQUIRED(filename, MDStringField, ); \
4495 REQUIRED(directory, MDStringField, ); \
4496 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4497 OPTIONAL(checksum, MDStringField, ); \
4498 OPTIONAL(source, MDStringField, );
4500 #undef VISIT_MD_FIELDS
4502 Optional
<DIFile::ChecksumInfo
<MDString
*>> OptChecksum
;
4503 if (checksumkind
.Seen
&& checksum
.Seen
)
4504 OptChecksum
.emplace(checksumkind
.Val
, checksum
.Val
);
4505 else if (checksumkind
.Seen
|| checksum
.Seen
)
4506 return Lex
.Error("'checksumkind' and 'checksum' must be provided together");
4508 Optional
<MDString
*> OptSource
;
4510 OptSource
= source
.Val
;
4511 Result
= GET_OR_DISTINCT(DIFile
, (Context
, filename
.Val
, directory
.Val
,
4512 OptChecksum
, OptSource
));
4516 /// ParseDICompileUnit:
4517 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4518 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4519 /// splitDebugFilename: "abc.debug",
4520 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4521 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4522 bool LLParser::ParseDICompileUnit(MDNode
*&Result
, bool IsDistinct
) {
4524 return Lex
.Error("missing 'distinct', required for !DICompileUnit");
4526 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4527 REQUIRED(language, DwarfLangField, ); \
4528 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4529 OPTIONAL(producer, MDStringField, ); \
4530 OPTIONAL(isOptimized, MDBoolField, ); \
4531 OPTIONAL(flags, MDStringField, ); \
4532 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4533 OPTIONAL(splitDebugFilename, MDStringField, ); \
4534 OPTIONAL(emissionKind, EmissionKindField, ); \
4535 OPTIONAL(enums, MDField, ); \
4536 OPTIONAL(retainedTypes, MDField, ); \
4537 OPTIONAL(globals, MDField, ); \
4538 OPTIONAL(imports, MDField, ); \
4539 OPTIONAL(macros, MDField, ); \
4540 OPTIONAL(dwoId, MDUnsignedField, ); \
4541 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4542 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4543 OPTIONAL(nameTableKind, NameTableKindField, ); \
4544 OPTIONAL(debugBaseAddress, MDBoolField, = false);
4546 #undef VISIT_MD_FIELDS
4548 Result
= DICompileUnit::getDistinct(
4549 Context
, language
.Val
, file
.Val
, producer
.Val
, isOptimized
.Val
, flags
.Val
,
4550 runtimeVersion
.Val
, splitDebugFilename
.Val
, emissionKind
.Val
, enums
.Val
,
4551 retainedTypes
.Val
, globals
.Val
, imports
.Val
, macros
.Val
, dwoId
.Val
,
4552 splitDebugInlining
.Val
, debugInfoForProfiling
.Val
, nameTableKind
.Val
,
4553 debugBaseAddress
.Val
);
4557 /// ParseDISubprogram:
4558 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4559 /// file: !1, line: 7, type: !2, isLocal: false,
4560 /// isDefinition: true, scopeLine: 8, containingType: !3,
4561 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4562 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4563 /// spFlags: 10, isOptimized: false, templateParams: !4,
4564 /// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4565 bool LLParser::ParseDISubprogram(MDNode
*&Result
, bool IsDistinct
) {
4566 auto Loc
= Lex
.getLoc();
4567 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4568 OPTIONAL(scope, MDField, ); \
4569 OPTIONAL(name, MDStringField, ); \
4570 OPTIONAL(linkageName, MDStringField, ); \
4571 OPTIONAL(file, MDField, ); \
4572 OPTIONAL(line, LineField, ); \
4573 OPTIONAL(type, MDField, ); \
4574 OPTIONAL(isLocal, MDBoolField, ); \
4575 OPTIONAL(isDefinition, MDBoolField, (true)); \
4576 OPTIONAL(scopeLine, LineField, ); \
4577 OPTIONAL(containingType, MDField, ); \
4578 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4579 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4580 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4581 OPTIONAL(flags, DIFlagField, ); \
4582 OPTIONAL(spFlags, DISPFlagField, ); \
4583 OPTIONAL(isOptimized, MDBoolField, ); \
4584 OPTIONAL(unit, MDField, ); \
4585 OPTIONAL(templateParams, MDField, ); \
4586 OPTIONAL(declaration, MDField, ); \
4587 OPTIONAL(retainedNodes, MDField, ); \
4588 OPTIONAL(thrownTypes, MDField, );
4590 #undef VISIT_MD_FIELDS
4592 // An explicit spFlags field takes precedence over individual fields in
4593 // older IR versions.
4594 DISubprogram::DISPFlags SPFlags
=
4595 spFlags
.Seen
? spFlags
.Val
4596 : DISubprogram::toSPFlags(isLocal
.Val
, isDefinition
.Val
,
4597 isOptimized
.Val
, virtuality
.Val
);
4598 if ((SPFlags
& DISubprogram::SPFlagDefinition
) && !IsDistinct
)
4601 "missing 'distinct', required for !DISubprogram that is a Definition");
4602 Result
= GET_OR_DISTINCT(
4604 (Context
, scope
.Val
, name
.Val
, linkageName
.Val
, file
.Val
, line
.Val
,
4605 type
.Val
, scopeLine
.Val
, containingType
.Val
, virtualIndex
.Val
,
4606 thisAdjustment
.Val
, flags
.Val
, SPFlags
, unit
.Val
, templateParams
.Val
,
4607 declaration
.Val
, retainedNodes
.Val
, thrownTypes
.Val
));
4611 /// ParseDILexicalBlock:
4612 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4613 bool LLParser::ParseDILexicalBlock(MDNode
*&Result
, bool IsDistinct
) {
4614 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4615 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4616 OPTIONAL(file, MDField, ); \
4617 OPTIONAL(line, LineField, ); \
4618 OPTIONAL(column, ColumnField, );
4620 #undef VISIT_MD_FIELDS
4622 Result
= GET_OR_DISTINCT(
4623 DILexicalBlock
, (Context
, scope
.Val
, file
.Val
, line
.Val
, column
.Val
));
4627 /// ParseDILexicalBlockFile:
4628 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4629 bool LLParser::ParseDILexicalBlockFile(MDNode
*&Result
, bool IsDistinct
) {
4630 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4631 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4632 OPTIONAL(file, MDField, ); \
4633 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4635 #undef VISIT_MD_FIELDS
4637 Result
= GET_OR_DISTINCT(DILexicalBlockFile
,
4638 (Context
, scope
.Val
, file
.Val
, discriminator
.Val
));
4642 /// ParseDINamespace:
4643 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4644 bool LLParser::ParseDINamespace(MDNode
*&Result
, bool IsDistinct
) {
4645 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4646 REQUIRED(scope, MDField, ); \
4647 OPTIONAL(name, MDStringField, ); \
4648 OPTIONAL(exportSymbols, MDBoolField, );
4650 #undef VISIT_MD_FIELDS
4652 Result
= GET_OR_DISTINCT(DINamespace
,
4653 (Context
, scope
.Val
, name
.Val
, exportSymbols
.Val
));
4658 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4659 bool LLParser::ParseDIMacro(MDNode
*&Result
, bool IsDistinct
) {
4660 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4661 REQUIRED(type, DwarfMacinfoTypeField, ); \
4662 OPTIONAL(line, LineField, ); \
4663 REQUIRED(name, MDStringField, ); \
4664 OPTIONAL(value, MDStringField, );
4666 #undef VISIT_MD_FIELDS
4668 Result
= GET_OR_DISTINCT(DIMacro
,
4669 (Context
, type
.Val
, line
.Val
, name
.Val
, value
.Val
));
4673 /// ParseDIMacroFile:
4674 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4675 bool LLParser::ParseDIMacroFile(MDNode
*&Result
, bool IsDistinct
) {
4676 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4677 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4678 OPTIONAL(line, LineField, ); \
4679 REQUIRED(file, MDField, ); \
4680 OPTIONAL(nodes, MDField, );
4682 #undef VISIT_MD_FIELDS
4684 Result
= GET_OR_DISTINCT(DIMacroFile
,
4685 (Context
, type
.Val
, line
.Val
, file
.Val
, nodes
.Val
));
4690 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4691 /// includePath: "/usr/include", isysroot: "/")
4692 bool LLParser::ParseDIModule(MDNode
*&Result
, bool IsDistinct
) {
4693 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4694 REQUIRED(scope, MDField, ); \
4695 REQUIRED(name, MDStringField, ); \
4696 OPTIONAL(configMacros, MDStringField, ); \
4697 OPTIONAL(includePath, MDStringField, ); \
4698 OPTIONAL(isysroot, MDStringField, );
4700 #undef VISIT_MD_FIELDS
4702 Result
= GET_OR_DISTINCT(DIModule
, (Context
, scope
.Val
, name
.Val
,
4703 configMacros
.Val
, includePath
.Val
, isysroot
.Val
));
4707 /// ParseDITemplateTypeParameter:
4708 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4709 bool LLParser::ParseDITemplateTypeParameter(MDNode
*&Result
, bool IsDistinct
) {
4710 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4711 OPTIONAL(name, MDStringField, ); \
4712 REQUIRED(type, MDField, );
4714 #undef VISIT_MD_FIELDS
4717 GET_OR_DISTINCT(DITemplateTypeParameter
, (Context
, name
.Val
, type
.Val
));
4721 /// ParseDITemplateValueParameter:
4722 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4723 /// name: "V", type: !1, value: i32 7)
4724 bool LLParser::ParseDITemplateValueParameter(MDNode
*&Result
, bool IsDistinct
) {
4725 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4726 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4727 OPTIONAL(name, MDStringField, ); \
4728 OPTIONAL(type, MDField, ); \
4729 REQUIRED(value, MDField, );
4731 #undef VISIT_MD_FIELDS
4733 Result
= GET_OR_DISTINCT(DITemplateValueParameter
,
4734 (Context
, tag
.Val
, name
.Val
, type
.Val
, value
.Val
));
4738 /// ParseDIGlobalVariable:
4739 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4740 /// file: !1, line: 7, type: !2, isLocal: false,
4741 /// isDefinition: true, templateParams: !3,
4742 /// declaration: !4, align: 8)
4743 bool LLParser::ParseDIGlobalVariable(MDNode
*&Result
, bool IsDistinct
) {
4744 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4745 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4746 OPTIONAL(scope, MDField, ); \
4747 OPTIONAL(linkageName, MDStringField, ); \
4748 OPTIONAL(file, MDField, ); \
4749 OPTIONAL(line, LineField, ); \
4750 OPTIONAL(type, MDField, ); \
4751 OPTIONAL(isLocal, MDBoolField, ); \
4752 OPTIONAL(isDefinition, MDBoolField, (true)); \
4753 OPTIONAL(templateParams, MDField, ); \
4754 OPTIONAL(declaration, MDField, ); \
4755 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4757 #undef VISIT_MD_FIELDS
4760 GET_OR_DISTINCT(DIGlobalVariable
,
4761 (Context
, scope
.Val
, name
.Val
, linkageName
.Val
, file
.Val
,
4762 line
.Val
, type
.Val
, isLocal
.Val
, isDefinition
.Val
,
4763 declaration
.Val
, templateParams
.Val
, align
.Val
));
4767 /// ParseDILocalVariable:
4768 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4769 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4771 /// ::= !DILocalVariable(scope: !0, name: "foo",
4772 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4774 bool LLParser::ParseDILocalVariable(MDNode
*&Result
, bool IsDistinct
) {
4775 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4776 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4777 OPTIONAL(name, MDStringField, ); \
4778 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4779 OPTIONAL(file, MDField, ); \
4780 OPTIONAL(line, LineField, ); \
4781 OPTIONAL(type, MDField, ); \
4782 OPTIONAL(flags, DIFlagField, ); \
4783 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4785 #undef VISIT_MD_FIELDS
4787 Result
= GET_OR_DISTINCT(DILocalVariable
,
4788 (Context
, scope
.Val
, name
.Val
, file
.Val
, line
.Val
,
4789 type
.Val
, arg
.Val
, flags
.Val
, align
.Val
));
4794 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4795 bool LLParser::ParseDILabel(MDNode
*&Result
, bool IsDistinct
) {
4796 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4797 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4798 REQUIRED(name, MDStringField, ); \
4799 REQUIRED(file, MDField, ); \
4800 REQUIRED(line, LineField, );
4802 #undef VISIT_MD_FIELDS
4804 Result
= GET_OR_DISTINCT(DILabel
,
4805 (Context
, scope
.Val
, name
.Val
, file
.Val
, line
.Val
));
4809 /// ParseDIExpression:
4810 /// ::= !DIExpression(0, 7, -1)
4811 bool LLParser::ParseDIExpression(MDNode
*&Result
, bool IsDistinct
) {
4812 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4815 if (ParseToken(lltok::lparen
, "expected '(' here"))
4818 SmallVector
<uint64_t, 8> Elements
;
4819 if (Lex
.getKind() != lltok::rparen
)
4821 if (Lex
.getKind() == lltok::DwarfOp
) {
4822 if (unsigned Op
= dwarf::getOperationEncoding(Lex
.getStrVal())) {
4824 Elements
.push_back(Op
);
4827 return TokError(Twine("invalid DWARF op '") + Lex
.getStrVal() + "'");
4830 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
4831 return TokError("expected unsigned integer");
4833 auto &U
= Lex
.getAPSIntVal();
4834 if (U
.ugt(UINT64_MAX
))
4835 return TokError("element too large, limit is " + Twine(UINT64_MAX
));
4836 Elements
.push_back(U
.getZExtValue());
4838 } while (EatIfPresent(lltok::comma
));
4840 if (ParseToken(lltok::rparen
, "expected ')' here"))
4843 Result
= GET_OR_DISTINCT(DIExpression
, (Context
, Elements
));
4847 /// ParseDIGlobalVariableExpression:
4848 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4849 bool LLParser::ParseDIGlobalVariableExpression(MDNode
*&Result
,
4851 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4852 REQUIRED(var, MDField, ); \
4853 REQUIRED(expr, MDField, );
4855 #undef VISIT_MD_FIELDS
4858 GET_OR_DISTINCT(DIGlobalVariableExpression
, (Context
, var
.Val
, expr
.Val
));
4862 /// ParseDIObjCProperty:
4863 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4864 /// getter: "getFoo", attributes: 7, type: !2)
4865 bool LLParser::ParseDIObjCProperty(MDNode
*&Result
, bool IsDistinct
) {
4866 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4867 OPTIONAL(name, MDStringField, ); \
4868 OPTIONAL(file, MDField, ); \
4869 OPTIONAL(line, LineField, ); \
4870 OPTIONAL(setter, MDStringField, ); \
4871 OPTIONAL(getter, MDStringField, ); \
4872 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4873 OPTIONAL(type, MDField, );
4875 #undef VISIT_MD_FIELDS
4877 Result
= GET_OR_DISTINCT(DIObjCProperty
,
4878 (Context
, name
.Val
, file
.Val
, line
.Val
, setter
.Val
,
4879 getter
.Val
, attributes
.Val
, type
.Val
));
4883 /// ParseDIImportedEntity:
4884 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4885 /// line: 7, name: "foo")
4886 bool LLParser::ParseDIImportedEntity(MDNode
*&Result
, bool IsDistinct
) {
4887 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4888 REQUIRED(tag, DwarfTagField, ); \
4889 REQUIRED(scope, MDField, ); \
4890 OPTIONAL(entity, MDField, ); \
4891 OPTIONAL(file, MDField, ); \
4892 OPTIONAL(line, LineField, ); \
4893 OPTIONAL(name, MDStringField, );
4895 #undef VISIT_MD_FIELDS
4897 Result
= GET_OR_DISTINCT(
4899 (Context
, tag
.Val
, scope
.Val
, entity
.Val
, file
.Val
, line
.Val
, name
.Val
));
4903 #undef PARSE_MD_FIELD
4905 #undef REQUIRE_FIELD
4906 #undef DECLARE_FIELD
4908 /// ParseMetadataAsValue
4909 /// ::= metadata i32 %local
4910 /// ::= metadata i32 @global
4911 /// ::= metadata i32 7
4913 /// ::= metadata !{...}
4914 /// ::= metadata !"string"
4915 bool LLParser::ParseMetadataAsValue(Value
*&V
, PerFunctionState
&PFS
) {
4916 // Note: the type 'metadata' has already been parsed.
4918 if (ParseMetadata(MD
, &PFS
))
4921 V
= MetadataAsValue::get(Context
, MD
);
4925 /// ParseValueAsMetadata
4929 bool LLParser::ParseValueAsMetadata(Metadata
*&MD
, const Twine
&TypeMsg
,
4930 PerFunctionState
*PFS
) {
4933 if (ParseType(Ty
, TypeMsg
, Loc
))
4935 if (Ty
->isMetadataTy())
4936 return Error(Loc
, "invalid metadata-value-metadata roundtrip");
4939 if (ParseValue(Ty
, V
, PFS
))
4942 MD
= ValueAsMetadata::get(V
);
4953 /// ::= !DILocation(...)
4954 bool LLParser::ParseMetadata(Metadata
*&MD
, PerFunctionState
*PFS
) {
4955 if (Lex
.getKind() == lltok::MetadataVar
) {
4957 if (ParseSpecializedMDNode(N
))
4965 if (Lex
.getKind() != lltok::exclaim
)
4966 return ParseValueAsMetadata(MD
, "expected metadata operand", PFS
);
4969 assert(Lex
.getKind() == lltok::exclaim
&& "Expected '!' here");
4973 // ::= '!' STRINGCONSTANT
4974 if (Lex
.getKind() == lltok::StringConstant
) {
4976 if (ParseMDString(S
))
4986 if (ParseMDNodeTail(N
))
4992 //===----------------------------------------------------------------------===//
4993 // Function Parsing.
4994 //===----------------------------------------------------------------------===//
4996 bool LLParser::ConvertValIDToValue(Type
*Ty
, ValID
&ID
, Value
*&V
,
4997 PerFunctionState
*PFS
, bool IsCall
) {
4998 if (Ty
->isFunctionTy())
4999 return Error(ID
.Loc
, "functions are not values, refer to them as pointers");
5002 case ValID::t_LocalID
:
5003 if (!PFS
) return Error(ID
.Loc
, "invalid use of function-local name");
5004 V
= PFS
->GetVal(ID
.UIntVal
, Ty
, ID
.Loc
, IsCall
);
5005 return V
== nullptr;
5006 case ValID::t_LocalName
:
5007 if (!PFS
) return Error(ID
.Loc
, "invalid use of function-local name");
5008 V
= PFS
->GetVal(ID
.StrVal
, Ty
, ID
.Loc
, IsCall
);
5009 return V
== nullptr;
5010 case ValID::t_InlineAsm
: {
5011 if (!ID
.FTy
|| !InlineAsm::Verify(ID
.FTy
, ID
.StrVal2
))
5012 return Error(ID
.Loc
, "invalid type for inline asm constraint string");
5013 V
= InlineAsm::get(ID
.FTy
, ID
.StrVal
, ID
.StrVal2
, ID
.UIntVal
& 1,
5014 (ID
.UIntVal
>> 1) & 1,
5015 (InlineAsm::AsmDialect(ID
.UIntVal
>> 2)));
5018 case ValID::t_GlobalName
:
5019 V
= GetGlobalVal(ID
.StrVal
, Ty
, ID
.Loc
, IsCall
);
5020 return V
== nullptr;
5021 case ValID::t_GlobalID
:
5022 V
= GetGlobalVal(ID
.UIntVal
, Ty
, ID
.Loc
, IsCall
);
5023 return V
== nullptr;
5024 case ValID::t_APSInt
:
5025 if (!Ty
->isIntegerTy())
5026 return Error(ID
.Loc
, "integer constant must have integer type");
5027 ID
.APSIntVal
= ID
.APSIntVal
.extOrTrunc(Ty
->getPrimitiveSizeInBits());
5028 V
= ConstantInt::get(Context
, ID
.APSIntVal
);
5030 case ValID::t_APFloat
:
5031 if (!Ty
->isFloatingPointTy() ||
5032 !ConstantFP::isValueValidForType(Ty
, ID
.APFloatVal
))
5033 return Error(ID
.Loc
, "floating point constant invalid for type");
5035 // The lexer has no type info, so builds all half, float, and double FP
5036 // constants as double. Fix this here. Long double does not need this.
5037 if (&ID
.APFloatVal
.getSemantics() == &APFloat::IEEEdouble()) {
5040 ID
.APFloatVal
.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven
,
5042 else if (Ty
->isFloatTy())
5043 ID
.APFloatVal
.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven
,
5046 V
= ConstantFP::get(Context
, ID
.APFloatVal
);
5048 if (V
->getType() != Ty
)
5049 return Error(ID
.Loc
, "floating point constant does not have type '" +
5050 getTypeString(Ty
) + "'");
5054 if (!Ty
->isPointerTy())
5055 return Error(ID
.Loc
, "null must be a pointer type");
5056 V
= ConstantPointerNull::get(cast
<PointerType
>(Ty
));
5058 case ValID::t_Undef
:
5059 // FIXME: LabelTy should not be a first-class type.
5060 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5061 return Error(ID
.Loc
, "invalid type for undef constant");
5062 V
= UndefValue::get(Ty
);
5064 case ValID::t_EmptyArray
:
5065 if (!Ty
->isArrayTy() || cast
<ArrayType
>(Ty
)->getNumElements() != 0)
5066 return Error(ID
.Loc
, "invalid empty array initializer");
5067 V
= UndefValue::get(Ty
);
5070 // FIXME: LabelTy should not be a first-class type.
5071 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5072 return Error(ID
.Loc
, "invalid type for null constant");
5073 V
= Constant::getNullValue(Ty
);
5076 if (!Ty
->isTokenTy())
5077 return Error(ID
.Loc
, "invalid type for none constant");
5078 V
= Constant::getNullValue(Ty
);
5080 case ValID::t_Constant
:
5081 if (ID
.ConstantVal
->getType() != Ty
)
5082 return Error(ID
.Loc
, "constant expression type mismatch");
5086 case ValID::t_ConstantStruct
:
5087 case ValID::t_PackedConstantStruct
:
5088 if (StructType
*ST
= dyn_cast
<StructType
>(Ty
)) {
5089 if (ST
->getNumElements() != ID
.UIntVal
)
5090 return Error(ID
.Loc
,
5091 "initializer with struct type has wrong # elements");
5092 if (ST
->isPacked() != (ID
.Kind
== ValID::t_PackedConstantStruct
))
5093 return Error(ID
.Loc
, "packed'ness of initializer and type don't match");
5095 // Verify that the elements are compatible with the structtype.
5096 for (unsigned i
= 0, e
= ID
.UIntVal
; i
!= e
; ++i
)
5097 if (ID
.ConstantStructElts
[i
]->getType() != ST
->getElementType(i
))
5098 return Error(ID
.Loc
, "element " + Twine(i
) +
5099 " of struct initializer doesn't match struct element type");
5101 V
= ConstantStruct::get(
5102 ST
, makeArrayRef(ID
.ConstantStructElts
.get(), ID
.UIntVal
));
5104 return Error(ID
.Loc
, "constant expression type mismatch");
5107 llvm_unreachable("Invalid ValID");
5110 bool LLParser::parseConstantValue(Type
*Ty
, Constant
*&C
) {
5113 auto Loc
= Lex
.getLoc();
5114 if (ParseValID(ID
, /*PFS=*/nullptr))
5117 case ValID::t_APSInt
:
5118 case ValID::t_APFloat
:
5119 case ValID::t_Undef
:
5120 case ValID::t_Constant
:
5121 case ValID::t_ConstantStruct
:
5122 case ValID::t_PackedConstantStruct
: {
5124 if (ConvertValIDToValue(Ty
, ID
, V
, /*PFS=*/nullptr, /*IsCall=*/false))
5126 assert(isa
<Constant
>(V
) && "Expected a constant value");
5127 C
= cast
<Constant
>(V
);
5131 C
= Constant::getNullValue(Ty
);
5134 return Error(Loc
, "expected a constant value");
5138 bool LLParser::ParseValue(Type
*Ty
, Value
*&V
, PerFunctionState
*PFS
) {
5141 return ParseValID(ID
, PFS
) ||
5142 ConvertValIDToValue(Ty
, ID
, V
, PFS
, /*IsCall=*/false);
5145 bool LLParser::ParseTypeAndValue(Value
*&V
, PerFunctionState
*PFS
) {
5147 return ParseType(Ty
) ||
5148 ParseValue(Ty
, V
, PFS
);
5151 bool LLParser::ParseTypeAndBasicBlock(BasicBlock
*&BB
, LocTy
&Loc
,
5152 PerFunctionState
&PFS
) {
5155 if (ParseTypeAndValue(V
, PFS
)) return true;
5156 if (!isa
<BasicBlock
>(V
))
5157 return Error(Loc
, "expected a basic block");
5158 BB
= cast
<BasicBlock
>(V
);
5163 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5164 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5165 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5166 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5167 bool LLParser::ParseFunctionHeader(Function
*&Fn
, bool isDefine
) {
5168 // Parse the linkage.
5169 LocTy LinkageLoc
= Lex
.getLoc();
5171 unsigned Visibility
;
5172 unsigned DLLStorageClass
;
5174 AttrBuilder RetAttrs
;
5177 Type
*RetType
= nullptr;
5178 LocTy RetTypeLoc
= Lex
.getLoc();
5179 if (ParseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
5181 ParseOptionalCallingConv(CC
) || ParseOptionalReturnAttrs(RetAttrs
) ||
5182 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/))
5185 // Verify that the linkage is ok.
5186 switch ((GlobalValue::LinkageTypes
)Linkage
) {
5187 case GlobalValue::ExternalLinkage
:
5188 break; // always ok.
5189 case GlobalValue::ExternalWeakLinkage
:
5191 return Error(LinkageLoc
, "invalid linkage for function definition");
5193 case GlobalValue::PrivateLinkage
:
5194 case GlobalValue::InternalLinkage
:
5195 case GlobalValue::AvailableExternallyLinkage
:
5196 case GlobalValue::LinkOnceAnyLinkage
:
5197 case GlobalValue::LinkOnceODRLinkage
:
5198 case GlobalValue::WeakAnyLinkage
:
5199 case GlobalValue::WeakODRLinkage
:
5201 return Error(LinkageLoc
, "invalid linkage for function declaration");
5203 case GlobalValue::AppendingLinkage
:
5204 case GlobalValue::CommonLinkage
:
5205 return Error(LinkageLoc
, "invalid function linkage type");
5208 if (!isValidVisibilityForLinkage(Visibility
, Linkage
))
5209 return Error(LinkageLoc
,
5210 "symbol with local linkage must have default visibility");
5212 if (!FunctionType::isValidReturnType(RetType
))
5213 return Error(RetTypeLoc
, "invalid function return type");
5215 LocTy NameLoc
= Lex
.getLoc();
5217 std::string FunctionName
;
5218 if (Lex
.getKind() == lltok::GlobalVar
) {
5219 FunctionName
= Lex
.getStrVal();
5220 } else if (Lex
.getKind() == lltok::GlobalID
) { // @42 is ok.
5221 unsigned NameID
= Lex
.getUIntVal();
5223 if (NameID
!= NumberedVals
.size())
5224 return TokError("function expected to be numbered '%" +
5225 Twine(NumberedVals
.size()) + "'");
5227 return TokError("expected function name");
5232 if (Lex
.getKind() != lltok::lparen
)
5233 return TokError("expected '(' in function argument list");
5235 SmallVector
<ArgInfo
, 8> ArgList
;
5237 AttrBuilder FuncAttrs
;
5238 std::vector
<unsigned> FwdRefAttrGrps
;
5240 std::string Section
;
5243 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
5244 unsigned AddrSpace
= 0;
5245 Constant
*Prefix
= nullptr;
5246 Constant
*Prologue
= nullptr;
5247 Constant
*PersonalityFn
= nullptr;
5250 if (ParseArgumentList(ArgList
, isVarArg
) ||
5251 ParseOptionalUnnamedAddr(UnnamedAddr
) ||
5252 ParseOptionalProgramAddrSpace(AddrSpace
) ||
5253 ParseFnAttributeValuePairs(FuncAttrs
, FwdRefAttrGrps
, false,
5255 (EatIfPresent(lltok::kw_section
) &&
5256 ParseStringConstant(Section
)) ||
5257 parseOptionalComdat(FunctionName
, C
) ||
5258 ParseOptionalAlignment(Alignment
) ||
5259 (EatIfPresent(lltok::kw_gc
) &&
5260 ParseStringConstant(GC
)) ||
5261 (EatIfPresent(lltok::kw_prefix
) &&
5262 ParseGlobalTypeAndValue(Prefix
)) ||
5263 (EatIfPresent(lltok::kw_prologue
) &&
5264 ParseGlobalTypeAndValue(Prologue
)) ||
5265 (EatIfPresent(lltok::kw_personality
) &&
5266 ParseGlobalTypeAndValue(PersonalityFn
)))
5269 if (FuncAttrs
.contains(Attribute::Builtin
))
5270 return Error(BuiltinLoc
, "'builtin' attribute not valid on function");
5272 // If the alignment was parsed as an attribute, move to the alignment field.
5273 if (FuncAttrs
.hasAlignmentAttr()) {
5274 Alignment
= FuncAttrs
.getAlignment();
5275 FuncAttrs
.removeAttribute(Attribute::Alignment
);
5278 // Okay, if we got here, the function is syntactically valid. Convert types
5279 // and do semantic checks.
5280 std::vector
<Type
*> ParamTypeList
;
5281 SmallVector
<AttributeSet
, 8> Attrs
;
5283 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
5284 ParamTypeList
.push_back(ArgList
[i
].Ty
);
5285 Attrs
.push_back(ArgList
[i
].Attrs
);
5289 AttributeList::get(Context
, AttributeSet::get(Context
, FuncAttrs
),
5290 AttributeSet::get(Context
, RetAttrs
), Attrs
);
5292 if (PAL
.hasAttribute(1, Attribute::StructRet
) && !RetType
->isVoidTy())
5293 return Error(RetTypeLoc
, "functions with 'sret' argument must return void");
5296 FunctionType::get(RetType
, ParamTypeList
, isVarArg
);
5297 PointerType
*PFT
= PointerType::get(FT
, AddrSpace
);
5300 if (!FunctionName
.empty()) {
5301 // If this was a definition of a forward reference, remove the definition
5302 // from the forward reference table and fill in the forward ref.
5303 auto FRVI
= ForwardRefVals
.find(FunctionName
);
5304 if (FRVI
!= ForwardRefVals
.end()) {
5305 Fn
= M
->getFunction(FunctionName
);
5307 return Error(FRVI
->second
.second
, "invalid forward reference to "
5308 "function as global value!");
5309 if (Fn
->getType() != PFT
)
5310 return Error(FRVI
->second
.second
, "invalid forward reference to "
5311 "function '" + FunctionName
+ "' with wrong type: "
5312 "expected '" + getTypeString(PFT
) + "' but was '" +
5313 getTypeString(Fn
->getType()) + "'");
5314 ForwardRefVals
.erase(FRVI
);
5315 } else if ((Fn
= M
->getFunction(FunctionName
))) {
5316 // Reject redefinitions.
5317 return Error(NameLoc
, "invalid redefinition of function '" +
5318 FunctionName
+ "'");
5319 } else if (M
->getNamedValue(FunctionName
)) {
5320 return Error(NameLoc
, "redefinition of function '@" + FunctionName
+ "'");
5324 // If this is a definition of a forward referenced function, make sure the
5326 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
5327 if (I
!= ForwardRefValIDs
.end()) {
5328 Fn
= cast
<Function
>(I
->second
.first
);
5329 if (Fn
->getType() != PFT
)
5330 return Error(NameLoc
, "type of definition and forward reference of '@" +
5331 Twine(NumberedVals
.size()) + "' disagree: "
5332 "expected '" + getTypeString(PFT
) + "' but was '" +
5333 getTypeString(Fn
->getType()) + "'");
5334 ForwardRefValIDs
.erase(I
);
5339 Fn
= Function::Create(FT
, GlobalValue::ExternalLinkage
, AddrSpace
,
5341 else // Move the forward-reference to the correct spot in the module.
5342 M
->getFunctionList().splice(M
->end(), M
->getFunctionList(), Fn
);
5344 assert(Fn
->getAddressSpace() == AddrSpace
&& "Created function in wrong AS");
5346 if (FunctionName
.empty())
5347 NumberedVals
.push_back(Fn
);
5349 Fn
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
5350 maybeSetDSOLocal(DSOLocal
, *Fn
);
5351 Fn
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
5352 Fn
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
5353 Fn
->setCallingConv(CC
);
5354 Fn
->setAttributes(PAL
);
5355 Fn
->setUnnamedAddr(UnnamedAddr
);
5356 Fn
->setAlignment(Alignment
);
5357 Fn
->setSection(Section
);
5359 Fn
->setPersonalityFn(PersonalityFn
);
5360 if (!GC
.empty()) Fn
->setGC(GC
);
5361 Fn
->setPrefixData(Prefix
);
5362 Fn
->setPrologueData(Prologue
);
5363 ForwardRefAttrGroups
[Fn
] = FwdRefAttrGrps
;
5365 // Add all of the arguments we parsed to the function.
5366 Function::arg_iterator ArgIt
= Fn
->arg_begin();
5367 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
, ++ArgIt
) {
5368 // If the argument has a name, insert it into the argument symbol table.
5369 if (ArgList
[i
].Name
.empty()) continue;
5371 // Set the name, if it conflicted, it will be auto-renamed.
5372 ArgIt
->setName(ArgList
[i
].Name
);
5374 if (ArgIt
->getName() != ArgList
[i
].Name
)
5375 return Error(ArgList
[i
].Loc
, "redefinition of argument '%" +
5376 ArgList
[i
].Name
+ "'");
5382 // Check the declaration has no block address forward references.
5384 if (FunctionName
.empty()) {
5385 ID
.Kind
= ValID::t_GlobalID
;
5386 ID
.UIntVal
= NumberedVals
.size() - 1;
5388 ID
.Kind
= ValID::t_GlobalName
;
5389 ID
.StrVal
= FunctionName
;
5391 auto Blocks
= ForwardRefBlockAddresses
.find(ID
);
5392 if (Blocks
!= ForwardRefBlockAddresses
.end())
5393 return Error(Blocks
->first
.Loc
,
5394 "cannot take blockaddress inside a declaration");
5398 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5400 if (FunctionNumber
== -1) {
5401 ID
.Kind
= ValID::t_GlobalName
;
5402 ID
.StrVal
= F
.getName();
5404 ID
.Kind
= ValID::t_GlobalID
;
5405 ID
.UIntVal
= FunctionNumber
;
5408 auto Blocks
= P
.ForwardRefBlockAddresses
.find(ID
);
5409 if (Blocks
== P
.ForwardRefBlockAddresses
.end())
5412 for (const auto &I
: Blocks
->second
) {
5413 const ValID
&BBID
= I
.first
;
5414 GlobalValue
*GV
= I
.second
;
5416 assert((BBID
.Kind
== ValID::t_LocalID
|| BBID
.Kind
== ValID::t_LocalName
) &&
5417 "Expected local id or name");
5419 if (BBID
.Kind
== ValID::t_LocalName
)
5420 BB
= GetBB(BBID
.StrVal
, BBID
.Loc
);
5422 BB
= GetBB(BBID
.UIntVal
, BBID
.Loc
);
5424 return P
.Error(BBID
.Loc
, "referenced value is not a basic block");
5426 GV
->replaceAllUsesWith(BlockAddress::get(&F
, BB
));
5427 GV
->eraseFromParent();
5430 P
.ForwardRefBlockAddresses
.erase(Blocks
);
5434 /// ParseFunctionBody
5435 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5436 bool LLParser::ParseFunctionBody(Function
&Fn
) {
5437 if (Lex
.getKind() != lltok::lbrace
)
5438 return TokError("expected '{' in function body");
5439 Lex
.Lex(); // eat the {.
5441 int FunctionNumber
= -1;
5442 if (!Fn
.hasName()) FunctionNumber
= NumberedVals
.size()-1;
5444 PerFunctionState
PFS(*this, Fn
, FunctionNumber
);
5446 // Resolve block addresses and allow basic blocks to be forward-declared
5447 // within this function.
5448 if (PFS
.resolveForwardRefBlockAddresses())
5450 SaveAndRestore
<PerFunctionState
*> ScopeExit(BlockAddressPFS
, &PFS
);
5452 // We need at least one basic block.
5453 if (Lex
.getKind() == lltok::rbrace
|| Lex
.getKind() == lltok::kw_uselistorder
)
5454 return TokError("function body requires at least one basic block");
5456 while (Lex
.getKind() != lltok::rbrace
&&
5457 Lex
.getKind() != lltok::kw_uselistorder
)
5458 if (ParseBasicBlock(PFS
)) return true;
5460 while (Lex
.getKind() != lltok::rbrace
)
5461 if (ParseUseListOrder(&PFS
))
5467 // Verify function is ok.
5468 return PFS
.FinishFunction();
5472 /// ::= LabelStr? Instruction*
5473 bool LLParser::ParseBasicBlock(PerFunctionState
&PFS
) {
5474 // If this basic block starts out with a name, remember it.
5476 LocTy NameLoc
= Lex
.getLoc();
5477 if (Lex
.getKind() == lltok::LabelStr
) {
5478 Name
= Lex
.getStrVal();
5482 BasicBlock
*BB
= PFS
.DefineBB(Name
, NameLoc
);
5484 return Error(NameLoc
,
5485 "unable to create block named '" + Name
+ "'");
5487 std::string NameStr
;
5489 // Parse the instructions in this block until we get a terminator.
5492 // This instruction may have three possibilities for a name: a) none
5493 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5494 LocTy NameLoc
= Lex
.getLoc();
5498 if (Lex
.getKind() == lltok::LocalVarID
) {
5499 NameID
= Lex
.getUIntVal();
5501 if (ParseToken(lltok::equal
, "expected '=' after instruction id"))
5503 } else if (Lex
.getKind() == lltok::LocalVar
) {
5504 NameStr
= Lex
.getStrVal();
5506 if (ParseToken(lltok::equal
, "expected '=' after instruction name"))
5510 switch (ParseInstruction(Inst
, BB
, PFS
)) {
5511 default: llvm_unreachable("Unknown ParseInstruction result!");
5512 case InstError
: return true;
5514 BB
->getInstList().push_back(Inst
);
5516 // With a normal result, we check to see if the instruction is followed by
5517 // a comma and metadata.
5518 if (EatIfPresent(lltok::comma
))
5519 if (ParseInstructionMetadata(*Inst
))
5522 case InstExtraComma
:
5523 BB
->getInstList().push_back(Inst
);
5525 // If the instruction parser ate an extra comma at the end of it, it
5526 // *must* be followed by metadata.
5527 if (ParseInstructionMetadata(*Inst
))
5532 // Set the name on the instruction.
5533 if (PFS
.SetInstName(NameID
, NameStr
, NameLoc
, Inst
)) return true;
5534 } while (!Inst
->isTerminator());
5539 //===----------------------------------------------------------------------===//
5540 // Instruction Parsing.
5541 //===----------------------------------------------------------------------===//
5543 /// ParseInstruction - Parse one of the many different instructions.
5545 int LLParser::ParseInstruction(Instruction
*&Inst
, BasicBlock
*BB
,
5546 PerFunctionState
&PFS
) {
5547 lltok::Kind Token
= Lex
.getKind();
5548 if (Token
== lltok::Eof
)
5549 return TokError("found end of file when expecting more instructions");
5550 LocTy Loc
= Lex
.getLoc();
5551 unsigned KeywordVal
= Lex
.getUIntVal();
5552 Lex
.Lex(); // Eat the keyword.
5555 default: return Error(Loc
, "expected instruction opcode");
5556 // Terminator Instructions.
5557 case lltok::kw_unreachable
: Inst
= new UnreachableInst(Context
); return false;
5558 case lltok::kw_ret
: return ParseRet(Inst
, BB
, PFS
);
5559 case lltok::kw_br
: return ParseBr(Inst
, PFS
);
5560 case lltok::kw_switch
: return ParseSwitch(Inst
, PFS
);
5561 case lltok::kw_indirectbr
: return ParseIndirectBr(Inst
, PFS
);
5562 case lltok::kw_invoke
: return ParseInvoke(Inst
, PFS
);
5563 case lltok::kw_resume
: return ParseResume(Inst
, PFS
);
5564 case lltok::kw_cleanupret
: return ParseCleanupRet(Inst
, PFS
);
5565 case lltok::kw_catchret
: return ParseCatchRet(Inst
, PFS
);
5566 case lltok::kw_catchswitch
: return ParseCatchSwitch(Inst
, PFS
);
5567 case lltok::kw_catchpad
: return ParseCatchPad(Inst
, PFS
);
5568 case lltok::kw_cleanuppad
: return ParseCleanupPad(Inst
, PFS
);
5570 case lltok::kw_fneg
: {
5571 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5572 int Res
= ParseUnaryOp(Inst
, PFS
, KeywordVal
, 2);
5576 Inst
->setFastMathFlags(FMF
);
5579 // Binary Operators.
5583 case lltok::kw_shl
: {
5584 bool NUW
= EatIfPresent(lltok::kw_nuw
);
5585 bool NSW
= EatIfPresent(lltok::kw_nsw
);
5586 if (!NUW
) NUW
= EatIfPresent(lltok::kw_nuw
);
5588 if (ParseArithmetic(Inst
, PFS
, KeywordVal
, 1)) return true;
5590 if (NUW
) cast
<BinaryOperator
>(Inst
)->setHasNoUnsignedWrap(true);
5591 if (NSW
) cast
<BinaryOperator
>(Inst
)->setHasNoSignedWrap(true);
5594 case lltok::kw_fadd
:
5595 case lltok::kw_fsub
:
5596 case lltok::kw_fmul
:
5597 case lltok::kw_fdiv
:
5598 case lltok::kw_frem
: {
5599 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5600 int Res
= ParseArithmetic(Inst
, PFS
, KeywordVal
, 2);
5604 Inst
->setFastMathFlags(FMF
);
5608 case lltok::kw_sdiv
:
5609 case lltok::kw_udiv
:
5610 case lltok::kw_lshr
:
5611 case lltok::kw_ashr
: {
5612 bool Exact
= EatIfPresent(lltok::kw_exact
);
5614 if (ParseArithmetic(Inst
, PFS
, KeywordVal
, 1)) return true;
5615 if (Exact
) cast
<BinaryOperator
>(Inst
)->setIsExact(true);
5619 case lltok::kw_urem
:
5620 case lltok::kw_srem
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 1);
5623 case lltok::kw_xor
: return ParseLogical(Inst
, PFS
, KeywordVal
);
5624 case lltok::kw_icmp
: return ParseCompare(Inst
, PFS
, KeywordVal
);
5625 case lltok::kw_fcmp
: {
5626 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5627 int Res
= ParseCompare(Inst
, PFS
, KeywordVal
);
5631 Inst
->setFastMathFlags(FMF
);
5636 case lltok::kw_trunc
:
5637 case lltok::kw_zext
:
5638 case lltok::kw_sext
:
5639 case lltok::kw_fptrunc
:
5640 case lltok::kw_fpext
:
5641 case lltok::kw_bitcast
:
5642 case lltok::kw_addrspacecast
:
5643 case lltok::kw_uitofp
:
5644 case lltok::kw_sitofp
:
5645 case lltok::kw_fptoui
:
5646 case lltok::kw_fptosi
:
5647 case lltok::kw_inttoptr
:
5648 case lltok::kw_ptrtoint
: return ParseCast(Inst
, PFS
, KeywordVal
);
5650 case lltok::kw_select
: return ParseSelect(Inst
, PFS
);
5651 case lltok::kw_va_arg
: return ParseVA_Arg(Inst
, PFS
);
5652 case lltok::kw_extractelement
: return ParseExtractElement(Inst
, PFS
);
5653 case lltok::kw_insertelement
: return ParseInsertElement(Inst
, PFS
);
5654 case lltok::kw_shufflevector
: return ParseShuffleVector(Inst
, PFS
);
5655 case lltok::kw_phi
: return ParsePHI(Inst
, PFS
);
5656 case lltok::kw_landingpad
: return ParseLandingPad(Inst
, PFS
);
5658 case lltok::kw_call
: return ParseCall(Inst
, PFS
, CallInst::TCK_None
);
5659 case lltok::kw_tail
: return ParseCall(Inst
, PFS
, CallInst::TCK_Tail
);
5660 case lltok::kw_musttail
: return ParseCall(Inst
, PFS
, CallInst::TCK_MustTail
);
5661 case lltok::kw_notail
: return ParseCall(Inst
, PFS
, CallInst::TCK_NoTail
);
5663 case lltok::kw_alloca
: return ParseAlloc(Inst
, PFS
);
5664 case lltok::kw_load
: return ParseLoad(Inst
, PFS
);
5665 case lltok::kw_store
: return ParseStore(Inst
, PFS
);
5666 case lltok::kw_cmpxchg
: return ParseCmpXchg(Inst
, PFS
);
5667 case lltok::kw_atomicrmw
: return ParseAtomicRMW(Inst
, PFS
);
5668 case lltok::kw_fence
: return ParseFence(Inst
, PFS
);
5669 case lltok::kw_getelementptr
: return ParseGetElementPtr(Inst
, PFS
);
5670 case lltok::kw_extractvalue
: return ParseExtractValue(Inst
, PFS
);
5671 case lltok::kw_insertvalue
: return ParseInsertValue(Inst
, PFS
);
5675 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5676 bool LLParser::ParseCmpPredicate(unsigned &P
, unsigned Opc
) {
5677 if (Opc
== Instruction::FCmp
) {
5678 switch (Lex
.getKind()) {
5679 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5680 case lltok::kw_oeq
: P
= CmpInst::FCMP_OEQ
; break;
5681 case lltok::kw_one
: P
= CmpInst::FCMP_ONE
; break;
5682 case lltok::kw_olt
: P
= CmpInst::FCMP_OLT
; break;
5683 case lltok::kw_ogt
: P
= CmpInst::FCMP_OGT
; break;
5684 case lltok::kw_ole
: P
= CmpInst::FCMP_OLE
; break;
5685 case lltok::kw_oge
: P
= CmpInst::FCMP_OGE
; break;
5686 case lltok::kw_ord
: P
= CmpInst::FCMP_ORD
; break;
5687 case lltok::kw_uno
: P
= CmpInst::FCMP_UNO
; break;
5688 case lltok::kw_ueq
: P
= CmpInst::FCMP_UEQ
; break;
5689 case lltok::kw_une
: P
= CmpInst::FCMP_UNE
; break;
5690 case lltok::kw_ult
: P
= CmpInst::FCMP_ULT
; break;
5691 case lltok::kw_ugt
: P
= CmpInst::FCMP_UGT
; break;
5692 case lltok::kw_ule
: P
= CmpInst::FCMP_ULE
; break;
5693 case lltok::kw_uge
: P
= CmpInst::FCMP_UGE
; break;
5694 case lltok::kw_true
: P
= CmpInst::FCMP_TRUE
; break;
5695 case lltok::kw_false
: P
= CmpInst::FCMP_FALSE
; break;
5698 switch (Lex
.getKind()) {
5699 default: return TokError("expected icmp predicate (e.g. 'eq')");
5700 case lltok::kw_eq
: P
= CmpInst::ICMP_EQ
; break;
5701 case lltok::kw_ne
: P
= CmpInst::ICMP_NE
; break;
5702 case lltok::kw_slt
: P
= CmpInst::ICMP_SLT
; break;
5703 case lltok::kw_sgt
: P
= CmpInst::ICMP_SGT
; break;
5704 case lltok::kw_sle
: P
= CmpInst::ICMP_SLE
; break;
5705 case lltok::kw_sge
: P
= CmpInst::ICMP_SGE
; break;
5706 case lltok::kw_ult
: P
= CmpInst::ICMP_ULT
; break;
5707 case lltok::kw_ugt
: P
= CmpInst::ICMP_UGT
; break;
5708 case lltok::kw_ule
: P
= CmpInst::ICMP_ULE
; break;
5709 case lltok::kw_uge
: P
= CmpInst::ICMP_UGE
; break;
5716 //===----------------------------------------------------------------------===//
5717 // Terminator Instructions.
5718 //===----------------------------------------------------------------------===//
5720 /// ParseRet - Parse a return instruction.
5721 /// ::= 'ret' void (',' !dbg, !1)*
5722 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5723 bool LLParser::ParseRet(Instruction
*&Inst
, BasicBlock
*BB
,
5724 PerFunctionState
&PFS
) {
5725 SMLoc TypeLoc
= Lex
.getLoc();
5727 if (ParseType(Ty
, true /*void allowed*/)) return true;
5729 Type
*ResType
= PFS
.getFunction().getReturnType();
5731 if (Ty
->isVoidTy()) {
5732 if (!ResType
->isVoidTy())
5733 return Error(TypeLoc
, "value doesn't match function result type '" +
5734 getTypeString(ResType
) + "'");
5736 Inst
= ReturnInst::Create(Context
);
5741 if (ParseValue(Ty
, RV
, PFS
)) return true;
5743 if (ResType
!= RV
->getType())
5744 return Error(TypeLoc
, "value doesn't match function result type '" +
5745 getTypeString(ResType
) + "'");
5747 Inst
= ReturnInst::Create(Context
, RV
);
5752 /// ::= 'br' TypeAndValue
5753 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5754 bool LLParser::ParseBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
5757 BasicBlock
*Op1
, *Op2
;
5758 if (ParseTypeAndValue(Op0
, Loc
, PFS
)) return true;
5760 if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(Op0
)) {
5761 Inst
= BranchInst::Create(BB
);
5765 if (Op0
->getType() != Type::getInt1Ty(Context
))
5766 return Error(Loc
, "branch condition must have 'i1' type");
5768 if (ParseToken(lltok::comma
, "expected ',' after branch condition") ||
5769 ParseTypeAndBasicBlock(Op1
, Loc
, PFS
) ||
5770 ParseToken(lltok::comma
, "expected ',' after true destination") ||
5771 ParseTypeAndBasicBlock(Op2
, Loc2
, PFS
))
5774 Inst
= BranchInst::Create(Op1
, Op2
, Op0
);
5780 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5782 /// ::= (TypeAndValue ',' TypeAndValue)*
5783 bool LLParser::ParseSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
5784 LocTy CondLoc
, BBLoc
;
5786 BasicBlock
*DefaultBB
;
5787 if (ParseTypeAndValue(Cond
, CondLoc
, PFS
) ||
5788 ParseToken(lltok::comma
, "expected ',' after switch condition") ||
5789 ParseTypeAndBasicBlock(DefaultBB
, BBLoc
, PFS
) ||
5790 ParseToken(lltok::lsquare
, "expected '[' with switch table"))
5793 if (!Cond
->getType()->isIntegerTy())
5794 return Error(CondLoc
, "switch condition must have integer type");
5796 // Parse the jump table pairs.
5797 SmallPtrSet
<Value
*, 32> SeenCases
;
5798 SmallVector
<std::pair
<ConstantInt
*, BasicBlock
*>, 32> Table
;
5799 while (Lex
.getKind() != lltok::rsquare
) {
5803 if (ParseTypeAndValue(Constant
, CondLoc
, PFS
) ||
5804 ParseToken(lltok::comma
, "expected ',' after case value") ||
5805 ParseTypeAndBasicBlock(DestBB
, PFS
))
5808 if (!SeenCases
.insert(Constant
).second
)
5809 return Error(CondLoc
, "duplicate case value in switch");
5810 if (!isa
<ConstantInt
>(Constant
))
5811 return Error(CondLoc
, "case value is not a constant integer");
5813 Table
.push_back(std::make_pair(cast
<ConstantInt
>(Constant
), DestBB
));
5816 Lex
.Lex(); // Eat the ']'.
5818 SwitchInst
*SI
= SwitchInst::Create(Cond
, DefaultBB
, Table
.size());
5819 for (unsigned i
= 0, e
= Table
.size(); i
!= e
; ++i
)
5820 SI
->addCase(Table
[i
].first
, Table
[i
].second
);
5827 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5828 bool LLParser::ParseIndirectBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
5831 if (ParseTypeAndValue(Address
, AddrLoc
, PFS
) ||
5832 ParseToken(lltok::comma
, "expected ',' after indirectbr address") ||
5833 ParseToken(lltok::lsquare
, "expected '[' with indirectbr"))
5836 if (!Address
->getType()->isPointerTy())
5837 return Error(AddrLoc
, "indirectbr address must have pointer type");
5839 // Parse the destination list.
5840 SmallVector
<BasicBlock
*, 16> DestList
;
5842 if (Lex
.getKind() != lltok::rsquare
) {
5844 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
5846 DestList
.push_back(DestBB
);
5848 while (EatIfPresent(lltok::comma
)) {
5849 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
5851 DestList
.push_back(DestBB
);
5855 if (ParseToken(lltok::rsquare
, "expected ']' at end of block list"))
5858 IndirectBrInst
*IBI
= IndirectBrInst::Create(Address
, DestList
.size());
5859 for (unsigned i
= 0, e
= DestList
.size(); i
!= e
; ++i
)
5860 IBI
->addDestination(DestList
[i
]);
5866 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5867 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5868 bool LLParser::ParseInvoke(Instruction
*&Inst
, PerFunctionState
&PFS
) {
5869 LocTy CallLoc
= Lex
.getLoc();
5870 AttrBuilder RetAttrs
, FnAttrs
;
5871 std::vector
<unsigned> FwdRefAttrGrps
;
5874 unsigned InvokeAddrSpace
;
5875 Type
*RetType
= nullptr;
5878 SmallVector
<ParamInfo
, 16> ArgList
;
5879 SmallVector
<OperandBundleDef
, 2> BundleList
;
5881 BasicBlock
*NormalBB
, *UnwindBB
;
5882 if (ParseOptionalCallingConv(CC
) || ParseOptionalReturnAttrs(RetAttrs
) ||
5883 ParseOptionalProgramAddrSpace(InvokeAddrSpace
) ||
5884 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
5885 ParseValID(CalleeID
) || ParseParameterList(ArgList
, PFS
) ||
5886 ParseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false,
5888 ParseOptionalOperandBundles(BundleList
, PFS
) ||
5889 ParseToken(lltok::kw_to
, "expected 'to' in invoke") ||
5890 ParseTypeAndBasicBlock(NormalBB
, PFS
) ||
5891 ParseToken(lltok::kw_unwind
, "expected 'unwind' in invoke") ||
5892 ParseTypeAndBasicBlock(UnwindBB
, PFS
))
5895 // If RetType is a non-function pointer type, then this is the short syntax
5896 // for the call, which means that RetType is just the return type. Infer the
5897 // rest of the function argument types from the arguments that are present.
5898 FunctionType
*Ty
= dyn_cast
<FunctionType
>(RetType
);
5900 // Pull out the types of all of the arguments...
5901 std::vector
<Type
*> ParamTypes
;
5902 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
5903 ParamTypes
.push_back(ArgList
[i
].V
->getType());
5905 if (!FunctionType::isValidReturnType(RetType
))
5906 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
5908 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
5913 // Look up the callee.
5915 if (ConvertValIDToValue(PointerType::get(Ty
, InvokeAddrSpace
), CalleeID
,
5916 Callee
, &PFS
, /*IsCall=*/true))
5919 // Set up the Attribute for the function.
5920 SmallVector
<Value
*, 8> Args
;
5921 SmallVector
<AttributeSet
, 8> ArgAttrs
;
5923 // Loop through FunctionType's arguments and ensure they are specified
5924 // correctly. Also, gather any parameter attributes.
5925 FunctionType::param_iterator I
= Ty
->param_begin();
5926 FunctionType::param_iterator E
= Ty
->param_end();
5927 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
5928 Type
*ExpectedTy
= nullptr;
5931 } else if (!Ty
->isVarArg()) {
5932 return Error(ArgList
[i
].Loc
, "too many arguments specified");
5935 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
5936 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
5937 getTypeString(ExpectedTy
) + "'");
5938 Args
.push_back(ArgList
[i
].V
);
5939 ArgAttrs
.push_back(ArgList
[i
].Attrs
);
5943 return Error(CallLoc
, "not enough parameters specified for call");
5945 if (FnAttrs
.hasAlignmentAttr())
5946 return Error(CallLoc
, "invoke instructions may not have an alignment");
5948 // Finish off the Attribute and check them
5950 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
5951 AttributeSet::get(Context
, RetAttrs
), ArgAttrs
);
5954 InvokeInst::Create(Ty
, Callee
, NormalBB
, UnwindBB
, Args
, BundleList
);
5955 II
->setCallingConv(CC
);
5956 II
->setAttributes(PAL
);
5957 ForwardRefAttrGroups
[II
] = FwdRefAttrGrps
;
5963 /// ::= 'resume' TypeAndValue
5964 bool LLParser::ParseResume(Instruction
*&Inst
, PerFunctionState
&PFS
) {
5965 Value
*Exn
; LocTy ExnLoc
;
5966 if (ParseTypeAndValue(Exn
, ExnLoc
, PFS
))
5969 ResumeInst
*RI
= ResumeInst::Create(Exn
);
5974 bool LLParser::ParseExceptionArgs(SmallVectorImpl
<Value
*> &Args
,
5975 PerFunctionState
&PFS
) {
5976 if (ParseToken(lltok::lsquare
, "expected '[' in catchpad/cleanuppad"))
5979 while (Lex
.getKind() != lltok::rsquare
) {
5980 // If this isn't the first argument, we need a comma.
5981 if (!Args
.empty() &&
5982 ParseToken(lltok::comma
, "expected ',' in argument list"))
5985 // Parse the argument.
5987 Type
*ArgTy
= nullptr;
5988 if (ParseType(ArgTy
, ArgLoc
))
5992 if (ArgTy
->isMetadataTy()) {
5993 if (ParseMetadataAsValue(V
, PFS
))
5996 if (ParseValue(ArgTy
, V
, PFS
))
6002 Lex
.Lex(); // Lex the ']'.
6007 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6008 bool LLParser::ParseCleanupRet(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6009 Value
*CleanupPad
= nullptr;
6011 if (ParseToken(lltok::kw_from
, "expected 'from' after cleanupret"))
6014 if (ParseValue(Type::getTokenTy(Context
), CleanupPad
, PFS
))
6017 if (ParseToken(lltok::kw_unwind
, "expected 'unwind' in cleanupret"))
6020 BasicBlock
*UnwindBB
= nullptr;
6021 if (Lex
.getKind() == lltok::kw_to
) {
6023 if (ParseToken(lltok::kw_caller
, "expected 'caller' in cleanupret"))
6026 if (ParseTypeAndBasicBlock(UnwindBB
, PFS
)) {
6031 Inst
= CleanupReturnInst::Create(CleanupPad
, UnwindBB
);
6036 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6037 bool LLParser::ParseCatchRet(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6038 Value
*CatchPad
= nullptr;
6040 if (ParseToken(lltok::kw_from
, "expected 'from' after catchret"))
6043 if (ParseValue(Type::getTokenTy(Context
), CatchPad
, PFS
))
6047 if (ParseToken(lltok::kw_to
, "expected 'to' in catchret") ||
6048 ParseTypeAndBasicBlock(BB
, PFS
))
6051 Inst
= CatchReturnInst::Create(CatchPad
, BB
);
6055 /// ParseCatchSwitch
6056 /// ::= 'catchswitch' within Parent
6057 bool LLParser::ParseCatchSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6060 if (ParseToken(lltok::kw_within
, "expected 'within' after catchswitch"))
6063 if (Lex
.getKind() != lltok::kw_none
&& Lex
.getKind() != lltok::LocalVar
&&
6064 Lex
.getKind() != lltok::LocalVarID
)
6065 return TokError("expected scope value for catchswitch");
6067 if (ParseValue(Type::getTokenTy(Context
), ParentPad
, PFS
))
6070 if (ParseToken(lltok::lsquare
, "expected '[' with catchswitch labels"))
6073 SmallVector
<BasicBlock
*, 32> Table
;
6076 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
6078 Table
.push_back(DestBB
);
6079 } while (EatIfPresent(lltok::comma
));
6081 if (ParseToken(lltok::rsquare
, "expected ']' after catchswitch labels"))
6084 if (ParseToken(lltok::kw_unwind
,
6085 "expected 'unwind' after catchswitch scope"))
6088 BasicBlock
*UnwindBB
= nullptr;
6089 if (EatIfPresent(lltok::kw_to
)) {
6090 if (ParseToken(lltok::kw_caller
, "expected 'caller' in catchswitch"))
6093 if (ParseTypeAndBasicBlock(UnwindBB
, PFS
))
6098 CatchSwitchInst::Create(ParentPad
, UnwindBB
, Table
.size());
6099 for (BasicBlock
*DestBB
: Table
)
6100 CatchSwitch
->addHandler(DestBB
);
6106 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6107 bool LLParser::ParseCatchPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6108 Value
*CatchSwitch
= nullptr;
6110 if (ParseToken(lltok::kw_within
, "expected 'within' after catchpad"))
6113 if (Lex
.getKind() != lltok::LocalVar
&& Lex
.getKind() != lltok::LocalVarID
)
6114 return TokError("expected scope value for catchpad");
6116 if (ParseValue(Type::getTokenTy(Context
), CatchSwitch
, PFS
))
6119 SmallVector
<Value
*, 8> Args
;
6120 if (ParseExceptionArgs(Args
, PFS
))
6123 Inst
= CatchPadInst::Create(CatchSwitch
, Args
);
6128 /// ::= 'cleanuppad' within Parent ParamList
6129 bool LLParser::ParseCleanupPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6130 Value
*ParentPad
= nullptr;
6132 if (ParseToken(lltok::kw_within
, "expected 'within' after cleanuppad"))
6135 if (Lex
.getKind() != lltok::kw_none
&& Lex
.getKind() != lltok::LocalVar
&&
6136 Lex
.getKind() != lltok::LocalVarID
)
6137 return TokError("expected scope value for cleanuppad");
6139 if (ParseValue(Type::getTokenTy(Context
), ParentPad
, PFS
))
6142 SmallVector
<Value
*, 8> Args
;
6143 if (ParseExceptionArgs(Args
, PFS
))
6146 Inst
= CleanupPadInst::Create(ParentPad
, Args
);
6150 //===----------------------------------------------------------------------===//
6152 //===----------------------------------------------------------------------===//
6155 /// ::= UnaryOp TypeAndValue ',' Value
6157 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6158 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
6159 bool LLParser::ParseUnaryOp(Instruction
*&Inst
, PerFunctionState
&PFS
,
6160 unsigned Opc
, unsigned OperandType
) {
6161 LocTy Loc
; Value
*LHS
;
6162 if (ParseTypeAndValue(LHS
, Loc
, PFS
))
6166 switch (OperandType
) {
6167 default: llvm_unreachable("Unknown operand type!");
6168 case 0: // int or FP.
6169 Valid
= LHS
->getType()->isIntOrIntVectorTy() ||
6170 LHS
->getType()->isFPOrFPVectorTy();
6173 Valid
= LHS
->getType()->isIntOrIntVectorTy();
6176 Valid
= LHS
->getType()->isFPOrFPVectorTy();
6181 return Error(Loc
, "invalid operand type for instruction");
6183 Inst
= UnaryOperator::Create((Instruction::UnaryOps
)Opc
, LHS
);
6187 //===----------------------------------------------------------------------===//
6188 // Binary Operators.
6189 //===----------------------------------------------------------------------===//
6192 /// ::= ArithmeticOps TypeAndValue ',' Value
6194 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6195 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
6196 bool LLParser::ParseArithmetic(Instruction
*&Inst
, PerFunctionState
&PFS
,
6197 unsigned Opc
, unsigned OperandType
) {
6198 LocTy Loc
; Value
*LHS
, *RHS
;
6199 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
6200 ParseToken(lltok::comma
, "expected ',' in arithmetic operation") ||
6201 ParseValue(LHS
->getType(), RHS
, PFS
))
6205 switch (OperandType
) {
6206 default: llvm_unreachable("Unknown operand type!");
6207 case 0: // int or FP.
6208 Valid
= LHS
->getType()->isIntOrIntVectorTy() ||
6209 LHS
->getType()->isFPOrFPVectorTy();
6211 case 1: Valid
= LHS
->getType()->isIntOrIntVectorTy(); break;
6212 case 2: Valid
= LHS
->getType()->isFPOrFPVectorTy(); break;
6216 return Error(Loc
, "invalid operand type for instruction");
6218 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
6223 /// ::= ArithmeticOps TypeAndValue ',' Value {
6224 bool LLParser::ParseLogical(Instruction
*&Inst
, PerFunctionState
&PFS
,
6226 LocTy Loc
; Value
*LHS
, *RHS
;
6227 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
6228 ParseToken(lltok::comma
, "expected ',' in logical operation") ||
6229 ParseValue(LHS
->getType(), RHS
, PFS
))
6232 if (!LHS
->getType()->isIntOrIntVectorTy())
6233 return Error(Loc
,"instruction requires integer or integer vector operands");
6235 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
6240 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
6241 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
6242 bool LLParser::ParseCompare(Instruction
*&Inst
, PerFunctionState
&PFS
,
6244 // Parse the integer/fp comparison predicate.
6248 if (ParseCmpPredicate(Pred
, Opc
) ||
6249 ParseTypeAndValue(LHS
, Loc
, PFS
) ||
6250 ParseToken(lltok::comma
, "expected ',' after compare value") ||
6251 ParseValue(LHS
->getType(), RHS
, PFS
))
6254 if (Opc
== Instruction::FCmp
) {
6255 if (!LHS
->getType()->isFPOrFPVectorTy())
6256 return Error(Loc
, "fcmp requires floating point operands");
6257 Inst
= new FCmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
6259 assert(Opc
== Instruction::ICmp
&& "Unknown opcode for CmpInst!");
6260 if (!LHS
->getType()->isIntOrIntVectorTy() &&
6261 !LHS
->getType()->isPtrOrPtrVectorTy())
6262 return Error(Loc
, "icmp requires integer operands");
6263 Inst
= new ICmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
6268 //===----------------------------------------------------------------------===//
6269 // Other Instructions.
6270 //===----------------------------------------------------------------------===//
6274 /// ::= CastOpc TypeAndValue 'to' Type
6275 bool LLParser::ParseCast(Instruction
*&Inst
, PerFunctionState
&PFS
,
6279 Type
*DestTy
= nullptr;
6280 if (ParseTypeAndValue(Op
, Loc
, PFS
) ||
6281 ParseToken(lltok::kw_to
, "expected 'to' after cast value") ||
6285 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
)) {
6286 CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
);
6287 return Error(Loc
, "invalid cast opcode for cast from '" +
6288 getTypeString(Op
->getType()) + "' to '" +
6289 getTypeString(DestTy
) + "'");
6291 Inst
= CastInst::Create((Instruction::CastOps
)Opc
, Op
, DestTy
);
6296 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6297 bool LLParser::ParseSelect(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6299 Value
*Op0
, *Op1
, *Op2
;
6300 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
6301 ParseToken(lltok::comma
, "expected ',' after select condition") ||
6302 ParseTypeAndValue(Op1
, PFS
) ||
6303 ParseToken(lltok::comma
, "expected ',' after select value") ||
6304 ParseTypeAndValue(Op2
, PFS
))
6307 if (const char *Reason
= SelectInst::areInvalidOperands(Op0
, Op1
, Op2
))
6308 return Error(Loc
, Reason
);
6310 Inst
= SelectInst::Create(Op0
, Op1
, Op2
);
6315 /// ::= 'va_arg' TypeAndValue ',' Type
6316 bool LLParser::ParseVA_Arg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6318 Type
*EltTy
= nullptr;
6320 if (ParseTypeAndValue(Op
, PFS
) ||
6321 ParseToken(lltok::comma
, "expected ',' after vaarg operand") ||
6322 ParseType(EltTy
, TypeLoc
))
6325 if (!EltTy
->isFirstClassType())
6326 return Error(TypeLoc
, "va_arg requires operand with first class type");
6328 Inst
= new VAArgInst(Op
, EltTy
);
6332 /// ParseExtractElement
6333 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6334 bool LLParser::ParseExtractElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6337 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
6338 ParseToken(lltok::comma
, "expected ',' after extract value") ||
6339 ParseTypeAndValue(Op1
, PFS
))
6342 if (!ExtractElementInst::isValidOperands(Op0
, Op1
))
6343 return Error(Loc
, "invalid extractelement operands");
6345 Inst
= ExtractElementInst::Create(Op0
, Op1
);
6349 /// ParseInsertElement
6350 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6351 bool LLParser::ParseInsertElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6353 Value
*Op0
, *Op1
, *Op2
;
6354 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
6355 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
6356 ParseTypeAndValue(Op1
, PFS
) ||
6357 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
6358 ParseTypeAndValue(Op2
, PFS
))
6361 if (!InsertElementInst::isValidOperands(Op0
, Op1
, Op2
))
6362 return Error(Loc
, "invalid insertelement operands");
6364 Inst
= InsertElementInst::Create(Op0
, Op1
, Op2
);
6368 /// ParseShuffleVector
6369 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6370 bool LLParser::ParseShuffleVector(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6372 Value
*Op0
, *Op1
, *Op2
;
6373 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
6374 ParseToken(lltok::comma
, "expected ',' after shuffle mask") ||
6375 ParseTypeAndValue(Op1
, PFS
) ||
6376 ParseToken(lltok::comma
, "expected ',' after shuffle value") ||
6377 ParseTypeAndValue(Op2
, PFS
))
6380 if (!ShuffleVectorInst::isValidOperands(Op0
, Op1
, Op2
))
6381 return Error(Loc
, "invalid shufflevector operands");
6383 Inst
= new ShuffleVectorInst(Op0
, Op1
, Op2
);
6388 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6389 int LLParser::ParsePHI(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6390 Type
*Ty
= nullptr; LocTy TypeLoc
;
6393 if (ParseType(Ty
, TypeLoc
) ||
6394 ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
6395 ParseValue(Ty
, Op0
, PFS
) ||
6396 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
6397 ParseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
6398 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
6401 bool AteExtraComma
= false;
6402 SmallVector
<std::pair
<Value
*, BasicBlock
*>, 16> PHIVals
;
6405 PHIVals
.push_back(std::make_pair(Op0
, cast
<BasicBlock
>(Op1
)));
6407 if (!EatIfPresent(lltok::comma
))
6410 if (Lex
.getKind() == lltok::MetadataVar
) {
6411 AteExtraComma
= true;
6415 if (ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
6416 ParseValue(Ty
, Op0
, PFS
) ||
6417 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
6418 ParseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
6419 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
6423 if (!Ty
->isFirstClassType())
6424 return Error(TypeLoc
, "phi node must have first class type");
6426 PHINode
*PN
= PHINode::Create(Ty
, PHIVals
.size());
6427 for (unsigned i
= 0, e
= PHIVals
.size(); i
!= e
; ++i
)
6428 PN
->addIncoming(PHIVals
[i
].first
, PHIVals
[i
].second
);
6430 return AteExtraComma
? InstExtraComma
: InstNormal
;
6434 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6436 /// ::= 'catch' TypeAndValue
6438 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6439 bool LLParser::ParseLandingPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6440 Type
*Ty
= nullptr; LocTy TyLoc
;
6442 if (ParseType(Ty
, TyLoc
))
6445 std::unique_ptr
<LandingPadInst
> LP(LandingPadInst::Create(Ty
, 0));
6446 LP
->setCleanup(EatIfPresent(lltok::kw_cleanup
));
6448 while (Lex
.getKind() == lltok::kw_catch
|| Lex
.getKind() == lltok::kw_filter
){
6449 LandingPadInst::ClauseType CT
;
6450 if (EatIfPresent(lltok::kw_catch
))
6451 CT
= LandingPadInst::Catch
;
6452 else if (EatIfPresent(lltok::kw_filter
))
6453 CT
= LandingPadInst::Filter
;
6455 return TokError("expected 'catch' or 'filter' clause type");
6459 if (ParseTypeAndValue(V
, VLoc
, PFS
))
6462 // A 'catch' type expects a non-array constant. A filter clause expects an
6464 if (CT
== LandingPadInst::Catch
) {
6465 if (isa
<ArrayType
>(V
->getType()))
6466 Error(VLoc
, "'catch' clause has an invalid type");
6468 if (!isa
<ArrayType
>(V
->getType()))
6469 Error(VLoc
, "'filter' clause has an invalid type");
6472 Constant
*CV
= dyn_cast
<Constant
>(V
);
6474 return Error(VLoc
, "clause argument must be a constant");
6478 Inst
= LP
.release();
6483 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6484 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6485 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6486 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6487 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6488 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6489 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6490 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6491 bool LLParser::ParseCall(Instruction
*&Inst
, PerFunctionState
&PFS
,
6492 CallInst::TailCallKind TCK
) {
6493 AttrBuilder RetAttrs
, FnAttrs
;
6494 std::vector
<unsigned> FwdRefAttrGrps
;
6496 unsigned CallAddrSpace
;
6498 Type
*RetType
= nullptr;
6501 SmallVector
<ParamInfo
, 16> ArgList
;
6502 SmallVector
<OperandBundleDef
, 2> BundleList
;
6503 LocTy CallLoc
= Lex
.getLoc();
6505 if (TCK
!= CallInst::TCK_None
&&
6506 ParseToken(lltok::kw_call
,
6507 "expected 'tail call', 'musttail call', or 'notail call'"))
6510 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6512 if (ParseOptionalCallingConv(CC
) || ParseOptionalReturnAttrs(RetAttrs
) ||
6513 ParseOptionalProgramAddrSpace(CallAddrSpace
) ||
6514 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
6515 ParseValID(CalleeID
) ||
6516 ParseParameterList(ArgList
, PFS
, TCK
== CallInst::TCK_MustTail
,
6517 PFS
.getFunction().isVarArg()) ||
6518 ParseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false, BuiltinLoc
) ||
6519 ParseOptionalOperandBundles(BundleList
, PFS
))
6522 if (FMF
.any() && !RetType
->isFPOrFPVectorTy())
6523 return Error(CallLoc
, "fast-math-flags specified for call without "
6524 "floating-point scalar or vector return type");
6526 // If RetType is a non-function pointer type, then this is the short syntax
6527 // for the call, which means that RetType is just the return type. Infer the
6528 // rest of the function argument types from the arguments that are present.
6529 FunctionType
*Ty
= dyn_cast
<FunctionType
>(RetType
);
6531 // Pull out the types of all of the arguments...
6532 std::vector
<Type
*> ParamTypes
;
6533 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
6534 ParamTypes
.push_back(ArgList
[i
].V
->getType());
6536 if (!FunctionType::isValidReturnType(RetType
))
6537 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
6539 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
6544 // Look up the callee.
6546 if (ConvertValIDToValue(PointerType::get(Ty
, CallAddrSpace
), CalleeID
, Callee
,
6547 &PFS
, /*IsCall=*/true))
6550 // Set up the Attribute for the function.
6551 SmallVector
<AttributeSet
, 8> Attrs
;
6553 SmallVector
<Value
*, 8> Args
;
6555 // Loop through FunctionType's arguments and ensure they are specified
6556 // correctly. Also, gather any parameter attributes.
6557 FunctionType::param_iterator I
= Ty
->param_begin();
6558 FunctionType::param_iterator E
= Ty
->param_end();
6559 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
6560 Type
*ExpectedTy
= nullptr;
6563 } else if (!Ty
->isVarArg()) {
6564 return Error(ArgList
[i
].Loc
, "too many arguments specified");
6567 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
6568 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
6569 getTypeString(ExpectedTy
) + "'");
6570 Args
.push_back(ArgList
[i
].V
);
6571 Attrs
.push_back(ArgList
[i
].Attrs
);
6575 return Error(CallLoc
, "not enough parameters specified for call");
6577 if (FnAttrs
.hasAlignmentAttr())
6578 return Error(CallLoc
, "call instructions may not have an alignment");
6580 // Finish off the Attribute and check them
6582 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
6583 AttributeSet::get(Context
, RetAttrs
), Attrs
);
6585 CallInst
*CI
= CallInst::Create(Ty
, Callee
, Args
, BundleList
);
6586 CI
->setTailCallKind(TCK
);
6587 CI
->setCallingConv(CC
);
6589 CI
->setFastMathFlags(FMF
);
6590 CI
->setAttributes(PAL
);
6591 ForwardRefAttrGroups
[CI
] = FwdRefAttrGrps
;
6596 //===----------------------------------------------------------------------===//
6597 // Memory Instructions.
6598 //===----------------------------------------------------------------------===//
6601 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6602 /// (',' 'align' i32)? (',', 'addrspace(n))?
6603 int LLParser::ParseAlloc(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6604 Value
*Size
= nullptr;
6605 LocTy SizeLoc
, TyLoc
, ASLoc
;
6606 unsigned Alignment
= 0;
6607 unsigned AddrSpace
= 0;
6610 bool IsInAlloca
= EatIfPresent(lltok::kw_inalloca
);
6611 bool IsSwiftError
= EatIfPresent(lltok::kw_swifterror
);
6613 if (ParseType(Ty
, TyLoc
)) return true;
6615 if (Ty
->isFunctionTy() || !PointerType::isValidElementType(Ty
))
6616 return Error(TyLoc
, "invalid type for alloca");
6618 bool AteExtraComma
= false;
6619 if (EatIfPresent(lltok::comma
)) {
6620 if (Lex
.getKind() == lltok::kw_align
) {
6621 if (ParseOptionalAlignment(Alignment
))
6623 if (ParseOptionalCommaAddrSpace(AddrSpace
, ASLoc
, AteExtraComma
))
6625 } else if (Lex
.getKind() == lltok::kw_addrspace
) {
6626 ASLoc
= Lex
.getLoc();
6627 if (ParseOptionalAddrSpace(AddrSpace
))
6629 } else if (Lex
.getKind() == lltok::MetadataVar
) {
6630 AteExtraComma
= true;
6632 if (ParseTypeAndValue(Size
, SizeLoc
, PFS
))
6634 if (EatIfPresent(lltok::comma
)) {
6635 if (Lex
.getKind() == lltok::kw_align
) {
6636 if (ParseOptionalAlignment(Alignment
))
6638 if (ParseOptionalCommaAddrSpace(AddrSpace
, ASLoc
, AteExtraComma
))
6640 } else if (Lex
.getKind() == lltok::kw_addrspace
) {
6641 ASLoc
= Lex
.getLoc();
6642 if (ParseOptionalAddrSpace(AddrSpace
))
6644 } else if (Lex
.getKind() == lltok::MetadataVar
) {
6645 AteExtraComma
= true;
6651 if (Size
&& !Size
->getType()->isIntegerTy())
6652 return Error(SizeLoc
, "element count must have integer type");
6654 AllocaInst
*AI
= new AllocaInst(Ty
, AddrSpace
, Size
, Alignment
);
6655 AI
->setUsedWithInAlloca(IsInAlloca
);
6656 AI
->setSwiftError(IsSwiftError
);
6658 return AteExtraComma
? InstExtraComma
: InstNormal
;
6662 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6663 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6664 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6665 int LLParser::ParseLoad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6666 Value
*Val
; LocTy Loc
;
6667 unsigned Alignment
= 0;
6668 bool AteExtraComma
= false;
6669 bool isAtomic
= false;
6670 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
6671 SyncScope::ID SSID
= SyncScope::System
;
6673 if (Lex
.getKind() == lltok::kw_atomic
) {
6678 bool isVolatile
= false;
6679 if (Lex
.getKind() == lltok::kw_volatile
) {
6685 LocTy ExplicitTypeLoc
= Lex
.getLoc();
6686 if (ParseType(Ty
) ||
6687 ParseToken(lltok::comma
, "expected comma after load's type") ||
6688 ParseTypeAndValue(Val
, Loc
, PFS
) ||
6689 ParseScopeAndOrdering(isAtomic
, SSID
, Ordering
) ||
6690 ParseOptionalCommaAlign(Alignment
, AteExtraComma
))
6693 if (!Val
->getType()->isPointerTy() || !Ty
->isFirstClassType())
6694 return Error(Loc
, "load operand must be a pointer to a first class type");
6695 if (isAtomic
&& !Alignment
)
6696 return Error(Loc
, "atomic load must have explicit non-zero alignment");
6697 if (Ordering
== AtomicOrdering::Release
||
6698 Ordering
== AtomicOrdering::AcquireRelease
)
6699 return Error(Loc
, "atomic load cannot use Release ordering");
6701 if (Ty
!= cast
<PointerType
>(Val
->getType())->getElementType())
6702 return Error(ExplicitTypeLoc
,
6703 "explicit pointee type doesn't match operand's pointee type");
6705 Inst
= new LoadInst(Ty
, Val
, "", isVolatile
, Alignment
, Ordering
, SSID
);
6706 return AteExtraComma
? InstExtraComma
: InstNormal
;
6711 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6712 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6713 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6714 int LLParser::ParseStore(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6715 Value
*Val
, *Ptr
; LocTy Loc
, PtrLoc
;
6716 unsigned Alignment
= 0;
6717 bool AteExtraComma
= false;
6718 bool isAtomic
= false;
6719 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
6720 SyncScope::ID SSID
= SyncScope::System
;
6722 if (Lex
.getKind() == lltok::kw_atomic
) {
6727 bool isVolatile
= false;
6728 if (Lex
.getKind() == lltok::kw_volatile
) {
6733 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
6734 ParseToken(lltok::comma
, "expected ',' after store operand") ||
6735 ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
6736 ParseScopeAndOrdering(isAtomic
, SSID
, Ordering
) ||
6737 ParseOptionalCommaAlign(Alignment
, AteExtraComma
))
6740 if (!Ptr
->getType()->isPointerTy())
6741 return Error(PtrLoc
, "store operand must be a pointer");
6742 if (!Val
->getType()->isFirstClassType())
6743 return Error(Loc
, "store operand must be a first class value");
6744 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Val
->getType())
6745 return Error(Loc
, "stored value and pointer type do not match");
6746 if (isAtomic
&& !Alignment
)
6747 return Error(Loc
, "atomic store must have explicit non-zero alignment");
6748 if (Ordering
== AtomicOrdering::Acquire
||
6749 Ordering
== AtomicOrdering::AcquireRelease
)
6750 return Error(Loc
, "atomic store cannot use Acquire ordering");
6752 Inst
= new StoreInst(Val
, Ptr
, isVolatile
, Alignment
, Ordering
, SSID
);
6753 return AteExtraComma
? InstExtraComma
: InstNormal
;
6757 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6758 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6759 int LLParser::ParseCmpXchg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6760 Value
*Ptr
, *Cmp
, *New
; LocTy PtrLoc
, CmpLoc
, NewLoc
;
6761 bool AteExtraComma
= false;
6762 AtomicOrdering SuccessOrdering
= AtomicOrdering::NotAtomic
;
6763 AtomicOrdering FailureOrdering
= AtomicOrdering::NotAtomic
;
6764 SyncScope::ID SSID
= SyncScope::System
;
6765 bool isVolatile
= false;
6766 bool isWeak
= false;
6768 if (EatIfPresent(lltok::kw_weak
))
6771 if (EatIfPresent(lltok::kw_volatile
))
6774 if (ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
6775 ParseToken(lltok::comma
, "expected ',' after cmpxchg address") ||
6776 ParseTypeAndValue(Cmp
, CmpLoc
, PFS
) ||
6777 ParseToken(lltok::comma
, "expected ',' after cmpxchg cmp operand") ||
6778 ParseTypeAndValue(New
, NewLoc
, PFS
) ||
6779 ParseScopeAndOrdering(true /*Always atomic*/, SSID
, SuccessOrdering
) ||
6780 ParseOrdering(FailureOrdering
))
6783 if (SuccessOrdering
== AtomicOrdering::Unordered
||
6784 FailureOrdering
== AtomicOrdering::Unordered
)
6785 return TokError("cmpxchg cannot be unordered");
6786 if (isStrongerThan(FailureOrdering
, SuccessOrdering
))
6787 return TokError("cmpxchg failure argument shall be no stronger than the "
6788 "success argument");
6789 if (FailureOrdering
== AtomicOrdering::Release
||
6790 FailureOrdering
== AtomicOrdering::AcquireRelease
)
6792 "cmpxchg failure ordering cannot include release semantics");
6793 if (!Ptr
->getType()->isPointerTy())
6794 return Error(PtrLoc
, "cmpxchg operand must be a pointer");
6795 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Cmp
->getType())
6796 return Error(CmpLoc
, "compare value and pointer type do not match");
6797 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != New
->getType())
6798 return Error(NewLoc
, "new value and pointer type do not match");
6799 if (!New
->getType()->isFirstClassType())
6800 return Error(NewLoc
, "cmpxchg operand must be a first class value");
6801 AtomicCmpXchgInst
*CXI
= new AtomicCmpXchgInst(
6802 Ptr
, Cmp
, New
, SuccessOrdering
, FailureOrdering
, SSID
);
6803 CXI
->setVolatile(isVolatile
);
6804 CXI
->setWeak(isWeak
);
6806 return AteExtraComma
? InstExtraComma
: InstNormal
;
6810 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6811 /// 'singlethread'? AtomicOrdering
6812 int LLParser::ParseAtomicRMW(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6813 Value
*Ptr
, *Val
; LocTy PtrLoc
, ValLoc
;
6814 bool AteExtraComma
= false;
6815 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
6816 SyncScope::ID SSID
= SyncScope::System
;
6817 bool isVolatile
= false;
6819 AtomicRMWInst::BinOp Operation
;
6821 if (EatIfPresent(lltok::kw_volatile
))
6824 switch (Lex
.getKind()) {
6825 default: return TokError("expected binary operation in atomicrmw");
6826 case lltok::kw_xchg
: Operation
= AtomicRMWInst::Xchg
; break;
6827 case lltok::kw_add
: Operation
= AtomicRMWInst::Add
; break;
6828 case lltok::kw_sub
: Operation
= AtomicRMWInst::Sub
; break;
6829 case lltok::kw_and
: Operation
= AtomicRMWInst::And
; break;
6830 case lltok::kw_nand
: Operation
= AtomicRMWInst::Nand
; break;
6831 case lltok::kw_or
: Operation
= AtomicRMWInst::Or
; break;
6832 case lltok::kw_xor
: Operation
= AtomicRMWInst::Xor
; break;
6833 case lltok::kw_max
: Operation
= AtomicRMWInst::Max
; break;
6834 case lltok::kw_min
: Operation
= AtomicRMWInst::Min
; break;
6835 case lltok::kw_umax
: Operation
= AtomicRMWInst::UMax
; break;
6836 case lltok::kw_umin
: Operation
= AtomicRMWInst::UMin
; break;
6837 case lltok::kw_fadd
:
6838 Operation
= AtomicRMWInst::FAdd
;
6841 case lltok::kw_fsub
:
6842 Operation
= AtomicRMWInst::FSub
;
6846 Lex
.Lex(); // Eat the operation.
6848 if (ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
6849 ParseToken(lltok::comma
, "expected ',' after atomicrmw address") ||
6850 ParseTypeAndValue(Val
, ValLoc
, PFS
) ||
6851 ParseScopeAndOrdering(true /*Always atomic*/, SSID
, Ordering
))
6854 if (Ordering
== AtomicOrdering::Unordered
)
6855 return TokError("atomicrmw cannot be unordered");
6856 if (!Ptr
->getType()->isPointerTy())
6857 return Error(PtrLoc
, "atomicrmw operand must be a pointer");
6858 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Val
->getType())
6859 return Error(ValLoc
, "atomicrmw value and pointer type do not match");
6861 if (Operation
== AtomicRMWInst::Xchg
) {
6862 if (!Val
->getType()->isIntegerTy() &&
6863 !Val
->getType()->isFloatingPointTy()) {
6864 return Error(ValLoc
, "atomicrmw " +
6865 AtomicRMWInst::getOperationName(Operation
) +
6866 " operand must be an integer or floating point type");
6869 if (!Val
->getType()->isFloatingPointTy()) {
6870 return Error(ValLoc
, "atomicrmw " +
6871 AtomicRMWInst::getOperationName(Operation
) +
6872 " operand must be a floating point type");
6875 if (!Val
->getType()->isIntegerTy()) {
6876 return Error(ValLoc
, "atomicrmw " +
6877 AtomicRMWInst::getOperationName(Operation
) +
6878 " operand must be an integer");
6882 unsigned Size
= Val
->getType()->getPrimitiveSizeInBits();
6883 if (Size
< 8 || (Size
& (Size
- 1)))
6884 return Error(ValLoc
, "atomicrmw operand must be power-of-two byte-sized"
6887 AtomicRMWInst
*RMWI
=
6888 new AtomicRMWInst(Operation
, Ptr
, Val
, Ordering
, SSID
);
6889 RMWI
->setVolatile(isVolatile
);
6891 return AteExtraComma
? InstExtraComma
: InstNormal
;
6895 /// ::= 'fence' 'singlethread'? AtomicOrdering
6896 int LLParser::ParseFence(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6897 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
6898 SyncScope::ID SSID
= SyncScope::System
;
6899 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID
, Ordering
))
6902 if (Ordering
== AtomicOrdering::Unordered
)
6903 return TokError("fence cannot be unordered");
6904 if (Ordering
== AtomicOrdering::Monotonic
)
6905 return TokError("fence cannot be monotonic");
6907 Inst
= new FenceInst(Context
, Ordering
, SSID
);
6911 /// ParseGetElementPtr
6912 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
6913 int LLParser::ParseGetElementPtr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6914 Value
*Ptr
= nullptr;
6915 Value
*Val
= nullptr;
6918 bool InBounds
= EatIfPresent(lltok::kw_inbounds
);
6921 LocTy ExplicitTypeLoc
= Lex
.getLoc();
6922 if (ParseType(Ty
) ||
6923 ParseToken(lltok::comma
, "expected comma after getelementptr's type") ||
6924 ParseTypeAndValue(Ptr
, Loc
, PFS
))
6927 Type
*BaseType
= Ptr
->getType();
6928 PointerType
*BasePointerType
= dyn_cast
<PointerType
>(BaseType
->getScalarType());
6929 if (!BasePointerType
)
6930 return Error(Loc
, "base of getelementptr must be a pointer");
6932 if (Ty
!= BasePointerType
->getElementType())
6933 return Error(ExplicitTypeLoc
,
6934 "explicit pointee type doesn't match operand's pointee type");
6936 SmallVector
<Value
*, 16> Indices
;
6937 bool AteExtraComma
= false;
6938 // GEP returns a vector of pointers if at least one of parameters is a vector.
6939 // All vector parameters should have the same vector width.
6940 unsigned GEPWidth
= BaseType
->isVectorTy() ?
6941 BaseType
->getVectorNumElements() : 0;
6943 while (EatIfPresent(lltok::comma
)) {
6944 if (Lex
.getKind() == lltok::MetadataVar
) {
6945 AteExtraComma
= true;
6948 if (ParseTypeAndValue(Val
, EltLoc
, PFS
)) return true;
6949 if (!Val
->getType()->isIntOrIntVectorTy())
6950 return Error(EltLoc
, "getelementptr index must be an integer");
6952 if (Val
->getType()->isVectorTy()) {
6953 unsigned ValNumEl
= Val
->getType()->getVectorNumElements();
6954 if (GEPWidth
&& GEPWidth
!= ValNumEl
)
6955 return Error(EltLoc
,
6956 "getelementptr vector index has a wrong number of elements");
6957 GEPWidth
= ValNumEl
;
6959 Indices
.push_back(Val
);
6962 SmallPtrSet
<Type
*, 4> Visited
;
6963 if (!Indices
.empty() && !Ty
->isSized(&Visited
))
6964 return Error(Loc
, "base element of getelementptr must be sized");
6966 if (!GetElementPtrInst::getIndexedType(Ty
, Indices
))
6967 return Error(Loc
, "invalid getelementptr indices");
6968 Inst
= GetElementPtrInst::Create(Ty
, Ptr
, Indices
);
6970 cast
<GetElementPtrInst
>(Inst
)->setIsInBounds(true);
6971 return AteExtraComma
? InstExtraComma
: InstNormal
;
6974 /// ParseExtractValue
6975 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
6976 int LLParser::ParseExtractValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6977 Value
*Val
; LocTy Loc
;
6978 SmallVector
<unsigned, 4> Indices
;
6980 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
6981 ParseIndexList(Indices
, AteExtraComma
))
6984 if (!Val
->getType()->isAggregateType())
6985 return Error(Loc
, "extractvalue operand must be aggregate type");
6987 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
))
6988 return Error(Loc
, "invalid indices for extractvalue");
6989 Inst
= ExtractValueInst::Create(Val
, Indices
);
6990 return AteExtraComma
? InstExtraComma
: InstNormal
;
6993 /// ParseInsertValue
6994 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
6995 int LLParser::ParseInsertValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6996 Value
*Val0
, *Val1
; LocTy Loc0
, Loc1
;
6997 SmallVector
<unsigned, 4> Indices
;
6999 if (ParseTypeAndValue(Val0
, Loc0
, PFS
) ||
7000 ParseToken(lltok::comma
, "expected comma after insertvalue operand") ||
7001 ParseTypeAndValue(Val1
, Loc1
, PFS
) ||
7002 ParseIndexList(Indices
, AteExtraComma
))
7005 if (!Val0
->getType()->isAggregateType())
7006 return Error(Loc0
, "insertvalue operand must be aggregate type");
7008 Type
*IndexedType
= ExtractValueInst::getIndexedType(Val0
->getType(), Indices
);
7010 return Error(Loc0
, "invalid indices for insertvalue");
7011 if (IndexedType
!= Val1
->getType())
7012 return Error(Loc1
, "insertvalue operand and field disagree in type: '" +
7013 getTypeString(Val1
->getType()) + "' instead of '" +
7014 getTypeString(IndexedType
) + "'");
7015 Inst
= InsertValueInst::Create(Val0
, Val1
, Indices
);
7016 return AteExtraComma
? InstExtraComma
: InstNormal
;
7019 //===----------------------------------------------------------------------===//
7020 // Embedded metadata.
7021 //===----------------------------------------------------------------------===//
7023 /// ParseMDNodeVector
7024 /// ::= { Element (',' Element)* }
7026 /// ::= 'null' | TypeAndValue
7027 bool LLParser::ParseMDNodeVector(SmallVectorImpl
<Metadata
*> &Elts
) {
7028 if (ParseToken(lltok::lbrace
, "expected '{' here"))
7031 // Check for an empty list.
7032 if (EatIfPresent(lltok::rbrace
))
7036 // Null is a special case since it is typeless.
7037 if (EatIfPresent(lltok::kw_null
)) {
7038 Elts
.push_back(nullptr);
7043 if (ParseMetadata(MD
, nullptr))
7046 } while (EatIfPresent(lltok::comma
));
7048 return ParseToken(lltok::rbrace
, "expected end of metadata node");
7051 //===----------------------------------------------------------------------===//
7052 // Use-list order directives.
7053 //===----------------------------------------------------------------------===//
7054 bool LLParser::sortUseListOrder(Value
*V
, ArrayRef
<unsigned> Indexes
,
7057 return Error(Loc
, "value has no uses");
7059 unsigned NumUses
= 0;
7060 SmallDenseMap
<const Use
*, unsigned, 16> Order
;
7061 for (const Use
&U
: V
->uses()) {
7062 if (++NumUses
> Indexes
.size())
7064 Order
[&U
] = Indexes
[NumUses
- 1];
7067 return Error(Loc
, "value only has one use");
7068 if (Order
.size() != Indexes
.size() || NumUses
> Indexes
.size())
7070 "wrong number of indexes, expected " + Twine(V
->getNumUses()));
7072 V
->sortUseList([&](const Use
&L
, const Use
&R
) {
7073 return Order
.lookup(&L
) < Order
.lookup(&R
);
7078 /// ParseUseListOrderIndexes
7079 /// ::= '{' uint32 (',' uint32)+ '}'
7080 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl
<unsigned> &Indexes
) {
7081 SMLoc Loc
= Lex
.getLoc();
7082 if (ParseToken(lltok::lbrace
, "expected '{' here"))
7084 if (Lex
.getKind() == lltok::rbrace
)
7085 return Lex
.Error("expected non-empty list of uselistorder indexes");
7087 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7088 // indexes should be distinct numbers in the range [0, size-1], and should
7090 unsigned Offset
= 0;
7092 bool IsOrdered
= true;
7093 assert(Indexes
.empty() && "Expected empty order vector");
7096 if (ParseUInt32(Index
))
7099 // Update consistency checks.
7100 Offset
+= Index
- Indexes
.size();
7101 Max
= std::max(Max
, Index
);
7102 IsOrdered
&= Index
== Indexes
.size();
7104 Indexes
.push_back(Index
);
7105 } while (EatIfPresent(lltok::comma
));
7107 if (ParseToken(lltok::rbrace
, "expected '}' here"))
7110 if (Indexes
.size() < 2)
7111 return Error(Loc
, "expected >= 2 uselistorder indexes");
7112 if (Offset
!= 0 || Max
>= Indexes
.size())
7113 return Error(Loc
, "expected distinct uselistorder indexes in range [0, size)");
7115 return Error(Loc
, "expected uselistorder indexes to change the order");
7120 /// ParseUseListOrder
7121 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7122 bool LLParser::ParseUseListOrder(PerFunctionState
*PFS
) {
7123 SMLoc Loc
= Lex
.getLoc();
7124 if (ParseToken(lltok::kw_uselistorder
, "expected uselistorder directive"))
7128 SmallVector
<unsigned, 16> Indexes
;
7129 if (ParseTypeAndValue(V
, PFS
) ||
7130 ParseToken(lltok::comma
, "expected comma in uselistorder directive") ||
7131 ParseUseListOrderIndexes(Indexes
))
7134 return sortUseListOrder(V
, Indexes
, Loc
);
7137 /// ParseUseListOrderBB
7138 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7139 bool LLParser::ParseUseListOrderBB() {
7140 assert(Lex
.getKind() == lltok::kw_uselistorder_bb
);
7141 SMLoc Loc
= Lex
.getLoc();
7145 SmallVector
<unsigned, 16> Indexes
;
7146 if (ParseValID(Fn
) ||
7147 ParseToken(lltok::comma
, "expected comma in uselistorder_bb directive") ||
7148 ParseValID(Label
) ||
7149 ParseToken(lltok::comma
, "expected comma in uselistorder_bb directive") ||
7150 ParseUseListOrderIndexes(Indexes
))
7153 // Check the function.
7155 if (Fn
.Kind
== ValID::t_GlobalName
)
7156 GV
= M
->getNamedValue(Fn
.StrVal
);
7157 else if (Fn
.Kind
== ValID::t_GlobalID
)
7158 GV
= Fn
.UIntVal
< NumberedVals
.size() ? NumberedVals
[Fn
.UIntVal
] : nullptr;
7160 return Error(Fn
.Loc
, "expected function name in uselistorder_bb");
7162 return Error(Fn
.Loc
, "invalid function forward reference in uselistorder_bb");
7163 auto *F
= dyn_cast
<Function
>(GV
);
7165 return Error(Fn
.Loc
, "expected function name in uselistorder_bb");
7166 if (F
->isDeclaration())
7167 return Error(Fn
.Loc
, "invalid declaration in uselistorder_bb");
7169 // Check the basic block.
7170 if (Label
.Kind
== ValID::t_LocalID
)
7171 return Error(Label
.Loc
, "invalid numeric label in uselistorder_bb");
7172 if (Label
.Kind
!= ValID::t_LocalName
)
7173 return Error(Label
.Loc
, "expected basic block name in uselistorder_bb");
7174 Value
*V
= F
->getValueSymbolTable()->lookup(Label
.StrVal
);
7176 return Error(Label
.Loc
, "invalid basic block in uselistorder_bb");
7177 if (!isa
<BasicBlock
>(V
))
7178 return Error(Label
.Loc
, "expected basic block in uselistorder_bb");
7180 return sortUseListOrder(V
, Indexes
, Loc
);
7184 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7185 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7186 bool LLParser::ParseModuleEntry(unsigned ID
) {
7187 assert(Lex
.getKind() == lltok::kw_module
);
7191 if (ParseToken(lltok::colon
, "expected ':' here") ||
7192 ParseToken(lltok::lparen
, "expected '(' here") ||
7193 ParseToken(lltok::kw_path
, "expected 'path' here") ||
7194 ParseToken(lltok::colon
, "expected ':' here") ||
7195 ParseStringConstant(Path
) ||
7196 ParseToken(lltok::comma
, "expected ',' here") ||
7197 ParseToken(lltok::kw_hash
, "expected 'hash' here") ||
7198 ParseToken(lltok::colon
, "expected ':' here") ||
7199 ParseToken(lltok::lparen
, "expected '(' here"))
7203 if (ParseUInt32(Hash
[0]) || ParseToken(lltok::comma
, "expected ',' here") ||
7204 ParseUInt32(Hash
[1]) || ParseToken(lltok::comma
, "expected ',' here") ||
7205 ParseUInt32(Hash
[2]) || ParseToken(lltok::comma
, "expected ',' here") ||
7206 ParseUInt32(Hash
[3]) || ParseToken(lltok::comma
, "expected ',' here") ||
7207 ParseUInt32(Hash
[4]))
7210 if (ParseToken(lltok::rparen
, "expected ')' here") ||
7211 ParseToken(lltok::rparen
, "expected ')' here"))
7214 auto ModuleEntry
= Index
->addModule(Path
, ID
, Hash
);
7215 ModuleIdMap
[ID
] = ModuleEntry
->first();
7221 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7222 bool LLParser::ParseTypeIdEntry(unsigned ID
) {
7223 assert(Lex
.getKind() == lltok::kw_typeid
);
7227 if (ParseToken(lltok::colon
, "expected ':' here") ||
7228 ParseToken(lltok::lparen
, "expected '(' here") ||
7229 ParseToken(lltok::kw_name
, "expected 'name' here") ||
7230 ParseToken(lltok::colon
, "expected ':' here") ||
7231 ParseStringConstant(Name
))
7234 TypeIdSummary
&TIS
= Index
->getOrInsertTypeIdSummary(Name
);
7235 if (ParseToken(lltok::comma
, "expected ',' here") ||
7236 ParseTypeIdSummary(TIS
) || ParseToken(lltok::rparen
, "expected ')' here"))
7239 // Check if this ID was forward referenced, and if so, update the
7240 // corresponding GUIDs.
7241 auto FwdRefTIDs
= ForwardRefTypeIds
.find(ID
);
7242 if (FwdRefTIDs
!= ForwardRefTypeIds
.end()) {
7243 for (auto TIDRef
: FwdRefTIDs
->second
) {
7244 assert(!*TIDRef
.first
&&
7245 "Forward referenced type id GUID expected to be 0");
7246 *TIDRef
.first
= GlobalValue::getGUID(Name
);
7248 ForwardRefTypeIds
.erase(FwdRefTIDs
);
7255 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7256 bool LLParser::ParseTypeIdSummary(TypeIdSummary
&TIS
) {
7257 if (ParseToken(lltok::kw_summary
, "expected 'summary' here") ||
7258 ParseToken(lltok::colon
, "expected ':' here") ||
7259 ParseToken(lltok::lparen
, "expected '(' here") ||
7260 ParseTypeTestResolution(TIS
.TTRes
))
7263 if (EatIfPresent(lltok::comma
)) {
7264 // Expect optional wpdResolutions field
7265 if (ParseOptionalWpdResolutions(TIS
.WPDRes
))
7269 if (ParseToken(lltok::rparen
, "expected ')' here"))
7275 /// TypeTestResolution
7276 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
7277 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7278 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7279 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7280 /// [',' 'inlinesBits' ':' UInt64]? ')'
7281 bool LLParser::ParseTypeTestResolution(TypeTestResolution
&TTRes
) {
7282 if (ParseToken(lltok::kw_typeTestRes
, "expected 'typeTestRes' here") ||
7283 ParseToken(lltok::colon
, "expected ':' here") ||
7284 ParseToken(lltok::lparen
, "expected '(' here") ||
7285 ParseToken(lltok::kw_kind
, "expected 'kind' here") ||
7286 ParseToken(lltok::colon
, "expected ':' here"))
7289 switch (Lex
.getKind()) {
7290 case lltok::kw_unsat
:
7291 TTRes
.TheKind
= TypeTestResolution::Unsat
;
7293 case lltok::kw_byteArray
:
7294 TTRes
.TheKind
= TypeTestResolution::ByteArray
;
7296 case lltok::kw_inline
:
7297 TTRes
.TheKind
= TypeTestResolution::Inline
;
7299 case lltok::kw_single
:
7300 TTRes
.TheKind
= TypeTestResolution::Single
;
7302 case lltok::kw_allOnes
:
7303 TTRes
.TheKind
= TypeTestResolution::AllOnes
;
7306 return Error(Lex
.getLoc(), "unexpected TypeTestResolution kind");
7310 if (ParseToken(lltok::comma
, "expected ',' here") ||
7311 ParseToken(lltok::kw_sizeM1BitWidth
, "expected 'sizeM1BitWidth' here") ||
7312 ParseToken(lltok::colon
, "expected ':' here") ||
7313 ParseUInt32(TTRes
.SizeM1BitWidth
))
7316 // Parse optional fields
7317 while (EatIfPresent(lltok::comma
)) {
7318 switch (Lex
.getKind()) {
7319 case lltok::kw_alignLog2
:
7321 if (ParseToken(lltok::colon
, "expected ':'") ||
7322 ParseUInt64(TTRes
.AlignLog2
))
7325 case lltok::kw_sizeM1
:
7327 if (ParseToken(lltok::colon
, "expected ':'") || ParseUInt64(TTRes
.SizeM1
))
7330 case lltok::kw_bitMask
: {
7333 if (ParseToken(lltok::colon
, "expected ':'") || ParseUInt32(Val
))
7335 assert(Val
<= 0xff);
7336 TTRes
.BitMask
= (uint8_t)Val
;
7339 case lltok::kw_inlineBits
:
7341 if (ParseToken(lltok::colon
, "expected ':'") ||
7342 ParseUInt64(TTRes
.InlineBits
))
7346 return Error(Lex
.getLoc(), "expected optional TypeTestResolution field");
7350 if (ParseToken(lltok::rparen
, "expected ')' here"))
7356 /// OptionalWpdResolutions
7357 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7358 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7359 bool LLParser::ParseOptionalWpdResolutions(
7360 std::map
<uint64_t, WholeProgramDevirtResolution
> &WPDResMap
) {
7361 if (ParseToken(lltok::kw_wpdResolutions
, "expected 'wpdResolutions' here") ||
7362 ParseToken(lltok::colon
, "expected ':' here") ||
7363 ParseToken(lltok::lparen
, "expected '(' here"))
7368 WholeProgramDevirtResolution WPDRes
;
7369 if (ParseToken(lltok::lparen
, "expected '(' here") ||
7370 ParseToken(lltok::kw_offset
, "expected 'offset' here") ||
7371 ParseToken(lltok::colon
, "expected ':' here") || ParseUInt64(Offset
) ||
7372 ParseToken(lltok::comma
, "expected ',' here") || ParseWpdRes(WPDRes
) ||
7373 ParseToken(lltok::rparen
, "expected ')' here"))
7375 WPDResMap
[Offset
] = WPDRes
;
7376 } while (EatIfPresent(lltok::comma
));
7378 if (ParseToken(lltok::rparen
, "expected ')' here"))
7385 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7386 /// [',' OptionalResByArg]? ')'
7387 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7388 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
7389 /// [',' OptionalResByArg]? ')'
7390 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7391 /// [',' OptionalResByArg]? ')'
7392 bool LLParser::ParseWpdRes(WholeProgramDevirtResolution
&WPDRes
) {
7393 if (ParseToken(lltok::kw_wpdRes
, "expected 'wpdRes' here") ||
7394 ParseToken(lltok::colon
, "expected ':' here") ||
7395 ParseToken(lltok::lparen
, "expected '(' here") ||
7396 ParseToken(lltok::kw_kind
, "expected 'kind' here") ||
7397 ParseToken(lltok::colon
, "expected ':' here"))
7400 switch (Lex
.getKind()) {
7401 case lltok::kw_indir
:
7402 WPDRes
.TheKind
= WholeProgramDevirtResolution::Indir
;
7404 case lltok::kw_singleImpl
:
7405 WPDRes
.TheKind
= WholeProgramDevirtResolution::SingleImpl
;
7407 case lltok::kw_branchFunnel
:
7408 WPDRes
.TheKind
= WholeProgramDevirtResolution::BranchFunnel
;
7411 return Error(Lex
.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7415 // Parse optional fields
7416 while (EatIfPresent(lltok::comma
)) {
7417 switch (Lex
.getKind()) {
7418 case lltok::kw_singleImplName
:
7420 if (ParseToken(lltok::colon
, "expected ':' here") ||
7421 ParseStringConstant(WPDRes
.SingleImplName
))
7424 case lltok::kw_resByArg
:
7425 if (ParseOptionalResByArg(WPDRes
.ResByArg
))
7429 return Error(Lex
.getLoc(),
7430 "expected optional WholeProgramDevirtResolution field");
7434 if (ParseToken(lltok::rparen
, "expected ')' here"))
7440 /// OptionalResByArg
7441 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7442 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7443 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7444 /// 'virtualConstProp' )
7445 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7446 /// [',' 'bit' ':' UInt32]? ')'
7447 bool LLParser::ParseOptionalResByArg(
7448 std::map
<std::vector
<uint64_t>, WholeProgramDevirtResolution::ByArg
>
7450 if (ParseToken(lltok::kw_resByArg
, "expected 'resByArg' here") ||
7451 ParseToken(lltok::colon
, "expected ':' here") ||
7452 ParseToken(lltok::lparen
, "expected '(' here"))
7456 std::vector
<uint64_t> Args
;
7457 if (ParseArgs(Args
) || ParseToken(lltok::comma
, "expected ',' here") ||
7458 ParseToken(lltok::kw_byArg
, "expected 'byArg here") ||
7459 ParseToken(lltok::colon
, "expected ':' here") ||
7460 ParseToken(lltok::lparen
, "expected '(' here") ||
7461 ParseToken(lltok::kw_kind
, "expected 'kind' here") ||
7462 ParseToken(lltok::colon
, "expected ':' here"))
7465 WholeProgramDevirtResolution::ByArg ByArg
;
7466 switch (Lex
.getKind()) {
7467 case lltok::kw_indir
:
7468 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::Indir
;
7470 case lltok::kw_uniformRetVal
:
7471 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::UniformRetVal
;
7473 case lltok::kw_uniqueRetVal
:
7474 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::UniqueRetVal
;
7476 case lltok::kw_virtualConstProp
:
7477 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::VirtualConstProp
;
7480 return Error(Lex
.getLoc(),
7481 "unexpected WholeProgramDevirtResolution::ByArg kind");
7485 // Parse optional fields
7486 while (EatIfPresent(lltok::comma
)) {
7487 switch (Lex
.getKind()) {
7488 case lltok::kw_info
:
7490 if (ParseToken(lltok::colon
, "expected ':' here") ||
7491 ParseUInt64(ByArg
.Info
))
7494 case lltok::kw_byte
:
7496 if (ParseToken(lltok::colon
, "expected ':' here") ||
7497 ParseUInt32(ByArg
.Byte
))
7502 if (ParseToken(lltok::colon
, "expected ':' here") ||
7503 ParseUInt32(ByArg
.Bit
))
7507 return Error(Lex
.getLoc(),
7508 "expected optional whole program devirt field");
7512 if (ParseToken(lltok::rparen
, "expected ')' here"))
7515 ResByArg
[Args
] = ByArg
;
7516 } while (EatIfPresent(lltok::comma
));
7518 if (ParseToken(lltok::rparen
, "expected ')' here"))
7524 /// OptionalResByArg
7525 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7526 bool LLParser::ParseArgs(std::vector
<uint64_t> &Args
) {
7527 if (ParseToken(lltok::kw_args
, "expected 'args' here") ||
7528 ParseToken(lltok::colon
, "expected ':' here") ||
7529 ParseToken(lltok::lparen
, "expected '(' here"))
7534 if (ParseUInt64(Val
))
7536 Args
.push_back(Val
);
7537 } while (EatIfPresent(lltok::comma
));
7539 if (ParseToken(lltok::rparen
, "expected ')' here"))
7545 static const auto FwdVIRef
= (GlobalValueSummaryMapTy::value_type
*)-8;
7547 static void resolveFwdRef(ValueInfo
*Fwd
, ValueInfo
&Resolved
) {
7548 bool ReadOnly
= Fwd
->isReadOnly();
7554 /// Stores the given Name/GUID and associated summary into the Index.
7555 /// Also updates any forward references to the associated entry ID.
7556 void LLParser::AddGlobalValueToIndex(
7557 std::string Name
, GlobalValue::GUID GUID
, GlobalValue::LinkageTypes Linkage
,
7558 unsigned ID
, std::unique_ptr
<GlobalValueSummary
> Summary
) {
7559 // First create the ValueInfo utilizing the Name or GUID.
7562 assert(Name
.empty());
7563 VI
= Index
->getOrInsertValueInfo(GUID
);
7565 assert(!Name
.empty());
7567 auto *GV
= M
->getNamedValue(Name
);
7569 VI
= Index
->getOrInsertValueInfo(GV
);
7572 (!GlobalValue::isLocalLinkage(Linkage
) || !SourceFileName
.empty()) &&
7573 "Need a source_filename to compute GUID for local");
7574 GUID
= GlobalValue::getGUID(
7575 GlobalValue::getGlobalIdentifier(Name
, Linkage
, SourceFileName
));
7576 VI
= Index
->getOrInsertValueInfo(GUID
, Index
->saveString(Name
));
7580 // Add the summary if one was provided.
7582 Index
->addGlobalValueSummary(VI
, std::move(Summary
));
7584 // Resolve forward references from calls/refs
7585 auto FwdRefVIs
= ForwardRefValueInfos
.find(ID
);
7586 if (FwdRefVIs
!= ForwardRefValueInfos
.end()) {
7587 for (auto VIRef
: FwdRefVIs
->second
) {
7588 assert(VIRef
.first
->getRef() == FwdVIRef
&&
7589 "Forward referenced ValueInfo expected to be empty");
7590 resolveFwdRef(VIRef
.first
, VI
);
7592 ForwardRefValueInfos
.erase(FwdRefVIs
);
7595 // Resolve forward references from aliases
7596 auto FwdRefAliasees
= ForwardRefAliasees
.find(ID
);
7597 if (FwdRefAliasees
!= ForwardRefAliasees
.end()) {
7598 for (auto AliaseeRef
: FwdRefAliasees
->second
) {
7599 assert(!AliaseeRef
.first
->hasAliasee() &&
7600 "Forward referencing alias already has aliasee");
7601 AliaseeRef
.first
->setAliasee(VI
.getSummaryList().front().get());
7603 ForwardRefAliasees
.erase(FwdRefAliasees
);
7606 // Save the associated ValueInfo for use in later references by ID.
7607 if (ID
== NumberedValueInfos
.size())
7608 NumberedValueInfos
.push_back(VI
);
7610 // Handle non-continuous numbers (to make test simplification easier).
7611 if (ID
> NumberedValueInfos
.size())
7612 NumberedValueInfos
.resize(ID
+ 1);
7613 NumberedValueInfos
[ID
] = VI
;
7618 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7619 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7620 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7621 bool LLParser::ParseGVEntry(unsigned ID
) {
7622 assert(Lex
.getKind() == lltok::kw_gv
);
7625 if (ParseToken(lltok::colon
, "expected ':' here") ||
7626 ParseToken(lltok::lparen
, "expected '(' here"))
7630 GlobalValue::GUID GUID
= 0;
7631 switch (Lex
.getKind()) {
7632 case lltok::kw_name
:
7634 if (ParseToken(lltok::colon
, "expected ':' here") ||
7635 ParseStringConstant(Name
))
7637 // Can't create GUID/ValueInfo until we have the linkage.
7639 case lltok::kw_guid
:
7641 if (ParseToken(lltok::colon
, "expected ':' here") || ParseUInt64(GUID
))
7645 return Error(Lex
.getLoc(), "expected name or guid tag");
7648 if (!EatIfPresent(lltok::comma
)) {
7649 // No summaries. Wrap up.
7650 if (ParseToken(lltok::rparen
, "expected ')' here"))
7652 // This was created for a call to an external or indirect target.
7653 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
7654 // created for indirect calls with VP. A Name with no GUID came from
7655 // an external definition. We pass ExternalLinkage since that is only
7656 // used when the GUID must be computed from Name, and in that case
7657 // the symbol must have external linkage.
7658 AddGlobalValueToIndex(Name
, GUID
, GlobalValue::ExternalLinkage
, ID
,
7663 // Have a list of summaries
7664 if (ParseToken(lltok::kw_summaries
, "expected 'summaries' here") ||
7665 ParseToken(lltok::colon
, "expected ':' here"))
7669 if (ParseToken(lltok::lparen
, "expected '(' here"))
7671 switch (Lex
.getKind()) {
7672 case lltok::kw_function
:
7673 if (ParseFunctionSummary(Name
, GUID
, ID
))
7676 case lltok::kw_variable
:
7677 if (ParseVariableSummary(Name
, GUID
, ID
))
7680 case lltok::kw_alias
:
7681 if (ParseAliasSummary(Name
, GUID
, ID
))
7685 return Error(Lex
.getLoc(), "expected summary type");
7687 if (ParseToken(lltok::rparen
, "expected ')' here"))
7689 } while (EatIfPresent(lltok::comma
));
7691 if (ParseToken(lltok::rparen
, "expected ')' here"))
7698 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7699 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
7700 /// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
7701 bool LLParser::ParseFunctionSummary(std::string Name
, GlobalValue::GUID GUID
,
7703 assert(Lex
.getKind() == lltok::kw_function
);
7706 StringRef ModulePath
;
7707 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
7708 /*Linkage=*/GlobalValue::ExternalLinkage
, /*NotEligibleToImport=*/false,
7709 /*Live=*/false, /*IsLocal=*/false);
7711 std::vector
<FunctionSummary::EdgeTy
> Calls
;
7712 FunctionSummary::TypeIdInfo TypeIdInfo
;
7713 std::vector
<ValueInfo
> Refs
;
7714 // Default is all-zeros (conservative values).
7715 FunctionSummary::FFlags FFlags
= {};
7716 if (ParseToken(lltok::colon
, "expected ':' here") ||
7717 ParseToken(lltok::lparen
, "expected '(' here") ||
7718 ParseModuleReference(ModulePath
) ||
7719 ParseToken(lltok::comma
, "expected ',' here") || ParseGVFlags(GVFlags
) ||
7720 ParseToken(lltok::comma
, "expected ',' here") ||
7721 ParseToken(lltok::kw_insts
, "expected 'insts' here") ||
7722 ParseToken(lltok::colon
, "expected ':' here") || ParseUInt32(InstCount
))
7725 // Parse optional fields
7726 while (EatIfPresent(lltok::comma
)) {
7727 switch (Lex
.getKind()) {
7728 case lltok::kw_funcFlags
:
7729 if (ParseOptionalFFlags(FFlags
))
7732 case lltok::kw_calls
:
7733 if (ParseOptionalCalls(Calls
))
7736 case lltok::kw_typeIdInfo
:
7737 if (ParseOptionalTypeIdInfo(TypeIdInfo
))
7740 case lltok::kw_refs
:
7741 if (ParseOptionalRefs(Refs
))
7745 return Error(Lex
.getLoc(), "expected optional function summary field");
7749 if (ParseToken(lltok::rparen
, "expected ')' here"))
7752 auto FS
= llvm::make_unique
<FunctionSummary
>(
7753 GVFlags
, InstCount
, FFlags
, /*EntryCount=*/0, std::move(Refs
),
7754 std::move(Calls
), std::move(TypeIdInfo
.TypeTests
),
7755 std::move(TypeIdInfo
.TypeTestAssumeVCalls
),
7756 std::move(TypeIdInfo
.TypeCheckedLoadVCalls
),
7757 std::move(TypeIdInfo
.TypeTestAssumeConstVCalls
),
7758 std::move(TypeIdInfo
.TypeCheckedLoadConstVCalls
));
7760 FS
->setModulePath(ModulePath
);
7762 AddGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
7769 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7770 /// [',' OptionalRefs]? ')'
7771 bool LLParser::ParseVariableSummary(std::string Name
, GlobalValue::GUID GUID
,
7773 assert(Lex
.getKind() == lltok::kw_variable
);
7776 StringRef ModulePath
;
7777 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
7778 /*Linkage=*/GlobalValue::ExternalLinkage
, /*NotEligibleToImport=*/false,
7779 /*Live=*/false, /*IsLocal=*/false);
7780 GlobalVarSummary::GVarFlags
GVarFlags(/*ReadOnly*/ false);
7781 std::vector
<ValueInfo
> Refs
;
7782 if (ParseToken(lltok::colon
, "expected ':' here") ||
7783 ParseToken(lltok::lparen
, "expected '(' here") ||
7784 ParseModuleReference(ModulePath
) ||
7785 ParseToken(lltok::comma
, "expected ',' here") || ParseGVFlags(GVFlags
) ||
7786 ParseToken(lltok::comma
, "expected ',' here") ||
7787 ParseGVarFlags(GVarFlags
))
7790 // Parse optional refs field
7791 if (EatIfPresent(lltok::comma
)) {
7792 if (ParseOptionalRefs(Refs
))
7796 if (ParseToken(lltok::rparen
, "expected ')' here"))
7800 llvm::make_unique
<GlobalVarSummary
>(GVFlags
, GVarFlags
, std::move(Refs
));
7802 GS
->setModulePath(ModulePath
);
7804 AddGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
7811 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
7812 /// 'aliasee' ':' GVReference ')'
7813 bool LLParser::ParseAliasSummary(std::string Name
, GlobalValue::GUID GUID
,
7815 assert(Lex
.getKind() == lltok::kw_alias
);
7816 LocTy Loc
= Lex
.getLoc();
7819 StringRef ModulePath
;
7820 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
7821 /*Linkage=*/GlobalValue::ExternalLinkage
, /*NotEligibleToImport=*/false,
7822 /*Live=*/false, /*IsLocal=*/false);
7823 if (ParseToken(lltok::colon
, "expected ':' here") ||
7824 ParseToken(lltok::lparen
, "expected '(' here") ||
7825 ParseModuleReference(ModulePath
) ||
7826 ParseToken(lltok::comma
, "expected ',' here") || ParseGVFlags(GVFlags
) ||
7827 ParseToken(lltok::comma
, "expected ',' here") ||
7828 ParseToken(lltok::kw_aliasee
, "expected 'aliasee' here") ||
7829 ParseToken(lltok::colon
, "expected ':' here"))
7832 ValueInfo AliaseeVI
;
7834 if (ParseGVReference(AliaseeVI
, GVId
))
7837 if (ParseToken(lltok::rparen
, "expected ')' here"))
7840 auto AS
= llvm::make_unique
<AliasSummary
>(GVFlags
);
7842 AS
->setModulePath(ModulePath
);
7844 // Record forward reference if the aliasee is not parsed yet.
7845 if (AliaseeVI
.getRef() == FwdVIRef
) {
7846 auto FwdRef
= ForwardRefAliasees
.insert(
7847 std::make_pair(GVId
, std::vector
<std::pair
<AliasSummary
*, LocTy
>>()));
7848 FwdRef
.first
->second
.push_back(std::make_pair(AS
.get(), Loc
));
7850 AS
->setAliasee(AliaseeVI
.getSummaryList().front().get());
7852 AddGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
7860 bool LLParser::ParseFlag(unsigned &Val
) {
7861 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
7862 return TokError("expected integer");
7863 Val
= (unsigned)Lex
.getAPSIntVal().getBoolValue();
7869 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
7870 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
7871 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
7872 /// [',' 'noInline' ':' Flag]? ')'
7873 bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags
&FFlags
) {
7874 assert(Lex
.getKind() == lltok::kw_funcFlags
);
7877 if (ParseToken(lltok::colon
, "expected ':' in funcFlags") |
7878 ParseToken(lltok::lparen
, "expected '(' in funcFlags"))
7883 switch (Lex
.getKind()) {
7884 case lltok::kw_readNone
:
7886 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
7888 FFlags
.ReadNone
= Val
;
7890 case lltok::kw_readOnly
:
7892 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
7894 FFlags
.ReadOnly
= Val
;
7896 case lltok::kw_noRecurse
:
7898 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
7900 FFlags
.NoRecurse
= Val
;
7902 case lltok::kw_returnDoesNotAlias
:
7904 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
7906 FFlags
.ReturnDoesNotAlias
= Val
;
7908 case lltok::kw_noInline
:
7910 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
7912 FFlags
.NoInline
= Val
;
7915 return Error(Lex
.getLoc(), "expected function flag type");
7917 } while (EatIfPresent(lltok::comma
));
7919 if (ParseToken(lltok::rparen
, "expected ')' in funcFlags"))
7926 /// := 'calls' ':' '(' Call [',' Call]* ')'
7927 /// Call ::= '(' 'callee' ':' GVReference
7928 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
7929 bool LLParser::ParseOptionalCalls(std::vector
<FunctionSummary::EdgeTy
> &Calls
) {
7930 assert(Lex
.getKind() == lltok::kw_calls
);
7933 if (ParseToken(lltok::colon
, "expected ':' in calls") |
7934 ParseToken(lltok::lparen
, "expected '(' in calls"))
7937 IdToIndexMapType IdToIndexMap
;
7938 // Parse each call edge
7941 if (ParseToken(lltok::lparen
, "expected '(' in call") ||
7942 ParseToken(lltok::kw_callee
, "expected 'callee' in call") ||
7943 ParseToken(lltok::colon
, "expected ':'"))
7946 LocTy Loc
= Lex
.getLoc();
7948 if (ParseGVReference(VI
, GVId
))
7951 CalleeInfo::HotnessType Hotness
= CalleeInfo::HotnessType::Unknown
;
7953 if (EatIfPresent(lltok::comma
)) {
7954 // Expect either hotness or relbf
7955 if (EatIfPresent(lltok::kw_hotness
)) {
7956 if (ParseToken(lltok::colon
, "expected ':'") || ParseHotness(Hotness
))
7959 if (ParseToken(lltok::kw_relbf
, "expected relbf") ||
7960 ParseToken(lltok::colon
, "expected ':'") || ParseUInt32(RelBF
))
7964 // Keep track of the Call array index needing a forward reference.
7965 // We will save the location of the ValueInfo needing an update, but
7966 // can only do so once the std::vector is finalized.
7967 if (VI
.getRef() == FwdVIRef
)
7968 IdToIndexMap
[GVId
].push_back(std::make_pair(Calls
.size(), Loc
));
7969 Calls
.push_back(FunctionSummary::EdgeTy
{VI
, CalleeInfo(Hotness
, RelBF
)});
7971 if (ParseToken(lltok::rparen
, "expected ')' in call"))
7973 } while (EatIfPresent(lltok::comma
));
7975 // Now that the Calls vector is finalized, it is safe to save the locations
7976 // of any forward GV references that need updating later.
7977 for (auto I
: IdToIndexMap
) {
7978 for (auto P
: I
.second
) {
7979 assert(Calls
[P
.first
].first
.getRef() == FwdVIRef
&&
7980 "Forward referenced ValueInfo expected to be empty");
7981 auto FwdRef
= ForwardRefValueInfos
.insert(std::make_pair(
7982 I
.first
, std::vector
<std::pair
<ValueInfo
*, LocTy
>>()));
7983 FwdRef
.first
->second
.push_back(
7984 std::make_pair(&Calls
[P
.first
].first
, P
.second
));
7988 if (ParseToken(lltok::rparen
, "expected ')' in calls"))
7995 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
7996 bool LLParser::ParseHotness(CalleeInfo::HotnessType
&Hotness
) {
7997 switch (Lex
.getKind()) {
7998 case lltok::kw_unknown
:
7999 Hotness
= CalleeInfo::HotnessType::Unknown
;
8001 case lltok::kw_cold
:
8002 Hotness
= CalleeInfo::HotnessType::Cold
;
8004 case lltok::kw_none
:
8005 Hotness
= CalleeInfo::HotnessType::None
;
8008 Hotness
= CalleeInfo::HotnessType::Hot
;
8010 case lltok::kw_critical
:
8011 Hotness
= CalleeInfo::HotnessType::Critical
;
8014 return Error(Lex
.getLoc(), "invalid call edge hotness");
8021 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8022 bool LLParser::ParseOptionalRefs(std::vector
<ValueInfo
> &Refs
) {
8023 assert(Lex
.getKind() == lltok::kw_refs
);
8026 if (ParseToken(lltok::colon
, "expected ':' in refs") |
8027 ParseToken(lltok::lparen
, "expected '(' in refs"))
8030 struct ValueContext
{
8035 std::vector
<ValueContext
> VContexts
;
8036 // Parse each ref edge
8039 VC
.Loc
= Lex
.getLoc();
8040 if (ParseGVReference(VC
.VI
, VC
.GVId
))
8042 VContexts
.push_back(VC
);
8043 } while (EatIfPresent(lltok::comma
));
8045 // Sort value contexts so that ones with readonly ValueInfo are at the end
8046 // of VContexts vector. This is needed to match immutableRefCount() behavior.
8047 llvm::sort(VContexts
, [](const ValueContext
&VC1
, const ValueContext
&VC2
) {
8048 return VC1
.VI
.isReadOnly() < VC2
.VI
.isReadOnly();
8051 IdToIndexMapType IdToIndexMap
;
8052 for (auto &VC
: VContexts
) {
8053 // Keep track of the Refs array index needing a forward reference.
8054 // We will save the location of the ValueInfo needing an update, but
8055 // can only do so once the std::vector is finalized.
8056 if (VC
.VI
.getRef() == FwdVIRef
)
8057 IdToIndexMap
[VC
.GVId
].push_back(std::make_pair(Refs
.size(), VC
.Loc
));
8058 Refs
.push_back(VC
.VI
);
8061 // Now that the Refs vector is finalized, it is safe to save the locations
8062 // of any forward GV references that need updating later.
8063 for (auto I
: IdToIndexMap
) {
8064 for (auto P
: I
.second
) {
8065 assert(Refs
[P
.first
].getRef() == FwdVIRef
&&
8066 "Forward referenced ValueInfo expected to be empty");
8067 auto FwdRef
= ForwardRefValueInfos
.insert(std::make_pair(
8068 I
.first
, std::vector
<std::pair
<ValueInfo
*, LocTy
>>()));
8069 FwdRef
.first
->second
.push_back(std::make_pair(&Refs
[P
.first
], P
.second
));
8073 if (ParseToken(lltok::rparen
, "expected ')' in refs"))
8079 /// OptionalTypeIdInfo
8080 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8081 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8082 /// [',' TypeCheckedLoadConstVCalls]? ')'
8083 bool LLParser::ParseOptionalTypeIdInfo(
8084 FunctionSummary::TypeIdInfo
&TypeIdInfo
) {
8085 assert(Lex
.getKind() == lltok::kw_typeIdInfo
);
8088 if (ParseToken(lltok::colon
, "expected ':' here") ||
8089 ParseToken(lltok::lparen
, "expected '(' in typeIdInfo"))
8093 switch (Lex
.getKind()) {
8094 case lltok::kw_typeTests
:
8095 if (ParseTypeTests(TypeIdInfo
.TypeTests
))
8098 case lltok::kw_typeTestAssumeVCalls
:
8099 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls
,
8100 TypeIdInfo
.TypeTestAssumeVCalls
))
8103 case lltok::kw_typeCheckedLoadVCalls
:
8104 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls
,
8105 TypeIdInfo
.TypeCheckedLoadVCalls
))
8108 case lltok::kw_typeTestAssumeConstVCalls
:
8109 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls
,
8110 TypeIdInfo
.TypeTestAssumeConstVCalls
))
8113 case lltok::kw_typeCheckedLoadConstVCalls
:
8114 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls
,
8115 TypeIdInfo
.TypeCheckedLoadConstVCalls
))
8119 return Error(Lex
.getLoc(), "invalid typeIdInfo list type");
8121 } while (EatIfPresent(lltok::comma
));
8123 if (ParseToken(lltok::rparen
, "expected ')' in typeIdInfo"))
8130 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8131 /// [',' (SummaryID | UInt64)]* ')'
8132 bool LLParser::ParseTypeTests(std::vector
<GlobalValue::GUID
> &TypeTests
) {
8133 assert(Lex
.getKind() == lltok::kw_typeTests
);
8136 if (ParseToken(lltok::colon
, "expected ':' here") ||
8137 ParseToken(lltok::lparen
, "expected '(' in typeIdInfo"))
8140 IdToIndexMapType IdToIndexMap
;
8142 GlobalValue::GUID GUID
= 0;
8143 if (Lex
.getKind() == lltok::SummaryID
) {
8144 unsigned ID
= Lex
.getUIntVal();
8145 LocTy Loc
= Lex
.getLoc();
8146 // Keep track of the TypeTests array index needing a forward reference.
8147 // We will save the location of the GUID needing an update, but
8148 // can only do so once the std::vector is finalized.
8149 IdToIndexMap
[ID
].push_back(std::make_pair(TypeTests
.size(), Loc
));
8151 } else if (ParseUInt64(GUID
))
8153 TypeTests
.push_back(GUID
);
8154 } while (EatIfPresent(lltok::comma
));
8156 // Now that the TypeTests vector is finalized, it is safe to save the
8157 // locations of any forward GV references that need updating later.
8158 for (auto I
: IdToIndexMap
) {
8159 for (auto P
: I
.second
) {
8160 assert(TypeTests
[P
.first
] == 0 &&
8161 "Forward referenced type id GUID expected to be 0");
8162 auto FwdRef
= ForwardRefTypeIds
.insert(std::make_pair(
8163 I
.first
, std::vector
<std::pair
<GlobalValue::GUID
*, LocTy
>>()));
8164 FwdRef
.first
->second
.push_back(
8165 std::make_pair(&TypeTests
[P
.first
], P
.second
));
8169 if (ParseToken(lltok::rparen
, "expected ')' in typeIdInfo"))
8176 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
8177 bool LLParser::ParseVFuncIdList(
8178 lltok::Kind Kind
, std::vector
<FunctionSummary::VFuncId
> &VFuncIdList
) {
8179 assert(Lex
.getKind() == Kind
);
8182 if (ParseToken(lltok::colon
, "expected ':' here") ||
8183 ParseToken(lltok::lparen
, "expected '(' here"))
8186 IdToIndexMapType IdToIndexMap
;
8188 FunctionSummary::VFuncId VFuncId
;
8189 if (ParseVFuncId(VFuncId
, IdToIndexMap
, VFuncIdList
.size()))
8191 VFuncIdList
.push_back(VFuncId
);
8192 } while (EatIfPresent(lltok::comma
));
8194 if (ParseToken(lltok::rparen
, "expected ')' here"))
8197 // Now that the VFuncIdList vector is finalized, it is safe to save the
8198 // locations of any forward GV references that need updating later.
8199 for (auto I
: IdToIndexMap
) {
8200 for (auto P
: I
.second
) {
8201 assert(VFuncIdList
[P
.first
].GUID
== 0 &&
8202 "Forward referenced type id GUID expected to be 0");
8203 auto FwdRef
= ForwardRefTypeIds
.insert(std::make_pair(
8204 I
.first
, std::vector
<std::pair
<GlobalValue::GUID
*, LocTy
>>()));
8205 FwdRef
.first
->second
.push_back(
8206 std::make_pair(&VFuncIdList
[P
.first
].GUID
, P
.second
));
8214 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8215 bool LLParser::ParseConstVCallList(
8217 std::vector
<FunctionSummary::ConstVCall
> &ConstVCallList
) {
8218 assert(Lex
.getKind() == Kind
);
8221 if (ParseToken(lltok::colon
, "expected ':' here") ||
8222 ParseToken(lltok::lparen
, "expected '(' here"))
8225 IdToIndexMapType IdToIndexMap
;
8227 FunctionSummary::ConstVCall ConstVCall
;
8228 if (ParseConstVCall(ConstVCall
, IdToIndexMap
, ConstVCallList
.size()))
8230 ConstVCallList
.push_back(ConstVCall
);
8231 } while (EatIfPresent(lltok::comma
));
8233 if (ParseToken(lltok::rparen
, "expected ')' here"))
8236 // Now that the ConstVCallList vector is finalized, it is safe to save the
8237 // locations of any forward GV references that need updating later.
8238 for (auto I
: IdToIndexMap
) {
8239 for (auto P
: I
.second
) {
8240 assert(ConstVCallList
[P
.first
].VFunc
.GUID
== 0 &&
8241 "Forward referenced type id GUID expected to be 0");
8242 auto FwdRef
= ForwardRefTypeIds
.insert(std::make_pair(
8243 I
.first
, std::vector
<std::pair
<GlobalValue::GUID
*, LocTy
>>()));
8244 FwdRef
.first
->second
.push_back(
8245 std::make_pair(&ConstVCallList
[P
.first
].VFunc
.GUID
, P
.second
));
8253 /// ::= '(' VFuncId ',' Args ')'
8254 bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall
&ConstVCall
,
8255 IdToIndexMapType
&IdToIndexMap
, unsigned Index
) {
8256 if (ParseToken(lltok::lparen
, "expected '(' here") ||
8257 ParseVFuncId(ConstVCall
.VFunc
, IdToIndexMap
, Index
))
8260 if (EatIfPresent(lltok::comma
))
8261 if (ParseArgs(ConstVCall
.Args
))
8264 if (ParseToken(lltok::rparen
, "expected ')' here"))
8271 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8272 /// 'offset' ':' UInt64 ')'
8273 bool LLParser::ParseVFuncId(FunctionSummary::VFuncId
&VFuncId
,
8274 IdToIndexMapType
&IdToIndexMap
, unsigned Index
) {
8275 assert(Lex
.getKind() == lltok::kw_vFuncId
);
8278 if (ParseToken(lltok::colon
, "expected ':' here") ||
8279 ParseToken(lltok::lparen
, "expected '(' here"))
8282 if (Lex
.getKind() == lltok::SummaryID
) {
8284 unsigned ID
= Lex
.getUIntVal();
8285 LocTy Loc
= Lex
.getLoc();
8286 // Keep track of the array index needing a forward reference.
8287 // We will save the location of the GUID needing an update, but
8288 // can only do so once the caller's std::vector is finalized.
8289 IdToIndexMap
[ID
].push_back(std::make_pair(Index
, Loc
));
8291 } else if (ParseToken(lltok::kw_guid
, "expected 'guid' here") ||
8292 ParseToken(lltok::colon
, "expected ':' here") ||
8293 ParseUInt64(VFuncId
.GUID
))
8296 if (ParseToken(lltok::comma
, "expected ',' here") ||
8297 ParseToken(lltok::kw_offset
, "expected 'offset' here") ||
8298 ParseToken(lltok::colon
, "expected ':' here") ||
8299 ParseUInt64(VFuncId
.Offset
) ||
8300 ParseToken(lltok::rparen
, "expected ')' here"))
8307 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8308 /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8309 /// 'dsoLocal' ':' Flag ')'
8310 bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags
&GVFlags
) {
8311 assert(Lex
.getKind() == lltok::kw_flags
);
8315 if (ParseToken(lltok::colon
, "expected ':' here") ||
8316 ParseToken(lltok::lparen
, "expected '(' here") ||
8317 ParseToken(lltok::kw_linkage
, "expected 'linkage' here") ||
8318 ParseToken(lltok::colon
, "expected ':' here"))
8321 GVFlags
.Linkage
= parseOptionalLinkageAux(Lex
.getKind(), HasLinkage
);
8322 assert(HasLinkage
&& "Linkage not optional in summary entry");
8326 if (ParseToken(lltok::comma
, "expected ',' here") ||
8327 ParseToken(lltok::kw_notEligibleToImport
,
8328 "expected 'notEligibleToImport' here") ||
8329 ParseToken(lltok::colon
, "expected ':' here") || ParseFlag(Flag
))
8331 GVFlags
.NotEligibleToImport
= Flag
;
8333 if (ParseToken(lltok::comma
, "expected ',' here") ||
8334 ParseToken(lltok::kw_live
, "expected 'live' here") ||
8335 ParseToken(lltok::colon
, "expected ':' here") || ParseFlag(Flag
))
8337 GVFlags
.Live
= Flag
;
8339 if (ParseToken(lltok::comma
, "expected ',' here") ||
8340 ParseToken(lltok::kw_dsoLocal
, "expected 'dsoLocal' here") ||
8341 ParseToken(lltok::colon
, "expected ':' here") || ParseFlag(Flag
))
8343 GVFlags
.DSOLocal
= Flag
;
8345 if (ParseToken(lltok::rparen
, "expected ')' here"))
8352 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag ')'
8353 bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags
&GVarFlags
) {
8354 assert(Lex
.getKind() == lltok::kw_varFlags
);
8358 if (ParseToken(lltok::colon
, "expected ':' here") ||
8359 ParseToken(lltok::lparen
, "expected '(' here") ||
8360 ParseToken(lltok::kw_readonly
, "expected 'readonly' here") ||
8361 ParseToken(lltok::colon
, "expected ':' here"))
8365 GVarFlags
.ReadOnly
= Flag
;
8367 if (ParseToken(lltok::rparen
, "expected ')' here"))
8373 /// ::= 'module' ':' UInt
8374 bool LLParser::ParseModuleReference(StringRef
&ModulePath
) {
8376 if (ParseToken(lltok::kw_module
, "expected 'module' here") ||
8377 ParseToken(lltok::colon
, "expected ':' here") ||
8378 ParseToken(lltok::SummaryID
, "expected module ID"))
8381 unsigned ModuleID
= Lex
.getUIntVal();
8382 auto I
= ModuleIdMap
.find(ModuleID
);
8383 // We should have already parsed all module IDs
8384 assert(I
!= ModuleIdMap
.end());
8385 ModulePath
= I
->second
;
8391 bool LLParser::ParseGVReference(ValueInfo
&VI
, unsigned &GVId
) {
8392 bool ReadOnly
= EatIfPresent(lltok::kw_readonly
);
8393 if (ParseToken(lltok::SummaryID
, "expected GV ID"))
8396 GVId
= Lex
.getUIntVal();
8397 // Check if we already have a VI for this GV
8398 if (GVId
< NumberedValueInfos
.size()) {
8399 assert(NumberedValueInfos
[GVId
].getRef() != FwdVIRef
);
8400 VI
= NumberedValueInfos
[GVId
];
8402 // We will create a forward reference to the stored location.
8403 VI
= ValueInfo(false, FwdVIRef
);