1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the parser class for .ll files.
11 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/SlotMapping.h"
20 #include "llvm/BinaryFormat/Dwarf.h"
21 #include "llvm/IR/Argument.h"
22 #include "llvm/IR/AutoUpgrade.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Comdat.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugInfoMetadata.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalIFunc.h"
31 #include "llvm/IR/GlobalObject.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/IR/ValueSymbolTable.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/SaveAndRestore.h"
47 #include "llvm/Support/raw_ostream.h"
56 static std::string
getTypeString(Type
*T
) {
58 raw_string_ostream
Tmp(Result
);
63 /// Run: module ::= toplevelentity*
64 bool LLParser::Run() {
68 if (Context
.shouldDiscardValueNames())
71 "Can't read textual IR with a Context that discards named Values");
73 return ParseTopLevelEntities() || ValidateEndOfModule() ||
77 bool LLParser::parseStandaloneConstantValue(Constant
*&C
,
78 const SlotMapping
*Slots
) {
79 restoreParsingState(Slots
);
83 if (ParseType(Ty
) || parseConstantValue(Ty
, C
))
85 if (Lex
.getKind() != lltok::Eof
)
86 return Error(Lex
.getLoc(), "expected end of string");
90 bool LLParser::parseTypeAtBeginning(Type
*&Ty
, unsigned &Read
,
91 const SlotMapping
*Slots
) {
92 restoreParsingState(Slots
);
96 SMLoc Start
= Lex
.getLoc();
100 SMLoc End
= Lex
.getLoc();
101 Read
= End
.getPointer() - Start
.getPointer();
106 void LLParser::restoreParsingState(const SlotMapping
*Slots
) {
109 NumberedVals
= Slots
->GlobalValues
;
110 NumberedMetadata
= Slots
->MetadataNodes
;
111 for (const auto &I
: Slots
->NamedTypes
)
113 std::make_pair(I
.getKey(), std::make_pair(I
.second
, LocTy())));
114 for (const auto &I
: Slots
->Types
)
115 NumberedTypes
.insert(
116 std::make_pair(I
.first
, std::make_pair(I
.second
, LocTy())));
119 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
121 bool LLParser::ValidateEndOfModule() {
124 // Handle any function attribute group forward references.
125 for (const auto &RAG
: ForwardRefAttrGroups
) {
126 Value
*V
= RAG
.first
;
127 const std::vector
<unsigned> &Attrs
= RAG
.second
;
130 for (const auto &Attr
: Attrs
)
131 B
.merge(NumberedAttrBuilders
[Attr
]);
133 if (Function
*Fn
= dyn_cast
<Function
>(V
)) {
134 AttributeList AS
= Fn
->getAttributes();
135 AttrBuilder
FnAttrs(AS
.getFnAttributes());
136 AS
= AS
.removeAttributes(Context
, AttributeList::FunctionIndex
);
140 // If the alignment was parsed as an attribute, move to the alignment
142 if (FnAttrs
.hasAlignmentAttr()) {
143 Fn
->setAlignment(FnAttrs
.getAlignment());
144 FnAttrs
.removeAttribute(Attribute::Alignment
);
147 AS
= AS
.addAttributes(Context
, AttributeList::FunctionIndex
,
148 AttributeSet::get(Context
, FnAttrs
));
149 Fn
->setAttributes(AS
);
150 } else if (CallInst
*CI
= dyn_cast
<CallInst
>(V
)) {
151 AttributeList AS
= CI
->getAttributes();
152 AttrBuilder
FnAttrs(AS
.getFnAttributes());
153 AS
= AS
.removeAttributes(Context
, AttributeList::FunctionIndex
);
155 AS
= AS
.addAttributes(Context
, AttributeList::FunctionIndex
,
156 AttributeSet::get(Context
, FnAttrs
));
157 CI
->setAttributes(AS
);
158 } else if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(V
)) {
159 AttributeList AS
= II
->getAttributes();
160 AttrBuilder
FnAttrs(AS
.getFnAttributes());
161 AS
= AS
.removeAttributes(Context
, AttributeList::FunctionIndex
);
163 AS
= AS
.addAttributes(Context
, AttributeList::FunctionIndex
,
164 AttributeSet::get(Context
, FnAttrs
));
165 II
->setAttributes(AS
);
166 } else if (CallBrInst
*CBI
= dyn_cast
<CallBrInst
>(V
)) {
167 AttributeList AS
= CBI
->getAttributes();
168 AttrBuilder
FnAttrs(AS
.getFnAttributes());
169 AS
= AS
.removeAttributes(Context
, AttributeList::FunctionIndex
);
171 AS
= AS
.addAttributes(Context
, AttributeList::FunctionIndex
,
172 AttributeSet::get(Context
, FnAttrs
));
173 CBI
->setAttributes(AS
);
174 } else if (auto *GV
= dyn_cast
<GlobalVariable
>(V
)) {
175 AttrBuilder
Attrs(GV
->getAttributes());
177 GV
->setAttributes(AttributeSet::get(Context
,Attrs
));
179 llvm_unreachable("invalid object with forward attribute group reference");
183 // If there are entries in ForwardRefBlockAddresses at this point, the
184 // function was never defined.
185 if (!ForwardRefBlockAddresses
.empty())
186 return Error(ForwardRefBlockAddresses
.begin()->first
.Loc
,
187 "expected function name in blockaddress");
189 for (const auto &NT
: NumberedTypes
)
190 if (NT
.second
.second
.isValid())
191 return Error(NT
.second
.second
,
192 "use of undefined type '%" + Twine(NT
.first
) + "'");
194 for (StringMap
<std::pair
<Type
*, LocTy
> >::iterator I
=
195 NamedTypes
.begin(), E
= NamedTypes
.end(); I
!= E
; ++I
)
196 if (I
->second
.second
.isValid())
197 return Error(I
->second
.second
,
198 "use of undefined type named '" + I
->getKey() + "'");
200 if (!ForwardRefComdats
.empty())
201 return Error(ForwardRefComdats
.begin()->second
,
202 "use of undefined comdat '$" +
203 ForwardRefComdats
.begin()->first
+ "'");
205 if (!ForwardRefVals
.empty())
206 return Error(ForwardRefVals
.begin()->second
.second
,
207 "use of undefined value '@" + ForwardRefVals
.begin()->first
+
210 if (!ForwardRefValIDs
.empty())
211 return Error(ForwardRefValIDs
.begin()->second
.second
,
212 "use of undefined value '@" +
213 Twine(ForwardRefValIDs
.begin()->first
) + "'");
215 if (!ForwardRefMDNodes
.empty())
216 return Error(ForwardRefMDNodes
.begin()->second
.second
,
217 "use of undefined metadata '!" +
218 Twine(ForwardRefMDNodes
.begin()->first
) + "'");
220 // Resolve metadata cycles.
221 for (auto &N
: NumberedMetadata
) {
222 if (N
.second
&& !N
.second
->isResolved())
223 N
.second
->resolveCycles();
226 for (auto *Inst
: InstsWithTBAATag
) {
227 MDNode
*MD
= Inst
->getMetadata(LLVMContext::MD_tbaa
);
228 assert(MD
&& "UpgradeInstWithTBAATag should have a TBAA tag");
229 auto *UpgradedMD
= UpgradeTBAANode(*MD
);
230 if (MD
!= UpgradedMD
)
231 Inst
->setMetadata(LLVMContext::MD_tbaa
, UpgradedMD
);
234 // Look for intrinsic functions and CallInst that need to be upgraded
235 for (Module::iterator FI
= M
->begin(), FE
= M
->end(); FI
!= FE
; )
236 UpgradeCallsToIntrinsic(&*FI
++); // must be post-increment, as we remove
238 // Some types could be renamed during loading if several modules are
239 // loaded in the same LLVMContext (LTO scenario). In this case we should
240 // remangle intrinsics names as well.
241 for (Module::iterator FI
= M
->begin(), FE
= M
->end(); FI
!= FE
; ) {
242 Function
*F
= &*FI
++;
243 if (auto Remangled
= Intrinsic::remangleIntrinsicFunction(F
)) {
244 F
->replaceAllUsesWith(Remangled
.getValue());
245 F
->eraseFromParent();
249 if (UpgradeDebugInfo
)
250 llvm::UpgradeDebugInfo(*M
);
252 UpgradeModuleFlags(*M
);
253 UpgradeSectionAttributes(*M
);
257 // Initialize the slot mapping.
258 // Because by this point we've parsed and validated everything, we can "steal"
259 // the mapping from LLParser as it doesn't need it anymore.
260 Slots
->GlobalValues
= std::move(NumberedVals
);
261 Slots
->MetadataNodes
= std::move(NumberedMetadata
);
262 for (const auto &I
: NamedTypes
)
263 Slots
->NamedTypes
.insert(std::make_pair(I
.getKey(), I
.second
.first
));
264 for (const auto &I
: NumberedTypes
)
265 Slots
->Types
.insert(std::make_pair(I
.first
, I
.second
.first
));
270 /// Do final validity and sanity checks at the end of the index.
271 bool LLParser::ValidateEndOfIndex() {
275 if (!ForwardRefValueInfos
.empty())
276 return Error(ForwardRefValueInfos
.begin()->second
.front().second
,
277 "use of undefined summary '^" +
278 Twine(ForwardRefValueInfos
.begin()->first
) + "'");
280 if (!ForwardRefAliasees
.empty())
281 return Error(ForwardRefAliasees
.begin()->second
.front().second
,
282 "use of undefined summary '^" +
283 Twine(ForwardRefAliasees
.begin()->first
) + "'");
285 if (!ForwardRefTypeIds
.empty())
286 return Error(ForwardRefTypeIds
.begin()->second
.front().second
,
287 "use of undefined type id summary '^" +
288 Twine(ForwardRefTypeIds
.begin()->first
) + "'");
293 //===----------------------------------------------------------------------===//
294 // Top-Level Entities
295 //===----------------------------------------------------------------------===//
297 bool LLParser::ParseTopLevelEntities() {
298 // If there is no Module, then parse just the summary index entries.
301 switch (Lex
.getKind()) {
304 case lltok::SummaryID
:
305 if (ParseSummaryEntry())
308 case lltok::kw_source_filename
:
309 if (ParseSourceFileName())
313 // Skip everything else
319 switch (Lex
.getKind()) {
320 default: return TokError("expected top-level entity");
321 case lltok::Eof
: return false;
322 case lltok::kw_declare
: if (ParseDeclare()) return true; break;
323 case lltok::kw_define
: if (ParseDefine()) return true; break;
324 case lltok::kw_module
: if (ParseModuleAsm()) return true; break;
325 case lltok::kw_target
: if (ParseTargetDefinition()) return true; break;
326 case lltok::kw_source_filename
:
327 if (ParseSourceFileName())
330 case lltok::kw_deplibs
: if (ParseDepLibs()) return true; break;
331 case lltok::LocalVarID
: if (ParseUnnamedType()) return true; break;
332 case lltok::LocalVar
: if (ParseNamedType()) return true; break;
333 case lltok::GlobalID
: if (ParseUnnamedGlobal()) return true; break;
334 case lltok::GlobalVar
: if (ParseNamedGlobal()) return true; break;
335 case lltok::ComdatVar
: if (parseComdat()) return true; break;
336 case lltok::exclaim
: if (ParseStandaloneMetadata()) return true; break;
337 case lltok::SummaryID
:
338 if (ParseSummaryEntry())
341 case lltok::MetadataVar
:if (ParseNamedMetadata()) return true; break;
342 case lltok::kw_attributes
: if (ParseUnnamedAttrGrp()) return true; break;
343 case lltok::kw_uselistorder
: if (ParseUseListOrder()) return true; break;
344 case lltok::kw_uselistorder_bb
:
345 if (ParseUseListOrderBB())
353 /// ::= 'module' 'asm' STRINGCONSTANT
354 bool LLParser::ParseModuleAsm() {
355 assert(Lex
.getKind() == lltok::kw_module
);
359 if (ParseToken(lltok::kw_asm
, "expected 'module asm'") ||
360 ParseStringConstant(AsmStr
)) return true;
362 M
->appendModuleInlineAsm(AsmStr
);
367 /// ::= 'target' 'triple' '=' STRINGCONSTANT
368 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
369 bool LLParser::ParseTargetDefinition() {
370 assert(Lex
.getKind() == lltok::kw_target
);
373 default: return TokError("unknown target property");
374 case lltok::kw_triple
:
376 if (ParseToken(lltok::equal
, "expected '=' after target triple") ||
377 ParseStringConstant(Str
))
379 M
->setTargetTriple(Str
);
381 case lltok::kw_datalayout
:
383 if (ParseToken(lltok::equal
, "expected '=' after target datalayout") ||
384 ParseStringConstant(Str
))
386 if (DataLayoutStr
.empty())
387 M
->setDataLayout(Str
);
393 /// ::= 'source_filename' '=' STRINGCONSTANT
394 bool LLParser::ParseSourceFileName() {
395 assert(Lex
.getKind() == lltok::kw_source_filename
);
397 if (ParseToken(lltok::equal
, "expected '=' after source_filename") ||
398 ParseStringConstant(SourceFileName
))
401 M
->setSourceFileName(SourceFileName
);
406 /// ::= 'deplibs' '=' '[' ']'
407 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
408 /// FIXME: Remove in 4.0. Currently parse, but ignore.
409 bool LLParser::ParseDepLibs() {
410 assert(Lex
.getKind() == lltok::kw_deplibs
);
412 if (ParseToken(lltok::equal
, "expected '=' after deplibs") ||
413 ParseToken(lltok::lsquare
, "expected '=' after deplibs"))
416 if (EatIfPresent(lltok::rsquare
))
421 if (ParseStringConstant(Str
)) return true;
422 } while (EatIfPresent(lltok::comma
));
424 return ParseToken(lltok::rsquare
, "expected ']' at end of list");
427 /// ParseUnnamedType:
428 /// ::= LocalVarID '=' 'type' type
429 bool LLParser::ParseUnnamedType() {
430 LocTy TypeLoc
= Lex
.getLoc();
431 unsigned TypeID
= Lex
.getUIntVal();
432 Lex
.Lex(); // eat LocalVarID;
434 if (ParseToken(lltok::equal
, "expected '=' after name") ||
435 ParseToken(lltok::kw_type
, "expected 'type' after '='"))
438 Type
*Result
= nullptr;
439 if (ParseStructDefinition(TypeLoc
, "",
440 NumberedTypes
[TypeID
], Result
)) return true;
442 if (!isa
<StructType
>(Result
)) {
443 std::pair
<Type
*, LocTy
> &Entry
= NumberedTypes
[TypeID
];
445 return Error(TypeLoc
, "non-struct types may not be recursive");
446 Entry
.first
= Result
;
447 Entry
.second
= SMLoc();
454 /// ::= LocalVar '=' 'type' type
455 bool LLParser::ParseNamedType() {
456 std::string Name
= Lex
.getStrVal();
457 LocTy NameLoc
= Lex
.getLoc();
458 Lex
.Lex(); // eat LocalVar.
460 if (ParseToken(lltok::equal
, "expected '=' after name") ||
461 ParseToken(lltok::kw_type
, "expected 'type' after name"))
464 Type
*Result
= nullptr;
465 if (ParseStructDefinition(NameLoc
, Name
,
466 NamedTypes
[Name
], Result
)) return true;
468 if (!isa
<StructType
>(Result
)) {
469 std::pair
<Type
*, LocTy
> &Entry
= NamedTypes
[Name
];
471 return Error(NameLoc
, "non-struct types may not be recursive");
472 Entry
.first
= Result
;
473 Entry
.second
= SMLoc();
480 /// ::= 'declare' FunctionHeader
481 bool LLParser::ParseDeclare() {
482 assert(Lex
.getKind() == lltok::kw_declare
);
485 std::vector
<std::pair
<unsigned, MDNode
*>> MDs
;
486 while (Lex
.getKind() == lltok::MetadataVar
) {
489 if (ParseMetadataAttachment(MDK
, N
))
491 MDs
.push_back({MDK
, N
});
495 if (ParseFunctionHeader(F
, false))
498 F
->addMetadata(MD
.first
, *MD
.second
);
503 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
504 bool LLParser::ParseDefine() {
505 assert(Lex
.getKind() == lltok::kw_define
);
509 return ParseFunctionHeader(F
, true) ||
510 ParseOptionalFunctionMetadata(*F
) ||
511 ParseFunctionBody(*F
);
517 bool LLParser::ParseGlobalType(bool &IsConstant
) {
518 if (Lex
.getKind() == lltok::kw_constant
)
520 else if (Lex
.getKind() == lltok::kw_global
)
524 return TokError("expected 'global' or 'constant'");
530 bool LLParser::ParseOptionalUnnamedAddr(
531 GlobalVariable::UnnamedAddr
&UnnamedAddr
) {
532 if (EatIfPresent(lltok::kw_unnamed_addr
))
533 UnnamedAddr
= GlobalValue::UnnamedAddr::Global
;
534 else if (EatIfPresent(lltok::kw_local_unnamed_addr
))
535 UnnamedAddr
= GlobalValue::UnnamedAddr::Local
;
537 UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
541 /// ParseUnnamedGlobal:
542 /// OptionalVisibility (ALIAS | IFUNC) ...
543 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
544 /// OptionalDLLStorageClass
545 /// ... -> global variable
546 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
547 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
548 /// OptionalDLLStorageClass
549 /// ... -> global variable
550 bool LLParser::ParseUnnamedGlobal() {
551 unsigned VarID
= NumberedVals
.size();
553 LocTy NameLoc
= Lex
.getLoc();
555 // Handle the GlobalID form.
556 if (Lex
.getKind() == lltok::GlobalID
) {
557 if (Lex
.getUIntVal() != VarID
)
558 return Error(Lex
.getLoc(), "variable expected to be numbered '%" +
560 Lex
.Lex(); // eat GlobalID;
562 if (ParseToken(lltok::equal
, "expected '=' after name"))
567 unsigned Linkage
, Visibility
, DLLStorageClass
;
569 GlobalVariable::ThreadLocalMode TLM
;
570 GlobalVariable::UnnamedAddr UnnamedAddr
;
571 if (ParseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
573 ParseOptionalThreadLocal(TLM
) || ParseOptionalUnnamedAddr(UnnamedAddr
))
576 if (Lex
.getKind() != lltok::kw_alias
&& Lex
.getKind() != lltok::kw_ifunc
)
577 return ParseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
,
578 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
580 return parseIndirectSymbol(Name
, NameLoc
, Linkage
, Visibility
,
581 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
584 /// ParseNamedGlobal:
585 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
586 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
587 /// OptionalVisibility OptionalDLLStorageClass
588 /// ... -> global variable
589 bool LLParser::ParseNamedGlobal() {
590 assert(Lex
.getKind() == lltok::GlobalVar
);
591 LocTy NameLoc
= Lex
.getLoc();
592 std::string Name
= Lex
.getStrVal();
596 unsigned Linkage
, Visibility
, DLLStorageClass
;
598 GlobalVariable::ThreadLocalMode TLM
;
599 GlobalVariable::UnnamedAddr UnnamedAddr
;
600 if (ParseToken(lltok::equal
, "expected '=' in global variable") ||
601 ParseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
603 ParseOptionalThreadLocal(TLM
) || ParseOptionalUnnamedAddr(UnnamedAddr
))
606 if (Lex
.getKind() != lltok::kw_alias
&& Lex
.getKind() != lltok::kw_ifunc
)
607 return ParseGlobal(Name
, NameLoc
, Linkage
, HasLinkage
, Visibility
,
608 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
610 return parseIndirectSymbol(Name
, NameLoc
, Linkage
, Visibility
,
611 DLLStorageClass
, DSOLocal
, TLM
, UnnamedAddr
);
614 bool LLParser::parseComdat() {
615 assert(Lex
.getKind() == lltok::ComdatVar
);
616 std::string Name
= Lex
.getStrVal();
617 LocTy NameLoc
= Lex
.getLoc();
620 if (ParseToken(lltok::equal
, "expected '=' here"))
623 if (ParseToken(lltok::kw_comdat
, "expected comdat keyword"))
624 return TokError("expected comdat type");
626 Comdat::SelectionKind SK
;
627 switch (Lex
.getKind()) {
629 return TokError("unknown selection kind");
633 case lltok::kw_exactmatch
:
634 SK
= Comdat::ExactMatch
;
636 case lltok::kw_largest
:
637 SK
= Comdat::Largest
;
639 case lltok::kw_noduplicates
:
640 SK
= Comdat::NoDuplicates
;
642 case lltok::kw_samesize
:
643 SK
= Comdat::SameSize
;
648 // See if the comdat was forward referenced, if so, use the comdat.
649 Module::ComdatSymTabType
&ComdatSymTab
= M
->getComdatSymbolTable();
650 Module::ComdatSymTabType::iterator I
= ComdatSymTab
.find(Name
);
651 if (I
!= ComdatSymTab
.end() && !ForwardRefComdats
.erase(Name
))
652 return Error(NameLoc
, "redefinition of comdat '$" + Name
+ "'");
655 if (I
!= ComdatSymTab
.end())
658 C
= M
->getOrInsertComdat(Name
);
659 C
->setSelectionKind(SK
);
665 // ::= '!' STRINGCONSTANT
666 bool LLParser::ParseMDString(MDString
*&Result
) {
668 if (ParseStringConstant(Str
)) return true;
669 Result
= MDString::get(Context
, Str
);
674 // ::= '!' MDNodeNumber
675 bool LLParser::ParseMDNodeID(MDNode
*&Result
) {
676 // !{ ..., !42, ... }
677 LocTy IDLoc
= Lex
.getLoc();
679 if (ParseUInt32(MID
))
682 // If not a forward reference, just return it now.
683 if (NumberedMetadata
.count(MID
)) {
684 Result
= NumberedMetadata
[MID
];
688 // Otherwise, create MDNode forward reference.
689 auto &FwdRef
= ForwardRefMDNodes
[MID
];
690 FwdRef
= std::make_pair(MDTuple::getTemporary(Context
, None
), IDLoc
);
692 Result
= FwdRef
.first
.get();
693 NumberedMetadata
[MID
].reset(Result
);
697 /// ParseNamedMetadata:
698 /// !foo = !{ !1, !2 }
699 bool LLParser::ParseNamedMetadata() {
700 assert(Lex
.getKind() == lltok::MetadataVar
);
701 std::string Name
= Lex
.getStrVal();
704 if (ParseToken(lltok::equal
, "expected '=' here") ||
705 ParseToken(lltok::exclaim
, "Expected '!' here") ||
706 ParseToken(lltok::lbrace
, "Expected '{' here"))
709 NamedMDNode
*NMD
= M
->getOrInsertNamedMetadata(Name
);
710 if (Lex
.getKind() != lltok::rbrace
)
713 // Parse DIExpressions inline as a special case. They are still MDNodes,
714 // so they can still appear in named metadata. Remove this logic if they
715 // become plain Metadata.
716 if (Lex
.getKind() == lltok::MetadataVar
&&
717 Lex
.getStrVal() == "DIExpression") {
718 if (ParseDIExpression(N
, /*IsDistinct=*/false))
720 } else if (ParseToken(lltok::exclaim
, "Expected '!' here") ||
725 } while (EatIfPresent(lltok::comma
));
727 return ParseToken(lltok::rbrace
, "expected end of metadata node");
730 /// ParseStandaloneMetadata:
732 bool LLParser::ParseStandaloneMetadata() {
733 assert(Lex
.getKind() == lltok::exclaim
);
735 unsigned MetadataID
= 0;
738 if (ParseUInt32(MetadataID
) ||
739 ParseToken(lltok::equal
, "expected '=' here"))
742 // Detect common error, from old metadata syntax.
743 if (Lex
.getKind() == lltok::Type
)
744 return TokError("unexpected type in metadata definition");
746 bool IsDistinct
= EatIfPresent(lltok::kw_distinct
);
747 if (Lex
.getKind() == lltok::MetadataVar
) {
748 if (ParseSpecializedMDNode(Init
, IsDistinct
))
750 } else if (ParseToken(lltok::exclaim
, "Expected '!' here") ||
751 ParseMDTuple(Init
, IsDistinct
))
754 // See if this was forward referenced, if so, handle it.
755 auto FI
= ForwardRefMDNodes
.find(MetadataID
);
756 if (FI
!= ForwardRefMDNodes
.end()) {
757 FI
->second
.first
->replaceAllUsesWith(Init
);
758 ForwardRefMDNodes
.erase(FI
);
760 assert(NumberedMetadata
[MetadataID
] == Init
&& "Tracking VH didn't work");
762 if (NumberedMetadata
.count(MetadataID
))
763 return TokError("Metadata id is already used");
764 NumberedMetadata
[MetadataID
].reset(Init
);
770 // Skips a single module summary entry.
771 bool LLParser::SkipModuleSummaryEntry() {
772 // Each module summary entry consists of a tag for the entry
773 // type, followed by a colon, then the fields surrounded by nested sets of
774 // parentheses. The "tag:" looks like a Label. Once parsing support is
775 // in place we will look for the tokens corresponding to the expected tags.
776 if (Lex
.getKind() != lltok::kw_gv
&& Lex
.getKind() != lltok::kw_module
&&
777 Lex
.getKind() != lltok::kw_typeid
)
779 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
781 if (ParseToken(lltok::colon
, "expected ':' at start of summary entry") ||
782 ParseToken(lltok::lparen
, "expected '(' at start of summary entry"))
784 // Now walk through the parenthesized entry, until the number of open
785 // parentheses goes back down to 0 (the first '(' was parsed above).
786 unsigned NumOpenParen
= 1;
788 switch (Lex
.getKind()) {
796 return TokError("found end of file while parsing summary entry");
798 // Skip everything in between parentheses.
802 } while (NumOpenParen
> 0);
807 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
808 bool LLParser::ParseSummaryEntry() {
809 assert(Lex
.getKind() == lltok::SummaryID
);
810 unsigned SummaryID
= Lex
.getUIntVal();
812 // For summary entries, colons should be treated as distinct tokens,
813 // not an indication of the end of a label token.
814 Lex
.setIgnoreColonInIdentifiers(true);
817 if (ParseToken(lltok::equal
, "expected '=' here"))
820 // If we don't have an index object, skip the summary entry.
822 return SkipModuleSummaryEntry();
824 switch (Lex
.getKind()) {
826 return ParseGVEntry(SummaryID
);
827 case lltok::kw_module
:
828 return ParseModuleEntry(SummaryID
);
829 case lltok::kw_typeid
:
830 return ParseTypeIdEntry(SummaryID
);
833 return Error(Lex
.getLoc(), "unexpected summary kind");
835 Lex
.setIgnoreColonInIdentifiers(false);
839 static bool isValidVisibilityForLinkage(unsigned V
, unsigned L
) {
840 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes
)L
) ||
841 (GlobalValue::VisibilityTypes
)V
== GlobalValue::DefaultVisibility
;
844 // If there was an explicit dso_local, update GV. In the absence of an explicit
845 // dso_local we keep the default value.
846 static void maybeSetDSOLocal(bool DSOLocal
, GlobalValue
&GV
) {
848 GV
.setDSOLocal(true);
851 /// parseIndirectSymbol:
852 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
853 /// OptionalVisibility OptionalDLLStorageClass
854 /// OptionalThreadLocal OptionalUnnamedAddr
855 // 'alias|ifunc' IndirectSymbol
860 /// Everything through OptionalUnnamedAddr has already been parsed.
862 bool LLParser::parseIndirectSymbol(const std::string
&Name
, LocTy NameLoc
,
863 unsigned L
, unsigned Visibility
,
864 unsigned DLLStorageClass
, bool DSOLocal
,
865 GlobalVariable::ThreadLocalMode TLM
,
866 GlobalVariable::UnnamedAddr UnnamedAddr
) {
868 if (Lex
.getKind() == lltok::kw_alias
)
870 else if (Lex
.getKind() == lltok::kw_ifunc
)
873 llvm_unreachable("Not an alias or ifunc!");
876 GlobalValue::LinkageTypes Linkage
= (GlobalValue::LinkageTypes
) L
;
878 if(IsAlias
&& !GlobalAlias::isValidLinkage(Linkage
))
879 return Error(NameLoc
, "invalid linkage type for alias");
881 if (!isValidVisibilityForLinkage(Visibility
, L
))
882 return Error(NameLoc
,
883 "symbol with local linkage must have default visibility");
886 LocTy ExplicitTypeLoc
= Lex
.getLoc();
888 ParseToken(lltok::comma
, "expected comma after alias or ifunc's type"))
892 LocTy AliaseeLoc
= Lex
.getLoc();
893 if (Lex
.getKind() != lltok::kw_bitcast
&&
894 Lex
.getKind() != lltok::kw_getelementptr
&&
895 Lex
.getKind() != lltok::kw_addrspacecast
&&
896 Lex
.getKind() != lltok::kw_inttoptr
) {
897 if (ParseGlobalTypeAndValue(Aliasee
))
900 // The bitcast dest type is not present, it is implied by the dest type.
904 if (ID
.Kind
!= ValID::t_Constant
)
905 return Error(AliaseeLoc
, "invalid aliasee");
906 Aliasee
= ID
.ConstantVal
;
909 Type
*AliaseeType
= Aliasee
->getType();
910 auto *PTy
= dyn_cast
<PointerType
>(AliaseeType
);
912 return Error(AliaseeLoc
, "An alias or ifunc must have pointer type");
913 unsigned AddrSpace
= PTy
->getAddressSpace();
915 if (IsAlias
&& Ty
!= PTy
->getElementType())
918 "explicit pointee type doesn't match operand's pointee type");
920 if (!IsAlias
&& !PTy
->getElementType()->isFunctionTy())
923 "explicit pointee type should be a function type");
925 GlobalValue
*GVal
= nullptr;
927 // See if the alias was forward referenced, if so, prepare to replace the
928 // forward reference.
930 GVal
= M
->getNamedValue(Name
);
932 if (!ForwardRefVals
.erase(Name
))
933 return Error(NameLoc
, "redefinition of global '@" + Name
+ "'");
936 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
937 if (I
!= ForwardRefValIDs
.end()) {
938 GVal
= I
->second
.first
;
939 ForwardRefValIDs
.erase(I
);
943 // Okay, create the alias but do not insert it into the module yet.
944 std::unique_ptr
<GlobalIndirectSymbol
> GA
;
946 GA
.reset(GlobalAlias::create(Ty
, AddrSpace
,
947 (GlobalValue::LinkageTypes
)Linkage
, Name
,
948 Aliasee
, /*Parent*/ nullptr));
950 GA
.reset(GlobalIFunc::create(Ty
, AddrSpace
,
951 (GlobalValue::LinkageTypes
)Linkage
, Name
,
952 Aliasee
, /*Parent*/ nullptr));
953 GA
->setThreadLocalMode(TLM
);
954 GA
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
955 GA
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
956 GA
->setUnnamedAddr(UnnamedAddr
);
957 maybeSetDSOLocal(DSOLocal
, *GA
);
960 NumberedVals
.push_back(GA
.get());
963 // Verify that types agree.
964 if (GVal
->getType() != GA
->getType())
967 "forward reference and definition of alias have different types");
969 // If they agree, just RAUW the old value with the alias and remove the
971 GVal
->replaceAllUsesWith(GA
.get());
972 GVal
->eraseFromParent();
975 // Insert into the module, we know its name won't collide now.
977 M
->getAliasList().push_back(cast
<GlobalAlias
>(GA
.get()));
979 M
->getIFuncList().push_back(cast
<GlobalIFunc
>(GA
.get()));
980 assert(GA
->getName() == Name
&& "Should not be a name conflict!");
982 // The module owns this now
989 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
990 /// OptionalVisibility OptionalDLLStorageClass
991 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
992 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
993 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
994 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
995 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
996 /// Const OptionalAttrs
998 /// Everything up to and including OptionalUnnamedAddr has been parsed
1001 bool LLParser::ParseGlobal(const std::string
&Name
, LocTy NameLoc
,
1002 unsigned Linkage
, bool HasLinkage
,
1003 unsigned Visibility
, unsigned DLLStorageClass
,
1004 bool DSOLocal
, GlobalVariable::ThreadLocalMode TLM
,
1005 GlobalVariable::UnnamedAddr UnnamedAddr
) {
1006 if (!isValidVisibilityForLinkage(Visibility
, Linkage
))
1007 return Error(NameLoc
,
1008 "symbol with local linkage must have default visibility");
1011 bool IsConstant
, IsExternallyInitialized
;
1012 LocTy IsExternallyInitializedLoc
;
1016 if (ParseOptionalAddrSpace(AddrSpace
) ||
1017 ParseOptionalToken(lltok::kw_externally_initialized
,
1018 IsExternallyInitialized
,
1019 &IsExternallyInitializedLoc
) ||
1020 ParseGlobalType(IsConstant
) ||
1021 ParseType(Ty
, TyLoc
))
1024 // If the linkage is specified and is external, then no initializer is
1026 Constant
*Init
= nullptr;
1028 !GlobalValue::isValidDeclarationLinkage(
1029 (GlobalValue::LinkageTypes
)Linkage
)) {
1030 if (ParseGlobalValue(Ty
, Init
))
1034 if (Ty
->isFunctionTy() || !PointerType::isValidElementType(Ty
))
1035 return Error(TyLoc
, "invalid type for global variable");
1037 GlobalValue
*GVal
= nullptr;
1039 // See if the global was forward referenced, if so, use the global.
1040 if (!Name
.empty()) {
1041 GVal
= M
->getNamedValue(Name
);
1043 if (!ForwardRefVals
.erase(Name
))
1044 return Error(NameLoc
, "redefinition of global '@" + Name
+ "'");
1047 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
1048 if (I
!= ForwardRefValIDs
.end()) {
1049 GVal
= I
->second
.first
;
1050 ForwardRefValIDs
.erase(I
);
1056 GV
= new GlobalVariable(*M
, Ty
, false, GlobalValue::ExternalLinkage
, nullptr,
1057 Name
, nullptr, GlobalVariable::NotThreadLocal
,
1060 if (GVal
->getValueType() != Ty
)
1062 "forward reference and definition of global have different types");
1064 GV
= cast
<GlobalVariable
>(GVal
);
1066 // Move the forward-reference to the correct spot in the module.
1067 M
->getGlobalList().splice(M
->global_end(), M
->getGlobalList(), GV
);
1071 NumberedVals
.push_back(GV
);
1073 // Set the parsed properties on the global.
1075 GV
->setInitializer(Init
);
1076 GV
->setConstant(IsConstant
);
1077 GV
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
1078 maybeSetDSOLocal(DSOLocal
, *GV
);
1079 GV
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
1080 GV
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
1081 GV
->setExternallyInitialized(IsExternallyInitialized
);
1082 GV
->setThreadLocalMode(TLM
);
1083 GV
->setUnnamedAddr(UnnamedAddr
);
1085 // Parse attributes on the global.
1086 while (Lex
.getKind() == lltok::comma
) {
1089 if (Lex
.getKind() == lltok::kw_section
) {
1091 GV
->setSection(Lex
.getStrVal());
1092 if (ParseToken(lltok::StringConstant
, "expected global section string"))
1094 } else if (Lex
.getKind() == lltok::kw_align
) {
1096 if (ParseOptionalAlignment(Alignment
)) return true;
1097 GV
->setAlignment(Alignment
);
1098 } else if (Lex
.getKind() == lltok::MetadataVar
) {
1099 if (ParseGlobalObjectMetadataAttachment(*GV
))
1103 if (parseOptionalComdat(Name
, C
))
1108 return TokError("unknown global variable property!");
1114 std::vector
<unsigned> FwdRefAttrGrps
;
1115 if (ParseFnAttributeValuePairs(Attrs
, FwdRefAttrGrps
, false, BuiltinLoc
))
1117 if (Attrs
.hasAttributes() || !FwdRefAttrGrps
.empty()) {
1118 GV
->setAttributes(AttributeSet::get(Context
, Attrs
));
1119 ForwardRefAttrGroups
[GV
] = FwdRefAttrGrps
;
1125 /// ParseUnnamedAttrGrp
1126 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1127 bool LLParser::ParseUnnamedAttrGrp() {
1128 assert(Lex
.getKind() == lltok::kw_attributes
);
1129 LocTy AttrGrpLoc
= Lex
.getLoc();
1132 if (Lex
.getKind() != lltok::AttrGrpID
)
1133 return TokError("expected attribute group id");
1135 unsigned VarID
= Lex
.getUIntVal();
1136 std::vector
<unsigned> unused
;
1140 if (ParseToken(lltok::equal
, "expected '=' here") ||
1141 ParseToken(lltok::lbrace
, "expected '{' here") ||
1142 ParseFnAttributeValuePairs(NumberedAttrBuilders
[VarID
], unused
, true,
1144 ParseToken(lltok::rbrace
, "expected end of attribute group"))
1147 if (!NumberedAttrBuilders
[VarID
].hasAttributes())
1148 return Error(AttrGrpLoc
, "attribute group has no attributes");
1153 /// ParseFnAttributeValuePairs
1154 /// ::= <attr> | <attr> '=' <value>
1155 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder
&B
,
1156 std::vector
<unsigned> &FwdRefAttrGrps
,
1157 bool inAttrGrp
, LocTy
&BuiltinLoc
) {
1158 bool HaveError
= false;
1163 lltok::Kind Token
= Lex
.getKind();
1164 if (Token
== lltok::kw_builtin
)
1165 BuiltinLoc
= Lex
.getLoc();
1168 if (!inAttrGrp
) return HaveError
;
1169 return Error(Lex
.getLoc(), "unterminated attribute group");
1174 case lltok::AttrGrpID
: {
1175 // Allow a function to reference an attribute group:
1177 // define void @foo() #1 { ... }
1181 "cannot have an attribute group reference in an attribute group");
1183 unsigned AttrGrpNum
= Lex
.getUIntVal();
1184 if (inAttrGrp
) break;
1186 // Save the reference to the attribute group. We'll fill it in later.
1187 FwdRefAttrGrps
.push_back(AttrGrpNum
);
1190 // Target-dependent attributes:
1191 case lltok::StringConstant
: {
1192 if (ParseStringAttribute(B
))
1197 // Target-independent attributes:
1198 case lltok::kw_align
: {
1199 // As a hack, we allow function alignment to be initially parsed as an
1200 // attribute on a function declaration/definition or added to an attribute
1201 // group and later moved to the alignment field.
1205 if (ParseToken(lltok::equal
, "expected '=' here") ||
1206 ParseUInt32(Alignment
))
1209 if (ParseOptionalAlignment(Alignment
))
1212 B
.addAlignmentAttr(Alignment
);
1215 case lltok::kw_alignstack
: {
1219 if (ParseToken(lltok::equal
, "expected '=' here") ||
1220 ParseUInt32(Alignment
))
1223 if (ParseOptionalStackAlignment(Alignment
))
1226 B
.addStackAlignmentAttr(Alignment
);
1229 case lltok::kw_allocsize
: {
1230 unsigned ElemSizeArg
;
1231 Optional
<unsigned> NumElemsArg
;
1232 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1233 if (parseAllocSizeArguments(ElemSizeArg
, NumElemsArg
))
1235 B
.addAllocSizeAttr(ElemSizeArg
, NumElemsArg
);
1238 case lltok::kw_alwaysinline
: B
.addAttribute(Attribute::AlwaysInline
); break;
1239 case lltok::kw_argmemonly
: B
.addAttribute(Attribute::ArgMemOnly
); break;
1240 case lltok::kw_builtin
: B
.addAttribute(Attribute::Builtin
); break;
1241 case lltok::kw_cold
: B
.addAttribute(Attribute::Cold
); break;
1242 case lltok::kw_convergent
: B
.addAttribute(Attribute::Convergent
); break;
1243 case lltok::kw_inaccessiblememonly
:
1244 B
.addAttribute(Attribute::InaccessibleMemOnly
); break;
1245 case lltok::kw_inaccessiblemem_or_argmemonly
:
1246 B
.addAttribute(Attribute::InaccessibleMemOrArgMemOnly
); break;
1247 case lltok::kw_inlinehint
: B
.addAttribute(Attribute::InlineHint
); break;
1248 case lltok::kw_jumptable
: B
.addAttribute(Attribute::JumpTable
); break;
1249 case lltok::kw_minsize
: B
.addAttribute(Attribute::MinSize
); break;
1250 case lltok::kw_naked
: B
.addAttribute(Attribute::Naked
); break;
1251 case lltok::kw_nobuiltin
: B
.addAttribute(Attribute::NoBuiltin
); break;
1252 case lltok::kw_noduplicate
: B
.addAttribute(Attribute::NoDuplicate
); break;
1253 case lltok::kw_noimplicitfloat
:
1254 B
.addAttribute(Attribute::NoImplicitFloat
); break;
1255 case lltok::kw_noinline
: B
.addAttribute(Attribute::NoInline
); break;
1256 case lltok::kw_nonlazybind
: B
.addAttribute(Attribute::NonLazyBind
); break;
1257 case lltok::kw_noredzone
: B
.addAttribute(Attribute::NoRedZone
); break;
1258 case lltok::kw_noreturn
: B
.addAttribute(Attribute::NoReturn
); break;
1259 case lltok::kw_nocf_check
: B
.addAttribute(Attribute::NoCfCheck
); break;
1260 case lltok::kw_norecurse
: B
.addAttribute(Attribute::NoRecurse
); break;
1261 case lltok::kw_nounwind
: B
.addAttribute(Attribute::NoUnwind
); break;
1262 case lltok::kw_optforfuzzing
:
1263 B
.addAttribute(Attribute::OptForFuzzing
); break;
1264 case lltok::kw_optnone
: B
.addAttribute(Attribute::OptimizeNone
); break;
1265 case lltok::kw_optsize
: B
.addAttribute(Attribute::OptimizeForSize
); break;
1266 case lltok::kw_readnone
: B
.addAttribute(Attribute::ReadNone
); break;
1267 case lltok::kw_readonly
: B
.addAttribute(Attribute::ReadOnly
); break;
1268 case lltok::kw_returns_twice
:
1269 B
.addAttribute(Attribute::ReturnsTwice
); break;
1270 case lltok::kw_speculatable
: B
.addAttribute(Attribute::Speculatable
); break;
1271 case lltok::kw_ssp
: B
.addAttribute(Attribute::StackProtect
); break;
1272 case lltok::kw_sspreq
: B
.addAttribute(Attribute::StackProtectReq
); break;
1273 case lltok::kw_sspstrong
:
1274 B
.addAttribute(Attribute::StackProtectStrong
); break;
1275 case lltok::kw_safestack
: B
.addAttribute(Attribute::SafeStack
); break;
1276 case lltok::kw_shadowcallstack
:
1277 B
.addAttribute(Attribute::ShadowCallStack
); break;
1278 case lltok::kw_sanitize_address
:
1279 B
.addAttribute(Attribute::SanitizeAddress
); break;
1280 case lltok::kw_sanitize_hwaddress
:
1281 B
.addAttribute(Attribute::SanitizeHWAddress
); break;
1282 case lltok::kw_sanitize_thread
:
1283 B
.addAttribute(Attribute::SanitizeThread
); break;
1284 case lltok::kw_sanitize_memory
:
1285 B
.addAttribute(Attribute::SanitizeMemory
); break;
1286 case lltok::kw_speculative_load_hardening
:
1287 B
.addAttribute(Attribute::SpeculativeLoadHardening
);
1289 case lltok::kw_strictfp
: B
.addAttribute(Attribute::StrictFP
); break;
1290 case lltok::kw_uwtable
: B
.addAttribute(Attribute::UWTable
); break;
1291 case lltok::kw_writeonly
: B
.addAttribute(Attribute::WriteOnly
); break;
1294 case lltok::kw_inreg
:
1295 case lltok::kw_signext
:
1296 case lltok::kw_zeroext
:
1299 "invalid use of attribute on a function");
1301 case lltok::kw_byval
:
1302 case lltok::kw_dereferenceable
:
1303 case lltok::kw_dereferenceable_or_null
:
1304 case lltok::kw_inalloca
:
1305 case lltok::kw_nest
:
1306 case lltok::kw_noalias
:
1307 case lltok::kw_nocapture
:
1308 case lltok::kw_nonnull
:
1309 case lltok::kw_returned
:
1310 case lltok::kw_sret
:
1311 case lltok::kw_swifterror
:
1312 case lltok::kw_swiftself
:
1313 case lltok::kw_immarg
:
1316 "invalid use of parameter-only attribute on a function");
1324 //===----------------------------------------------------------------------===//
1325 // GlobalValue Reference/Resolution Routines.
1326 //===----------------------------------------------------------------------===//
1328 static inline GlobalValue
*createGlobalFwdRef(Module
*M
, PointerType
*PTy
,
1329 const std::string
&Name
) {
1330 if (auto *FT
= dyn_cast
<FunctionType
>(PTy
->getElementType()))
1331 return Function::Create(FT
, GlobalValue::ExternalWeakLinkage
,
1332 PTy
->getAddressSpace(), Name
, M
);
1334 return new GlobalVariable(*M
, PTy
->getElementType(), false,
1335 GlobalValue::ExternalWeakLinkage
, nullptr, Name
,
1336 nullptr, GlobalVariable::NotThreadLocal
,
1337 PTy
->getAddressSpace());
1340 Value
*LLParser::checkValidVariableType(LocTy Loc
, const Twine
&Name
, Type
*Ty
,
1341 Value
*Val
, bool IsCall
) {
1342 if (Val
->getType() == Ty
)
1344 // For calls we also accept variables in the program address space.
1345 Type
*SuggestedTy
= Ty
;
1346 if (IsCall
&& isa
<PointerType
>(Ty
)) {
1347 Type
*TyInProgAS
= cast
<PointerType
>(Ty
)->getElementType()->getPointerTo(
1348 M
->getDataLayout().getProgramAddressSpace());
1349 SuggestedTy
= TyInProgAS
;
1350 if (Val
->getType() == TyInProgAS
)
1353 if (Ty
->isLabelTy())
1354 Error(Loc
, "'" + Name
+ "' is not a basic block");
1356 Error(Loc
, "'" + Name
+ "' defined with type '" +
1357 getTypeString(Val
->getType()) + "' but expected '" +
1358 getTypeString(SuggestedTy
) + "'");
1362 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1363 /// forward reference record if needed. This can return null if the value
1364 /// exists but does not have the right type.
1365 GlobalValue
*LLParser::GetGlobalVal(const std::string
&Name
, Type
*Ty
,
1366 LocTy Loc
, bool IsCall
) {
1367 PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
1369 Error(Loc
, "global variable reference must have pointer type");
1373 // Look this name up in the normal function symbol table.
1375 cast_or_null
<GlobalValue
>(M
->getValueSymbolTable().lookup(Name
));
1377 // If this is a forward reference for the value, see if we already created a
1378 // forward ref record.
1380 auto I
= ForwardRefVals
.find(Name
);
1381 if (I
!= ForwardRefVals
.end())
1382 Val
= I
->second
.first
;
1385 // If we have the value in the symbol table or fwd-ref table, return it.
1387 return cast_or_null
<GlobalValue
>(
1388 checkValidVariableType(Loc
, "@" + Name
, Ty
, Val
, IsCall
));
1390 // Otherwise, create a new forward reference for this value and remember it.
1391 GlobalValue
*FwdVal
= createGlobalFwdRef(M
, PTy
, Name
);
1392 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
1396 GlobalValue
*LLParser::GetGlobalVal(unsigned ID
, Type
*Ty
, LocTy Loc
,
1398 PointerType
*PTy
= dyn_cast
<PointerType
>(Ty
);
1400 Error(Loc
, "global variable reference must have pointer type");
1404 GlobalValue
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : nullptr;
1406 // If this is a forward reference for the value, see if we already created a
1407 // forward ref record.
1409 auto I
= ForwardRefValIDs
.find(ID
);
1410 if (I
!= ForwardRefValIDs
.end())
1411 Val
= I
->second
.first
;
1414 // If we have the value in the symbol table or fwd-ref table, return it.
1416 return cast_or_null
<GlobalValue
>(
1417 checkValidVariableType(Loc
, "@" + Twine(ID
), Ty
, Val
, IsCall
));
1419 // Otherwise, create a new forward reference for this value and remember it.
1420 GlobalValue
*FwdVal
= createGlobalFwdRef(M
, PTy
, "");
1421 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
1425 //===----------------------------------------------------------------------===//
1426 // Comdat Reference/Resolution Routines.
1427 //===----------------------------------------------------------------------===//
1429 Comdat
*LLParser::getComdat(const std::string
&Name
, LocTy Loc
) {
1430 // Look this name up in the comdat symbol table.
1431 Module::ComdatSymTabType
&ComdatSymTab
= M
->getComdatSymbolTable();
1432 Module::ComdatSymTabType::iterator I
= ComdatSymTab
.find(Name
);
1433 if (I
!= ComdatSymTab
.end())
1436 // Otherwise, create a new forward reference for this value and remember it.
1437 Comdat
*C
= M
->getOrInsertComdat(Name
);
1438 ForwardRefComdats
[Name
] = Loc
;
1442 //===----------------------------------------------------------------------===//
1444 //===----------------------------------------------------------------------===//
1446 /// ParseToken - If the current token has the specified kind, eat it and return
1447 /// success. Otherwise, emit the specified error and return failure.
1448 bool LLParser::ParseToken(lltok::Kind T
, const char *ErrMsg
) {
1449 if (Lex
.getKind() != T
)
1450 return TokError(ErrMsg
);
1455 /// ParseStringConstant
1456 /// ::= StringConstant
1457 bool LLParser::ParseStringConstant(std::string
&Result
) {
1458 if (Lex
.getKind() != lltok::StringConstant
)
1459 return TokError("expected string constant");
1460 Result
= Lex
.getStrVal();
1467 bool LLParser::ParseUInt32(uint32_t &Val
) {
1468 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
1469 return TokError("expected integer");
1470 uint64_t Val64
= Lex
.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL
+1);
1471 if (Val64
!= unsigned(Val64
))
1472 return TokError("expected 32-bit integer (too large)");
1480 bool LLParser::ParseUInt64(uint64_t &Val
) {
1481 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
1482 return TokError("expected integer");
1483 Val
= Lex
.getAPSIntVal().getLimitedValue();
1489 /// := 'localdynamic'
1490 /// := 'initialexec'
1492 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode
&TLM
) {
1493 switch (Lex
.getKind()) {
1495 return TokError("expected localdynamic, initialexec or localexec");
1496 case lltok::kw_localdynamic
:
1497 TLM
= GlobalVariable::LocalDynamicTLSModel
;
1499 case lltok::kw_initialexec
:
1500 TLM
= GlobalVariable::InitialExecTLSModel
;
1502 case lltok::kw_localexec
:
1503 TLM
= GlobalVariable::LocalExecTLSModel
;
1511 /// ParseOptionalThreadLocal
1513 /// := 'thread_local'
1514 /// := 'thread_local' '(' tlsmodel ')'
1515 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode
&TLM
) {
1516 TLM
= GlobalVariable::NotThreadLocal
;
1517 if (!EatIfPresent(lltok::kw_thread_local
))
1520 TLM
= GlobalVariable::GeneralDynamicTLSModel
;
1521 if (Lex
.getKind() == lltok::lparen
) {
1523 return ParseTLSModel(TLM
) ||
1524 ParseToken(lltok::rparen
, "expected ')' after thread local model");
1529 /// ParseOptionalAddrSpace
1531 /// := 'addrspace' '(' uint32 ')'
1532 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace
, unsigned DefaultAS
) {
1533 AddrSpace
= DefaultAS
;
1534 if (!EatIfPresent(lltok::kw_addrspace
))
1536 return ParseToken(lltok::lparen
, "expected '(' in address space") ||
1537 ParseUInt32(AddrSpace
) ||
1538 ParseToken(lltok::rparen
, "expected ')' in address space");
1541 /// ParseStringAttribute
1542 /// := StringConstant
1543 /// := StringConstant '=' StringConstant
1544 bool LLParser::ParseStringAttribute(AttrBuilder
&B
) {
1545 std::string Attr
= Lex
.getStrVal();
1548 if (EatIfPresent(lltok::equal
) && ParseStringConstant(Val
))
1550 B
.addAttribute(Attr
, Val
);
1554 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1555 bool LLParser::ParseOptionalParamAttrs(AttrBuilder
&B
) {
1556 bool HaveError
= false;
1561 lltok::Kind Token
= Lex
.getKind();
1563 default: // End of attributes.
1565 case lltok::StringConstant
: {
1566 if (ParseStringAttribute(B
))
1570 case lltok::kw_align
: {
1572 if (ParseOptionalAlignment(Alignment
))
1574 B
.addAlignmentAttr(Alignment
);
1577 case lltok::kw_byval
: B
.addAttribute(Attribute::ByVal
); break;
1578 case lltok::kw_dereferenceable
: {
1580 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable
, Bytes
))
1582 B
.addDereferenceableAttr(Bytes
);
1585 case lltok::kw_dereferenceable_or_null
: {
1587 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null
, Bytes
))
1589 B
.addDereferenceableOrNullAttr(Bytes
);
1592 case lltok::kw_inalloca
: B
.addAttribute(Attribute::InAlloca
); break;
1593 case lltok::kw_inreg
: B
.addAttribute(Attribute::InReg
); break;
1594 case lltok::kw_nest
: B
.addAttribute(Attribute::Nest
); break;
1595 case lltok::kw_noalias
: B
.addAttribute(Attribute::NoAlias
); break;
1596 case lltok::kw_nocapture
: B
.addAttribute(Attribute::NoCapture
); break;
1597 case lltok::kw_nonnull
: B
.addAttribute(Attribute::NonNull
); break;
1598 case lltok::kw_readnone
: B
.addAttribute(Attribute::ReadNone
); break;
1599 case lltok::kw_readonly
: B
.addAttribute(Attribute::ReadOnly
); break;
1600 case lltok::kw_returned
: B
.addAttribute(Attribute::Returned
); break;
1601 case lltok::kw_signext
: B
.addAttribute(Attribute::SExt
); break;
1602 case lltok::kw_sret
: B
.addAttribute(Attribute::StructRet
); break;
1603 case lltok::kw_swifterror
: B
.addAttribute(Attribute::SwiftError
); break;
1604 case lltok::kw_swiftself
: B
.addAttribute(Attribute::SwiftSelf
); break;
1605 case lltok::kw_writeonly
: B
.addAttribute(Attribute::WriteOnly
); break;
1606 case lltok::kw_zeroext
: B
.addAttribute(Attribute::ZExt
); break;
1607 case lltok::kw_immarg
: B
.addAttribute(Attribute::ImmArg
); break;
1609 case lltok::kw_alignstack
:
1610 case lltok::kw_alwaysinline
:
1611 case lltok::kw_argmemonly
:
1612 case lltok::kw_builtin
:
1613 case lltok::kw_inlinehint
:
1614 case lltok::kw_jumptable
:
1615 case lltok::kw_minsize
:
1616 case lltok::kw_naked
:
1617 case lltok::kw_nobuiltin
:
1618 case lltok::kw_noduplicate
:
1619 case lltok::kw_noimplicitfloat
:
1620 case lltok::kw_noinline
:
1621 case lltok::kw_nonlazybind
:
1622 case lltok::kw_noredzone
:
1623 case lltok::kw_noreturn
:
1624 case lltok::kw_nocf_check
:
1625 case lltok::kw_nounwind
:
1626 case lltok::kw_optforfuzzing
:
1627 case lltok::kw_optnone
:
1628 case lltok::kw_optsize
:
1629 case lltok::kw_returns_twice
:
1630 case lltok::kw_sanitize_address
:
1631 case lltok::kw_sanitize_hwaddress
:
1632 case lltok::kw_sanitize_memory
:
1633 case lltok::kw_sanitize_thread
:
1634 case lltok::kw_speculative_load_hardening
:
1636 case lltok::kw_sspreq
:
1637 case lltok::kw_sspstrong
:
1638 case lltok::kw_safestack
:
1639 case lltok::kw_shadowcallstack
:
1640 case lltok::kw_strictfp
:
1641 case lltok::kw_uwtable
:
1642 HaveError
|= Error(Lex
.getLoc(), "invalid use of function-only attribute");
1650 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1651 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder
&B
) {
1652 bool HaveError
= false;
1657 lltok::Kind Token
= Lex
.getKind();
1659 default: // End of attributes.
1661 case lltok::StringConstant
: {
1662 if (ParseStringAttribute(B
))
1666 case lltok::kw_dereferenceable
: {
1668 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable
, Bytes
))
1670 B
.addDereferenceableAttr(Bytes
);
1673 case lltok::kw_dereferenceable_or_null
: {
1675 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null
, Bytes
))
1677 B
.addDereferenceableOrNullAttr(Bytes
);
1680 case lltok::kw_align
: {
1682 if (ParseOptionalAlignment(Alignment
))
1684 B
.addAlignmentAttr(Alignment
);
1687 case lltok::kw_inreg
: B
.addAttribute(Attribute::InReg
); break;
1688 case lltok::kw_noalias
: B
.addAttribute(Attribute::NoAlias
); break;
1689 case lltok::kw_nonnull
: B
.addAttribute(Attribute::NonNull
); break;
1690 case lltok::kw_signext
: B
.addAttribute(Attribute::SExt
); break;
1691 case lltok::kw_zeroext
: B
.addAttribute(Attribute::ZExt
); break;
1694 case lltok::kw_byval
:
1695 case lltok::kw_inalloca
:
1696 case lltok::kw_nest
:
1697 case lltok::kw_nocapture
:
1698 case lltok::kw_returned
:
1699 case lltok::kw_sret
:
1700 case lltok::kw_swifterror
:
1701 case lltok::kw_swiftself
:
1702 case lltok::kw_immarg
:
1703 HaveError
|= Error(Lex
.getLoc(), "invalid use of parameter-only attribute");
1706 case lltok::kw_alignstack
:
1707 case lltok::kw_alwaysinline
:
1708 case lltok::kw_argmemonly
:
1709 case lltok::kw_builtin
:
1710 case lltok::kw_cold
:
1711 case lltok::kw_inlinehint
:
1712 case lltok::kw_jumptable
:
1713 case lltok::kw_minsize
:
1714 case lltok::kw_naked
:
1715 case lltok::kw_nobuiltin
:
1716 case lltok::kw_noduplicate
:
1717 case lltok::kw_noimplicitfloat
:
1718 case lltok::kw_noinline
:
1719 case lltok::kw_nonlazybind
:
1720 case lltok::kw_noredzone
:
1721 case lltok::kw_noreturn
:
1722 case lltok::kw_nocf_check
:
1723 case lltok::kw_nounwind
:
1724 case lltok::kw_optforfuzzing
:
1725 case lltok::kw_optnone
:
1726 case lltok::kw_optsize
:
1727 case lltok::kw_returns_twice
:
1728 case lltok::kw_sanitize_address
:
1729 case lltok::kw_sanitize_hwaddress
:
1730 case lltok::kw_sanitize_memory
:
1731 case lltok::kw_sanitize_thread
:
1732 case lltok::kw_speculative_load_hardening
:
1734 case lltok::kw_sspreq
:
1735 case lltok::kw_sspstrong
:
1736 case lltok::kw_safestack
:
1737 case lltok::kw_shadowcallstack
:
1738 case lltok::kw_strictfp
:
1739 case lltok::kw_uwtable
:
1740 HaveError
|= Error(Lex
.getLoc(), "invalid use of function-only attribute");
1743 case lltok::kw_readnone
:
1744 case lltok::kw_readonly
:
1745 HaveError
|= Error(Lex
.getLoc(), "invalid use of attribute on return type");
1752 static unsigned parseOptionalLinkageAux(lltok::Kind Kind
, bool &HasLinkage
) {
1757 return GlobalValue::ExternalLinkage
;
1758 case lltok::kw_private
:
1759 return GlobalValue::PrivateLinkage
;
1760 case lltok::kw_internal
:
1761 return GlobalValue::InternalLinkage
;
1762 case lltok::kw_weak
:
1763 return GlobalValue::WeakAnyLinkage
;
1764 case lltok::kw_weak_odr
:
1765 return GlobalValue::WeakODRLinkage
;
1766 case lltok::kw_linkonce
:
1767 return GlobalValue::LinkOnceAnyLinkage
;
1768 case lltok::kw_linkonce_odr
:
1769 return GlobalValue::LinkOnceODRLinkage
;
1770 case lltok::kw_available_externally
:
1771 return GlobalValue::AvailableExternallyLinkage
;
1772 case lltok::kw_appending
:
1773 return GlobalValue::AppendingLinkage
;
1774 case lltok::kw_common
:
1775 return GlobalValue::CommonLinkage
;
1776 case lltok::kw_extern_weak
:
1777 return GlobalValue::ExternalWeakLinkage
;
1778 case lltok::kw_external
:
1779 return GlobalValue::ExternalLinkage
;
1783 /// ParseOptionalLinkage
1790 /// ::= 'linkonce_odr'
1791 /// ::= 'available_externally'
1794 /// ::= 'extern_weak'
1796 bool LLParser::ParseOptionalLinkage(unsigned &Res
, bool &HasLinkage
,
1797 unsigned &Visibility
,
1798 unsigned &DLLStorageClass
,
1800 Res
= parseOptionalLinkageAux(Lex
.getKind(), HasLinkage
);
1803 ParseOptionalDSOLocal(DSOLocal
);
1804 ParseOptionalVisibility(Visibility
);
1805 ParseOptionalDLLStorageClass(DLLStorageClass
);
1807 if (DSOLocal
&& DLLStorageClass
== GlobalValue::DLLImportStorageClass
) {
1808 return Error(Lex
.getLoc(), "dso_location and DLL-StorageClass mismatch");
1814 void LLParser::ParseOptionalDSOLocal(bool &DSOLocal
) {
1815 switch (Lex
.getKind()) {
1819 case lltok::kw_dso_local
:
1823 case lltok::kw_dso_preemptable
:
1830 /// ParseOptionalVisibility
1836 void LLParser::ParseOptionalVisibility(unsigned &Res
) {
1837 switch (Lex
.getKind()) {
1839 Res
= GlobalValue::DefaultVisibility
;
1841 case lltok::kw_default
:
1842 Res
= GlobalValue::DefaultVisibility
;
1844 case lltok::kw_hidden
:
1845 Res
= GlobalValue::HiddenVisibility
;
1847 case lltok::kw_protected
:
1848 Res
= GlobalValue::ProtectedVisibility
;
1854 /// ParseOptionalDLLStorageClass
1859 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res
) {
1860 switch (Lex
.getKind()) {
1862 Res
= GlobalValue::DefaultStorageClass
;
1864 case lltok::kw_dllimport
:
1865 Res
= GlobalValue::DLLImportStorageClass
;
1867 case lltok::kw_dllexport
:
1868 Res
= GlobalValue::DLLExportStorageClass
;
1874 /// ParseOptionalCallingConv
1878 /// ::= 'intel_ocl_bicc'
1880 /// ::= 'x86_stdcallcc'
1881 /// ::= 'x86_fastcallcc'
1882 /// ::= 'x86_thiscallcc'
1883 /// ::= 'x86_vectorcallcc'
1884 /// ::= 'arm_apcscc'
1885 /// ::= 'arm_aapcscc'
1886 /// ::= 'arm_aapcs_vfpcc'
1887 /// ::= 'aarch64_vector_pcs'
1888 /// ::= 'msp430_intrcc'
1889 /// ::= 'avr_intrcc'
1890 /// ::= 'avr_signalcc'
1891 /// ::= 'ptx_kernel'
1892 /// ::= 'ptx_device'
1894 /// ::= 'spir_kernel'
1895 /// ::= 'x86_64_sysvcc'
1897 /// ::= 'webkit_jscc'
1899 /// ::= 'preserve_mostcc'
1900 /// ::= 'preserve_allcc'
1903 /// ::= 'x86_intrcc'
1906 /// ::= 'cxx_fast_tlscc'
1914 /// ::= 'amdgpu_kernel'
1917 bool LLParser::ParseOptionalCallingConv(unsigned &CC
) {
1918 switch (Lex
.getKind()) {
1919 default: CC
= CallingConv::C
; return false;
1920 case lltok::kw_ccc
: CC
= CallingConv::C
; break;
1921 case lltok::kw_fastcc
: CC
= CallingConv::Fast
; break;
1922 case lltok::kw_coldcc
: CC
= CallingConv::Cold
; break;
1923 case lltok::kw_x86_stdcallcc
: CC
= CallingConv::X86_StdCall
; break;
1924 case lltok::kw_x86_fastcallcc
: CC
= CallingConv::X86_FastCall
; break;
1925 case lltok::kw_x86_regcallcc
: CC
= CallingConv::X86_RegCall
; break;
1926 case lltok::kw_x86_thiscallcc
: CC
= CallingConv::X86_ThisCall
; break;
1927 case lltok::kw_x86_vectorcallcc
:CC
= CallingConv::X86_VectorCall
; break;
1928 case lltok::kw_arm_apcscc
: CC
= CallingConv::ARM_APCS
; break;
1929 case lltok::kw_arm_aapcscc
: CC
= CallingConv::ARM_AAPCS
; break;
1930 case lltok::kw_arm_aapcs_vfpcc
:CC
= CallingConv::ARM_AAPCS_VFP
; break;
1931 case lltok::kw_aarch64_vector_pcs
:CC
= CallingConv::AArch64_VectorCall
; break;
1932 case lltok::kw_msp430_intrcc
: CC
= CallingConv::MSP430_INTR
; break;
1933 case lltok::kw_avr_intrcc
: CC
= CallingConv::AVR_INTR
; break;
1934 case lltok::kw_avr_signalcc
: CC
= CallingConv::AVR_SIGNAL
; break;
1935 case lltok::kw_ptx_kernel
: CC
= CallingConv::PTX_Kernel
; break;
1936 case lltok::kw_ptx_device
: CC
= CallingConv::PTX_Device
; break;
1937 case lltok::kw_spir_kernel
: CC
= CallingConv::SPIR_KERNEL
; break;
1938 case lltok::kw_spir_func
: CC
= CallingConv::SPIR_FUNC
; break;
1939 case lltok::kw_intel_ocl_bicc
: CC
= CallingConv::Intel_OCL_BI
; break;
1940 case lltok::kw_x86_64_sysvcc
: CC
= CallingConv::X86_64_SysV
; break;
1941 case lltok::kw_win64cc
: CC
= CallingConv::Win64
; break;
1942 case lltok::kw_webkit_jscc
: CC
= CallingConv::WebKit_JS
; break;
1943 case lltok::kw_anyregcc
: CC
= CallingConv::AnyReg
; break;
1944 case lltok::kw_preserve_mostcc
:CC
= CallingConv::PreserveMost
; break;
1945 case lltok::kw_preserve_allcc
: CC
= CallingConv::PreserveAll
; break;
1946 case lltok::kw_ghccc
: CC
= CallingConv::GHC
; break;
1947 case lltok::kw_swiftcc
: CC
= CallingConv::Swift
; break;
1948 case lltok::kw_x86_intrcc
: CC
= CallingConv::X86_INTR
; break;
1949 case lltok::kw_hhvmcc
: CC
= CallingConv::HHVM
; break;
1950 case lltok::kw_hhvm_ccc
: CC
= CallingConv::HHVM_C
; break;
1951 case lltok::kw_cxx_fast_tlscc
: CC
= CallingConv::CXX_FAST_TLS
; break;
1952 case lltok::kw_amdgpu_vs
: CC
= CallingConv::AMDGPU_VS
; break;
1953 case lltok::kw_amdgpu_ls
: CC
= CallingConv::AMDGPU_LS
; break;
1954 case lltok::kw_amdgpu_hs
: CC
= CallingConv::AMDGPU_HS
; break;
1955 case lltok::kw_amdgpu_es
: CC
= CallingConv::AMDGPU_ES
; break;
1956 case lltok::kw_amdgpu_gs
: CC
= CallingConv::AMDGPU_GS
; break;
1957 case lltok::kw_amdgpu_ps
: CC
= CallingConv::AMDGPU_PS
; break;
1958 case lltok::kw_amdgpu_cs
: CC
= CallingConv::AMDGPU_CS
; break;
1959 case lltok::kw_amdgpu_kernel
: CC
= CallingConv::AMDGPU_KERNEL
; break;
1960 case lltok::kw_cc
: {
1962 return ParseUInt32(CC
);
1970 /// ParseMetadataAttachment
1972 bool LLParser::ParseMetadataAttachment(unsigned &Kind
, MDNode
*&MD
) {
1973 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata attachment");
1975 std::string Name
= Lex
.getStrVal();
1976 Kind
= M
->getMDKindID(Name
);
1979 return ParseMDNode(MD
);
1982 /// ParseInstructionMetadata
1983 /// ::= !dbg !42 (',' !dbg !57)*
1984 bool LLParser::ParseInstructionMetadata(Instruction
&Inst
) {
1986 if (Lex
.getKind() != lltok::MetadataVar
)
1987 return TokError("expected metadata after comma");
1991 if (ParseMetadataAttachment(MDK
, N
))
1994 Inst
.setMetadata(MDK
, N
);
1995 if (MDK
== LLVMContext::MD_tbaa
)
1996 InstsWithTBAATag
.push_back(&Inst
);
1998 // If this is the end of the list, we're done.
1999 } while (EatIfPresent(lltok::comma
));
2003 /// ParseGlobalObjectMetadataAttachment
2005 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject
&GO
) {
2008 if (ParseMetadataAttachment(MDK
, N
))
2011 GO
.addMetadata(MDK
, *N
);
2015 /// ParseOptionalFunctionMetadata
2017 bool LLParser::ParseOptionalFunctionMetadata(Function
&F
) {
2018 while (Lex
.getKind() == lltok::MetadataVar
)
2019 if (ParseGlobalObjectMetadataAttachment(F
))
2024 /// ParseOptionalAlignment
2027 bool LLParser::ParseOptionalAlignment(unsigned &Alignment
) {
2029 if (!EatIfPresent(lltok::kw_align
))
2031 LocTy AlignLoc
= Lex
.getLoc();
2032 if (ParseUInt32(Alignment
)) return true;
2033 if (!isPowerOf2_32(Alignment
))
2034 return Error(AlignLoc
, "alignment is not a power of two");
2035 if (Alignment
> Value::MaximumAlignment
)
2036 return Error(AlignLoc
, "huge alignments are not supported yet");
2040 /// ParseOptionalDerefAttrBytes
2042 /// ::= AttrKind '(' 4 ')'
2044 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2045 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind
,
2047 assert((AttrKind
== lltok::kw_dereferenceable
||
2048 AttrKind
== lltok::kw_dereferenceable_or_null
) &&
2052 if (!EatIfPresent(AttrKind
))
2054 LocTy ParenLoc
= Lex
.getLoc();
2055 if (!EatIfPresent(lltok::lparen
))
2056 return Error(ParenLoc
, "expected '('");
2057 LocTy DerefLoc
= Lex
.getLoc();
2058 if (ParseUInt64(Bytes
)) return true;
2059 ParenLoc
= Lex
.getLoc();
2060 if (!EatIfPresent(lltok::rparen
))
2061 return Error(ParenLoc
, "expected ')'");
2063 return Error(DerefLoc
, "dereferenceable bytes must be non-zero");
2067 /// ParseOptionalCommaAlign
2071 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2073 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment
,
2074 bool &AteExtraComma
) {
2075 AteExtraComma
= false;
2076 while (EatIfPresent(lltok::comma
)) {
2077 // Metadata at the end is an early exit.
2078 if (Lex
.getKind() == lltok::MetadataVar
) {
2079 AteExtraComma
= true;
2083 if (Lex
.getKind() != lltok::kw_align
)
2084 return Error(Lex
.getLoc(), "expected metadata or 'align'");
2086 if (ParseOptionalAlignment(Alignment
)) return true;
2092 /// ParseOptionalCommaAddrSpace
2094 /// ::= ',' addrspace(1)
2096 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2098 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace
,
2100 bool &AteExtraComma
) {
2101 AteExtraComma
= false;
2102 while (EatIfPresent(lltok::comma
)) {
2103 // Metadata at the end is an early exit.
2104 if (Lex
.getKind() == lltok::MetadataVar
) {
2105 AteExtraComma
= true;
2110 if (Lex
.getKind() != lltok::kw_addrspace
)
2111 return Error(Lex
.getLoc(), "expected metadata or 'addrspace'");
2113 if (ParseOptionalAddrSpace(AddrSpace
))
2120 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg
,
2121 Optional
<unsigned> &HowManyArg
) {
2124 auto StartParen
= Lex
.getLoc();
2125 if (!EatIfPresent(lltok::lparen
))
2126 return Error(StartParen
, "expected '('");
2128 if (ParseUInt32(BaseSizeArg
))
2131 if (EatIfPresent(lltok::comma
)) {
2132 auto HowManyAt
= Lex
.getLoc();
2134 if (ParseUInt32(HowMany
))
2136 if (HowMany
== BaseSizeArg
)
2137 return Error(HowManyAt
,
2138 "'allocsize' indices can't refer to the same parameter");
2139 HowManyArg
= HowMany
;
2143 auto EndParen
= Lex
.getLoc();
2144 if (!EatIfPresent(lltok::rparen
))
2145 return Error(EndParen
, "expected ')'");
2149 /// ParseScopeAndOrdering
2150 /// if isAtomic: ::= SyncScope? AtomicOrdering
2153 /// This sets Scope and Ordering to the parsed values.
2154 bool LLParser::ParseScopeAndOrdering(bool isAtomic
, SyncScope::ID
&SSID
,
2155 AtomicOrdering
&Ordering
) {
2159 return ParseScope(SSID
) || ParseOrdering(Ordering
);
2163 /// ::= syncscope("singlethread" | "<target scope>")?
2165 /// This sets synchronization scope ID to the ID of the parsed value.
2166 bool LLParser::ParseScope(SyncScope::ID
&SSID
) {
2167 SSID
= SyncScope::System
;
2168 if (EatIfPresent(lltok::kw_syncscope
)) {
2169 auto StartParenAt
= Lex
.getLoc();
2170 if (!EatIfPresent(lltok::lparen
))
2171 return Error(StartParenAt
, "Expected '(' in syncscope");
2174 auto SSNAt
= Lex
.getLoc();
2175 if (ParseStringConstant(SSN
))
2176 return Error(SSNAt
, "Expected synchronization scope name");
2178 auto EndParenAt
= Lex
.getLoc();
2179 if (!EatIfPresent(lltok::rparen
))
2180 return Error(EndParenAt
, "Expected ')' in syncscope");
2182 SSID
= Context
.getOrInsertSyncScopeID(SSN
);
2189 /// ::= AtomicOrdering
2191 /// This sets Ordering to the parsed value.
2192 bool LLParser::ParseOrdering(AtomicOrdering
&Ordering
) {
2193 switch (Lex
.getKind()) {
2194 default: return TokError("Expected ordering on atomic instruction");
2195 case lltok::kw_unordered
: Ordering
= AtomicOrdering::Unordered
; break;
2196 case lltok::kw_monotonic
: Ordering
= AtomicOrdering::Monotonic
; break;
2197 // Not specified yet:
2198 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2199 case lltok::kw_acquire
: Ordering
= AtomicOrdering::Acquire
; break;
2200 case lltok::kw_release
: Ordering
= AtomicOrdering::Release
; break;
2201 case lltok::kw_acq_rel
: Ordering
= AtomicOrdering::AcquireRelease
; break;
2202 case lltok::kw_seq_cst
:
2203 Ordering
= AtomicOrdering::SequentiallyConsistent
;
2210 /// ParseOptionalStackAlignment
2212 /// ::= 'alignstack' '(' 4 ')'
2213 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment
) {
2215 if (!EatIfPresent(lltok::kw_alignstack
))
2217 LocTy ParenLoc
= Lex
.getLoc();
2218 if (!EatIfPresent(lltok::lparen
))
2219 return Error(ParenLoc
, "expected '('");
2220 LocTy AlignLoc
= Lex
.getLoc();
2221 if (ParseUInt32(Alignment
)) return true;
2222 ParenLoc
= Lex
.getLoc();
2223 if (!EatIfPresent(lltok::rparen
))
2224 return Error(ParenLoc
, "expected ')'");
2225 if (!isPowerOf2_32(Alignment
))
2226 return Error(AlignLoc
, "stack alignment is not a power of two");
2230 /// ParseIndexList - This parses the index list for an insert/extractvalue
2231 /// instruction. This sets AteExtraComma in the case where we eat an extra
2232 /// comma at the end of the line and find that it is followed by metadata.
2233 /// Clients that don't allow metadata can call the version of this function that
2234 /// only takes one argument.
2237 /// ::= (',' uint32)+
2239 bool LLParser::ParseIndexList(SmallVectorImpl
<unsigned> &Indices
,
2240 bool &AteExtraComma
) {
2241 AteExtraComma
= false;
2243 if (Lex
.getKind() != lltok::comma
)
2244 return TokError("expected ',' as start of index list");
2246 while (EatIfPresent(lltok::comma
)) {
2247 if (Lex
.getKind() == lltok::MetadataVar
) {
2248 if (Indices
.empty()) return TokError("expected index");
2249 AteExtraComma
= true;
2253 if (ParseUInt32(Idx
)) return true;
2254 Indices
.push_back(Idx
);
2260 //===----------------------------------------------------------------------===//
2262 //===----------------------------------------------------------------------===//
2264 /// ParseType - Parse a type.
2265 bool LLParser::ParseType(Type
*&Result
, const Twine
&Msg
, bool AllowVoid
) {
2266 SMLoc TypeLoc
= Lex
.getLoc();
2267 switch (Lex
.getKind()) {
2269 return TokError(Msg
);
2271 // Type ::= 'float' | 'void' (etc)
2272 Result
= Lex
.getTyVal();
2276 // Type ::= StructType
2277 if (ParseAnonStructType(Result
, false))
2280 case lltok::lsquare
:
2281 // Type ::= '[' ... ']'
2282 Lex
.Lex(); // eat the lsquare.
2283 if (ParseArrayVectorType(Result
, false))
2286 case lltok::less
: // Either vector or packed struct.
2287 // Type ::= '<' ... '>'
2289 if (Lex
.getKind() == lltok::lbrace
) {
2290 if (ParseAnonStructType(Result
, true) ||
2291 ParseToken(lltok::greater
, "expected '>' at end of packed struct"))
2293 } else if (ParseArrayVectorType(Result
, true))
2296 case lltok::LocalVar
: {
2298 std::pair
<Type
*, LocTy
> &Entry
= NamedTypes
[Lex
.getStrVal()];
2300 // If the type hasn't been defined yet, create a forward definition and
2301 // remember where that forward def'n was seen (in case it never is defined).
2303 Entry
.first
= StructType::create(Context
, Lex
.getStrVal());
2304 Entry
.second
= Lex
.getLoc();
2306 Result
= Entry
.first
;
2311 case lltok::LocalVarID
: {
2313 std::pair
<Type
*, LocTy
> &Entry
= NumberedTypes
[Lex
.getUIntVal()];
2315 // If the type hasn't been defined yet, create a forward definition and
2316 // remember where that forward def'n was seen (in case it never is defined).
2318 Entry
.first
= StructType::create(Context
);
2319 Entry
.second
= Lex
.getLoc();
2321 Result
= Entry
.first
;
2327 // Parse the type suffixes.
2329 switch (Lex
.getKind()) {
2332 if (!AllowVoid
&& Result
->isVoidTy())
2333 return Error(TypeLoc
, "void type only allowed for function results");
2336 // Type ::= Type '*'
2338 if (Result
->isLabelTy())
2339 return TokError("basic block pointers are invalid");
2340 if (Result
->isVoidTy())
2341 return TokError("pointers to void are invalid - use i8* instead");
2342 if (!PointerType::isValidElementType(Result
))
2343 return TokError("pointer to this type is invalid");
2344 Result
= PointerType::getUnqual(Result
);
2348 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2349 case lltok::kw_addrspace
: {
2350 if (Result
->isLabelTy())
2351 return TokError("basic block pointers are invalid");
2352 if (Result
->isVoidTy())
2353 return TokError("pointers to void are invalid; use i8* instead");
2354 if (!PointerType::isValidElementType(Result
))
2355 return TokError("pointer to this type is invalid");
2357 if (ParseOptionalAddrSpace(AddrSpace
) ||
2358 ParseToken(lltok::star
, "expected '*' in address space"))
2361 Result
= PointerType::get(Result
, AddrSpace
);
2365 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2367 if (ParseFunctionType(Result
))
2374 /// ParseParameterList
2376 /// ::= '(' Arg (',' Arg)* ')'
2378 /// ::= Type OptionalAttributes Value OptionalAttributes
2379 bool LLParser::ParseParameterList(SmallVectorImpl
<ParamInfo
> &ArgList
,
2380 PerFunctionState
&PFS
, bool IsMustTailCall
,
2381 bool InVarArgsFunc
) {
2382 if (ParseToken(lltok::lparen
, "expected '(' in call"))
2385 while (Lex
.getKind() != lltok::rparen
) {
2386 // If this isn't the first argument, we need a comma.
2387 if (!ArgList
.empty() &&
2388 ParseToken(lltok::comma
, "expected ',' in argument list"))
2391 // Parse an ellipsis if this is a musttail call in a variadic function.
2392 if (Lex
.getKind() == lltok::dotdotdot
) {
2393 const char *Msg
= "unexpected ellipsis in argument list for ";
2394 if (!IsMustTailCall
)
2395 return TokError(Twine(Msg
) + "non-musttail call");
2397 return TokError(Twine(Msg
) + "musttail call in non-varargs function");
2398 Lex
.Lex(); // Lex the '...', it is purely for readability.
2399 return ParseToken(lltok::rparen
, "expected ')' at end of argument list");
2402 // Parse the argument.
2404 Type
*ArgTy
= nullptr;
2405 AttrBuilder ArgAttrs
;
2407 if (ParseType(ArgTy
, ArgLoc
))
2410 if (ArgTy
->isMetadataTy()) {
2411 if (ParseMetadataAsValue(V
, PFS
))
2414 // Otherwise, handle normal operands.
2415 if (ParseOptionalParamAttrs(ArgAttrs
) || ParseValue(ArgTy
, V
, PFS
))
2418 ArgList
.push_back(ParamInfo(
2419 ArgLoc
, V
, AttributeSet::get(V
->getContext(), ArgAttrs
)));
2422 if (IsMustTailCall
&& InVarArgsFunc
)
2423 return TokError("expected '...' at end of argument list for musttail call "
2424 "in varargs function");
2426 Lex
.Lex(); // Lex the ')'.
2430 /// ParseOptionalOperandBundles
2432 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2435 /// ::= bundle-tag '(' ')'
2436 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2438 /// bundle-tag ::= String Constant
2439 bool LLParser::ParseOptionalOperandBundles(
2440 SmallVectorImpl
<OperandBundleDef
> &BundleList
, PerFunctionState
&PFS
) {
2441 LocTy BeginLoc
= Lex
.getLoc();
2442 if (!EatIfPresent(lltok::lsquare
))
2445 while (Lex
.getKind() != lltok::rsquare
) {
2446 // If this isn't the first operand bundle, we need a comma.
2447 if (!BundleList
.empty() &&
2448 ParseToken(lltok::comma
, "expected ',' in input list"))
2452 if (ParseStringConstant(Tag
))
2455 if (ParseToken(lltok::lparen
, "expected '(' in operand bundle"))
2458 std::vector
<Value
*> Inputs
;
2459 while (Lex
.getKind() != lltok::rparen
) {
2460 // If this isn't the first input, we need a comma.
2461 if (!Inputs
.empty() &&
2462 ParseToken(lltok::comma
, "expected ',' in input list"))
2466 Value
*Input
= nullptr;
2467 if (ParseType(Ty
) || ParseValue(Ty
, Input
, PFS
))
2469 Inputs
.push_back(Input
);
2472 BundleList
.emplace_back(std::move(Tag
), std::move(Inputs
));
2474 Lex
.Lex(); // Lex the ')'.
2477 if (BundleList
.empty())
2478 return Error(BeginLoc
, "operand bundle set must not be empty");
2480 Lex
.Lex(); // Lex the ']'.
2484 /// ParseArgumentList - Parse the argument list for a function type or function
2486 /// ::= '(' ArgTypeListI ')'
2490 /// ::= ArgTypeList ',' '...'
2491 /// ::= ArgType (',' ArgType)*
2493 bool LLParser::ParseArgumentList(SmallVectorImpl
<ArgInfo
> &ArgList
,
2496 assert(Lex
.getKind() == lltok::lparen
);
2497 Lex
.Lex(); // eat the (.
2499 if (Lex
.getKind() == lltok::rparen
) {
2501 } else if (Lex
.getKind() == lltok::dotdotdot
) {
2505 LocTy TypeLoc
= Lex
.getLoc();
2506 Type
*ArgTy
= nullptr;
2510 if (ParseType(ArgTy
) ||
2511 ParseOptionalParamAttrs(Attrs
)) return true;
2513 if (ArgTy
->isVoidTy())
2514 return Error(TypeLoc
, "argument can not have void type");
2516 if (Lex
.getKind() == lltok::LocalVar
) {
2517 Name
= Lex
.getStrVal();
2521 if (!FunctionType::isValidArgumentType(ArgTy
))
2522 return Error(TypeLoc
, "invalid type for function argument");
2524 ArgList
.emplace_back(TypeLoc
, ArgTy
,
2525 AttributeSet::get(ArgTy
->getContext(), Attrs
),
2528 while (EatIfPresent(lltok::comma
)) {
2529 // Handle ... at end of arg list.
2530 if (EatIfPresent(lltok::dotdotdot
)) {
2535 // Otherwise must be an argument type.
2536 TypeLoc
= Lex
.getLoc();
2537 if (ParseType(ArgTy
) || ParseOptionalParamAttrs(Attrs
)) return true;
2539 if (ArgTy
->isVoidTy())
2540 return Error(TypeLoc
, "argument can not have void type");
2542 if (Lex
.getKind() == lltok::LocalVar
) {
2543 Name
= Lex
.getStrVal();
2549 if (!ArgTy
->isFirstClassType())
2550 return Error(TypeLoc
, "invalid type for function argument");
2552 ArgList
.emplace_back(TypeLoc
, ArgTy
,
2553 AttributeSet::get(ArgTy
->getContext(), Attrs
),
2558 return ParseToken(lltok::rparen
, "expected ')' at end of argument list");
2561 /// ParseFunctionType
2562 /// ::= Type ArgumentList OptionalAttrs
2563 bool LLParser::ParseFunctionType(Type
*&Result
) {
2564 assert(Lex
.getKind() == lltok::lparen
);
2566 if (!FunctionType::isValidReturnType(Result
))
2567 return TokError("invalid function return type");
2569 SmallVector
<ArgInfo
, 8> ArgList
;
2571 if (ParseArgumentList(ArgList
, isVarArg
))
2574 // Reject names on the arguments lists.
2575 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
2576 if (!ArgList
[i
].Name
.empty())
2577 return Error(ArgList
[i
].Loc
, "argument name invalid in function type");
2578 if (ArgList
[i
].Attrs
.hasAttributes())
2579 return Error(ArgList
[i
].Loc
,
2580 "argument attributes invalid in function type");
2583 SmallVector
<Type
*, 16> ArgListTy
;
2584 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
2585 ArgListTy
.push_back(ArgList
[i
].Ty
);
2587 Result
= FunctionType::get(Result
, ArgListTy
, isVarArg
);
2591 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2593 bool LLParser::ParseAnonStructType(Type
*&Result
, bool Packed
) {
2594 SmallVector
<Type
*, 8> Elts
;
2595 if (ParseStructBody(Elts
)) return true;
2597 Result
= StructType::get(Context
, Elts
, Packed
);
2601 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2602 bool LLParser::ParseStructDefinition(SMLoc TypeLoc
, StringRef Name
,
2603 std::pair
<Type
*, LocTy
> &Entry
,
2605 // If the type was already defined, diagnose the redefinition.
2606 if (Entry
.first
&& !Entry
.second
.isValid())
2607 return Error(TypeLoc
, "redefinition of type");
2609 // If we have opaque, just return without filling in the definition for the
2610 // struct. This counts as a definition as far as the .ll file goes.
2611 if (EatIfPresent(lltok::kw_opaque
)) {
2612 // This type is being defined, so clear the location to indicate this.
2613 Entry
.second
= SMLoc();
2615 // If this type number has never been uttered, create it.
2617 Entry
.first
= StructType::create(Context
, Name
);
2618 ResultTy
= Entry
.first
;
2622 // If the type starts with '<', then it is either a packed struct or a vector.
2623 bool isPacked
= EatIfPresent(lltok::less
);
2625 // If we don't have a struct, then we have a random type alias, which we
2626 // accept for compatibility with old files. These types are not allowed to be
2627 // forward referenced and not allowed to be recursive.
2628 if (Lex
.getKind() != lltok::lbrace
) {
2630 return Error(TypeLoc
, "forward references to non-struct type");
2634 return ParseArrayVectorType(ResultTy
, true);
2635 return ParseType(ResultTy
);
2638 // This type is being defined, so clear the location to indicate this.
2639 Entry
.second
= SMLoc();
2641 // If this type number has never been uttered, create it.
2643 Entry
.first
= StructType::create(Context
, Name
);
2645 StructType
*STy
= cast
<StructType
>(Entry
.first
);
2647 SmallVector
<Type
*, 8> Body
;
2648 if (ParseStructBody(Body
) ||
2649 (isPacked
&& ParseToken(lltok::greater
, "expected '>' in packed struct")))
2652 STy
->setBody(Body
, isPacked
);
2657 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2660 /// ::= '{' Type (',' Type)* '}'
2661 /// ::= '<' '{' '}' '>'
2662 /// ::= '<' '{' Type (',' Type)* '}' '>'
2663 bool LLParser::ParseStructBody(SmallVectorImpl
<Type
*> &Body
) {
2664 assert(Lex
.getKind() == lltok::lbrace
);
2665 Lex
.Lex(); // Consume the '{'
2667 // Handle the empty struct.
2668 if (EatIfPresent(lltok::rbrace
))
2671 LocTy EltTyLoc
= Lex
.getLoc();
2673 if (ParseType(Ty
)) return true;
2676 if (!StructType::isValidElementType(Ty
))
2677 return Error(EltTyLoc
, "invalid element type for struct");
2679 while (EatIfPresent(lltok::comma
)) {
2680 EltTyLoc
= Lex
.getLoc();
2681 if (ParseType(Ty
)) return true;
2683 if (!StructType::isValidElementType(Ty
))
2684 return Error(EltTyLoc
, "invalid element type for struct");
2689 return ParseToken(lltok::rbrace
, "expected '}' at end of struct");
2692 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2693 /// token has already been consumed.
2695 /// ::= '[' APSINTVAL 'x' Types ']'
2696 /// ::= '<' APSINTVAL 'x' Types '>'
2697 bool LLParser::ParseArrayVectorType(Type
*&Result
, bool isVector
) {
2698 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned() ||
2699 Lex
.getAPSIntVal().getBitWidth() > 64)
2700 return TokError("expected number in address space");
2702 LocTy SizeLoc
= Lex
.getLoc();
2703 uint64_t Size
= Lex
.getAPSIntVal().getZExtValue();
2706 if (ParseToken(lltok::kw_x
, "expected 'x' after element count"))
2709 LocTy TypeLoc
= Lex
.getLoc();
2710 Type
*EltTy
= nullptr;
2711 if (ParseType(EltTy
)) return true;
2713 if (ParseToken(isVector
? lltok::greater
: lltok::rsquare
,
2714 "expected end of sequential type"))
2719 return Error(SizeLoc
, "zero element vector is illegal");
2720 if ((unsigned)Size
!= Size
)
2721 return Error(SizeLoc
, "size too large for vector");
2722 if (!VectorType::isValidElementType(EltTy
))
2723 return Error(TypeLoc
, "invalid vector element type");
2724 Result
= VectorType::get(EltTy
, unsigned(Size
));
2726 if (!ArrayType::isValidElementType(EltTy
))
2727 return Error(TypeLoc
, "invalid array element type");
2728 Result
= ArrayType::get(EltTy
, Size
);
2733 //===----------------------------------------------------------------------===//
2734 // Function Semantic Analysis.
2735 //===----------------------------------------------------------------------===//
2737 LLParser::PerFunctionState::PerFunctionState(LLParser
&p
, Function
&f
,
2739 : P(p
), F(f
), FunctionNumber(functionNumber
) {
2741 // Insert unnamed arguments into the NumberedVals list.
2742 for (Argument
&A
: F
.args())
2744 NumberedVals
.push_back(&A
);
2747 LLParser::PerFunctionState::~PerFunctionState() {
2748 // If there were any forward referenced non-basicblock values, delete them.
2750 for (const auto &P
: ForwardRefVals
) {
2751 if (isa
<BasicBlock
>(P
.second
.first
))
2753 P
.second
.first
->replaceAllUsesWith(
2754 UndefValue::get(P
.second
.first
->getType()));
2755 P
.second
.first
->deleteValue();
2758 for (const auto &P
: ForwardRefValIDs
) {
2759 if (isa
<BasicBlock
>(P
.second
.first
))
2761 P
.second
.first
->replaceAllUsesWith(
2762 UndefValue::get(P
.second
.first
->getType()));
2763 P
.second
.first
->deleteValue();
2767 bool LLParser::PerFunctionState::FinishFunction() {
2768 if (!ForwardRefVals
.empty())
2769 return P
.Error(ForwardRefVals
.begin()->second
.second
,
2770 "use of undefined value '%" + ForwardRefVals
.begin()->first
+
2772 if (!ForwardRefValIDs
.empty())
2773 return P
.Error(ForwardRefValIDs
.begin()->second
.second
,
2774 "use of undefined value '%" +
2775 Twine(ForwardRefValIDs
.begin()->first
) + "'");
2779 /// GetVal - Get a value with the specified name or ID, creating a
2780 /// forward reference record if needed. This can return null if the value
2781 /// exists but does not have the right type.
2782 Value
*LLParser::PerFunctionState::GetVal(const std::string
&Name
, Type
*Ty
,
2783 LocTy Loc
, bool IsCall
) {
2784 // Look this name up in the normal function symbol table.
2785 Value
*Val
= F
.getValueSymbolTable()->lookup(Name
);
2787 // If this is a forward reference for the value, see if we already created a
2788 // forward ref record.
2790 auto I
= ForwardRefVals
.find(Name
);
2791 if (I
!= ForwardRefVals
.end())
2792 Val
= I
->second
.first
;
2795 // If we have the value in the symbol table or fwd-ref table, return it.
2797 return P
.checkValidVariableType(Loc
, "%" + Name
, Ty
, Val
, IsCall
);
2799 // Don't make placeholders with invalid type.
2800 if (!Ty
->isFirstClassType()) {
2801 P
.Error(Loc
, "invalid use of a non-first-class type");
2805 // Otherwise, create a new forward reference for this value and remember it.
2807 if (Ty
->isLabelTy()) {
2808 FwdVal
= BasicBlock::Create(F
.getContext(), Name
, &F
);
2810 FwdVal
= new Argument(Ty
, Name
);
2813 ForwardRefVals
[Name
] = std::make_pair(FwdVal
, Loc
);
2817 Value
*LLParser::PerFunctionState::GetVal(unsigned ID
, Type
*Ty
, LocTy Loc
,
2819 // Look this name up in the normal function symbol table.
2820 Value
*Val
= ID
< NumberedVals
.size() ? NumberedVals
[ID
] : nullptr;
2822 // If this is a forward reference for the value, see if we already created a
2823 // forward ref record.
2825 auto I
= ForwardRefValIDs
.find(ID
);
2826 if (I
!= ForwardRefValIDs
.end())
2827 Val
= I
->second
.first
;
2830 // If we have the value in the symbol table or fwd-ref table, return it.
2832 return P
.checkValidVariableType(Loc
, "%" + Twine(ID
), Ty
, Val
, IsCall
);
2834 if (!Ty
->isFirstClassType()) {
2835 P
.Error(Loc
, "invalid use of a non-first-class type");
2839 // Otherwise, create a new forward reference for this value and remember it.
2841 if (Ty
->isLabelTy()) {
2842 FwdVal
= BasicBlock::Create(F
.getContext(), "", &F
);
2844 FwdVal
= new Argument(Ty
);
2847 ForwardRefValIDs
[ID
] = std::make_pair(FwdVal
, Loc
);
2851 /// SetInstName - After an instruction is parsed and inserted into its
2852 /// basic block, this installs its name.
2853 bool LLParser::PerFunctionState::SetInstName(int NameID
,
2854 const std::string
&NameStr
,
2855 LocTy NameLoc
, Instruction
*Inst
) {
2856 // If this instruction has void type, it cannot have a name or ID specified.
2857 if (Inst
->getType()->isVoidTy()) {
2858 if (NameID
!= -1 || !NameStr
.empty())
2859 return P
.Error(NameLoc
, "instructions returning void cannot have a name");
2863 // If this was a numbered instruction, verify that the instruction is the
2864 // expected value and resolve any forward references.
2865 if (NameStr
.empty()) {
2866 // If neither a name nor an ID was specified, just use the next ID.
2868 NameID
= NumberedVals
.size();
2870 if (unsigned(NameID
) != NumberedVals
.size())
2871 return P
.Error(NameLoc
, "instruction expected to be numbered '%" +
2872 Twine(NumberedVals
.size()) + "'");
2874 auto FI
= ForwardRefValIDs
.find(NameID
);
2875 if (FI
!= ForwardRefValIDs
.end()) {
2876 Value
*Sentinel
= FI
->second
.first
;
2877 if (Sentinel
->getType() != Inst
->getType())
2878 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
2879 getTypeString(FI
->second
.first
->getType()) + "'");
2881 Sentinel
->replaceAllUsesWith(Inst
);
2882 Sentinel
->deleteValue();
2883 ForwardRefValIDs
.erase(FI
);
2886 NumberedVals
.push_back(Inst
);
2890 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2891 auto FI
= ForwardRefVals
.find(NameStr
);
2892 if (FI
!= ForwardRefVals
.end()) {
2893 Value
*Sentinel
= FI
->second
.first
;
2894 if (Sentinel
->getType() != Inst
->getType())
2895 return P
.Error(NameLoc
, "instruction forward referenced with type '" +
2896 getTypeString(FI
->second
.first
->getType()) + "'");
2898 Sentinel
->replaceAllUsesWith(Inst
);
2899 Sentinel
->deleteValue();
2900 ForwardRefVals
.erase(FI
);
2903 // Set the name on the instruction.
2904 Inst
->setName(NameStr
);
2906 if (Inst
->getName() != NameStr
)
2907 return P
.Error(NameLoc
, "multiple definition of local value named '" +
2912 /// GetBB - Get a basic block with the specified name or ID, creating a
2913 /// forward reference record if needed.
2914 BasicBlock
*LLParser::PerFunctionState::GetBB(const std::string
&Name
,
2916 return dyn_cast_or_null
<BasicBlock
>(
2917 GetVal(Name
, Type::getLabelTy(F
.getContext()), Loc
, /*IsCall=*/false));
2920 BasicBlock
*LLParser::PerFunctionState::GetBB(unsigned ID
, LocTy Loc
) {
2921 return dyn_cast_or_null
<BasicBlock
>(
2922 GetVal(ID
, Type::getLabelTy(F
.getContext()), Loc
, /*IsCall=*/false));
2925 /// DefineBB - Define the specified basic block, which is either named or
2926 /// unnamed. If there is an error, this returns null otherwise it returns
2927 /// the block being defined.
2928 BasicBlock
*LLParser::PerFunctionState::DefineBB(const std::string
&Name
,
2929 int NameID
, LocTy Loc
) {
2932 if (NameID
!= -1 && unsigned(NameID
) != NumberedVals
.size()) {
2933 P
.Error(Loc
, "label expected to be numbered '" +
2934 Twine(NumberedVals
.size()) + "'");
2937 BB
= GetBB(NumberedVals
.size(), Loc
);
2939 P
.Error(Loc
, "unable to create block numbered '" +
2940 Twine(NumberedVals
.size()) + "'");
2944 BB
= GetBB(Name
, Loc
);
2946 P
.Error(Loc
, "unable to create block named '" + Name
+ "'");
2951 // Move the block to the end of the function. Forward ref'd blocks are
2952 // inserted wherever they happen to be referenced.
2953 F
.getBasicBlockList().splice(F
.end(), F
.getBasicBlockList(), BB
);
2955 // Remove the block from forward ref sets.
2957 ForwardRefValIDs
.erase(NumberedVals
.size());
2958 NumberedVals
.push_back(BB
);
2960 // BB forward references are already in the function symbol table.
2961 ForwardRefVals
.erase(Name
);
2967 //===----------------------------------------------------------------------===//
2969 //===----------------------------------------------------------------------===//
2971 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2972 /// type implied. For example, if we parse "4" we don't know what integer type
2973 /// it has. The value will later be combined with its type and checked for
2974 /// sanity. PFS is used to convert function-local operands of metadata (since
2975 /// metadata operands are not just parsed here but also converted to values).
2976 /// PFS can be null when we are not parsing metadata values inside a function.
2977 bool LLParser::ParseValID(ValID
&ID
, PerFunctionState
*PFS
) {
2978 ID
.Loc
= Lex
.getLoc();
2979 switch (Lex
.getKind()) {
2980 default: return TokError("expected value token");
2981 case lltok::GlobalID
: // @42
2982 ID
.UIntVal
= Lex
.getUIntVal();
2983 ID
.Kind
= ValID::t_GlobalID
;
2985 case lltok::GlobalVar
: // @foo
2986 ID
.StrVal
= Lex
.getStrVal();
2987 ID
.Kind
= ValID::t_GlobalName
;
2989 case lltok::LocalVarID
: // %42
2990 ID
.UIntVal
= Lex
.getUIntVal();
2991 ID
.Kind
= ValID::t_LocalID
;
2993 case lltok::LocalVar
: // %foo
2994 ID
.StrVal
= Lex
.getStrVal();
2995 ID
.Kind
= ValID::t_LocalName
;
2998 ID
.APSIntVal
= Lex
.getAPSIntVal();
2999 ID
.Kind
= ValID::t_APSInt
;
3001 case lltok::APFloat
:
3002 ID
.APFloatVal
= Lex
.getAPFloatVal();
3003 ID
.Kind
= ValID::t_APFloat
;
3005 case lltok::kw_true
:
3006 ID
.ConstantVal
= ConstantInt::getTrue(Context
);
3007 ID
.Kind
= ValID::t_Constant
;
3009 case lltok::kw_false
:
3010 ID
.ConstantVal
= ConstantInt::getFalse(Context
);
3011 ID
.Kind
= ValID::t_Constant
;
3013 case lltok::kw_null
: ID
.Kind
= ValID::t_Null
; break;
3014 case lltok::kw_undef
: ID
.Kind
= ValID::t_Undef
; break;
3015 case lltok::kw_zeroinitializer
: ID
.Kind
= ValID::t_Zero
; break;
3016 case lltok::kw_none
: ID
.Kind
= ValID::t_None
; break;
3018 case lltok::lbrace
: {
3019 // ValID ::= '{' ConstVector '}'
3021 SmallVector
<Constant
*, 16> Elts
;
3022 if (ParseGlobalValueVector(Elts
) ||
3023 ParseToken(lltok::rbrace
, "expected end of struct constant"))
3026 ID
.ConstantStructElts
= make_unique
<Constant
*[]>(Elts
.size());
3027 ID
.UIntVal
= Elts
.size();
3028 memcpy(ID
.ConstantStructElts
.get(), Elts
.data(),
3029 Elts
.size() * sizeof(Elts
[0]));
3030 ID
.Kind
= ValID::t_ConstantStruct
;
3034 // ValID ::= '<' ConstVector '>' --> Vector.
3035 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3037 bool isPackedStruct
= EatIfPresent(lltok::lbrace
);
3039 SmallVector
<Constant
*, 16> Elts
;
3040 LocTy FirstEltLoc
= Lex
.getLoc();
3041 if (ParseGlobalValueVector(Elts
) ||
3043 ParseToken(lltok::rbrace
, "expected end of packed struct")) ||
3044 ParseToken(lltok::greater
, "expected end of constant"))
3047 if (isPackedStruct
) {
3048 ID
.ConstantStructElts
= make_unique
<Constant
*[]>(Elts
.size());
3049 memcpy(ID
.ConstantStructElts
.get(), Elts
.data(),
3050 Elts
.size() * sizeof(Elts
[0]));
3051 ID
.UIntVal
= Elts
.size();
3052 ID
.Kind
= ValID::t_PackedConstantStruct
;
3057 return Error(ID
.Loc
, "constant vector must not be empty");
3059 if (!Elts
[0]->getType()->isIntegerTy() &&
3060 !Elts
[0]->getType()->isFloatingPointTy() &&
3061 !Elts
[0]->getType()->isPointerTy())
3062 return Error(FirstEltLoc
,
3063 "vector elements must have integer, pointer or floating point type");
3065 // Verify that all the vector elements have the same type.
3066 for (unsigned i
= 1, e
= Elts
.size(); i
!= e
; ++i
)
3067 if (Elts
[i
]->getType() != Elts
[0]->getType())
3068 return Error(FirstEltLoc
,
3069 "vector element #" + Twine(i
) +
3070 " is not of type '" + getTypeString(Elts
[0]->getType()));
3072 ID
.ConstantVal
= ConstantVector::get(Elts
);
3073 ID
.Kind
= ValID::t_Constant
;
3076 case lltok::lsquare
: { // Array Constant
3078 SmallVector
<Constant
*, 16> Elts
;
3079 LocTy FirstEltLoc
= Lex
.getLoc();
3080 if (ParseGlobalValueVector(Elts
) ||
3081 ParseToken(lltok::rsquare
, "expected end of array constant"))
3084 // Handle empty element.
3086 // Use undef instead of an array because it's inconvenient to determine
3087 // the element type at this point, there being no elements to examine.
3088 ID
.Kind
= ValID::t_EmptyArray
;
3092 if (!Elts
[0]->getType()->isFirstClassType())
3093 return Error(FirstEltLoc
, "invalid array element type: " +
3094 getTypeString(Elts
[0]->getType()));
3096 ArrayType
*ATy
= ArrayType::get(Elts
[0]->getType(), Elts
.size());
3098 // Verify all elements are correct type!
3099 for (unsigned i
= 0, e
= Elts
.size(); i
!= e
; ++i
) {
3100 if (Elts
[i
]->getType() != Elts
[0]->getType())
3101 return Error(FirstEltLoc
,
3102 "array element #" + Twine(i
) +
3103 " is not of type '" + getTypeString(Elts
[0]->getType()));
3106 ID
.ConstantVal
= ConstantArray::get(ATy
, Elts
);
3107 ID
.Kind
= ValID::t_Constant
;
3110 case lltok::kw_c
: // c "foo"
3112 ID
.ConstantVal
= ConstantDataArray::getString(Context
, Lex
.getStrVal(),
3114 if (ParseToken(lltok::StringConstant
, "expected string")) return true;
3115 ID
.Kind
= ValID::t_Constant
;
3118 case lltok::kw_asm
: {
3119 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3121 bool HasSideEffect
, AlignStack
, AsmDialect
;
3123 if (ParseOptionalToken(lltok::kw_sideeffect
, HasSideEffect
) ||
3124 ParseOptionalToken(lltok::kw_alignstack
, AlignStack
) ||
3125 ParseOptionalToken(lltok::kw_inteldialect
, AsmDialect
) ||
3126 ParseStringConstant(ID
.StrVal
) ||
3127 ParseToken(lltok::comma
, "expected comma in inline asm expression") ||
3128 ParseToken(lltok::StringConstant
, "expected constraint string"))
3130 ID
.StrVal2
= Lex
.getStrVal();
3131 ID
.UIntVal
= unsigned(HasSideEffect
) | (unsigned(AlignStack
)<<1) |
3132 (unsigned(AsmDialect
)<<2);
3133 ID
.Kind
= ValID::t_InlineAsm
;
3137 case lltok::kw_blockaddress
: {
3138 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3143 if (ParseToken(lltok::lparen
, "expected '(' in block address expression") ||
3145 ParseToken(lltok::comma
, "expected comma in block address expression")||
3146 ParseValID(Label
) ||
3147 ParseToken(lltok::rparen
, "expected ')' in block address expression"))
3150 if (Fn
.Kind
!= ValID::t_GlobalID
&& Fn
.Kind
!= ValID::t_GlobalName
)
3151 return Error(Fn
.Loc
, "expected function name in blockaddress");
3152 if (Label
.Kind
!= ValID::t_LocalID
&& Label
.Kind
!= ValID::t_LocalName
)
3153 return Error(Label
.Loc
, "expected basic block name in blockaddress");
3155 // Try to find the function (but skip it if it's forward-referenced).
3156 GlobalValue
*GV
= nullptr;
3157 if (Fn
.Kind
== ValID::t_GlobalID
) {
3158 if (Fn
.UIntVal
< NumberedVals
.size())
3159 GV
= NumberedVals
[Fn
.UIntVal
];
3160 } else if (!ForwardRefVals
.count(Fn
.StrVal
)) {
3161 GV
= M
->getNamedValue(Fn
.StrVal
);
3163 Function
*F
= nullptr;
3165 // Confirm that it's actually a function with a definition.
3166 if (!isa
<Function
>(GV
))
3167 return Error(Fn
.Loc
, "expected function name in blockaddress");
3168 F
= cast
<Function
>(GV
);
3169 if (F
->isDeclaration())
3170 return Error(Fn
.Loc
, "cannot take blockaddress inside a declaration");
3174 // Make a global variable as a placeholder for this reference.
3175 GlobalValue
*&FwdRef
=
3176 ForwardRefBlockAddresses
.insert(std::make_pair(
3178 std::map
<ValID
, GlobalValue
*>()))
3179 .first
->second
.insert(std::make_pair(std::move(Label
), nullptr))
3182 FwdRef
= new GlobalVariable(*M
, Type::getInt8Ty(Context
), false,
3183 GlobalValue::InternalLinkage
, nullptr, "");
3184 ID
.ConstantVal
= FwdRef
;
3185 ID
.Kind
= ValID::t_Constant
;
3189 // We found the function; now find the basic block. Don't use PFS, since we
3190 // might be inside a constant expression.
3192 if (BlockAddressPFS
&& F
== &BlockAddressPFS
->getFunction()) {
3193 if (Label
.Kind
== ValID::t_LocalID
)
3194 BB
= BlockAddressPFS
->GetBB(Label
.UIntVal
, Label
.Loc
);
3196 BB
= BlockAddressPFS
->GetBB(Label
.StrVal
, Label
.Loc
);
3198 return Error(Label
.Loc
, "referenced value is not a basic block");
3200 if (Label
.Kind
== ValID::t_LocalID
)
3201 return Error(Label
.Loc
, "cannot take address of numeric label after "
3202 "the function is defined");
3203 BB
= dyn_cast_or_null
<BasicBlock
>(
3204 F
->getValueSymbolTable()->lookup(Label
.StrVal
));
3206 return Error(Label
.Loc
, "referenced value is not a basic block");
3209 ID
.ConstantVal
= BlockAddress::get(F
, BB
);
3210 ID
.Kind
= ValID::t_Constant
;
3214 case lltok::kw_trunc
:
3215 case lltok::kw_zext
:
3216 case lltok::kw_sext
:
3217 case lltok::kw_fptrunc
:
3218 case lltok::kw_fpext
:
3219 case lltok::kw_bitcast
:
3220 case lltok::kw_addrspacecast
:
3221 case lltok::kw_uitofp
:
3222 case lltok::kw_sitofp
:
3223 case lltok::kw_fptoui
:
3224 case lltok::kw_fptosi
:
3225 case lltok::kw_inttoptr
:
3226 case lltok::kw_ptrtoint
: {
3227 unsigned Opc
= Lex
.getUIntVal();
3228 Type
*DestTy
= nullptr;
3231 if (ParseToken(lltok::lparen
, "expected '(' after constantexpr cast") ||
3232 ParseGlobalTypeAndValue(SrcVal
) ||
3233 ParseToken(lltok::kw_to
, "expected 'to' in constantexpr cast") ||
3234 ParseType(DestTy
) ||
3235 ParseToken(lltok::rparen
, "expected ')' at end of constantexpr cast"))
3237 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, SrcVal
, DestTy
))
3238 return Error(ID
.Loc
, "invalid cast opcode for cast from '" +
3239 getTypeString(SrcVal
->getType()) + "' to '" +
3240 getTypeString(DestTy
) + "'");
3241 ID
.ConstantVal
= ConstantExpr::getCast((Instruction::CastOps
)Opc
,
3243 ID
.Kind
= ValID::t_Constant
;
3246 case lltok::kw_extractvalue
: {
3249 SmallVector
<unsigned, 4> Indices
;
3250 if (ParseToken(lltok::lparen
, "expected '(' in extractvalue constantexpr")||
3251 ParseGlobalTypeAndValue(Val
) ||
3252 ParseIndexList(Indices
) ||
3253 ParseToken(lltok::rparen
, "expected ')' in extractvalue constantexpr"))
3256 if (!Val
->getType()->isAggregateType())
3257 return Error(ID
.Loc
, "extractvalue operand must be aggregate type");
3258 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
))
3259 return Error(ID
.Loc
, "invalid indices for extractvalue");
3260 ID
.ConstantVal
= ConstantExpr::getExtractValue(Val
, Indices
);
3261 ID
.Kind
= ValID::t_Constant
;
3264 case lltok::kw_insertvalue
: {
3266 Constant
*Val0
, *Val1
;
3267 SmallVector
<unsigned, 4> Indices
;
3268 if (ParseToken(lltok::lparen
, "expected '(' in insertvalue constantexpr")||
3269 ParseGlobalTypeAndValue(Val0
) ||
3270 ParseToken(lltok::comma
, "expected comma in insertvalue constantexpr")||
3271 ParseGlobalTypeAndValue(Val1
) ||
3272 ParseIndexList(Indices
) ||
3273 ParseToken(lltok::rparen
, "expected ')' in insertvalue constantexpr"))
3275 if (!Val0
->getType()->isAggregateType())
3276 return Error(ID
.Loc
, "insertvalue operand must be aggregate type");
3278 ExtractValueInst::getIndexedType(Val0
->getType(), Indices
);
3280 return Error(ID
.Loc
, "invalid indices for insertvalue");
3281 if (IndexedType
!= Val1
->getType())
3282 return Error(ID
.Loc
, "insertvalue operand and field disagree in type: '" +
3283 getTypeString(Val1
->getType()) +
3284 "' instead of '" + getTypeString(IndexedType
) +
3286 ID
.ConstantVal
= ConstantExpr::getInsertValue(Val0
, Val1
, Indices
);
3287 ID
.Kind
= ValID::t_Constant
;
3290 case lltok::kw_icmp
:
3291 case lltok::kw_fcmp
: {
3292 unsigned PredVal
, Opc
= Lex
.getUIntVal();
3293 Constant
*Val0
, *Val1
;
3295 if (ParseCmpPredicate(PredVal
, Opc
) ||
3296 ParseToken(lltok::lparen
, "expected '(' in compare constantexpr") ||
3297 ParseGlobalTypeAndValue(Val0
) ||
3298 ParseToken(lltok::comma
, "expected comma in compare constantexpr") ||
3299 ParseGlobalTypeAndValue(Val1
) ||
3300 ParseToken(lltok::rparen
, "expected ')' in compare constantexpr"))
3303 if (Val0
->getType() != Val1
->getType())
3304 return Error(ID
.Loc
, "compare operands must have the same type");
3306 CmpInst::Predicate Pred
= (CmpInst::Predicate
)PredVal
;
3308 if (Opc
== Instruction::FCmp
) {
3309 if (!Val0
->getType()->isFPOrFPVectorTy())
3310 return Error(ID
.Loc
, "fcmp requires floating point operands");
3311 ID
.ConstantVal
= ConstantExpr::getFCmp(Pred
, Val0
, Val1
);
3313 assert(Opc
== Instruction::ICmp
&& "Unexpected opcode for CmpInst!");
3314 if (!Val0
->getType()->isIntOrIntVectorTy() &&
3315 !Val0
->getType()->isPtrOrPtrVectorTy())
3316 return Error(ID
.Loc
, "icmp requires pointer or integer operands");
3317 ID
.ConstantVal
= ConstantExpr::getICmp(Pred
, Val0
, Val1
);
3319 ID
.Kind
= ValID::t_Constant
;
3324 case lltok::kw_fneg
: {
3325 unsigned Opc
= Lex
.getUIntVal();
3328 if (ParseToken(lltok::lparen
, "expected '(' in unary constantexpr") ||
3329 ParseGlobalTypeAndValue(Val
) ||
3330 ParseToken(lltok::rparen
, "expected ')' in unary constantexpr"))
3333 // Check that the type is valid for the operator.
3335 case Instruction::FNeg
:
3336 if (!Val
->getType()->isFPOrFPVectorTy())
3337 return Error(ID
.Loc
, "constexpr requires fp operands");
3339 default: llvm_unreachable("Unknown unary operator!");
3342 Constant
*C
= ConstantExpr::get(Opc
, Val
, Flags
);
3344 ID
.Kind
= ValID::t_Constant
;
3347 // Binary Operators.
3349 case lltok::kw_fadd
:
3351 case lltok::kw_fsub
:
3353 case lltok::kw_fmul
:
3354 case lltok::kw_udiv
:
3355 case lltok::kw_sdiv
:
3356 case lltok::kw_fdiv
:
3357 case lltok::kw_urem
:
3358 case lltok::kw_srem
:
3359 case lltok::kw_frem
:
3361 case lltok::kw_lshr
:
3362 case lltok::kw_ashr
: {
3366 unsigned Opc
= Lex
.getUIntVal();
3367 Constant
*Val0
, *Val1
;
3369 LocTy ModifierLoc
= Lex
.getLoc();
3370 if (Opc
== Instruction::Add
|| Opc
== Instruction::Sub
||
3371 Opc
== Instruction::Mul
|| Opc
== Instruction::Shl
) {
3372 if (EatIfPresent(lltok::kw_nuw
))
3374 if (EatIfPresent(lltok::kw_nsw
)) {
3376 if (EatIfPresent(lltok::kw_nuw
))
3379 } else if (Opc
== Instruction::SDiv
|| Opc
== Instruction::UDiv
||
3380 Opc
== Instruction::LShr
|| Opc
== Instruction::AShr
) {
3381 if (EatIfPresent(lltok::kw_exact
))
3384 if (ParseToken(lltok::lparen
, "expected '(' in binary constantexpr") ||
3385 ParseGlobalTypeAndValue(Val0
) ||
3386 ParseToken(lltok::comma
, "expected comma in binary constantexpr") ||
3387 ParseGlobalTypeAndValue(Val1
) ||
3388 ParseToken(lltok::rparen
, "expected ')' in binary constantexpr"))
3390 if (Val0
->getType() != Val1
->getType())
3391 return Error(ID
.Loc
, "operands of constexpr must have same type");
3392 if (!Val0
->getType()->isIntOrIntVectorTy()) {
3394 return Error(ModifierLoc
, "nuw only applies to integer operations");
3396 return Error(ModifierLoc
, "nsw only applies to integer operations");
3398 // Check that the type is valid for the operator.
3400 case Instruction::Add
:
3401 case Instruction::Sub
:
3402 case Instruction::Mul
:
3403 case Instruction::UDiv
:
3404 case Instruction::SDiv
:
3405 case Instruction::URem
:
3406 case Instruction::SRem
:
3407 case Instruction::Shl
:
3408 case Instruction::AShr
:
3409 case Instruction::LShr
:
3410 if (!Val0
->getType()->isIntOrIntVectorTy())
3411 return Error(ID
.Loc
, "constexpr requires integer operands");
3413 case Instruction::FAdd
:
3414 case Instruction::FSub
:
3415 case Instruction::FMul
:
3416 case Instruction::FDiv
:
3417 case Instruction::FRem
:
3418 if (!Val0
->getType()->isFPOrFPVectorTy())
3419 return Error(ID
.Loc
, "constexpr requires fp operands");
3421 default: llvm_unreachable("Unknown binary operator!");
3424 if (NUW
) Flags
|= OverflowingBinaryOperator::NoUnsignedWrap
;
3425 if (NSW
) Flags
|= OverflowingBinaryOperator::NoSignedWrap
;
3426 if (Exact
) Flags
|= PossiblyExactOperator::IsExact
;
3427 Constant
*C
= ConstantExpr::get(Opc
, Val0
, Val1
, Flags
);
3429 ID
.Kind
= ValID::t_Constant
;
3433 // Logical Operations
3436 case lltok::kw_xor
: {
3437 unsigned Opc
= Lex
.getUIntVal();
3438 Constant
*Val0
, *Val1
;
3440 if (ParseToken(lltok::lparen
, "expected '(' in logical constantexpr") ||
3441 ParseGlobalTypeAndValue(Val0
) ||
3442 ParseToken(lltok::comma
, "expected comma in logical constantexpr") ||
3443 ParseGlobalTypeAndValue(Val1
) ||
3444 ParseToken(lltok::rparen
, "expected ')' in logical constantexpr"))
3446 if (Val0
->getType() != Val1
->getType())
3447 return Error(ID
.Loc
, "operands of constexpr must have same type");
3448 if (!Val0
->getType()->isIntOrIntVectorTy())
3449 return Error(ID
.Loc
,
3450 "constexpr requires integer or integer vector operands");
3451 ID
.ConstantVal
= ConstantExpr::get(Opc
, Val0
, Val1
);
3452 ID
.Kind
= ValID::t_Constant
;
3456 case lltok::kw_getelementptr
:
3457 case lltok::kw_shufflevector
:
3458 case lltok::kw_insertelement
:
3459 case lltok::kw_extractelement
:
3460 case lltok::kw_select
: {
3461 unsigned Opc
= Lex
.getUIntVal();
3462 SmallVector
<Constant
*, 16> Elts
;
3463 bool InBounds
= false;
3467 if (Opc
== Instruction::GetElementPtr
)
3468 InBounds
= EatIfPresent(lltok::kw_inbounds
);
3470 if (ParseToken(lltok::lparen
, "expected '(' in constantexpr"))
3473 LocTy ExplicitTypeLoc
= Lex
.getLoc();
3474 if (Opc
== Instruction::GetElementPtr
) {
3475 if (ParseType(Ty
) ||
3476 ParseToken(lltok::comma
, "expected comma after getelementptr's type"))
3480 Optional
<unsigned> InRangeOp
;
3481 if (ParseGlobalValueVector(
3482 Elts
, Opc
== Instruction::GetElementPtr
? &InRangeOp
: nullptr) ||
3483 ParseToken(lltok::rparen
, "expected ')' in constantexpr"))
3486 if (Opc
== Instruction::GetElementPtr
) {
3487 if (Elts
.size() == 0 ||
3488 !Elts
[0]->getType()->isPtrOrPtrVectorTy())
3489 return Error(ID
.Loc
, "base of getelementptr must be a pointer");
3491 Type
*BaseType
= Elts
[0]->getType();
3492 auto *BasePointerType
= cast
<PointerType
>(BaseType
->getScalarType());
3493 if (Ty
!= BasePointerType
->getElementType())
3496 "explicit pointee type doesn't match operand's pointee type");
3499 BaseType
->isVectorTy() ? BaseType
->getVectorNumElements() : 0;
3501 ArrayRef
<Constant
*> Indices(Elts
.begin() + 1, Elts
.end());
3502 for (Constant
*Val
: Indices
) {
3503 Type
*ValTy
= Val
->getType();
3504 if (!ValTy
->isIntOrIntVectorTy())
3505 return Error(ID
.Loc
, "getelementptr index must be an integer");
3506 if (ValTy
->isVectorTy()) {
3507 unsigned ValNumEl
= ValTy
->getVectorNumElements();
3508 if (GEPWidth
&& (ValNumEl
!= GEPWidth
))
3511 "getelementptr vector index has a wrong number of elements");
3512 // GEPWidth may have been unknown because the base is a scalar,
3513 // but it is known now.
3514 GEPWidth
= ValNumEl
;
3518 SmallPtrSet
<Type
*, 4> Visited
;
3519 if (!Indices
.empty() && !Ty
->isSized(&Visited
))
3520 return Error(ID
.Loc
, "base element of getelementptr must be sized");
3522 if (!GetElementPtrInst::getIndexedType(Ty
, Indices
))
3523 return Error(ID
.Loc
, "invalid getelementptr indices");
3526 if (*InRangeOp
== 0)
3527 return Error(ID
.Loc
,
3528 "inrange keyword may not appear on pointer operand");
3532 ID
.ConstantVal
= ConstantExpr::getGetElementPtr(Ty
, Elts
[0], Indices
,
3533 InBounds
, InRangeOp
);
3534 } else if (Opc
== Instruction::Select
) {
3535 if (Elts
.size() != 3)
3536 return Error(ID
.Loc
, "expected three operands to select");
3537 if (const char *Reason
= SelectInst::areInvalidOperands(Elts
[0], Elts
[1],
3539 return Error(ID
.Loc
, Reason
);
3540 ID
.ConstantVal
= ConstantExpr::getSelect(Elts
[0], Elts
[1], Elts
[2]);
3541 } else if (Opc
== Instruction::ShuffleVector
) {
3542 if (Elts
.size() != 3)
3543 return Error(ID
.Loc
, "expected three operands to shufflevector");
3544 if (!ShuffleVectorInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
3545 return Error(ID
.Loc
, "invalid operands to shufflevector");
3547 ConstantExpr::getShuffleVector(Elts
[0], Elts
[1],Elts
[2]);
3548 } else if (Opc
== Instruction::ExtractElement
) {
3549 if (Elts
.size() != 2)
3550 return Error(ID
.Loc
, "expected two operands to extractelement");
3551 if (!ExtractElementInst::isValidOperands(Elts
[0], Elts
[1]))
3552 return Error(ID
.Loc
, "invalid extractelement operands");
3553 ID
.ConstantVal
= ConstantExpr::getExtractElement(Elts
[0], Elts
[1]);
3555 assert(Opc
== Instruction::InsertElement
&& "Unknown opcode");
3556 if (Elts
.size() != 3)
3557 return Error(ID
.Loc
, "expected three operands to insertelement");
3558 if (!InsertElementInst::isValidOperands(Elts
[0], Elts
[1], Elts
[2]))
3559 return Error(ID
.Loc
, "invalid insertelement operands");
3561 ConstantExpr::getInsertElement(Elts
[0], Elts
[1],Elts
[2]);
3564 ID
.Kind
= ValID::t_Constant
;
3573 /// ParseGlobalValue - Parse a global value with the specified type.
3574 bool LLParser::ParseGlobalValue(Type
*Ty
, Constant
*&C
) {
3578 bool Parsed
= ParseValID(ID
) ||
3579 ConvertValIDToValue(Ty
, ID
, V
, nullptr, /*IsCall=*/false);
3580 if (V
&& !(C
= dyn_cast
<Constant
>(V
)))
3581 return Error(ID
.Loc
, "global values must be constants");
3585 bool LLParser::ParseGlobalTypeAndValue(Constant
*&V
) {
3587 return ParseType(Ty
) ||
3588 ParseGlobalValue(Ty
, V
);
3591 bool LLParser::parseOptionalComdat(StringRef GlobalName
, Comdat
*&C
) {
3594 LocTy KwLoc
= Lex
.getLoc();
3595 if (!EatIfPresent(lltok::kw_comdat
))
3598 if (EatIfPresent(lltok::lparen
)) {
3599 if (Lex
.getKind() != lltok::ComdatVar
)
3600 return TokError("expected comdat variable");
3601 C
= getComdat(Lex
.getStrVal(), Lex
.getLoc());
3603 if (ParseToken(lltok::rparen
, "expected ')' after comdat var"))
3606 if (GlobalName
.empty())
3607 return TokError("comdat cannot be unnamed");
3608 C
= getComdat(GlobalName
, KwLoc
);
3614 /// ParseGlobalValueVector
3616 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3617 bool LLParser::ParseGlobalValueVector(SmallVectorImpl
<Constant
*> &Elts
,
3618 Optional
<unsigned> *InRangeOp
) {
3620 if (Lex
.getKind() == lltok::rbrace
||
3621 Lex
.getKind() == lltok::rsquare
||
3622 Lex
.getKind() == lltok::greater
||
3623 Lex
.getKind() == lltok::rparen
)
3627 if (InRangeOp
&& !*InRangeOp
&& EatIfPresent(lltok::kw_inrange
))
3628 *InRangeOp
= Elts
.size();
3631 if (ParseGlobalTypeAndValue(C
)) return true;
3633 } while (EatIfPresent(lltok::comma
));
3638 bool LLParser::ParseMDTuple(MDNode
*&MD
, bool IsDistinct
) {
3639 SmallVector
<Metadata
*, 16> Elts
;
3640 if (ParseMDNodeVector(Elts
))
3643 MD
= (IsDistinct
? MDTuple::getDistinct
: MDTuple::get
)(Context
, Elts
);
3650 /// ::= !DILocation(...)
3651 bool LLParser::ParseMDNode(MDNode
*&N
) {
3652 if (Lex
.getKind() == lltok::MetadataVar
)
3653 return ParseSpecializedMDNode(N
);
3655 return ParseToken(lltok::exclaim
, "expected '!' here") ||
3659 bool LLParser::ParseMDNodeTail(MDNode
*&N
) {
3661 if (Lex
.getKind() == lltok::lbrace
)
3662 return ParseMDTuple(N
);
3665 return ParseMDNodeID(N
);
3670 /// Structure to represent an optional metadata field.
3671 template <class FieldTy
> struct MDFieldImpl
{
3672 typedef MDFieldImpl ImplTy
;
3676 void assign(FieldTy Val
) {
3678 this->Val
= std::move(Val
);
3681 explicit MDFieldImpl(FieldTy Default
)
3682 : Val(std::move(Default
)), Seen(false) {}
3685 /// Structure to represent an optional metadata field that
3686 /// can be of either type (A or B) and encapsulates the
3687 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3688 /// to reimplement the specifics for representing each Field.
3689 template <class FieldTypeA
, class FieldTypeB
> struct MDEitherFieldImpl
{
3690 typedef MDEitherFieldImpl
<FieldTypeA
, FieldTypeB
> ImplTy
;
3701 void assign(FieldTypeA A
) {
3703 this->A
= std::move(A
);
3707 void assign(FieldTypeB B
) {
3709 this->B
= std::move(B
);
3713 explicit MDEitherFieldImpl(FieldTypeA DefaultA
, FieldTypeB DefaultB
)
3714 : A(std::move(DefaultA
)), B(std::move(DefaultB
)), Seen(false),
3715 WhatIs(IsInvalid
) {}
3718 struct MDUnsignedField
: public MDFieldImpl
<uint64_t> {
3721 MDUnsignedField(uint64_t Default
= 0, uint64_t Max
= UINT64_MAX
)
3722 : ImplTy(Default
), Max(Max
) {}
3725 struct LineField
: public MDUnsignedField
{
3726 LineField() : MDUnsignedField(0, UINT32_MAX
) {}
3729 struct ColumnField
: public MDUnsignedField
{
3730 ColumnField() : MDUnsignedField(0, UINT16_MAX
) {}
3733 struct DwarfTagField
: public MDUnsignedField
{
3734 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user
) {}
3735 DwarfTagField(dwarf::Tag DefaultTag
)
3736 : MDUnsignedField(DefaultTag
, dwarf::DW_TAG_hi_user
) {}
3739 struct DwarfMacinfoTypeField
: public MDUnsignedField
{
3740 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext
) {}
3741 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType
)
3742 : MDUnsignedField(DefaultType
, dwarf::DW_MACINFO_vendor_ext
) {}
3745 struct DwarfAttEncodingField
: public MDUnsignedField
{
3746 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user
) {}
3749 struct DwarfVirtualityField
: public MDUnsignedField
{
3750 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max
) {}
3753 struct DwarfLangField
: public MDUnsignedField
{
3754 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user
) {}
3757 struct DwarfCCField
: public MDUnsignedField
{
3758 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user
) {}
3761 struct EmissionKindField
: public MDUnsignedField
{
3762 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind
) {}
3765 struct NameTableKindField
: public MDUnsignedField
{
3766 NameTableKindField()
3769 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind
) {}
3772 struct DIFlagField
: public MDFieldImpl
<DINode::DIFlags
> {
3773 DIFlagField() : MDFieldImpl(DINode::FlagZero
) {}
3776 struct DISPFlagField
: public MDFieldImpl
<DISubprogram::DISPFlags
> {
3777 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero
) {}
3780 struct MDSignedField
: public MDFieldImpl
<int64_t> {
3784 MDSignedField(int64_t Default
= 0)
3785 : ImplTy(Default
), Min(INT64_MIN
), Max(INT64_MAX
) {}
3786 MDSignedField(int64_t Default
, int64_t Min
, int64_t Max
)
3787 : ImplTy(Default
), Min(Min
), Max(Max
) {}
3790 struct MDBoolField
: public MDFieldImpl
<bool> {
3791 MDBoolField(bool Default
= false) : ImplTy(Default
) {}
3794 struct MDField
: public MDFieldImpl
<Metadata
*> {
3797 MDField(bool AllowNull
= true) : ImplTy(nullptr), AllowNull(AllowNull
) {}
3800 struct MDConstant
: public MDFieldImpl
<ConstantAsMetadata
*> {
3801 MDConstant() : ImplTy(nullptr) {}
3804 struct MDStringField
: public MDFieldImpl
<MDString
*> {
3806 MDStringField(bool AllowEmpty
= true)
3807 : ImplTy(nullptr), AllowEmpty(AllowEmpty
) {}
3810 struct MDFieldList
: public MDFieldImpl
<SmallVector
<Metadata
*, 4>> {
3811 MDFieldList() : ImplTy(SmallVector
<Metadata
*, 4>()) {}
3814 struct ChecksumKindField
: public MDFieldImpl
<DIFile::ChecksumKind
> {
3815 ChecksumKindField(DIFile::ChecksumKind CSKind
) : ImplTy(CSKind
) {}
3818 struct MDSignedOrMDField
: MDEitherFieldImpl
<MDSignedField
, MDField
> {
3819 MDSignedOrMDField(int64_t Default
= 0, bool AllowNull
= true)
3820 : ImplTy(MDSignedField(Default
), MDField(AllowNull
)) {}
3822 MDSignedOrMDField(int64_t Default
, int64_t Min
, int64_t Max
,
3823 bool AllowNull
= true)
3824 : ImplTy(MDSignedField(Default
, Min
, Max
), MDField(AllowNull
)) {}
3826 bool isMDSignedField() const { return WhatIs
== IsTypeA
; }
3827 bool isMDField() const { return WhatIs
== IsTypeB
; }
3828 int64_t getMDSignedValue() const {
3829 assert(isMDSignedField() && "Wrong field type");
3832 Metadata
*getMDFieldValue() const {
3833 assert(isMDField() && "Wrong field type");
3838 struct MDSignedOrUnsignedField
3839 : MDEitherFieldImpl
<MDSignedField
, MDUnsignedField
> {
3840 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3842 bool isMDSignedField() const { return WhatIs
== IsTypeA
; }
3843 bool isMDUnsignedField() const { return WhatIs
== IsTypeB
; }
3844 int64_t getMDSignedValue() const {
3845 assert(isMDSignedField() && "Wrong field type");
3848 uint64_t getMDUnsignedValue() const {
3849 assert(isMDUnsignedField() && "Wrong field type");
3854 } // end anonymous namespace
3859 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
3860 MDUnsignedField
&Result
) {
3861 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
3862 return TokError("expected unsigned integer");
3864 auto &U
= Lex
.getAPSIntVal();
3865 if (U
.ugt(Result
.Max
))
3866 return TokError("value for '" + Name
+ "' too large, limit is " +
3868 Result
.assign(U
.getZExtValue());
3869 assert(Result
.Val
<= Result
.Max
&& "Expected value in range");
3875 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, LineField
&Result
) {
3876 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3879 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, ColumnField
&Result
) {
3880 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3884 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DwarfTagField
&Result
) {
3885 if (Lex
.getKind() == lltok::APSInt
)
3886 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3888 if (Lex
.getKind() != lltok::DwarfTag
)
3889 return TokError("expected DWARF tag");
3891 unsigned Tag
= dwarf::getTag(Lex
.getStrVal());
3892 if (Tag
== dwarf::DW_TAG_invalid
)
3893 return TokError("invalid DWARF tag" + Twine(" '") + Lex
.getStrVal() + "'");
3894 assert(Tag
<= Result
.Max
&& "Expected valid DWARF tag");
3902 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
3903 DwarfMacinfoTypeField
&Result
) {
3904 if (Lex
.getKind() == lltok::APSInt
)
3905 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3907 if (Lex
.getKind() != lltok::DwarfMacinfo
)
3908 return TokError("expected DWARF macinfo type");
3910 unsigned Macinfo
= dwarf::getMacinfo(Lex
.getStrVal());
3911 if (Macinfo
== dwarf::DW_MACINFO_invalid
)
3913 "invalid DWARF macinfo type" + Twine(" '") + Lex
.getStrVal() + "'");
3914 assert(Macinfo
<= Result
.Max
&& "Expected valid DWARF macinfo type");
3916 Result
.assign(Macinfo
);
3922 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
3923 DwarfVirtualityField
&Result
) {
3924 if (Lex
.getKind() == lltok::APSInt
)
3925 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3927 if (Lex
.getKind() != lltok::DwarfVirtuality
)
3928 return TokError("expected DWARF virtuality code");
3930 unsigned Virtuality
= dwarf::getVirtuality(Lex
.getStrVal());
3931 if (Virtuality
== dwarf::DW_VIRTUALITY_invalid
)
3932 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3933 Lex
.getStrVal() + "'");
3934 assert(Virtuality
<= Result
.Max
&& "Expected valid DWARF virtuality code");
3935 Result
.assign(Virtuality
);
3941 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DwarfLangField
&Result
) {
3942 if (Lex
.getKind() == lltok::APSInt
)
3943 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3945 if (Lex
.getKind() != lltok::DwarfLang
)
3946 return TokError("expected DWARF language");
3948 unsigned Lang
= dwarf::getLanguage(Lex
.getStrVal());
3950 return TokError("invalid DWARF language" + Twine(" '") + Lex
.getStrVal() +
3952 assert(Lang
<= Result
.Max
&& "Expected valid DWARF language");
3953 Result
.assign(Lang
);
3959 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DwarfCCField
&Result
) {
3960 if (Lex
.getKind() == lltok::APSInt
)
3961 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3963 if (Lex
.getKind() != lltok::DwarfCC
)
3964 return TokError("expected DWARF calling convention");
3966 unsigned CC
= dwarf::getCallingConvention(Lex
.getStrVal());
3968 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex
.getStrVal() +
3970 assert(CC
<= Result
.Max
&& "Expected valid DWARF calling convention");
3977 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, EmissionKindField
&Result
) {
3978 if (Lex
.getKind() == lltok::APSInt
)
3979 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
3981 if (Lex
.getKind() != lltok::EmissionKind
)
3982 return TokError("expected emission kind");
3984 auto Kind
= DICompileUnit::getEmissionKind(Lex
.getStrVal());
3986 return TokError("invalid emission kind" + Twine(" '") + Lex
.getStrVal() +
3988 assert(*Kind
<= Result
.Max
&& "Expected valid emission kind");
3989 Result
.assign(*Kind
);
3995 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
3996 NameTableKindField
&Result
) {
3997 if (Lex
.getKind() == lltok::APSInt
)
3998 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4000 if (Lex
.getKind() != lltok::NameTableKind
)
4001 return TokError("expected nameTable kind");
4003 auto Kind
= DICompileUnit::getNameTableKind(Lex
.getStrVal());
4005 return TokError("invalid nameTable kind" + Twine(" '") + Lex
.getStrVal() +
4007 assert(((unsigned)*Kind
) <= Result
.Max
&& "Expected valid nameTable kind");
4008 Result
.assign((unsigned)*Kind
);
4014 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4015 DwarfAttEncodingField
&Result
) {
4016 if (Lex
.getKind() == lltok::APSInt
)
4017 return ParseMDField(Loc
, Name
, static_cast<MDUnsignedField
&>(Result
));
4019 if (Lex
.getKind() != lltok::DwarfAttEncoding
)
4020 return TokError("expected DWARF type attribute encoding");
4022 unsigned Encoding
= dwarf::getAttributeEncoding(Lex
.getStrVal());
4024 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4025 Lex
.getStrVal() + "'");
4026 assert(Encoding
<= Result
.Max
&& "Expected valid DWARF language");
4027 Result
.assign(Encoding
);
4034 /// ::= DIFlagVector
4035 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4037 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DIFlagField
&Result
) {
4039 // Parser for a single flag.
4040 auto parseFlag
= [&](DINode::DIFlags
&Val
) {
4041 if (Lex
.getKind() == lltok::APSInt
&& !Lex
.getAPSIntVal().isSigned()) {
4042 uint32_t TempVal
= static_cast<uint32_t>(Val
);
4043 bool Res
= ParseUInt32(TempVal
);
4044 Val
= static_cast<DINode::DIFlags
>(TempVal
);
4048 if (Lex
.getKind() != lltok::DIFlag
)
4049 return TokError("expected debug info flag");
4051 Val
= DINode::getFlag(Lex
.getStrVal());
4053 return TokError(Twine("invalid debug info flag flag '") +
4054 Lex
.getStrVal() + "'");
4059 // Parse the flags and combine them together.
4060 DINode::DIFlags Combined
= DINode::FlagZero
;
4062 DINode::DIFlags Val
;
4066 } while (EatIfPresent(lltok::bar
));
4068 Result
.assign(Combined
);
4074 /// ::= DISPFlagVector
4075 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4077 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, DISPFlagField
&Result
) {
4079 // Parser for a single flag.
4080 auto parseFlag
= [&](DISubprogram::DISPFlags
&Val
) {
4081 if (Lex
.getKind() == lltok::APSInt
&& !Lex
.getAPSIntVal().isSigned()) {
4082 uint32_t TempVal
= static_cast<uint32_t>(Val
);
4083 bool Res
= ParseUInt32(TempVal
);
4084 Val
= static_cast<DISubprogram::DISPFlags
>(TempVal
);
4088 if (Lex
.getKind() != lltok::DISPFlag
)
4089 return TokError("expected debug info flag");
4091 Val
= DISubprogram::getFlag(Lex
.getStrVal());
4093 return TokError(Twine("invalid subprogram debug info flag '") +
4094 Lex
.getStrVal() + "'");
4099 // Parse the flags and combine them together.
4100 DISubprogram::DISPFlags Combined
= DISubprogram::SPFlagZero
;
4102 DISubprogram::DISPFlags Val
;
4106 } while (EatIfPresent(lltok::bar
));
4108 Result
.assign(Combined
);
4113 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4114 MDSignedField
&Result
) {
4115 if (Lex
.getKind() != lltok::APSInt
)
4116 return TokError("expected signed integer");
4118 auto &S
= Lex
.getAPSIntVal();
4120 return TokError("value for '" + Name
+ "' too small, limit is " +
4123 return TokError("value for '" + Name
+ "' too large, limit is " +
4125 Result
.assign(S
.getExtValue());
4126 assert(Result
.Val
>= Result
.Min
&& "Expected value in range");
4127 assert(Result
.Val
<= Result
.Max
&& "Expected value in range");
4133 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, MDBoolField
&Result
) {
4134 switch (Lex
.getKind()) {
4136 return TokError("expected 'true' or 'false'");
4137 case lltok::kw_true
:
4138 Result
.assign(true);
4140 case lltok::kw_false
:
4141 Result
.assign(false);
4149 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, MDField
&Result
) {
4150 if (Lex
.getKind() == lltok::kw_null
) {
4151 if (!Result
.AllowNull
)
4152 return TokError("'" + Name
+ "' cannot be null");
4154 Result
.assign(nullptr);
4159 if (ParseMetadata(MD
, nullptr))
4167 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4168 MDSignedOrMDField
&Result
) {
4169 // Try to parse a signed int.
4170 if (Lex
.getKind() == lltok::APSInt
) {
4171 MDSignedField Res
= Result
.A
;
4172 if (!ParseMDField(Loc
, Name
, Res
)) {
4179 // Otherwise, try to parse as an MDField.
4180 MDField Res
= Result
.B
;
4181 if (!ParseMDField(Loc
, Name
, Res
)) {
4190 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4191 MDSignedOrUnsignedField
&Result
) {
4192 if (Lex
.getKind() != lltok::APSInt
)
4195 if (Lex
.getAPSIntVal().isSigned()) {
4196 MDSignedField Res
= Result
.A
;
4197 if (ParseMDField(Loc
, Name
, Res
))
4203 MDUnsignedField Res
= Result
.B
;
4204 if (ParseMDField(Loc
, Name
, Res
))
4211 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, MDStringField
&Result
) {
4212 LocTy ValueLoc
= Lex
.getLoc();
4214 if (ParseStringConstant(S
))
4217 if (!Result
.AllowEmpty
&& S
.empty())
4218 return Error(ValueLoc
, "'" + Name
+ "' cannot be empty");
4220 Result
.assign(S
.empty() ? nullptr : MDString::get(Context
, S
));
4225 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
, MDFieldList
&Result
) {
4226 SmallVector
<Metadata
*, 4> MDs
;
4227 if (ParseMDNodeVector(MDs
))
4230 Result
.assign(std::move(MDs
));
4235 bool LLParser::ParseMDField(LocTy Loc
, StringRef Name
,
4236 ChecksumKindField
&Result
) {
4237 Optional
<DIFile::ChecksumKind
> CSKind
=
4238 DIFile::getChecksumKind(Lex
.getStrVal());
4240 if (Lex
.getKind() != lltok::ChecksumKind
|| !CSKind
)
4242 "invalid checksum kind" + Twine(" '") + Lex
.getStrVal() + "'");
4244 Result
.assign(*CSKind
);
4249 } // end namespace llvm
4251 template <class ParserTy
>
4252 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField
) {
4254 if (Lex
.getKind() != lltok::LabelStr
)
4255 return TokError("expected field label here");
4259 } while (EatIfPresent(lltok::comma
));
4264 template <class ParserTy
>
4265 bool LLParser::ParseMDFieldsImpl(ParserTy parseField
, LocTy
&ClosingLoc
) {
4266 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4269 if (ParseToken(lltok::lparen
, "expected '(' here"))
4271 if (Lex
.getKind() != lltok::rparen
)
4272 if (ParseMDFieldsImplBody(parseField
))
4275 ClosingLoc
= Lex
.getLoc();
4276 return ParseToken(lltok::rparen
, "expected ')' here");
4279 template <class FieldTy
>
4280 bool LLParser::ParseMDField(StringRef Name
, FieldTy
&Result
) {
4282 return TokError("field '" + Name
+ "' cannot be specified more than once");
4284 LocTy Loc
= Lex
.getLoc();
4286 return ParseMDField(Loc
, Name
, Result
);
4289 bool LLParser::ParseSpecializedMDNode(MDNode
*&N
, bool IsDistinct
) {
4290 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4292 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4293 if (Lex.getStrVal() == #CLASS) \
4294 return Parse##CLASS(N, IsDistinct);
4295 #include "llvm/IR/Metadata.def"
4297 return TokError("expected metadata type");
4300 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4301 #define NOP_FIELD(NAME, TYPE, INIT)
4302 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4304 return Error(ClosingLoc, "missing required field '" #NAME "'");
4305 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4306 if (Lex.getStrVal() == #NAME) \
4307 return ParseMDField(#NAME, NAME);
4308 #define PARSE_MD_FIELDS() \
4309 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4312 if (ParseMDFieldsImpl([&]() -> bool { \
4313 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4314 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4317 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4319 #define GET_OR_DISTINCT(CLASS, ARGS) \
4320 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4322 /// ParseDILocationFields:
4323 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4324 /// isImplicitCode: true)
4325 bool LLParser::ParseDILocation(MDNode
*&Result
, bool IsDistinct
) {
4326 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4327 OPTIONAL(line, LineField, ); \
4328 OPTIONAL(column, ColumnField, ); \
4329 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4330 OPTIONAL(inlinedAt, MDField, ); \
4331 OPTIONAL(isImplicitCode, MDBoolField, (false));
4333 #undef VISIT_MD_FIELDS
4336 GET_OR_DISTINCT(DILocation
, (Context
, line
.Val
, column
.Val
, scope
.Val
,
4337 inlinedAt
.Val
, isImplicitCode
.Val
));
4341 /// ParseGenericDINode:
4342 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4343 bool LLParser::ParseGenericDINode(MDNode
*&Result
, bool IsDistinct
) {
4344 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4345 REQUIRED(tag, DwarfTagField, ); \
4346 OPTIONAL(header, MDStringField, ); \
4347 OPTIONAL(operands, MDFieldList, );
4349 #undef VISIT_MD_FIELDS
4351 Result
= GET_OR_DISTINCT(GenericDINode
,
4352 (Context
, tag
.Val
, header
.Val
, operands
.Val
));
4356 /// ParseDISubrange:
4357 /// ::= !DISubrange(count: 30, lowerBound: 2)
4358 /// ::= !DISubrange(count: !node, lowerBound: 2)
4359 bool LLParser::ParseDISubrange(MDNode
*&Result
, bool IsDistinct
) {
4360 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4361 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4362 OPTIONAL(lowerBound, MDSignedField, );
4364 #undef VISIT_MD_FIELDS
4366 if (count
.isMDSignedField())
4367 Result
= GET_OR_DISTINCT(
4368 DISubrange
, (Context
, count
.getMDSignedValue(), lowerBound
.Val
));
4369 else if (count
.isMDField())
4370 Result
= GET_OR_DISTINCT(
4371 DISubrange
, (Context
, count
.getMDFieldValue(), lowerBound
.Val
));
4378 /// ParseDIEnumerator:
4379 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4380 bool LLParser::ParseDIEnumerator(MDNode
*&Result
, bool IsDistinct
) {
4381 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4382 REQUIRED(name, MDStringField, ); \
4383 REQUIRED(value, MDSignedOrUnsignedField, ); \
4384 OPTIONAL(isUnsigned, MDBoolField, (false));
4386 #undef VISIT_MD_FIELDS
4388 if (isUnsigned
.Val
&& value
.isMDSignedField())
4389 return TokError("unsigned enumerator with negative value");
4391 int64_t Value
= value
.isMDSignedField()
4392 ? value
.getMDSignedValue()
4393 : static_cast<int64_t>(value
.getMDUnsignedValue());
4395 GET_OR_DISTINCT(DIEnumerator
, (Context
, Value
, isUnsigned
.Val
, name
.Val
));
4400 /// ParseDIBasicType:
4401 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4402 /// encoding: DW_ATE_encoding, flags: 0)
4403 bool LLParser::ParseDIBasicType(MDNode
*&Result
, bool IsDistinct
) {
4404 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4405 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4406 OPTIONAL(name, MDStringField, ); \
4407 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4408 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4409 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4410 OPTIONAL(flags, DIFlagField, );
4412 #undef VISIT_MD_FIELDS
4414 Result
= GET_OR_DISTINCT(DIBasicType
, (Context
, tag
.Val
, name
.Val
, size
.Val
,
4415 align
.Val
, encoding
.Val
, flags
.Val
));
4419 /// ParseDIDerivedType:
4420 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4421 /// line: 7, scope: !1, baseType: !2, size: 32,
4422 /// align: 32, offset: 0, flags: 0, extraData: !3,
4423 /// dwarfAddressSpace: 3)
4424 bool LLParser::ParseDIDerivedType(MDNode
*&Result
, bool IsDistinct
) {
4425 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4426 REQUIRED(tag, DwarfTagField, ); \
4427 OPTIONAL(name, MDStringField, ); \
4428 OPTIONAL(file, MDField, ); \
4429 OPTIONAL(line, LineField, ); \
4430 OPTIONAL(scope, MDField, ); \
4431 REQUIRED(baseType, MDField, ); \
4432 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4433 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4434 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4435 OPTIONAL(flags, DIFlagField, ); \
4436 OPTIONAL(extraData, MDField, ); \
4437 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4439 #undef VISIT_MD_FIELDS
4441 Optional
<unsigned> DWARFAddressSpace
;
4442 if (dwarfAddressSpace
.Val
!= UINT32_MAX
)
4443 DWARFAddressSpace
= dwarfAddressSpace
.Val
;
4445 Result
= GET_OR_DISTINCT(DIDerivedType
,
4446 (Context
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
,
4447 scope
.Val
, baseType
.Val
, size
.Val
, align
.Val
,
4448 offset
.Val
, DWARFAddressSpace
, flags
.Val
,
4453 bool LLParser::ParseDICompositeType(MDNode
*&Result
, bool IsDistinct
) {
4454 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4455 REQUIRED(tag, DwarfTagField, ); \
4456 OPTIONAL(name, MDStringField, ); \
4457 OPTIONAL(file, MDField, ); \
4458 OPTIONAL(line, LineField, ); \
4459 OPTIONAL(scope, MDField, ); \
4460 OPTIONAL(baseType, MDField, ); \
4461 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4462 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4463 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4464 OPTIONAL(flags, DIFlagField, ); \
4465 OPTIONAL(elements, MDField, ); \
4466 OPTIONAL(runtimeLang, DwarfLangField, ); \
4467 OPTIONAL(vtableHolder, MDField, ); \
4468 OPTIONAL(templateParams, MDField, ); \
4469 OPTIONAL(identifier, MDStringField, ); \
4470 OPTIONAL(discriminator, MDField, );
4472 #undef VISIT_MD_FIELDS
4474 // If this has an identifier try to build an ODR type.
4476 if (auto *CT
= DICompositeType::buildODRType(
4477 Context
, *identifier
.Val
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
,
4478 scope
.Val
, baseType
.Val
, size
.Val
, align
.Val
, offset
.Val
, flags
.Val
,
4479 elements
.Val
, runtimeLang
.Val
, vtableHolder
.Val
,
4480 templateParams
.Val
, discriminator
.Val
)) {
4485 // Create a new node, and save it in the context if it belongs in the type
4487 Result
= GET_OR_DISTINCT(
4489 (Context
, tag
.Val
, name
.Val
, file
.Val
, line
.Val
, scope
.Val
, baseType
.Val
,
4490 size
.Val
, align
.Val
, offset
.Val
, flags
.Val
, elements
.Val
,
4491 runtimeLang
.Val
, vtableHolder
.Val
, templateParams
.Val
, identifier
.Val
,
4492 discriminator
.Val
));
4496 bool LLParser::ParseDISubroutineType(MDNode
*&Result
, bool IsDistinct
) {
4497 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4498 OPTIONAL(flags, DIFlagField, ); \
4499 OPTIONAL(cc, DwarfCCField, ); \
4500 REQUIRED(types, MDField, );
4502 #undef VISIT_MD_FIELDS
4504 Result
= GET_OR_DISTINCT(DISubroutineType
,
4505 (Context
, flags
.Val
, cc
.Val
, types
.Val
));
4509 /// ParseDIFileType:
4510 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4511 /// checksumkind: CSK_MD5,
4512 /// checksum: "000102030405060708090a0b0c0d0e0f",
4513 /// source: "source file contents")
4514 bool LLParser::ParseDIFile(MDNode
*&Result
, bool IsDistinct
) {
4515 // The default constructed value for checksumkind is required, but will never
4516 // be used, as the parser checks if the field was actually Seen before using
4518 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4519 REQUIRED(filename, MDStringField, ); \
4520 REQUIRED(directory, MDStringField, ); \
4521 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4522 OPTIONAL(checksum, MDStringField, ); \
4523 OPTIONAL(source, MDStringField, );
4525 #undef VISIT_MD_FIELDS
4527 Optional
<DIFile::ChecksumInfo
<MDString
*>> OptChecksum
;
4528 if (checksumkind
.Seen
&& checksum
.Seen
)
4529 OptChecksum
.emplace(checksumkind
.Val
, checksum
.Val
);
4530 else if (checksumkind
.Seen
|| checksum
.Seen
)
4531 return Lex
.Error("'checksumkind' and 'checksum' must be provided together");
4533 Optional
<MDString
*> OptSource
;
4535 OptSource
= source
.Val
;
4536 Result
= GET_OR_DISTINCT(DIFile
, (Context
, filename
.Val
, directory
.Val
,
4537 OptChecksum
, OptSource
));
4541 /// ParseDICompileUnit:
4542 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4543 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4544 /// splitDebugFilename: "abc.debug",
4545 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4546 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4547 bool LLParser::ParseDICompileUnit(MDNode
*&Result
, bool IsDistinct
) {
4549 return Lex
.Error("missing 'distinct', required for !DICompileUnit");
4551 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4552 REQUIRED(language, DwarfLangField, ); \
4553 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4554 OPTIONAL(producer, MDStringField, ); \
4555 OPTIONAL(isOptimized, MDBoolField, ); \
4556 OPTIONAL(flags, MDStringField, ); \
4557 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4558 OPTIONAL(splitDebugFilename, MDStringField, ); \
4559 OPTIONAL(emissionKind, EmissionKindField, ); \
4560 OPTIONAL(enums, MDField, ); \
4561 OPTIONAL(retainedTypes, MDField, ); \
4562 OPTIONAL(globals, MDField, ); \
4563 OPTIONAL(imports, MDField, ); \
4564 OPTIONAL(macros, MDField, ); \
4565 OPTIONAL(dwoId, MDUnsignedField, ); \
4566 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4567 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4568 OPTIONAL(nameTableKind, NameTableKindField, ); \
4569 OPTIONAL(debugBaseAddress, MDBoolField, = false);
4571 #undef VISIT_MD_FIELDS
4573 Result
= DICompileUnit::getDistinct(
4574 Context
, language
.Val
, file
.Val
, producer
.Val
, isOptimized
.Val
, flags
.Val
,
4575 runtimeVersion
.Val
, splitDebugFilename
.Val
, emissionKind
.Val
, enums
.Val
,
4576 retainedTypes
.Val
, globals
.Val
, imports
.Val
, macros
.Val
, dwoId
.Val
,
4577 splitDebugInlining
.Val
, debugInfoForProfiling
.Val
, nameTableKind
.Val
,
4578 debugBaseAddress
.Val
);
4582 /// ParseDISubprogram:
4583 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4584 /// file: !1, line: 7, type: !2, isLocal: false,
4585 /// isDefinition: true, scopeLine: 8, containingType: !3,
4586 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4587 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4588 /// spFlags: 10, isOptimized: false, templateParams: !4,
4589 /// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4590 bool LLParser::ParseDISubprogram(MDNode
*&Result
, bool IsDistinct
) {
4591 auto Loc
= Lex
.getLoc();
4592 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4593 OPTIONAL(scope, MDField, ); \
4594 OPTIONAL(name, MDStringField, ); \
4595 OPTIONAL(linkageName, MDStringField, ); \
4596 OPTIONAL(file, MDField, ); \
4597 OPTIONAL(line, LineField, ); \
4598 OPTIONAL(type, MDField, ); \
4599 OPTIONAL(isLocal, MDBoolField, ); \
4600 OPTIONAL(isDefinition, MDBoolField, (true)); \
4601 OPTIONAL(scopeLine, LineField, ); \
4602 OPTIONAL(containingType, MDField, ); \
4603 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4604 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4605 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4606 OPTIONAL(flags, DIFlagField, ); \
4607 OPTIONAL(spFlags, DISPFlagField, ); \
4608 OPTIONAL(isOptimized, MDBoolField, ); \
4609 OPTIONAL(unit, MDField, ); \
4610 OPTIONAL(templateParams, MDField, ); \
4611 OPTIONAL(declaration, MDField, ); \
4612 OPTIONAL(retainedNodes, MDField, ); \
4613 OPTIONAL(thrownTypes, MDField, );
4615 #undef VISIT_MD_FIELDS
4617 // An explicit spFlags field takes precedence over individual fields in
4618 // older IR versions.
4619 DISubprogram::DISPFlags SPFlags
=
4620 spFlags
.Seen
? spFlags
.Val
4621 : DISubprogram::toSPFlags(isLocal
.Val
, isDefinition
.Val
,
4622 isOptimized
.Val
, virtuality
.Val
);
4623 if ((SPFlags
& DISubprogram::SPFlagDefinition
) && !IsDistinct
)
4626 "missing 'distinct', required for !DISubprogram that is a Definition");
4627 Result
= GET_OR_DISTINCT(
4629 (Context
, scope
.Val
, name
.Val
, linkageName
.Val
, file
.Val
, line
.Val
,
4630 type
.Val
, scopeLine
.Val
, containingType
.Val
, virtualIndex
.Val
,
4631 thisAdjustment
.Val
, flags
.Val
, SPFlags
, unit
.Val
, templateParams
.Val
,
4632 declaration
.Val
, retainedNodes
.Val
, thrownTypes
.Val
));
4636 /// ParseDILexicalBlock:
4637 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4638 bool LLParser::ParseDILexicalBlock(MDNode
*&Result
, bool IsDistinct
) {
4639 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4640 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4641 OPTIONAL(file, MDField, ); \
4642 OPTIONAL(line, LineField, ); \
4643 OPTIONAL(column, ColumnField, );
4645 #undef VISIT_MD_FIELDS
4647 Result
= GET_OR_DISTINCT(
4648 DILexicalBlock
, (Context
, scope
.Val
, file
.Val
, line
.Val
, column
.Val
));
4652 /// ParseDILexicalBlockFile:
4653 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4654 bool LLParser::ParseDILexicalBlockFile(MDNode
*&Result
, bool IsDistinct
) {
4655 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4656 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4657 OPTIONAL(file, MDField, ); \
4658 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4660 #undef VISIT_MD_FIELDS
4662 Result
= GET_OR_DISTINCT(DILexicalBlockFile
,
4663 (Context
, scope
.Val
, file
.Val
, discriminator
.Val
));
4667 /// ParseDINamespace:
4668 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4669 bool LLParser::ParseDINamespace(MDNode
*&Result
, bool IsDistinct
) {
4670 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4671 REQUIRED(scope, MDField, ); \
4672 OPTIONAL(name, MDStringField, ); \
4673 OPTIONAL(exportSymbols, MDBoolField, );
4675 #undef VISIT_MD_FIELDS
4677 Result
= GET_OR_DISTINCT(DINamespace
,
4678 (Context
, scope
.Val
, name
.Val
, exportSymbols
.Val
));
4683 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4684 bool LLParser::ParseDIMacro(MDNode
*&Result
, bool IsDistinct
) {
4685 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4686 REQUIRED(type, DwarfMacinfoTypeField, ); \
4687 OPTIONAL(line, LineField, ); \
4688 REQUIRED(name, MDStringField, ); \
4689 OPTIONAL(value, MDStringField, );
4691 #undef VISIT_MD_FIELDS
4693 Result
= GET_OR_DISTINCT(DIMacro
,
4694 (Context
, type
.Val
, line
.Val
, name
.Val
, value
.Val
));
4698 /// ParseDIMacroFile:
4699 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4700 bool LLParser::ParseDIMacroFile(MDNode
*&Result
, bool IsDistinct
) {
4701 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4702 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4703 OPTIONAL(line, LineField, ); \
4704 REQUIRED(file, MDField, ); \
4705 OPTIONAL(nodes, MDField, );
4707 #undef VISIT_MD_FIELDS
4709 Result
= GET_OR_DISTINCT(DIMacroFile
,
4710 (Context
, type
.Val
, line
.Val
, file
.Val
, nodes
.Val
));
4715 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4716 /// includePath: "/usr/include", isysroot: "/")
4717 bool LLParser::ParseDIModule(MDNode
*&Result
, bool IsDistinct
) {
4718 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4719 REQUIRED(scope, MDField, ); \
4720 REQUIRED(name, MDStringField, ); \
4721 OPTIONAL(configMacros, MDStringField, ); \
4722 OPTIONAL(includePath, MDStringField, ); \
4723 OPTIONAL(isysroot, MDStringField, );
4725 #undef VISIT_MD_FIELDS
4727 Result
= GET_OR_DISTINCT(DIModule
, (Context
, scope
.Val
, name
.Val
,
4728 configMacros
.Val
, includePath
.Val
, isysroot
.Val
));
4732 /// ParseDITemplateTypeParameter:
4733 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4734 bool LLParser::ParseDITemplateTypeParameter(MDNode
*&Result
, bool IsDistinct
) {
4735 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4736 OPTIONAL(name, MDStringField, ); \
4737 REQUIRED(type, MDField, );
4739 #undef VISIT_MD_FIELDS
4742 GET_OR_DISTINCT(DITemplateTypeParameter
, (Context
, name
.Val
, type
.Val
));
4746 /// ParseDITemplateValueParameter:
4747 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4748 /// name: "V", type: !1, value: i32 7)
4749 bool LLParser::ParseDITemplateValueParameter(MDNode
*&Result
, bool IsDistinct
) {
4750 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4751 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4752 OPTIONAL(name, MDStringField, ); \
4753 OPTIONAL(type, MDField, ); \
4754 REQUIRED(value, MDField, );
4756 #undef VISIT_MD_FIELDS
4758 Result
= GET_OR_DISTINCT(DITemplateValueParameter
,
4759 (Context
, tag
.Val
, name
.Val
, type
.Val
, value
.Val
));
4763 /// ParseDIGlobalVariable:
4764 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4765 /// file: !1, line: 7, type: !2, isLocal: false,
4766 /// isDefinition: true, templateParams: !3,
4767 /// declaration: !4, align: 8)
4768 bool LLParser::ParseDIGlobalVariable(MDNode
*&Result
, bool IsDistinct
) {
4769 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4770 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4771 OPTIONAL(scope, MDField, ); \
4772 OPTIONAL(linkageName, MDStringField, ); \
4773 OPTIONAL(file, MDField, ); \
4774 OPTIONAL(line, LineField, ); \
4775 OPTIONAL(type, MDField, ); \
4776 OPTIONAL(isLocal, MDBoolField, ); \
4777 OPTIONAL(isDefinition, MDBoolField, (true)); \
4778 OPTIONAL(templateParams, MDField, ); \
4779 OPTIONAL(declaration, MDField, ); \
4780 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4782 #undef VISIT_MD_FIELDS
4785 GET_OR_DISTINCT(DIGlobalVariable
,
4786 (Context
, scope
.Val
, name
.Val
, linkageName
.Val
, file
.Val
,
4787 line
.Val
, type
.Val
, isLocal
.Val
, isDefinition
.Val
,
4788 declaration
.Val
, templateParams
.Val
, align
.Val
));
4792 /// ParseDILocalVariable:
4793 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4794 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4796 /// ::= !DILocalVariable(scope: !0, name: "foo",
4797 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4799 bool LLParser::ParseDILocalVariable(MDNode
*&Result
, bool IsDistinct
) {
4800 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4801 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4802 OPTIONAL(name, MDStringField, ); \
4803 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4804 OPTIONAL(file, MDField, ); \
4805 OPTIONAL(line, LineField, ); \
4806 OPTIONAL(type, MDField, ); \
4807 OPTIONAL(flags, DIFlagField, ); \
4808 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4810 #undef VISIT_MD_FIELDS
4812 Result
= GET_OR_DISTINCT(DILocalVariable
,
4813 (Context
, scope
.Val
, name
.Val
, file
.Val
, line
.Val
,
4814 type
.Val
, arg
.Val
, flags
.Val
, align
.Val
));
4819 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4820 bool LLParser::ParseDILabel(MDNode
*&Result
, bool IsDistinct
) {
4821 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4822 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4823 REQUIRED(name, MDStringField, ); \
4824 REQUIRED(file, MDField, ); \
4825 REQUIRED(line, LineField, );
4827 #undef VISIT_MD_FIELDS
4829 Result
= GET_OR_DISTINCT(DILabel
,
4830 (Context
, scope
.Val
, name
.Val
, file
.Val
, line
.Val
));
4834 /// ParseDIExpression:
4835 /// ::= !DIExpression(0, 7, -1)
4836 bool LLParser::ParseDIExpression(MDNode
*&Result
, bool IsDistinct
) {
4837 assert(Lex
.getKind() == lltok::MetadataVar
&& "Expected metadata type name");
4840 if (ParseToken(lltok::lparen
, "expected '(' here"))
4843 SmallVector
<uint64_t, 8> Elements
;
4844 if (Lex
.getKind() != lltok::rparen
)
4846 if (Lex
.getKind() == lltok::DwarfOp
) {
4847 if (unsigned Op
= dwarf::getOperationEncoding(Lex
.getStrVal())) {
4849 Elements
.push_back(Op
);
4852 return TokError(Twine("invalid DWARF op '") + Lex
.getStrVal() + "'");
4855 if (Lex
.getKind() == lltok::DwarfAttEncoding
) {
4856 if (unsigned Op
= dwarf::getAttributeEncoding(Lex
.getStrVal())) {
4858 Elements
.push_back(Op
);
4861 return TokError(Twine("invalid DWARF attribute encoding '") + Lex
.getStrVal() + "'");
4864 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
4865 return TokError("expected unsigned integer");
4867 auto &U
= Lex
.getAPSIntVal();
4868 if (U
.ugt(UINT64_MAX
))
4869 return TokError("element too large, limit is " + Twine(UINT64_MAX
));
4870 Elements
.push_back(U
.getZExtValue());
4872 } while (EatIfPresent(lltok::comma
));
4874 if (ParseToken(lltok::rparen
, "expected ')' here"))
4877 Result
= GET_OR_DISTINCT(DIExpression
, (Context
, Elements
));
4881 /// ParseDIGlobalVariableExpression:
4882 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4883 bool LLParser::ParseDIGlobalVariableExpression(MDNode
*&Result
,
4885 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4886 REQUIRED(var, MDField, ); \
4887 REQUIRED(expr, MDField, );
4889 #undef VISIT_MD_FIELDS
4892 GET_OR_DISTINCT(DIGlobalVariableExpression
, (Context
, var
.Val
, expr
.Val
));
4896 /// ParseDIObjCProperty:
4897 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4898 /// getter: "getFoo", attributes: 7, type: !2)
4899 bool LLParser::ParseDIObjCProperty(MDNode
*&Result
, bool IsDistinct
) {
4900 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4901 OPTIONAL(name, MDStringField, ); \
4902 OPTIONAL(file, MDField, ); \
4903 OPTIONAL(line, LineField, ); \
4904 OPTIONAL(setter, MDStringField, ); \
4905 OPTIONAL(getter, MDStringField, ); \
4906 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4907 OPTIONAL(type, MDField, );
4909 #undef VISIT_MD_FIELDS
4911 Result
= GET_OR_DISTINCT(DIObjCProperty
,
4912 (Context
, name
.Val
, file
.Val
, line
.Val
, setter
.Val
,
4913 getter
.Val
, attributes
.Val
, type
.Val
));
4917 /// ParseDIImportedEntity:
4918 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4919 /// line: 7, name: "foo")
4920 bool LLParser::ParseDIImportedEntity(MDNode
*&Result
, bool IsDistinct
) {
4921 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4922 REQUIRED(tag, DwarfTagField, ); \
4923 REQUIRED(scope, MDField, ); \
4924 OPTIONAL(entity, MDField, ); \
4925 OPTIONAL(file, MDField, ); \
4926 OPTIONAL(line, LineField, ); \
4927 OPTIONAL(name, MDStringField, );
4929 #undef VISIT_MD_FIELDS
4931 Result
= GET_OR_DISTINCT(
4933 (Context
, tag
.Val
, scope
.Val
, entity
.Val
, file
.Val
, line
.Val
, name
.Val
));
4937 #undef PARSE_MD_FIELD
4939 #undef REQUIRE_FIELD
4940 #undef DECLARE_FIELD
4942 /// ParseMetadataAsValue
4943 /// ::= metadata i32 %local
4944 /// ::= metadata i32 @global
4945 /// ::= metadata i32 7
4947 /// ::= metadata !{...}
4948 /// ::= metadata !"string"
4949 bool LLParser::ParseMetadataAsValue(Value
*&V
, PerFunctionState
&PFS
) {
4950 // Note: the type 'metadata' has already been parsed.
4952 if (ParseMetadata(MD
, &PFS
))
4955 V
= MetadataAsValue::get(Context
, MD
);
4959 /// ParseValueAsMetadata
4963 bool LLParser::ParseValueAsMetadata(Metadata
*&MD
, const Twine
&TypeMsg
,
4964 PerFunctionState
*PFS
) {
4967 if (ParseType(Ty
, TypeMsg
, Loc
))
4969 if (Ty
->isMetadataTy())
4970 return Error(Loc
, "invalid metadata-value-metadata roundtrip");
4973 if (ParseValue(Ty
, V
, PFS
))
4976 MD
= ValueAsMetadata::get(V
);
4987 /// ::= !DILocation(...)
4988 bool LLParser::ParseMetadata(Metadata
*&MD
, PerFunctionState
*PFS
) {
4989 if (Lex
.getKind() == lltok::MetadataVar
) {
4991 if (ParseSpecializedMDNode(N
))
4999 if (Lex
.getKind() != lltok::exclaim
)
5000 return ParseValueAsMetadata(MD
, "expected metadata operand", PFS
);
5003 assert(Lex
.getKind() == lltok::exclaim
&& "Expected '!' here");
5007 // ::= '!' STRINGCONSTANT
5008 if (Lex
.getKind() == lltok::StringConstant
) {
5010 if (ParseMDString(S
))
5020 if (ParseMDNodeTail(N
))
5026 //===----------------------------------------------------------------------===//
5027 // Function Parsing.
5028 //===----------------------------------------------------------------------===//
5030 bool LLParser::ConvertValIDToValue(Type
*Ty
, ValID
&ID
, Value
*&V
,
5031 PerFunctionState
*PFS
, bool IsCall
) {
5032 if (Ty
->isFunctionTy())
5033 return Error(ID
.Loc
, "functions are not values, refer to them as pointers");
5036 case ValID::t_LocalID
:
5037 if (!PFS
) return Error(ID
.Loc
, "invalid use of function-local name");
5038 V
= PFS
->GetVal(ID
.UIntVal
, Ty
, ID
.Loc
, IsCall
);
5039 return V
== nullptr;
5040 case ValID::t_LocalName
:
5041 if (!PFS
) return Error(ID
.Loc
, "invalid use of function-local name");
5042 V
= PFS
->GetVal(ID
.StrVal
, Ty
, ID
.Loc
, IsCall
);
5043 return V
== nullptr;
5044 case ValID::t_InlineAsm
: {
5045 if (!ID
.FTy
|| !InlineAsm::Verify(ID
.FTy
, ID
.StrVal2
))
5046 return Error(ID
.Loc
, "invalid type for inline asm constraint string");
5047 V
= InlineAsm::get(ID
.FTy
, ID
.StrVal
, ID
.StrVal2
, ID
.UIntVal
& 1,
5048 (ID
.UIntVal
>> 1) & 1,
5049 (InlineAsm::AsmDialect(ID
.UIntVal
>> 2)));
5052 case ValID::t_GlobalName
:
5053 V
= GetGlobalVal(ID
.StrVal
, Ty
, ID
.Loc
, IsCall
);
5054 return V
== nullptr;
5055 case ValID::t_GlobalID
:
5056 V
= GetGlobalVal(ID
.UIntVal
, Ty
, ID
.Loc
, IsCall
);
5057 return V
== nullptr;
5058 case ValID::t_APSInt
:
5059 if (!Ty
->isIntegerTy())
5060 return Error(ID
.Loc
, "integer constant must have integer type");
5061 ID
.APSIntVal
= ID
.APSIntVal
.extOrTrunc(Ty
->getPrimitiveSizeInBits());
5062 V
= ConstantInt::get(Context
, ID
.APSIntVal
);
5064 case ValID::t_APFloat
:
5065 if (!Ty
->isFloatingPointTy() ||
5066 !ConstantFP::isValueValidForType(Ty
, ID
.APFloatVal
))
5067 return Error(ID
.Loc
, "floating point constant invalid for type");
5069 // The lexer has no type info, so builds all half, float, and double FP
5070 // constants as double. Fix this here. Long double does not need this.
5071 if (&ID
.APFloatVal
.getSemantics() == &APFloat::IEEEdouble()) {
5074 ID
.APFloatVal
.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven
,
5076 else if (Ty
->isFloatTy())
5077 ID
.APFloatVal
.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven
,
5080 V
= ConstantFP::get(Context
, ID
.APFloatVal
);
5082 if (V
->getType() != Ty
)
5083 return Error(ID
.Loc
, "floating point constant does not have type '" +
5084 getTypeString(Ty
) + "'");
5088 if (!Ty
->isPointerTy())
5089 return Error(ID
.Loc
, "null must be a pointer type");
5090 V
= ConstantPointerNull::get(cast
<PointerType
>(Ty
));
5092 case ValID::t_Undef
:
5093 // FIXME: LabelTy should not be a first-class type.
5094 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5095 return Error(ID
.Loc
, "invalid type for undef constant");
5096 V
= UndefValue::get(Ty
);
5098 case ValID::t_EmptyArray
:
5099 if (!Ty
->isArrayTy() || cast
<ArrayType
>(Ty
)->getNumElements() != 0)
5100 return Error(ID
.Loc
, "invalid empty array initializer");
5101 V
= UndefValue::get(Ty
);
5104 // FIXME: LabelTy should not be a first-class type.
5105 if (!Ty
->isFirstClassType() || Ty
->isLabelTy())
5106 return Error(ID
.Loc
, "invalid type for null constant");
5107 V
= Constant::getNullValue(Ty
);
5110 if (!Ty
->isTokenTy())
5111 return Error(ID
.Loc
, "invalid type for none constant");
5112 V
= Constant::getNullValue(Ty
);
5114 case ValID::t_Constant
:
5115 if (ID
.ConstantVal
->getType() != Ty
)
5116 return Error(ID
.Loc
, "constant expression type mismatch");
5120 case ValID::t_ConstantStruct
:
5121 case ValID::t_PackedConstantStruct
:
5122 if (StructType
*ST
= dyn_cast
<StructType
>(Ty
)) {
5123 if (ST
->getNumElements() != ID
.UIntVal
)
5124 return Error(ID
.Loc
,
5125 "initializer with struct type has wrong # elements");
5126 if (ST
->isPacked() != (ID
.Kind
== ValID::t_PackedConstantStruct
))
5127 return Error(ID
.Loc
, "packed'ness of initializer and type don't match");
5129 // Verify that the elements are compatible with the structtype.
5130 for (unsigned i
= 0, e
= ID
.UIntVal
; i
!= e
; ++i
)
5131 if (ID
.ConstantStructElts
[i
]->getType() != ST
->getElementType(i
))
5132 return Error(ID
.Loc
, "element " + Twine(i
) +
5133 " of struct initializer doesn't match struct element type");
5135 V
= ConstantStruct::get(
5136 ST
, makeArrayRef(ID
.ConstantStructElts
.get(), ID
.UIntVal
));
5138 return Error(ID
.Loc
, "constant expression type mismatch");
5141 llvm_unreachable("Invalid ValID");
5144 bool LLParser::parseConstantValue(Type
*Ty
, Constant
*&C
) {
5147 auto Loc
= Lex
.getLoc();
5148 if (ParseValID(ID
, /*PFS=*/nullptr))
5151 case ValID::t_APSInt
:
5152 case ValID::t_APFloat
:
5153 case ValID::t_Undef
:
5154 case ValID::t_Constant
:
5155 case ValID::t_ConstantStruct
:
5156 case ValID::t_PackedConstantStruct
: {
5158 if (ConvertValIDToValue(Ty
, ID
, V
, /*PFS=*/nullptr, /*IsCall=*/false))
5160 assert(isa
<Constant
>(V
) && "Expected a constant value");
5161 C
= cast
<Constant
>(V
);
5165 C
= Constant::getNullValue(Ty
);
5168 return Error(Loc
, "expected a constant value");
5172 bool LLParser::ParseValue(Type
*Ty
, Value
*&V
, PerFunctionState
*PFS
) {
5175 return ParseValID(ID
, PFS
) ||
5176 ConvertValIDToValue(Ty
, ID
, V
, PFS
, /*IsCall=*/false);
5179 bool LLParser::ParseTypeAndValue(Value
*&V
, PerFunctionState
*PFS
) {
5181 return ParseType(Ty
) ||
5182 ParseValue(Ty
, V
, PFS
);
5185 bool LLParser::ParseTypeAndBasicBlock(BasicBlock
*&BB
, LocTy
&Loc
,
5186 PerFunctionState
&PFS
) {
5189 if (ParseTypeAndValue(V
, PFS
)) return true;
5190 if (!isa
<BasicBlock
>(V
))
5191 return Error(Loc
, "expected a basic block");
5192 BB
= cast
<BasicBlock
>(V
);
5197 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5198 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5199 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5200 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5201 bool LLParser::ParseFunctionHeader(Function
*&Fn
, bool isDefine
) {
5202 // Parse the linkage.
5203 LocTy LinkageLoc
= Lex
.getLoc();
5205 unsigned Visibility
;
5206 unsigned DLLStorageClass
;
5208 AttrBuilder RetAttrs
;
5211 Type
*RetType
= nullptr;
5212 LocTy RetTypeLoc
= Lex
.getLoc();
5213 if (ParseOptionalLinkage(Linkage
, HasLinkage
, Visibility
, DLLStorageClass
,
5215 ParseOptionalCallingConv(CC
) || ParseOptionalReturnAttrs(RetAttrs
) ||
5216 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/))
5219 // Verify that the linkage is ok.
5220 switch ((GlobalValue::LinkageTypes
)Linkage
) {
5221 case GlobalValue::ExternalLinkage
:
5222 break; // always ok.
5223 case GlobalValue::ExternalWeakLinkage
:
5225 return Error(LinkageLoc
, "invalid linkage for function definition");
5227 case GlobalValue::PrivateLinkage
:
5228 case GlobalValue::InternalLinkage
:
5229 case GlobalValue::AvailableExternallyLinkage
:
5230 case GlobalValue::LinkOnceAnyLinkage
:
5231 case GlobalValue::LinkOnceODRLinkage
:
5232 case GlobalValue::WeakAnyLinkage
:
5233 case GlobalValue::WeakODRLinkage
:
5235 return Error(LinkageLoc
, "invalid linkage for function declaration");
5237 case GlobalValue::AppendingLinkage
:
5238 case GlobalValue::CommonLinkage
:
5239 return Error(LinkageLoc
, "invalid function linkage type");
5242 if (!isValidVisibilityForLinkage(Visibility
, Linkage
))
5243 return Error(LinkageLoc
,
5244 "symbol with local linkage must have default visibility");
5246 if (!FunctionType::isValidReturnType(RetType
))
5247 return Error(RetTypeLoc
, "invalid function return type");
5249 LocTy NameLoc
= Lex
.getLoc();
5251 std::string FunctionName
;
5252 if (Lex
.getKind() == lltok::GlobalVar
) {
5253 FunctionName
= Lex
.getStrVal();
5254 } else if (Lex
.getKind() == lltok::GlobalID
) { // @42 is ok.
5255 unsigned NameID
= Lex
.getUIntVal();
5257 if (NameID
!= NumberedVals
.size())
5258 return TokError("function expected to be numbered '%" +
5259 Twine(NumberedVals
.size()) + "'");
5261 return TokError("expected function name");
5266 if (Lex
.getKind() != lltok::lparen
)
5267 return TokError("expected '(' in function argument list");
5269 SmallVector
<ArgInfo
, 8> ArgList
;
5271 AttrBuilder FuncAttrs
;
5272 std::vector
<unsigned> FwdRefAttrGrps
;
5274 std::string Section
;
5277 GlobalValue::UnnamedAddr UnnamedAddr
= GlobalValue::UnnamedAddr::None
;
5278 unsigned AddrSpace
= 0;
5279 Constant
*Prefix
= nullptr;
5280 Constant
*Prologue
= nullptr;
5281 Constant
*PersonalityFn
= nullptr;
5284 if (ParseArgumentList(ArgList
, isVarArg
) ||
5285 ParseOptionalUnnamedAddr(UnnamedAddr
) ||
5286 ParseOptionalProgramAddrSpace(AddrSpace
) ||
5287 ParseFnAttributeValuePairs(FuncAttrs
, FwdRefAttrGrps
, false,
5289 (EatIfPresent(lltok::kw_section
) &&
5290 ParseStringConstant(Section
)) ||
5291 parseOptionalComdat(FunctionName
, C
) ||
5292 ParseOptionalAlignment(Alignment
) ||
5293 (EatIfPresent(lltok::kw_gc
) &&
5294 ParseStringConstant(GC
)) ||
5295 (EatIfPresent(lltok::kw_prefix
) &&
5296 ParseGlobalTypeAndValue(Prefix
)) ||
5297 (EatIfPresent(lltok::kw_prologue
) &&
5298 ParseGlobalTypeAndValue(Prologue
)) ||
5299 (EatIfPresent(lltok::kw_personality
) &&
5300 ParseGlobalTypeAndValue(PersonalityFn
)))
5303 if (FuncAttrs
.contains(Attribute::Builtin
))
5304 return Error(BuiltinLoc
, "'builtin' attribute not valid on function");
5306 // If the alignment was parsed as an attribute, move to the alignment field.
5307 if (FuncAttrs
.hasAlignmentAttr()) {
5308 Alignment
= FuncAttrs
.getAlignment();
5309 FuncAttrs
.removeAttribute(Attribute::Alignment
);
5312 // Okay, if we got here, the function is syntactically valid. Convert types
5313 // and do semantic checks.
5314 std::vector
<Type
*> ParamTypeList
;
5315 SmallVector
<AttributeSet
, 8> Attrs
;
5317 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
5318 ParamTypeList
.push_back(ArgList
[i
].Ty
);
5319 Attrs
.push_back(ArgList
[i
].Attrs
);
5323 AttributeList::get(Context
, AttributeSet::get(Context
, FuncAttrs
),
5324 AttributeSet::get(Context
, RetAttrs
), Attrs
);
5326 if (PAL
.hasAttribute(1, Attribute::StructRet
) && !RetType
->isVoidTy())
5327 return Error(RetTypeLoc
, "functions with 'sret' argument must return void");
5330 FunctionType::get(RetType
, ParamTypeList
, isVarArg
);
5331 PointerType
*PFT
= PointerType::get(FT
, AddrSpace
);
5334 if (!FunctionName
.empty()) {
5335 // If this was a definition of a forward reference, remove the definition
5336 // from the forward reference table and fill in the forward ref.
5337 auto FRVI
= ForwardRefVals
.find(FunctionName
);
5338 if (FRVI
!= ForwardRefVals
.end()) {
5339 Fn
= M
->getFunction(FunctionName
);
5341 return Error(FRVI
->second
.second
, "invalid forward reference to "
5342 "function as global value!");
5343 if (Fn
->getType() != PFT
)
5344 return Error(FRVI
->second
.second
, "invalid forward reference to "
5345 "function '" + FunctionName
+ "' with wrong type: "
5346 "expected '" + getTypeString(PFT
) + "' but was '" +
5347 getTypeString(Fn
->getType()) + "'");
5348 ForwardRefVals
.erase(FRVI
);
5349 } else if ((Fn
= M
->getFunction(FunctionName
))) {
5350 // Reject redefinitions.
5351 return Error(NameLoc
, "invalid redefinition of function '" +
5352 FunctionName
+ "'");
5353 } else if (M
->getNamedValue(FunctionName
)) {
5354 return Error(NameLoc
, "redefinition of function '@" + FunctionName
+ "'");
5358 // If this is a definition of a forward referenced function, make sure the
5360 auto I
= ForwardRefValIDs
.find(NumberedVals
.size());
5361 if (I
!= ForwardRefValIDs
.end()) {
5362 Fn
= cast
<Function
>(I
->second
.first
);
5363 if (Fn
->getType() != PFT
)
5364 return Error(NameLoc
, "type of definition and forward reference of '@" +
5365 Twine(NumberedVals
.size()) + "' disagree: "
5366 "expected '" + getTypeString(PFT
) + "' but was '" +
5367 getTypeString(Fn
->getType()) + "'");
5368 ForwardRefValIDs
.erase(I
);
5373 Fn
= Function::Create(FT
, GlobalValue::ExternalLinkage
, AddrSpace
,
5375 else // Move the forward-reference to the correct spot in the module.
5376 M
->getFunctionList().splice(M
->end(), M
->getFunctionList(), Fn
);
5378 assert(Fn
->getAddressSpace() == AddrSpace
&& "Created function in wrong AS");
5380 if (FunctionName
.empty())
5381 NumberedVals
.push_back(Fn
);
5383 Fn
->setLinkage((GlobalValue::LinkageTypes
)Linkage
);
5384 maybeSetDSOLocal(DSOLocal
, *Fn
);
5385 Fn
->setVisibility((GlobalValue::VisibilityTypes
)Visibility
);
5386 Fn
->setDLLStorageClass((GlobalValue::DLLStorageClassTypes
)DLLStorageClass
);
5387 Fn
->setCallingConv(CC
);
5388 Fn
->setAttributes(PAL
);
5389 Fn
->setUnnamedAddr(UnnamedAddr
);
5390 Fn
->setAlignment(Alignment
);
5391 Fn
->setSection(Section
);
5393 Fn
->setPersonalityFn(PersonalityFn
);
5394 if (!GC
.empty()) Fn
->setGC(GC
);
5395 Fn
->setPrefixData(Prefix
);
5396 Fn
->setPrologueData(Prologue
);
5397 ForwardRefAttrGroups
[Fn
] = FwdRefAttrGrps
;
5399 // Add all of the arguments we parsed to the function.
5400 Function::arg_iterator ArgIt
= Fn
->arg_begin();
5401 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
, ++ArgIt
) {
5402 // If the argument has a name, insert it into the argument symbol table.
5403 if (ArgList
[i
].Name
.empty()) continue;
5405 // Set the name, if it conflicted, it will be auto-renamed.
5406 ArgIt
->setName(ArgList
[i
].Name
);
5408 if (ArgIt
->getName() != ArgList
[i
].Name
)
5409 return Error(ArgList
[i
].Loc
, "redefinition of argument '%" +
5410 ArgList
[i
].Name
+ "'");
5416 // Check the declaration has no block address forward references.
5418 if (FunctionName
.empty()) {
5419 ID
.Kind
= ValID::t_GlobalID
;
5420 ID
.UIntVal
= NumberedVals
.size() - 1;
5422 ID
.Kind
= ValID::t_GlobalName
;
5423 ID
.StrVal
= FunctionName
;
5425 auto Blocks
= ForwardRefBlockAddresses
.find(ID
);
5426 if (Blocks
!= ForwardRefBlockAddresses
.end())
5427 return Error(Blocks
->first
.Loc
,
5428 "cannot take blockaddress inside a declaration");
5432 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5434 if (FunctionNumber
== -1) {
5435 ID
.Kind
= ValID::t_GlobalName
;
5436 ID
.StrVal
= F
.getName();
5438 ID
.Kind
= ValID::t_GlobalID
;
5439 ID
.UIntVal
= FunctionNumber
;
5442 auto Blocks
= P
.ForwardRefBlockAddresses
.find(ID
);
5443 if (Blocks
== P
.ForwardRefBlockAddresses
.end())
5446 for (const auto &I
: Blocks
->second
) {
5447 const ValID
&BBID
= I
.first
;
5448 GlobalValue
*GV
= I
.second
;
5450 assert((BBID
.Kind
== ValID::t_LocalID
|| BBID
.Kind
== ValID::t_LocalName
) &&
5451 "Expected local id or name");
5453 if (BBID
.Kind
== ValID::t_LocalName
)
5454 BB
= GetBB(BBID
.StrVal
, BBID
.Loc
);
5456 BB
= GetBB(BBID
.UIntVal
, BBID
.Loc
);
5458 return P
.Error(BBID
.Loc
, "referenced value is not a basic block");
5460 GV
->replaceAllUsesWith(BlockAddress::get(&F
, BB
));
5461 GV
->eraseFromParent();
5464 P
.ForwardRefBlockAddresses
.erase(Blocks
);
5468 /// ParseFunctionBody
5469 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5470 bool LLParser::ParseFunctionBody(Function
&Fn
) {
5471 if (Lex
.getKind() != lltok::lbrace
)
5472 return TokError("expected '{' in function body");
5473 Lex
.Lex(); // eat the {.
5475 int FunctionNumber
= -1;
5476 if (!Fn
.hasName()) FunctionNumber
= NumberedVals
.size()-1;
5478 PerFunctionState
PFS(*this, Fn
, FunctionNumber
);
5480 // Resolve block addresses and allow basic blocks to be forward-declared
5481 // within this function.
5482 if (PFS
.resolveForwardRefBlockAddresses())
5484 SaveAndRestore
<PerFunctionState
*> ScopeExit(BlockAddressPFS
, &PFS
);
5486 // We need at least one basic block.
5487 if (Lex
.getKind() == lltok::rbrace
|| Lex
.getKind() == lltok::kw_uselistorder
)
5488 return TokError("function body requires at least one basic block");
5490 while (Lex
.getKind() != lltok::rbrace
&&
5491 Lex
.getKind() != lltok::kw_uselistorder
)
5492 if (ParseBasicBlock(PFS
)) return true;
5494 while (Lex
.getKind() != lltok::rbrace
)
5495 if (ParseUseListOrder(&PFS
))
5501 // Verify function is ok.
5502 return PFS
.FinishFunction();
5506 /// ::= (LabelStr|LabelID)? Instruction*
5507 bool LLParser::ParseBasicBlock(PerFunctionState
&PFS
) {
5508 // If this basic block starts out with a name, remember it.
5511 LocTy NameLoc
= Lex
.getLoc();
5512 if (Lex
.getKind() == lltok::LabelStr
) {
5513 Name
= Lex
.getStrVal();
5515 } else if (Lex
.getKind() == lltok::LabelID
) {
5516 NameID
= Lex
.getUIntVal();
5520 BasicBlock
*BB
= PFS
.DefineBB(Name
, NameID
, NameLoc
);
5524 std::string NameStr
;
5526 // Parse the instructions in this block until we get a terminator.
5529 // This instruction may have three possibilities for a name: a) none
5530 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5531 LocTy NameLoc
= Lex
.getLoc();
5535 if (Lex
.getKind() == lltok::LocalVarID
) {
5536 NameID
= Lex
.getUIntVal();
5538 if (ParseToken(lltok::equal
, "expected '=' after instruction id"))
5540 } else if (Lex
.getKind() == lltok::LocalVar
) {
5541 NameStr
= Lex
.getStrVal();
5543 if (ParseToken(lltok::equal
, "expected '=' after instruction name"))
5547 switch (ParseInstruction(Inst
, BB
, PFS
)) {
5548 default: llvm_unreachable("Unknown ParseInstruction result!");
5549 case InstError
: return true;
5551 BB
->getInstList().push_back(Inst
);
5553 // With a normal result, we check to see if the instruction is followed by
5554 // a comma and metadata.
5555 if (EatIfPresent(lltok::comma
))
5556 if (ParseInstructionMetadata(*Inst
))
5559 case InstExtraComma
:
5560 BB
->getInstList().push_back(Inst
);
5562 // If the instruction parser ate an extra comma at the end of it, it
5563 // *must* be followed by metadata.
5564 if (ParseInstructionMetadata(*Inst
))
5569 // Set the name on the instruction.
5570 if (PFS
.SetInstName(NameID
, NameStr
, NameLoc
, Inst
)) return true;
5571 } while (!Inst
->isTerminator());
5576 //===----------------------------------------------------------------------===//
5577 // Instruction Parsing.
5578 //===----------------------------------------------------------------------===//
5580 /// ParseInstruction - Parse one of the many different instructions.
5582 int LLParser::ParseInstruction(Instruction
*&Inst
, BasicBlock
*BB
,
5583 PerFunctionState
&PFS
) {
5584 lltok::Kind Token
= Lex
.getKind();
5585 if (Token
== lltok::Eof
)
5586 return TokError("found end of file when expecting more instructions");
5587 LocTy Loc
= Lex
.getLoc();
5588 unsigned KeywordVal
= Lex
.getUIntVal();
5589 Lex
.Lex(); // Eat the keyword.
5592 default: return Error(Loc
, "expected instruction opcode");
5593 // Terminator Instructions.
5594 case lltok::kw_unreachable
: Inst
= new UnreachableInst(Context
); return false;
5595 case lltok::kw_ret
: return ParseRet(Inst
, BB
, PFS
);
5596 case lltok::kw_br
: return ParseBr(Inst
, PFS
);
5597 case lltok::kw_switch
: return ParseSwitch(Inst
, PFS
);
5598 case lltok::kw_indirectbr
: return ParseIndirectBr(Inst
, PFS
);
5599 case lltok::kw_invoke
: return ParseInvoke(Inst
, PFS
);
5600 case lltok::kw_resume
: return ParseResume(Inst
, PFS
);
5601 case lltok::kw_cleanupret
: return ParseCleanupRet(Inst
, PFS
);
5602 case lltok::kw_catchret
: return ParseCatchRet(Inst
, PFS
);
5603 case lltok::kw_catchswitch
: return ParseCatchSwitch(Inst
, PFS
);
5604 case lltok::kw_catchpad
: return ParseCatchPad(Inst
, PFS
);
5605 case lltok::kw_cleanuppad
: return ParseCleanupPad(Inst
, PFS
);
5606 case lltok::kw_callbr
: return ParseCallBr(Inst
, PFS
);
5608 case lltok::kw_fneg
: {
5609 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5610 int Res
= ParseUnaryOp(Inst
, PFS
, KeywordVal
, 2);
5614 Inst
->setFastMathFlags(FMF
);
5617 // Binary Operators.
5621 case lltok::kw_shl
: {
5622 bool NUW
= EatIfPresent(lltok::kw_nuw
);
5623 bool NSW
= EatIfPresent(lltok::kw_nsw
);
5624 if (!NUW
) NUW
= EatIfPresent(lltok::kw_nuw
);
5626 if (ParseArithmetic(Inst
, PFS
, KeywordVal
, 1)) return true;
5628 if (NUW
) cast
<BinaryOperator
>(Inst
)->setHasNoUnsignedWrap(true);
5629 if (NSW
) cast
<BinaryOperator
>(Inst
)->setHasNoSignedWrap(true);
5632 case lltok::kw_fadd
:
5633 case lltok::kw_fsub
:
5634 case lltok::kw_fmul
:
5635 case lltok::kw_fdiv
:
5636 case lltok::kw_frem
: {
5637 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5638 int Res
= ParseArithmetic(Inst
, PFS
, KeywordVal
, 2);
5642 Inst
->setFastMathFlags(FMF
);
5646 case lltok::kw_sdiv
:
5647 case lltok::kw_udiv
:
5648 case lltok::kw_lshr
:
5649 case lltok::kw_ashr
: {
5650 bool Exact
= EatIfPresent(lltok::kw_exact
);
5652 if (ParseArithmetic(Inst
, PFS
, KeywordVal
, 1)) return true;
5653 if (Exact
) cast
<BinaryOperator
>(Inst
)->setIsExact(true);
5657 case lltok::kw_urem
:
5658 case lltok::kw_srem
: return ParseArithmetic(Inst
, PFS
, KeywordVal
, 1);
5661 case lltok::kw_xor
: return ParseLogical(Inst
, PFS
, KeywordVal
);
5662 case lltok::kw_icmp
: return ParseCompare(Inst
, PFS
, KeywordVal
);
5663 case lltok::kw_fcmp
: {
5664 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
5665 int Res
= ParseCompare(Inst
, PFS
, KeywordVal
);
5669 Inst
->setFastMathFlags(FMF
);
5674 case lltok::kw_trunc
:
5675 case lltok::kw_zext
:
5676 case lltok::kw_sext
:
5677 case lltok::kw_fptrunc
:
5678 case lltok::kw_fpext
:
5679 case lltok::kw_bitcast
:
5680 case lltok::kw_addrspacecast
:
5681 case lltok::kw_uitofp
:
5682 case lltok::kw_sitofp
:
5683 case lltok::kw_fptoui
:
5684 case lltok::kw_fptosi
:
5685 case lltok::kw_inttoptr
:
5686 case lltok::kw_ptrtoint
: return ParseCast(Inst
, PFS
, KeywordVal
);
5688 case lltok::kw_select
: return ParseSelect(Inst
, PFS
);
5689 case lltok::kw_va_arg
: return ParseVA_Arg(Inst
, PFS
);
5690 case lltok::kw_extractelement
: return ParseExtractElement(Inst
, PFS
);
5691 case lltok::kw_insertelement
: return ParseInsertElement(Inst
, PFS
);
5692 case lltok::kw_shufflevector
: return ParseShuffleVector(Inst
, PFS
);
5693 case lltok::kw_phi
: return ParsePHI(Inst
, PFS
);
5694 case lltok::kw_landingpad
: return ParseLandingPad(Inst
, PFS
);
5696 case lltok::kw_call
: return ParseCall(Inst
, PFS
, CallInst::TCK_None
);
5697 case lltok::kw_tail
: return ParseCall(Inst
, PFS
, CallInst::TCK_Tail
);
5698 case lltok::kw_musttail
: return ParseCall(Inst
, PFS
, CallInst::TCK_MustTail
);
5699 case lltok::kw_notail
: return ParseCall(Inst
, PFS
, CallInst::TCK_NoTail
);
5701 case lltok::kw_alloca
: return ParseAlloc(Inst
, PFS
);
5702 case lltok::kw_load
: return ParseLoad(Inst
, PFS
);
5703 case lltok::kw_store
: return ParseStore(Inst
, PFS
);
5704 case lltok::kw_cmpxchg
: return ParseCmpXchg(Inst
, PFS
);
5705 case lltok::kw_atomicrmw
: return ParseAtomicRMW(Inst
, PFS
);
5706 case lltok::kw_fence
: return ParseFence(Inst
, PFS
);
5707 case lltok::kw_getelementptr
: return ParseGetElementPtr(Inst
, PFS
);
5708 case lltok::kw_extractvalue
: return ParseExtractValue(Inst
, PFS
);
5709 case lltok::kw_insertvalue
: return ParseInsertValue(Inst
, PFS
);
5713 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5714 bool LLParser::ParseCmpPredicate(unsigned &P
, unsigned Opc
) {
5715 if (Opc
== Instruction::FCmp
) {
5716 switch (Lex
.getKind()) {
5717 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5718 case lltok::kw_oeq
: P
= CmpInst::FCMP_OEQ
; break;
5719 case lltok::kw_one
: P
= CmpInst::FCMP_ONE
; break;
5720 case lltok::kw_olt
: P
= CmpInst::FCMP_OLT
; break;
5721 case lltok::kw_ogt
: P
= CmpInst::FCMP_OGT
; break;
5722 case lltok::kw_ole
: P
= CmpInst::FCMP_OLE
; break;
5723 case lltok::kw_oge
: P
= CmpInst::FCMP_OGE
; break;
5724 case lltok::kw_ord
: P
= CmpInst::FCMP_ORD
; break;
5725 case lltok::kw_uno
: P
= CmpInst::FCMP_UNO
; break;
5726 case lltok::kw_ueq
: P
= CmpInst::FCMP_UEQ
; break;
5727 case lltok::kw_une
: P
= CmpInst::FCMP_UNE
; break;
5728 case lltok::kw_ult
: P
= CmpInst::FCMP_ULT
; break;
5729 case lltok::kw_ugt
: P
= CmpInst::FCMP_UGT
; break;
5730 case lltok::kw_ule
: P
= CmpInst::FCMP_ULE
; break;
5731 case lltok::kw_uge
: P
= CmpInst::FCMP_UGE
; break;
5732 case lltok::kw_true
: P
= CmpInst::FCMP_TRUE
; break;
5733 case lltok::kw_false
: P
= CmpInst::FCMP_FALSE
; break;
5736 switch (Lex
.getKind()) {
5737 default: return TokError("expected icmp predicate (e.g. 'eq')");
5738 case lltok::kw_eq
: P
= CmpInst::ICMP_EQ
; break;
5739 case lltok::kw_ne
: P
= CmpInst::ICMP_NE
; break;
5740 case lltok::kw_slt
: P
= CmpInst::ICMP_SLT
; break;
5741 case lltok::kw_sgt
: P
= CmpInst::ICMP_SGT
; break;
5742 case lltok::kw_sle
: P
= CmpInst::ICMP_SLE
; break;
5743 case lltok::kw_sge
: P
= CmpInst::ICMP_SGE
; break;
5744 case lltok::kw_ult
: P
= CmpInst::ICMP_ULT
; break;
5745 case lltok::kw_ugt
: P
= CmpInst::ICMP_UGT
; break;
5746 case lltok::kw_ule
: P
= CmpInst::ICMP_ULE
; break;
5747 case lltok::kw_uge
: P
= CmpInst::ICMP_UGE
; break;
5754 //===----------------------------------------------------------------------===//
5755 // Terminator Instructions.
5756 //===----------------------------------------------------------------------===//
5758 /// ParseRet - Parse a return instruction.
5759 /// ::= 'ret' void (',' !dbg, !1)*
5760 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5761 bool LLParser::ParseRet(Instruction
*&Inst
, BasicBlock
*BB
,
5762 PerFunctionState
&PFS
) {
5763 SMLoc TypeLoc
= Lex
.getLoc();
5765 if (ParseType(Ty
, true /*void allowed*/)) return true;
5767 Type
*ResType
= PFS
.getFunction().getReturnType();
5769 if (Ty
->isVoidTy()) {
5770 if (!ResType
->isVoidTy())
5771 return Error(TypeLoc
, "value doesn't match function result type '" +
5772 getTypeString(ResType
) + "'");
5774 Inst
= ReturnInst::Create(Context
);
5779 if (ParseValue(Ty
, RV
, PFS
)) return true;
5781 if (ResType
!= RV
->getType())
5782 return Error(TypeLoc
, "value doesn't match function result type '" +
5783 getTypeString(ResType
) + "'");
5785 Inst
= ReturnInst::Create(Context
, RV
);
5790 /// ::= 'br' TypeAndValue
5791 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5792 bool LLParser::ParseBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
5795 BasicBlock
*Op1
, *Op2
;
5796 if (ParseTypeAndValue(Op0
, Loc
, PFS
)) return true;
5798 if (BasicBlock
*BB
= dyn_cast
<BasicBlock
>(Op0
)) {
5799 Inst
= BranchInst::Create(BB
);
5803 if (Op0
->getType() != Type::getInt1Ty(Context
))
5804 return Error(Loc
, "branch condition must have 'i1' type");
5806 if (ParseToken(lltok::comma
, "expected ',' after branch condition") ||
5807 ParseTypeAndBasicBlock(Op1
, Loc
, PFS
) ||
5808 ParseToken(lltok::comma
, "expected ',' after true destination") ||
5809 ParseTypeAndBasicBlock(Op2
, Loc2
, PFS
))
5812 Inst
= BranchInst::Create(Op1
, Op2
, Op0
);
5818 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5820 /// ::= (TypeAndValue ',' TypeAndValue)*
5821 bool LLParser::ParseSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
5822 LocTy CondLoc
, BBLoc
;
5824 BasicBlock
*DefaultBB
;
5825 if (ParseTypeAndValue(Cond
, CondLoc
, PFS
) ||
5826 ParseToken(lltok::comma
, "expected ',' after switch condition") ||
5827 ParseTypeAndBasicBlock(DefaultBB
, BBLoc
, PFS
) ||
5828 ParseToken(lltok::lsquare
, "expected '[' with switch table"))
5831 if (!Cond
->getType()->isIntegerTy())
5832 return Error(CondLoc
, "switch condition must have integer type");
5834 // Parse the jump table pairs.
5835 SmallPtrSet
<Value
*, 32> SeenCases
;
5836 SmallVector
<std::pair
<ConstantInt
*, BasicBlock
*>, 32> Table
;
5837 while (Lex
.getKind() != lltok::rsquare
) {
5841 if (ParseTypeAndValue(Constant
, CondLoc
, PFS
) ||
5842 ParseToken(lltok::comma
, "expected ',' after case value") ||
5843 ParseTypeAndBasicBlock(DestBB
, PFS
))
5846 if (!SeenCases
.insert(Constant
).second
)
5847 return Error(CondLoc
, "duplicate case value in switch");
5848 if (!isa
<ConstantInt
>(Constant
))
5849 return Error(CondLoc
, "case value is not a constant integer");
5851 Table
.push_back(std::make_pair(cast
<ConstantInt
>(Constant
), DestBB
));
5854 Lex
.Lex(); // Eat the ']'.
5856 SwitchInst
*SI
= SwitchInst::Create(Cond
, DefaultBB
, Table
.size());
5857 for (unsigned i
= 0, e
= Table
.size(); i
!= e
; ++i
)
5858 SI
->addCase(Table
[i
].first
, Table
[i
].second
);
5865 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5866 bool LLParser::ParseIndirectBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
5869 if (ParseTypeAndValue(Address
, AddrLoc
, PFS
) ||
5870 ParseToken(lltok::comma
, "expected ',' after indirectbr address") ||
5871 ParseToken(lltok::lsquare
, "expected '[' with indirectbr"))
5874 if (!Address
->getType()->isPointerTy())
5875 return Error(AddrLoc
, "indirectbr address must have pointer type");
5877 // Parse the destination list.
5878 SmallVector
<BasicBlock
*, 16> DestList
;
5880 if (Lex
.getKind() != lltok::rsquare
) {
5882 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
5884 DestList
.push_back(DestBB
);
5886 while (EatIfPresent(lltok::comma
)) {
5887 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
5889 DestList
.push_back(DestBB
);
5893 if (ParseToken(lltok::rsquare
, "expected ']' at end of block list"))
5896 IndirectBrInst
*IBI
= IndirectBrInst::Create(Address
, DestList
.size());
5897 for (unsigned i
= 0, e
= DestList
.size(); i
!= e
; ++i
)
5898 IBI
->addDestination(DestList
[i
]);
5904 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5905 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5906 bool LLParser::ParseInvoke(Instruction
*&Inst
, PerFunctionState
&PFS
) {
5907 LocTy CallLoc
= Lex
.getLoc();
5908 AttrBuilder RetAttrs
, FnAttrs
;
5909 std::vector
<unsigned> FwdRefAttrGrps
;
5912 unsigned InvokeAddrSpace
;
5913 Type
*RetType
= nullptr;
5916 SmallVector
<ParamInfo
, 16> ArgList
;
5917 SmallVector
<OperandBundleDef
, 2> BundleList
;
5919 BasicBlock
*NormalBB
, *UnwindBB
;
5920 if (ParseOptionalCallingConv(CC
) || ParseOptionalReturnAttrs(RetAttrs
) ||
5921 ParseOptionalProgramAddrSpace(InvokeAddrSpace
) ||
5922 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
5923 ParseValID(CalleeID
) || ParseParameterList(ArgList
, PFS
) ||
5924 ParseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false,
5926 ParseOptionalOperandBundles(BundleList
, PFS
) ||
5927 ParseToken(lltok::kw_to
, "expected 'to' in invoke") ||
5928 ParseTypeAndBasicBlock(NormalBB
, PFS
) ||
5929 ParseToken(lltok::kw_unwind
, "expected 'unwind' in invoke") ||
5930 ParseTypeAndBasicBlock(UnwindBB
, PFS
))
5933 // If RetType is a non-function pointer type, then this is the short syntax
5934 // for the call, which means that RetType is just the return type. Infer the
5935 // rest of the function argument types from the arguments that are present.
5936 FunctionType
*Ty
= dyn_cast
<FunctionType
>(RetType
);
5938 // Pull out the types of all of the arguments...
5939 std::vector
<Type
*> ParamTypes
;
5940 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
5941 ParamTypes
.push_back(ArgList
[i
].V
->getType());
5943 if (!FunctionType::isValidReturnType(RetType
))
5944 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
5946 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
5951 // Look up the callee.
5953 if (ConvertValIDToValue(PointerType::get(Ty
, InvokeAddrSpace
), CalleeID
,
5954 Callee
, &PFS
, /*IsCall=*/true))
5957 // Set up the Attribute for the function.
5958 SmallVector
<Value
*, 8> Args
;
5959 SmallVector
<AttributeSet
, 8> ArgAttrs
;
5961 // Loop through FunctionType's arguments and ensure they are specified
5962 // correctly. Also, gather any parameter attributes.
5963 FunctionType::param_iterator I
= Ty
->param_begin();
5964 FunctionType::param_iterator E
= Ty
->param_end();
5965 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
5966 Type
*ExpectedTy
= nullptr;
5969 } else if (!Ty
->isVarArg()) {
5970 return Error(ArgList
[i
].Loc
, "too many arguments specified");
5973 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
5974 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
5975 getTypeString(ExpectedTy
) + "'");
5976 Args
.push_back(ArgList
[i
].V
);
5977 ArgAttrs
.push_back(ArgList
[i
].Attrs
);
5981 return Error(CallLoc
, "not enough parameters specified for call");
5983 if (FnAttrs
.hasAlignmentAttr())
5984 return Error(CallLoc
, "invoke instructions may not have an alignment");
5986 // Finish off the Attribute and check them
5988 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
5989 AttributeSet::get(Context
, RetAttrs
), ArgAttrs
);
5992 InvokeInst::Create(Ty
, Callee
, NormalBB
, UnwindBB
, Args
, BundleList
);
5993 II
->setCallingConv(CC
);
5994 II
->setAttributes(PAL
);
5995 ForwardRefAttrGroups
[II
] = FwdRefAttrGrps
;
6001 /// ::= 'resume' TypeAndValue
6002 bool LLParser::ParseResume(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6003 Value
*Exn
; LocTy ExnLoc
;
6004 if (ParseTypeAndValue(Exn
, ExnLoc
, PFS
))
6007 ResumeInst
*RI
= ResumeInst::Create(Exn
);
6012 bool LLParser::ParseExceptionArgs(SmallVectorImpl
<Value
*> &Args
,
6013 PerFunctionState
&PFS
) {
6014 if (ParseToken(lltok::lsquare
, "expected '[' in catchpad/cleanuppad"))
6017 while (Lex
.getKind() != lltok::rsquare
) {
6018 // If this isn't the first argument, we need a comma.
6019 if (!Args
.empty() &&
6020 ParseToken(lltok::comma
, "expected ',' in argument list"))
6023 // Parse the argument.
6025 Type
*ArgTy
= nullptr;
6026 if (ParseType(ArgTy
, ArgLoc
))
6030 if (ArgTy
->isMetadataTy()) {
6031 if (ParseMetadataAsValue(V
, PFS
))
6034 if (ParseValue(ArgTy
, V
, PFS
))
6040 Lex
.Lex(); // Lex the ']'.
6045 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6046 bool LLParser::ParseCleanupRet(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6047 Value
*CleanupPad
= nullptr;
6049 if (ParseToken(lltok::kw_from
, "expected 'from' after cleanupret"))
6052 if (ParseValue(Type::getTokenTy(Context
), CleanupPad
, PFS
))
6055 if (ParseToken(lltok::kw_unwind
, "expected 'unwind' in cleanupret"))
6058 BasicBlock
*UnwindBB
= nullptr;
6059 if (Lex
.getKind() == lltok::kw_to
) {
6061 if (ParseToken(lltok::kw_caller
, "expected 'caller' in cleanupret"))
6064 if (ParseTypeAndBasicBlock(UnwindBB
, PFS
)) {
6069 Inst
= CleanupReturnInst::Create(CleanupPad
, UnwindBB
);
6074 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6075 bool LLParser::ParseCatchRet(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6076 Value
*CatchPad
= nullptr;
6078 if (ParseToken(lltok::kw_from
, "expected 'from' after catchret"))
6081 if (ParseValue(Type::getTokenTy(Context
), CatchPad
, PFS
))
6085 if (ParseToken(lltok::kw_to
, "expected 'to' in catchret") ||
6086 ParseTypeAndBasicBlock(BB
, PFS
))
6089 Inst
= CatchReturnInst::Create(CatchPad
, BB
);
6093 /// ParseCatchSwitch
6094 /// ::= 'catchswitch' within Parent
6095 bool LLParser::ParseCatchSwitch(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6098 if (ParseToken(lltok::kw_within
, "expected 'within' after catchswitch"))
6101 if (Lex
.getKind() != lltok::kw_none
&& Lex
.getKind() != lltok::LocalVar
&&
6102 Lex
.getKind() != lltok::LocalVarID
)
6103 return TokError("expected scope value for catchswitch");
6105 if (ParseValue(Type::getTokenTy(Context
), ParentPad
, PFS
))
6108 if (ParseToken(lltok::lsquare
, "expected '[' with catchswitch labels"))
6111 SmallVector
<BasicBlock
*, 32> Table
;
6114 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
6116 Table
.push_back(DestBB
);
6117 } while (EatIfPresent(lltok::comma
));
6119 if (ParseToken(lltok::rsquare
, "expected ']' after catchswitch labels"))
6122 if (ParseToken(lltok::kw_unwind
,
6123 "expected 'unwind' after catchswitch scope"))
6126 BasicBlock
*UnwindBB
= nullptr;
6127 if (EatIfPresent(lltok::kw_to
)) {
6128 if (ParseToken(lltok::kw_caller
, "expected 'caller' in catchswitch"))
6131 if (ParseTypeAndBasicBlock(UnwindBB
, PFS
))
6136 CatchSwitchInst::Create(ParentPad
, UnwindBB
, Table
.size());
6137 for (BasicBlock
*DestBB
: Table
)
6138 CatchSwitch
->addHandler(DestBB
);
6144 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6145 bool LLParser::ParseCatchPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6146 Value
*CatchSwitch
= nullptr;
6148 if (ParseToken(lltok::kw_within
, "expected 'within' after catchpad"))
6151 if (Lex
.getKind() != lltok::LocalVar
&& Lex
.getKind() != lltok::LocalVarID
)
6152 return TokError("expected scope value for catchpad");
6154 if (ParseValue(Type::getTokenTy(Context
), CatchSwitch
, PFS
))
6157 SmallVector
<Value
*, 8> Args
;
6158 if (ParseExceptionArgs(Args
, PFS
))
6161 Inst
= CatchPadInst::Create(CatchSwitch
, Args
);
6166 /// ::= 'cleanuppad' within Parent ParamList
6167 bool LLParser::ParseCleanupPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6168 Value
*ParentPad
= nullptr;
6170 if (ParseToken(lltok::kw_within
, "expected 'within' after cleanuppad"))
6173 if (Lex
.getKind() != lltok::kw_none
&& Lex
.getKind() != lltok::LocalVar
&&
6174 Lex
.getKind() != lltok::LocalVarID
)
6175 return TokError("expected scope value for cleanuppad");
6177 if (ParseValue(Type::getTokenTy(Context
), ParentPad
, PFS
))
6180 SmallVector
<Value
*, 8> Args
;
6181 if (ParseExceptionArgs(Args
, PFS
))
6184 Inst
= CleanupPadInst::Create(ParentPad
, Args
);
6188 //===----------------------------------------------------------------------===//
6190 //===----------------------------------------------------------------------===//
6193 /// ::= UnaryOp TypeAndValue ',' Value
6195 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6196 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
6197 bool LLParser::ParseUnaryOp(Instruction
*&Inst
, PerFunctionState
&PFS
,
6198 unsigned Opc
, unsigned OperandType
) {
6199 LocTy Loc
; Value
*LHS
;
6200 if (ParseTypeAndValue(LHS
, Loc
, PFS
))
6204 switch (OperandType
) {
6205 default: llvm_unreachable("Unknown operand type!");
6206 case 0: // int or FP.
6207 Valid
= LHS
->getType()->isIntOrIntVectorTy() ||
6208 LHS
->getType()->isFPOrFPVectorTy();
6211 Valid
= LHS
->getType()->isIntOrIntVectorTy();
6214 Valid
= LHS
->getType()->isFPOrFPVectorTy();
6219 return Error(Loc
, "invalid operand type for instruction");
6221 Inst
= UnaryOperator::Create((Instruction::UnaryOps
)Opc
, LHS
);
6226 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6227 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6228 /// '[' LabelList ']'
6229 bool LLParser::ParseCallBr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6230 LocTy CallLoc
= Lex
.getLoc();
6231 AttrBuilder RetAttrs
, FnAttrs
;
6232 std::vector
<unsigned> FwdRefAttrGrps
;
6235 Type
*RetType
= nullptr;
6238 SmallVector
<ParamInfo
, 16> ArgList
;
6239 SmallVector
<OperandBundleDef
, 2> BundleList
;
6241 BasicBlock
*DefaultDest
;
6242 if (ParseOptionalCallingConv(CC
) || ParseOptionalReturnAttrs(RetAttrs
) ||
6243 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
6244 ParseValID(CalleeID
) || ParseParameterList(ArgList
, PFS
) ||
6245 ParseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false,
6247 ParseOptionalOperandBundles(BundleList
, PFS
) ||
6248 ParseToken(lltok::kw_to
, "expected 'to' in callbr") ||
6249 ParseTypeAndBasicBlock(DefaultDest
, PFS
) ||
6250 ParseToken(lltok::lsquare
, "expected '[' in callbr"))
6253 // Parse the destination list.
6254 SmallVector
<BasicBlock
*, 16> IndirectDests
;
6256 if (Lex
.getKind() != lltok::rsquare
) {
6258 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
6260 IndirectDests
.push_back(DestBB
);
6262 while (EatIfPresent(lltok::comma
)) {
6263 if (ParseTypeAndBasicBlock(DestBB
, PFS
))
6265 IndirectDests
.push_back(DestBB
);
6269 if (ParseToken(lltok::rsquare
, "expected ']' at end of block list"))
6272 // If RetType is a non-function pointer type, then this is the short syntax
6273 // for the call, which means that RetType is just the return type. Infer the
6274 // rest of the function argument types from the arguments that are present.
6275 FunctionType
*Ty
= dyn_cast
<FunctionType
>(RetType
);
6277 // Pull out the types of all of the arguments...
6278 std::vector
<Type
*> ParamTypes
;
6279 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
6280 ParamTypes
.push_back(ArgList
[i
].V
->getType());
6282 if (!FunctionType::isValidReturnType(RetType
))
6283 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
6285 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
6290 // Look up the callee.
6292 if (ConvertValIDToValue(PointerType::getUnqual(Ty
), CalleeID
, Callee
, &PFS
,
6296 if (isa
<InlineAsm
>(Callee
) && !Ty
->getReturnType()->isVoidTy())
6297 return Error(RetTypeLoc
, "asm-goto outputs not supported");
6299 // Set up the Attribute for the function.
6300 SmallVector
<Value
*, 8> Args
;
6301 SmallVector
<AttributeSet
, 8> ArgAttrs
;
6303 // Loop through FunctionType's arguments and ensure they are specified
6304 // correctly. Also, gather any parameter attributes.
6305 FunctionType::param_iterator I
= Ty
->param_begin();
6306 FunctionType::param_iterator E
= Ty
->param_end();
6307 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
6308 Type
*ExpectedTy
= nullptr;
6311 } else if (!Ty
->isVarArg()) {
6312 return Error(ArgList
[i
].Loc
, "too many arguments specified");
6315 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
6316 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
6317 getTypeString(ExpectedTy
) + "'");
6318 Args
.push_back(ArgList
[i
].V
);
6319 ArgAttrs
.push_back(ArgList
[i
].Attrs
);
6323 return Error(CallLoc
, "not enough parameters specified for call");
6325 if (FnAttrs
.hasAlignmentAttr())
6326 return Error(CallLoc
, "callbr instructions may not have an alignment");
6328 // Finish off the Attribute and check them
6330 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
6331 AttributeSet::get(Context
, RetAttrs
), ArgAttrs
);
6334 CallBrInst::Create(Ty
, Callee
, DefaultDest
, IndirectDests
, Args
,
6336 CBI
->setCallingConv(CC
);
6337 CBI
->setAttributes(PAL
);
6338 ForwardRefAttrGroups
[CBI
] = FwdRefAttrGrps
;
6343 //===----------------------------------------------------------------------===//
6344 // Binary Operators.
6345 //===----------------------------------------------------------------------===//
6348 /// ::= ArithmeticOps TypeAndValue ',' Value
6350 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6351 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
6352 bool LLParser::ParseArithmetic(Instruction
*&Inst
, PerFunctionState
&PFS
,
6353 unsigned Opc
, unsigned OperandType
) {
6354 LocTy Loc
; Value
*LHS
, *RHS
;
6355 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
6356 ParseToken(lltok::comma
, "expected ',' in arithmetic operation") ||
6357 ParseValue(LHS
->getType(), RHS
, PFS
))
6361 switch (OperandType
) {
6362 default: llvm_unreachable("Unknown operand type!");
6363 case 0: // int or FP.
6364 Valid
= LHS
->getType()->isIntOrIntVectorTy() ||
6365 LHS
->getType()->isFPOrFPVectorTy();
6367 case 1: Valid
= LHS
->getType()->isIntOrIntVectorTy(); break;
6368 case 2: Valid
= LHS
->getType()->isFPOrFPVectorTy(); break;
6372 return Error(Loc
, "invalid operand type for instruction");
6374 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
6379 /// ::= ArithmeticOps TypeAndValue ',' Value {
6380 bool LLParser::ParseLogical(Instruction
*&Inst
, PerFunctionState
&PFS
,
6382 LocTy Loc
; Value
*LHS
, *RHS
;
6383 if (ParseTypeAndValue(LHS
, Loc
, PFS
) ||
6384 ParseToken(lltok::comma
, "expected ',' in logical operation") ||
6385 ParseValue(LHS
->getType(), RHS
, PFS
))
6388 if (!LHS
->getType()->isIntOrIntVectorTy())
6389 return Error(Loc
,"instruction requires integer or integer vector operands");
6391 Inst
= BinaryOperator::Create((Instruction::BinaryOps
)Opc
, LHS
, RHS
);
6396 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
6397 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
6398 bool LLParser::ParseCompare(Instruction
*&Inst
, PerFunctionState
&PFS
,
6400 // Parse the integer/fp comparison predicate.
6404 if (ParseCmpPredicate(Pred
, Opc
) ||
6405 ParseTypeAndValue(LHS
, Loc
, PFS
) ||
6406 ParseToken(lltok::comma
, "expected ',' after compare value") ||
6407 ParseValue(LHS
->getType(), RHS
, PFS
))
6410 if (Opc
== Instruction::FCmp
) {
6411 if (!LHS
->getType()->isFPOrFPVectorTy())
6412 return Error(Loc
, "fcmp requires floating point operands");
6413 Inst
= new FCmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
6415 assert(Opc
== Instruction::ICmp
&& "Unknown opcode for CmpInst!");
6416 if (!LHS
->getType()->isIntOrIntVectorTy() &&
6417 !LHS
->getType()->isPtrOrPtrVectorTy())
6418 return Error(Loc
, "icmp requires integer operands");
6419 Inst
= new ICmpInst(CmpInst::Predicate(Pred
), LHS
, RHS
);
6424 //===----------------------------------------------------------------------===//
6425 // Other Instructions.
6426 //===----------------------------------------------------------------------===//
6430 /// ::= CastOpc TypeAndValue 'to' Type
6431 bool LLParser::ParseCast(Instruction
*&Inst
, PerFunctionState
&PFS
,
6435 Type
*DestTy
= nullptr;
6436 if (ParseTypeAndValue(Op
, Loc
, PFS
) ||
6437 ParseToken(lltok::kw_to
, "expected 'to' after cast value") ||
6441 if (!CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
)) {
6442 CastInst::castIsValid((Instruction::CastOps
)Opc
, Op
, DestTy
);
6443 return Error(Loc
, "invalid cast opcode for cast from '" +
6444 getTypeString(Op
->getType()) + "' to '" +
6445 getTypeString(DestTy
) + "'");
6447 Inst
= CastInst::Create((Instruction::CastOps
)Opc
, Op
, DestTy
);
6452 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6453 bool LLParser::ParseSelect(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6455 Value
*Op0
, *Op1
, *Op2
;
6456 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
6457 ParseToken(lltok::comma
, "expected ',' after select condition") ||
6458 ParseTypeAndValue(Op1
, PFS
) ||
6459 ParseToken(lltok::comma
, "expected ',' after select value") ||
6460 ParseTypeAndValue(Op2
, PFS
))
6463 if (const char *Reason
= SelectInst::areInvalidOperands(Op0
, Op1
, Op2
))
6464 return Error(Loc
, Reason
);
6466 Inst
= SelectInst::Create(Op0
, Op1
, Op2
);
6471 /// ::= 'va_arg' TypeAndValue ',' Type
6472 bool LLParser::ParseVA_Arg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6474 Type
*EltTy
= nullptr;
6476 if (ParseTypeAndValue(Op
, PFS
) ||
6477 ParseToken(lltok::comma
, "expected ',' after vaarg operand") ||
6478 ParseType(EltTy
, TypeLoc
))
6481 if (!EltTy
->isFirstClassType())
6482 return Error(TypeLoc
, "va_arg requires operand with first class type");
6484 Inst
= new VAArgInst(Op
, EltTy
);
6488 /// ParseExtractElement
6489 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6490 bool LLParser::ParseExtractElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6493 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
6494 ParseToken(lltok::comma
, "expected ',' after extract value") ||
6495 ParseTypeAndValue(Op1
, PFS
))
6498 if (!ExtractElementInst::isValidOperands(Op0
, Op1
))
6499 return Error(Loc
, "invalid extractelement operands");
6501 Inst
= ExtractElementInst::Create(Op0
, Op1
);
6505 /// ParseInsertElement
6506 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6507 bool LLParser::ParseInsertElement(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6509 Value
*Op0
, *Op1
, *Op2
;
6510 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
6511 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
6512 ParseTypeAndValue(Op1
, PFS
) ||
6513 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
6514 ParseTypeAndValue(Op2
, PFS
))
6517 if (!InsertElementInst::isValidOperands(Op0
, Op1
, Op2
))
6518 return Error(Loc
, "invalid insertelement operands");
6520 Inst
= InsertElementInst::Create(Op0
, Op1
, Op2
);
6524 /// ParseShuffleVector
6525 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6526 bool LLParser::ParseShuffleVector(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6528 Value
*Op0
, *Op1
, *Op2
;
6529 if (ParseTypeAndValue(Op0
, Loc
, PFS
) ||
6530 ParseToken(lltok::comma
, "expected ',' after shuffle mask") ||
6531 ParseTypeAndValue(Op1
, PFS
) ||
6532 ParseToken(lltok::comma
, "expected ',' after shuffle value") ||
6533 ParseTypeAndValue(Op2
, PFS
))
6536 if (!ShuffleVectorInst::isValidOperands(Op0
, Op1
, Op2
))
6537 return Error(Loc
, "invalid shufflevector operands");
6539 Inst
= new ShuffleVectorInst(Op0
, Op1
, Op2
);
6544 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6545 int LLParser::ParsePHI(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6546 Type
*Ty
= nullptr; LocTy TypeLoc
;
6549 if (ParseType(Ty
, TypeLoc
) ||
6550 ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
6551 ParseValue(Ty
, Op0
, PFS
) ||
6552 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
6553 ParseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
6554 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
6557 bool AteExtraComma
= false;
6558 SmallVector
<std::pair
<Value
*, BasicBlock
*>, 16> PHIVals
;
6561 PHIVals
.push_back(std::make_pair(Op0
, cast
<BasicBlock
>(Op1
)));
6563 if (!EatIfPresent(lltok::comma
))
6566 if (Lex
.getKind() == lltok::MetadataVar
) {
6567 AteExtraComma
= true;
6571 if (ParseToken(lltok::lsquare
, "expected '[' in phi value list") ||
6572 ParseValue(Ty
, Op0
, PFS
) ||
6573 ParseToken(lltok::comma
, "expected ',' after insertelement value") ||
6574 ParseValue(Type::getLabelTy(Context
), Op1
, PFS
) ||
6575 ParseToken(lltok::rsquare
, "expected ']' in phi value list"))
6579 if (!Ty
->isFirstClassType())
6580 return Error(TypeLoc
, "phi node must have first class type");
6582 PHINode
*PN
= PHINode::Create(Ty
, PHIVals
.size());
6583 for (unsigned i
= 0, e
= PHIVals
.size(); i
!= e
; ++i
)
6584 PN
->addIncoming(PHIVals
[i
].first
, PHIVals
[i
].second
);
6586 return AteExtraComma
? InstExtraComma
: InstNormal
;
6590 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6592 /// ::= 'catch' TypeAndValue
6594 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6595 bool LLParser::ParseLandingPad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6596 Type
*Ty
= nullptr; LocTy TyLoc
;
6598 if (ParseType(Ty
, TyLoc
))
6601 std::unique_ptr
<LandingPadInst
> LP(LandingPadInst::Create(Ty
, 0));
6602 LP
->setCleanup(EatIfPresent(lltok::kw_cleanup
));
6604 while (Lex
.getKind() == lltok::kw_catch
|| Lex
.getKind() == lltok::kw_filter
){
6605 LandingPadInst::ClauseType CT
;
6606 if (EatIfPresent(lltok::kw_catch
))
6607 CT
= LandingPadInst::Catch
;
6608 else if (EatIfPresent(lltok::kw_filter
))
6609 CT
= LandingPadInst::Filter
;
6611 return TokError("expected 'catch' or 'filter' clause type");
6615 if (ParseTypeAndValue(V
, VLoc
, PFS
))
6618 // A 'catch' type expects a non-array constant. A filter clause expects an
6620 if (CT
== LandingPadInst::Catch
) {
6621 if (isa
<ArrayType
>(V
->getType()))
6622 Error(VLoc
, "'catch' clause has an invalid type");
6624 if (!isa
<ArrayType
>(V
->getType()))
6625 Error(VLoc
, "'filter' clause has an invalid type");
6628 Constant
*CV
= dyn_cast
<Constant
>(V
);
6630 return Error(VLoc
, "clause argument must be a constant");
6634 Inst
= LP
.release();
6639 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6640 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6641 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6642 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6643 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6644 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6645 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6646 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6647 bool LLParser::ParseCall(Instruction
*&Inst
, PerFunctionState
&PFS
,
6648 CallInst::TailCallKind TCK
) {
6649 AttrBuilder RetAttrs
, FnAttrs
;
6650 std::vector
<unsigned> FwdRefAttrGrps
;
6652 unsigned CallAddrSpace
;
6654 Type
*RetType
= nullptr;
6657 SmallVector
<ParamInfo
, 16> ArgList
;
6658 SmallVector
<OperandBundleDef
, 2> BundleList
;
6659 LocTy CallLoc
= Lex
.getLoc();
6661 if (TCK
!= CallInst::TCK_None
&&
6662 ParseToken(lltok::kw_call
,
6663 "expected 'tail call', 'musttail call', or 'notail call'"))
6666 FastMathFlags FMF
= EatFastMathFlagsIfPresent();
6668 if (ParseOptionalCallingConv(CC
) || ParseOptionalReturnAttrs(RetAttrs
) ||
6669 ParseOptionalProgramAddrSpace(CallAddrSpace
) ||
6670 ParseType(RetType
, RetTypeLoc
, true /*void allowed*/) ||
6671 ParseValID(CalleeID
) ||
6672 ParseParameterList(ArgList
, PFS
, TCK
== CallInst::TCK_MustTail
,
6673 PFS
.getFunction().isVarArg()) ||
6674 ParseFnAttributeValuePairs(FnAttrs
, FwdRefAttrGrps
, false, BuiltinLoc
) ||
6675 ParseOptionalOperandBundles(BundleList
, PFS
))
6678 if (FMF
.any() && !RetType
->isFPOrFPVectorTy())
6679 return Error(CallLoc
, "fast-math-flags specified for call without "
6680 "floating-point scalar or vector return type");
6682 // If RetType is a non-function pointer type, then this is the short syntax
6683 // for the call, which means that RetType is just the return type. Infer the
6684 // rest of the function argument types from the arguments that are present.
6685 FunctionType
*Ty
= dyn_cast
<FunctionType
>(RetType
);
6687 // Pull out the types of all of the arguments...
6688 std::vector
<Type
*> ParamTypes
;
6689 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
)
6690 ParamTypes
.push_back(ArgList
[i
].V
->getType());
6692 if (!FunctionType::isValidReturnType(RetType
))
6693 return Error(RetTypeLoc
, "Invalid result type for LLVM function");
6695 Ty
= FunctionType::get(RetType
, ParamTypes
, false);
6700 // Look up the callee.
6702 if (ConvertValIDToValue(PointerType::get(Ty
, CallAddrSpace
), CalleeID
, Callee
,
6703 &PFS
, /*IsCall=*/true))
6706 // Set up the Attribute for the function.
6707 SmallVector
<AttributeSet
, 8> Attrs
;
6709 SmallVector
<Value
*, 8> Args
;
6711 // Loop through FunctionType's arguments and ensure they are specified
6712 // correctly. Also, gather any parameter attributes.
6713 FunctionType::param_iterator I
= Ty
->param_begin();
6714 FunctionType::param_iterator E
= Ty
->param_end();
6715 for (unsigned i
= 0, e
= ArgList
.size(); i
!= e
; ++i
) {
6716 Type
*ExpectedTy
= nullptr;
6719 } else if (!Ty
->isVarArg()) {
6720 return Error(ArgList
[i
].Loc
, "too many arguments specified");
6723 if (ExpectedTy
&& ExpectedTy
!= ArgList
[i
].V
->getType())
6724 return Error(ArgList
[i
].Loc
, "argument is not of expected type '" +
6725 getTypeString(ExpectedTy
) + "'");
6726 Args
.push_back(ArgList
[i
].V
);
6727 Attrs
.push_back(ArgList
[i
].Attrs
);
6731 return Error(CallLoc
, "not enough parameters specified for call");
6733 if (FnAttrs
.hasAlignmentAttr())
6734 return Error(CallLoc
, "call instructions may not have an alignment");
6736 // Finish off the Attribute and check them
6738 AttributeList::get(Context
, AttributeSet::get(Context
, FnAttrs
),
6739 AttributeSet::get(Context
, RetAttrs
), Attrs
);
6741 CallInst
*CI
= CallInst::Create(Ty
, Callee
, Args
, BundleList
);
6742 CI
->setTailCallKind(TCK
);
6743 CI
->setCallingConv(CC
);
6745 CI
->setFastMathFlags(FMF
);
6746 CI
->setAttributes(PAL
);
6747 ForwardRefAttrGroups
[CI
] = FwdRefAttrGrps
;
6752 //===----------------------------------------------------------------------===//
6753 // Memory Instructions.
6754 //===----------------------------------------------------------------------===//
6757 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6758 /// (',' 'align' i32)? (',', 'addrspace(n))?
6759 int LLParser::ParseAlloc(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6760 Value
*Size
= nullptr;
6761 LocTy SizeLoc
, TyLoc
, ASLoc
;
6762 unsigned Alignment
= 0;
6763 unsigned AddrSpace
= 0;
6766 bool IsInAlloca
= EatIfPresent(lltok::kw_inalloca
);
6767 bool IsSwiftError
= EatIfPresent(lltok::kw_swifterror
);
6769 if (ParseType(Ty
, TyLoc
)) return true;
6771 if (Ty
->isFunctionTy() || !PointerType::isValidElementType(Ty
))
6772 return Error(TyLoc
, "invalid type for alloca");
6774 bool AteExtraComma
= false;
6775 if (EatIfPresent(lltok::comma
)) {
6776 if (Lex
.getKind() == lltok::kw_align
) {
6777 if (ParseOptionalAlignment(Alignment
))
6779 if (ParseOptionalCommaAddrSpace(AddrSpace
, ASLoc
, AteExtraComma
))
6781 } else if (Lex
.getKind() == lltok::kw_addrspace
) {
6782 ASLoc
= Lex
.getLoc();
6783 if (ParseOptionalAddrSpace(AddrSpace
))
6785 } else if (Lex
.getKind() == lltok::MetadataVar
) {
6786 AteExtraComma
= true;
6788 if (ParseTypeAndValue(Size
, SizeLoc
, PFS
))
6790 if (EatIfPresent(lltok::comma
)) {
6791 if (Lex
.getKind() == lltok::kw_align
) {
6792 if (ParseOptionalAlignment(Alignment
))
6794 if (ParseOptionalCommaAddrSpace(AddrSpace
, ASLoc
, AteExtraComma
))
6796 } else if (Lex
.getKind() == lltok::kw_addrspace
) {
6797 ASLoc
= Lex
.getLoc();
6798 if (ParseOptionalAddrSpace(AddrSpace
))
6800 } else if (Lex
.getKind() == lltok::MetadataVar
) {
6801 AteExtraComma
= true;
6807 if (Size
&& !Size
->getType()->isIntegerTy())
6808 return Error(SizeLoc
, "element count must have integer type");
6810 AllocaInst
*AI
= new AllocaInst(Ty
, AddrSpace
, Size
, Alignment
);
6811 AI
->setUsedWithInAlloca(IsInAlloca
);
6812 AI
->setSwiftError(IsSwiftError
);
6814 return AteExtraComma
? InstExtraComma
: InstNormal
;
6818 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6819 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6820 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6821 int LLParser::ParseLoad(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6822 Value
*Val
; LocTy Loc
;
6823 unsigned Alignment
= 0;
6824 bool AteExtraComma
= false;
6825 bool isAtomic
= false;
6826 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
6827 SyncScope::ID SSID
= SyncScope::System
;
6829 if (Lex
.getKind() == lltok::kw_atomic
) {
6834 bool isVolatile
= false;
6835 if (Lex
.getKind() == lltok::kw_volatile
) {
6841 LocTy ExplicitTypeLoc
= Lex
.getLoc();
6842 if (ParseType(Ty
) ||
6843 ParseToken(lltok::comma
, "expected comma after load's type") ||
6844 ParseTypeAndValue(Val
, Loc
, PFS
) ||
6845 ParseScopeAndOrdering(isAtomic
, SSID
, Ordering
) ||
6846 ParseOptionalCommaAlign(Alignment
, AteExtraComma
))
6849 if (!Val
->getType()->isPointerTy() || !Ty
->isFirstClassType())
6850 return Error(Loc
, "load operand must be a pointer to a first class type");
6851 if (isAtomic
&& !Alignment
)
6852 return Error(Loc
, "atomic load must have explicit non-zero alignment");
6853 if (Ordering
== AtomicOrdering::Release
||
6854 Ordering
== AtomicOrdering::AcquireRelease
)
6855 return Error(Loc
, "atomic load cannot use Release ordering");
6857 if (Ty
!= cast
<PointerType
>(Val
->getType())->getElementType())
6858 return Error(ExplicitTypeLoc
,
6859 "explicit pointee type doesn't match operand's pointee type");
6861 Inst
= new LoadInst(Ty
, Val
, "", isVolatile
, Alignment
, Ordering
, SSID
);
6862 return AteExtraComma
? InstExtraComma
: InstNormal
;
6867 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6868 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6869 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6870 int LLParser::ParseStore(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6871 Value
*Val
, *Ptr
; LocTy Loc
, PtrLoc
;
6872 unsigned Alignment
= 0;
6873 bool AteExtraComma
= false;
6874 bool isAtomic
= false;
6875 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
6876 SyncScope::ID SSID
= SyncScope::System
;
6878 if (Lex
.getKind() == lltok::kw_atomic
) {
6883 bool isVolatile
= false;
6884 if (Lex
.getKind() == lltok::kw_volatile
) {
6889 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
6890 ParseToken(lltok::comma
, "expected ',' after store operand") ||
6891 ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
6892 ParseScopeAndOrdering(isAtomic
, SSID
, Ordering
) ||
6893 ParseOptionalCommaAlign(Alignment
, AteExtraComma
))
6896 if (!Ptr
->getType()->isPointerTy())
6897 return Error(PtrLoc
, "store operand must be a pointer");
6898 if (!Val
->getType()->isFirstClassType())
6899 return Error(Loc
, "store operand must be a first class value");
6900 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Val
->getType())
6901 return Error(Loc
, "stored value and pointer type do not match");
6902 if (isAtomic
&& !Alignment
)
6903 return Error(Loc
, "atomic store must have explicit non-zero alignment");
6904 if (Ordering
== AtomicOrdering::Acquire
||
6905 Ordering
== AtomicOrdering::AcquireRelease
)
6906 return Error(Loc
, "atomic store cannot use Acquire ordering");
6908 Inst
= new StoreInst(Val
, Ptr
, isVolatile
, Alignment
, Ordering
, SSID
);
6909 return AteExtraComma
? InstExtraComma
: InstNormal
;
6913 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6914 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6915 int LLParser::ParseCmpXchg(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6916 Value
*Ptr
, *Cmp
, *New
; LocTy PtrLoc
, CmpLoc
, NewLoc
;
6917 bool AteExtraComma
= false;
6918 AtomicOrdering SuccessOrdering
= AtomicOrdering::NotAtomic
;
6919 AtomicOrdering FailureOrdering
= AtomicOrdering::NotAtomic
;
6920 SyncScope::ID SSID
= SyncScope::System
;
6921 bool isVolatile
= false;
6922 bool isWeak
= false;
6924 if (EatIfPresent(lltok::kw_weak
))
6927 if (EatIfPresent(lltok::kw_volatile
))
6930 if (ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
6931 ParseToken(lltok::comma
, "expected ',' after cmpxchg address") ||
6932 ParseTypeAndValue(Cmp
, CmpLoc
, PFS
) ||
6933 ParseToken(lltok::comma
, "expected ',' after cmpxchg cmp operand") ||
6934 ParseTypeAndValue(New
, NewLoc
, PFS
) ||
6935 ParseScopeAndOrdering(true /*Always atomic*/, SSID
, SuccessOrdering
) ||
6936 ParseOrdering(FailureOrdering
))
6939 if (SuccessOrdering
== AtomicOrdering::Unordered
||
6940 FailureOrdering
== AtomicOrdering::Unordered
)
6941 return TokError("cmpxchg cannot be unordered");
6942 if (isStrongerThan(FailureOrdering
, SuccessOrdering
))
6943 return TokError("cmpxchg failure argument shall be no stronger than the "
6944 "success argument");
6945 if (FailureOrdering
== AtomicOrdering::Release
||
6946 FailureOrdering
== AtomicOrdering::AcquireRelease
)
6948 "cmpxchg failure ordering cannot include release semantics");
6949 if (!Ptr
->getType()->isPointerTy())
6950 return Error(PtrLoc
, "cmpxchg operand must be a pointer");
6951 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Cmp
->getType())
6952 return Error(CmpLoc
, "compare value and pointer type do not match");
6953 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != New
->getType())
6954 return Error(NewLoc
, "new value and pointer type do not match");
6955 if (!New
->getType()->isFirstClassType())
6956 return Error(NewLoc
, "cmpxchg operand must be a first class value");
6957 AtomicCmpXchgInst
*CXI
= new AtomicCmpXchgInst(
6958 Ptr
, Cmp
, New
, SuccessOrdering
, FailureOrdering
, SSID
);
6959 CXI
->setVolatile(isVolatile
);
6960 CXI
->setWeak(isWeak
);
6962 return AteExtraComma
? InstExtraComma
: InstNormal
;
6966 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6967 /// 'singlethread'? AtomicOrdering
6968 int LLParser::ParseAtomicRMW(Instruction
*&Inst
, PerFunctionState
&PFS
) {
6969 Value
*Ptr
, *Val
; LocTy PtrLoc
, ValLoc
;
6970 bool AteExtraComma
= false;
6971 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
6972 SyncScope::ID SSID
= SyncScope::System
;
6973 bool isVolatile
= false;
6975 AtomicRMWInst::BinOp Operation
;
6977 if (EatIfPresent(lltok::kw_volatile
))
6980 switch (Lex
.getKind()) {
6981 default: return TokError("expected binary operation in atomicrmw");
6982 case lltok::kw_xchg
: Operation
= AtomicRMWInst::Xchg
; break;
6983 case lltok::kw_add
: Operation
= AtomicRMWInst::Add
; break;
6984 case lltok::kw_sub
: Operation
= AtomicRMWInst::Sub
; break;
6985 case lltok::kw_and
: Operation
= AtomicRMWInst::And
; break;
6986 case lltok::kw_nand
: Operation
= AtomicRMWInst::Nand
; break;
6987 case lltok::kw_or
: Operation
= AtomicRMWInst::Or
; break;
6988 case lltok::kw_xor
: Operation
= AtomicRMWInst::Xor
; break;
6989 case lltok::kw_max
: Operation
= AtomicRMWInst::Max
; break;
6990 case lltok::kw_min
: Operation
= AtomicRMWInst::Min
; break;
6991 case lltok::kw_umax
: Operation
= AtomicRMWInst::UMax
; break;
6992 case lltok::kw_umin
: Operation
= AtomicRMWInst::UMin
; break;
6993 case lltok::kw_fadd
:
6994 Operation
= AtomicRMWInst::FAdd
;
6997 case lltok::kw_fsub
:
6998 Operation
= AtomicRMWInst::FSub
;
7002 Lex
.Lex(); // Eat the operation.
7004 if (ParseTypeAndValue(Ptr
, PtrLoc
, PFS
) ||
7005 ParseToken(lltok::comma
, "expected ',' after atomicrmw address") ||
7006 ParseTypeAndValue(Val
, ValLoc
, PFS
) ||
7007 ParseScopeAndOrdering(true /*Always atomic*/, SSID
, Ordering
))
7010 if (Ordering
== AtomicOrdering::Unordered
)
7011 return TokError("atomicrmw cannot be unordered");
7012 if (!Ptr
->getType()->isPointerTy())
7013 return Error(PtrLoc
, "atomicrmw operand must be a pointer");
7014 if (cast
<PointerType
>(Ptr
->getType())->getElementType() != Val
->getType())
7015 return Error(ValLoc
, "atomicrmw value and pointer type do not match");
7017 if (Operation
== AtomicRMWInst::Xchg
) {
7018 if (!Val
->getType()->isIntegerTy() &&
7019 !Val
->getType()->isFloatingPointTy()) {
7020 return Error(ValLoc
, "atomicrmw " +
7021 AtomicRMWInst::getOperationName(Operation
) +
7022 " operand must be an integer or floating point type");
7025 if (!Val
->getType()->isFloatingPointTy()) {
7026 return Error(ValLoc
, "atomicrmw " +
7027 AtomicRMWInst::getOperationName(Operation
) +
7028 " operand must be a floating point type");
7031 if (!Val
->getType()->isIntegerTy()) {
7032 return Error(ValLoc
, "atomicrmw " +
7033 AtomicRMWInst::getOperationName(Operation
) +
7034 " operand must be an integer");
7038 unsigned Size
= Val
->getType()->getPrimitiveSizeInBits();
7039 if (Size
< 8 || (Size
& (Size
- 1)))
7040 return Error(ValLoc
, "atomicrmw operand must be power-of-two byte-sized"
7043 AtomicRMWInst
*RMWI
=
7044 new AtomicRMWInst(Operation
, Ptr
, Val
, Ordering
, SSID
);
7045 RMWI
->setVolatile(isVolatile
);
7047 return AteExtraComma
? InstExtraComma
: InstNormal
;
7051 /// ::= 'fence' 'singlethread'? AtomicOrdering
7052 int LLParser::ParseFence(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7053 AtomicOrdering Ordering
= AtomicOrdering::NotAtomic
;
7054 SyncScope::ID SSID
= SyncScope::System
;
7055 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID
, Ordering
))
7058 if (Ordering
== AtomicOrdering::Unordered
)
7059 return TokError("fence cannot be unordered");
7060 if (Ordering
== AtomicOrdering::Monotonic
)
7061 return TokError("fence cannot be monotonic");
7063 Inst
= new FenceInst(Context
, Ordering
, SSID
);
7067 /// ParseGetElementPtr
7068 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7069 int LLParser::ParseGetElementPtr(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7070 Value
*Ptr
= nullptr;
7071 Value
*Val
= nullptr;
7074 bool InBounds
= EatIfPresent(lltok::kw_inbounds
);
7077 LocTy ExplicitTypeLoc
= Lex
.getLoc();
7078 if (ParseType(Ty
) ||
7079 ParseToken(lltok::comma
, "expected comma after getelementptr's type") ||
7080 ParseTypeAndValue(Ptr
, Loc
, PFS
))
7083 Type
*BaseType
= Ptr
->getType();
7084 PointerType
*BasePointerType
= dyn_cast
<PointerType
>(BaseType
->getScalarType());
7085 if (!BasePointerType
)
7086 return Error(Loc
, "base of getelementptr must be a pointer");
7088 if (Ty
!= BasePointerType
->getElementType())
7089 return Error(ExplicitTypeLoc
,
7090 "explicit pointee type doesn't match operand's pointee type");
7092 SmallVector
<Value
*, 16> Indices
;
7093 bool AteExtraComma
= false;
7094 // GEP returns a vector of pointers if at least one of parameters is a vector.
7095 // All vector parameters should have the same vector width.
7096 unsigned GEPWidth
= BaseType
->isVectorTy() ?
7097 BaseType
->getVectorNumElements() : 0;
7099 while (EatIfPresent(lltok::comma
)) {
7100 if (Lex
.getKind() == lltok::MetadataVar
) {
7101 AteExtraComma
= true;
7104 if (ParseTypeAndValue(Val
, EltLoc
, PFS
)) return true;
7105 if (!Val
->getType()->isIntOrIntVectorTy())
7106 return Error(EltLoc
, "getelementptr index must be an integer");
7108 if (Val
->getType()->isVectorTy()) {
7109 unsigned ValNumEl
= Val
->getType()->getVectorNumElements();
7110 if (GEPWidth
&& GEPWidth
!= ValNumEl
)
7111 return Error(EltLoc
,
7112 "getelementptr vector index has a wrong number of elements");
7113 GEPWidth
= ValNumEl
;
7115 Indices
.push_back(Val
);
7118 SmallPtrSet
<Type
*, 4> Visited
;
7119 if (!Indices
.empty() && !Ty
->isSized(&Visited
))
7120 return Error(Loc
, "base element of getelementptr must be sized");
7122 if (!GetElementPtrInst::getIndexedType(Ty
, Indices
))
7123 return Error(Loc
, "invalid getelementptr indices");
7124 Inst
= GetElementPtrInst::Create(Ty
, Ptr
, Indices
);
7126 cast
<GetElementPtrInst
>(Inst
)->setIsInBounds(true);
7127 return AteExtraComma
? InstExtraComma
: InstNormal
;
7130 /// ParseExtractValue
7131 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
7132 int LLParser::ParseExtractValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7133 Value
*Val
; LocTy Loc
;
7134 SmallVector
<unsigned, 4> Indices
;
7136 if (ParseTypeAndValue(Val
, Loc
, PFS
) ||
7137 ParseIndexList(Indices
, AteExtraComma
))
7140 if (!Val
->getType()->isAggregateType())
7141 return Error(Loc
, "extractvalue operand must be aggregate type");
7143 if (!ExtractValueInst::getIndexedType(Val
->getType(), Indices
))
7144 return Error(Loc
, "invalid indices for extractvalue");
7145 Inst
= ExtractValueInst::Create(Val
, Indices
);
7146 return AteExtraComma
? InstExtraComma
: InstNormal
;
7149 /// ParseInsertValue
7150 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7151 int LLParser::ParseInsertValue(Instruction
*&Inst
, PerFunctionState
&PFS
) {
7152 Value
*Val0
, *Val1
; LocTy Loc0
, Loc1
;
7153 SmallVector
<unsigned, 4> Indices
;
7155 if (ParseTypeAndValue(Val0
, Loc0
, PFS
) ||
7156 ParseToken(lltok::comma
, "expected comma after insertvalue operand") ||
7157 ParseTypeAndValue(Val1
, Loc1
, PFS
) ||
7158 ParseIndexList(Indices
, AteExtraComma
))
7161 if (!Val0
->getType()->isAggregateType())
7162 return Error(Loc0
, "insertvalue operand must be aggregate type");
7164 Type
*IndexedType
= ExtractValueInst::getIndexedType(Val0
->getType(), Indices
);
7166 return Error(Loc0
, "invalid indices for insertvalue");
7167 if (IndexedType
!= Val1
->getType())
7168 return Error(Loc1
, "insertvalue operand and field disagree in type: '" +
7169 getTypeString(Val1
->getType()) + "' instead of '" +
7170 getTypeString(IndexedType
) + "'");
7171 Inst
= InsertValueInst::Create(Val0
, Val1
, Indices
);
7172 return AteExtraComma
? InstExtraComma
: InstNormal
;
7175 //===----------------------------------------------------------------------===//
7176 // Embedded metadata.
7177 //===----------------------------------------------------------------------===//
7179 /// ParseMDNodeVector
7180 /// ::= { Element (',' Element)* }
7182 /// ::= 'null' | TypeAndValue
7183 bool LLParser::ParseMDNodeVector(SmallVectorImpl
<Metadata
*> &Elts
) {
7184 if (ParseToken(lltok::lbrace
, "expected '{' here"))
7187 // Check for an empty list.
7188 if (EatIfPresent(lltok::rbrace
))
7192 // Null is a special case since it is typeless.
7193 if (EatIfPresent(lltok::kw_null
)) {
7194 Elts
.push_back(nullptr);
7199 if (ParseMetadata(MD
, nullptr))
7202 } while (EatIfPresent(lltok::comma
));
7204 return ParseToken(lltok::rbrace
, "expected end of metadata node");
7207 //===----------------------------------------------------------------------===//
7208 // Use-list order directives.
7209 //===----------------------------------------------------------------------===//
7210 bool LLParser::sortUseListOrder(Value
*V
, ArrayRef
<unsigned> Indexes
,
7213 return Error(Loc
, "value has no uses");
7215 unsigned NumUses
= 0;
7216 SmallDenseMap
<const Use
*, unsigned, 16> Order
;
7217 for (const Use
&U
: V
->uses()) {
7218 if (++NumUses
> Indexes
.size())
7220 Order
[&U
] = Indexes
[NumUses
- 1];
7223 return Error(Loc
, "value only has one use");
7224 if (Order
.size() != Indexes
.size() || NumUses
> Indexes
.size())
7226 "wrong number of indexes, expected " + Twine(V
->getNumUses()));
7228 V
->sortUseList([&](const Use
&L
, const Use
&R
) {
7229 return Order
.lookup(&L
) < Order
.lookup(&R
);
7234 /// ParseUseListOrderIndexes
7235 /// ::= '{' uint32 (',' uint32)+ '}'
7236 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl
<unsigned> &Indexes
) {
7237 SMLoc Loc
= Lex
.getLoc();
7238 if (ParseToken(lltok::lbrace
, "expected '{' here"))
7240 if (Lex
.getKind() == lltok::rbrace
)
7241 return Lex
.Error("expected non-empty list of uselistorder indexes");
7243 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7244 // indexes should be distinct numbers in the range [0, size-1], and should
7246 unsigned Offset
= 0;
7248 bool IsOrdered
= true;
7249 assert(Indexes
.empty() && "Expected empty order vector");
7252 if (ParseUInt32(Index
))
7255 // Update consistency checks.
7256 Offset
+= Index
- Indexes
.size();
7257 Max
= std::max(Max
, Index
);
7258 IsOrdered
&= Index
== Indexes
.size();
7260 Indexes
.push_back(Index
);
7261 } while (EatIfPresent(lltok::comma
));
7263 if (ParseToken(lltok::rbrace
, "expected '}' here"))
7266 if (Indexes
.size() < 2)
7267 return Error(Loc
, "expected >= 2 uselistorder indexes");
7268 if (Offset
!= 0 || Max
>= Indexes
.size())
7269 return Error(Loc
, "expected distinct uselistorder indexes in range [0, size)");
7271 return Error(Loc
, "expected uselistorder indexes to change the order");
7276 /// ParseUseListOrder
7277 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7278 bool LLParser::ParseUseListOrder(PerFunctionState
*PFS
) {
7279 SMLoc Loc
= Lex
.getLoc();
7280 if (ParseToken(lltok::kw_uselistorder
, "expected uselistorder directive"))
7284 SmallVector
<unsigned, 16> Indexes
;
7285 if (ParseTypeAndValue(V
, PFS
) ||
7286 ParseToken(lltok::comma
, "expected comma in uselistorder directive") ||
7287 ParseUseListOrderIndexes(Indexes
))
7290 return sortUseListOrder(V
, Indexes
, Loc
);
7293 /// ParseUseListOrderBB
7294 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7295 bool LLParser::ParseUseListOrderBB() {
7296 assert(Lex
.getKind() == lltok::kw_uselistorder_bb
);
7297 SMLoc Loc
= Lex
.getLoc();
7301 SmallVector
<unsigned, 16> Indexes
;
7302 if (ParseValID(Fn
) ||
7303 ParseToken(lltok::comma
, "expected comma in uselistorder_bb directive") ||
7304 ParseValID(Label
) ||
7305 ParseToken(lltok::comma
, "expected comma in uselistorder_bb directive") ||
7306 ParseUseListOrderIndexes(Indexes
))
7309 // Check the function.
7311 if (Fn
.Kind
== ValID::t_GlobalName
)
7312 GV
= M
->getNamedValue(Fn
.StrVal
);
7313 else if (Fn
.Kind
== ValID::t_GlobalID
)
7314 GV
= Fn
.UIntVal
< NumberedVals
.size() ? NumberedVals
[Fn
.UIntVal
] : nullptr;
7316 return Error(Fn
.Loc
, "expected function name in uselistorder_bb");
7318 return Error(Fn
.Loc
, "invalid function forward reference in uselistorder_bb");
7319 auto *F
= dyn_cast
<Function
>(GV
);
7321 return Error(Fn
.Loc
, "expected function name in uselistorder_bb");
7322 if (F
->isDeclaration())
7323 return Error(Fn
.Loc
, "invalid declaration in uselistorder_bb");
7325 // Check the basic block.
7326 if (Label
.Kind
== ValID::t_LocalID
)
7327 return Error(Label
.Loc
, "invalid numeric label in uselistorder_bb");
7328 if (Label
.Kind
!= ValID::t_LocalName
)
7329 return Error(Label
.Loc
, "expected basic block name in uselistorder_bb");
7330 Value
*V
= F
->getValueSymbolTable()->lookup(Label
.StrVal
);
7332 return Error(Label
.Loc
, "invalid basic block in uselistorder_bb");
7333 if (!isa
<BasicBlock
>(V
))
7334 return Error(Label
.Loc
, "expected basic block in uselistorder_bb");
7336 return sortUseListOrder(V
, Indexes
, Loc
);
7340 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7341 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7342 bool LLParser::ParseModuleEntry(unsigned ID
) {
7343 assert(Lex
.getKind() == lltok::kw_module
);
7347 if (ParseToken(lltok::colon
, "expected ':' here") ||
7348 ParseToken(lltok::lparen
, "expected '(' here") ||
7349 ParseToken(lltok::kw_path
, "expected 'path' here") ||
7350 ParseToken(lltok::colon
, "expected ':' here") ||
7351 ParseStringConstant(Path
) ||
7352 ParseToken(lltok::comma
, "expected ',' here") ||
7353 ParseToken(lltok::kw_hash
, "expected 'hash' here") ||
7354 ParseToken(lltok::colon
, "expected ':' here") ||
7355 ParseToken(lltok::lparen
, "expected '(' here"))
7359 if (ParseUInt32(Hash
[0]) || ParseToken(lltok::comma
, "expected ',' here") ||
7360 ParseUInt32(Hash
[1]) || ParseToken(lltok::comma
, "expected ',' here") ||
7361 ParseUInt32(Hash
[2]) || ParseToken(lltok::comma
, "expected ',' here") ||
7362 ParseUInt32(Hash
[3]) || ParseToken(lltok::comma
, "expected ',' here") ||
7363 ParseUInt32(Hash
[4]))
7366 if (ParseToken(lltok::rparen
, "expected ')' here") ||
7367 ParseToken(lltok::rparen
, "expected ')' here"))
7370 auto ModuleEntry
= Index
->addModule(Path
, ID
, Hash
);
7371 ModuleIdMap
[ID
] = ModuleEntry
->first();
7377 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7378 bool LLParser::ParseTypeIdEntry(unsigned ID
) {
7379 assert(Lex
.getKind() == lltok::kw_typeid
);
7383 if (ParseToken(lltok::colon
, "expected ':' here") ||
7384 ParseToken(lltok::lparen
, "expected '(' here") ||
7385 ParseToken(lltok::kw_name
, "expected 'name' here") ||
7386 ParseToken(lltok::colon
, "expected ':' here") ||
7387 ParseStringConstant(Name
))
7390 TypeIdSummary
&TIS
= Index
->getOrInsertTypeIdSummary(Name
);
7391 if (ParseToken(lltok::comma
, "expected ',' here") ||
7392 ParseTypeIdSummary(TIS
) || ParseToken(lltok::rparen
, "expected ')' here"))
7395 // Check if this ID was forward referenced, and if so, update the
7396 // corresponding GUIDs.
7397 auto FwdRefTIDs
= ForwardRefTypeIds
.find(ID
);
7398 if (FwdRefTIDs
!= ForwardRefTypeIds
.end()) {
7399 for (auto TIDRef
: FwdRefTIDs
->second
) {
7400 assert(!*TIDRef
.first
&&
7401 "Forward referenced type id GUID expected to be 0");
7402 *TIDRef
.first
= GlobalValue::getGUID(Name
);
7404 ForwardRefTypeIds
.erase(FwdRefTIDs
);
7411 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7412 bool LLParser::ParseTypeIdSummary(TypeIdSummary
&TIS
) {
7413 if (ParseToken(lltok::kw_summary
, "expected 'summary' here") ||
7414 ParseToken(lltok::colon
, "expected ':' here") ||
7415 ParseToken(lltok::lparen
, "expected '(' here") ||
7416 ParseTypeTestResolution(TIS
.TTRes
))
7419 if (EatIfPresent(lltok::comma
)) {
7420 // Expect optional wpdResolutions field
7421 if (ParseOptionalWpdResolutions(TIS
.WPDRes
))
7425 if (ParseToken(lltok::rparen
, "expected ')' here"))
7431 /// TypeTestResolution
7432 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
7433 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7434 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7435 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7436 /// [',' 'inlinesBits' ':' UInt64]? ')'
7437 bool LLParser::ParseTypeTestResolution(TypeTestResolution
&TTRes
) {
7438 if (ParseToken(lltok::kw_typeTestRes
, "expected 'typeTestRes' here") ||
7439 ParseToken(lltok::colon
, "expected ':' here") ||
7440 ParseToken(lltok::lparen
, "expected '(' here") ||
7441 ParseToken(lltok::kw_kind
, "expected 'kind' here") ||
7442 ParseToken(lltok::colon
, "expected ':' here"))
7445 switch (Lex
.getKind()) {
7446 case lltok::kw_unsat
:
7447 TTRes
.TheKind
= TypeTestResolution::Unsat
;
7449 case lltok::kw_byteArray
:
7450 TTRes
.TheKind
= TypeTestResolution::ByteArray
;
7452 case lltok::kw_inline
:
7453 TTRes
.TheKind
= TypeTestResolution::Inline
;
7455 case lltok::kw_single
:
7456 TTRes
.TheKind
= TypeTestResolution::Single
;
7458 case lltok::kw_allOnes
:
7459 TTRes
.TheKind
= TypeTestResolution::AllOnes
;
7462 return Error(Lex
.getLoc(), "unexpected TypeTestResolution kind");
7466 if (ParseToken(lltok::comma
, "expected ',' here") ||
7467 ParseToken(lltok::kw_sizeM1BitWidth
, "expected 'sizeM1BitWidth' here") ||
7468 ParseToken(lltok::colon
, "expected ':' here") ||
7469 ParseUInt32(TTRes
.SizeM1BitWidth
))
7472 // Parse optional fields
7473 while (EatIfPresent(lltok::comma
)) {
7474 switch (Lex
.getKind()) {
7475 case lltok::kw_alignLog2
:
7477 if (ParseToken(lltok::colon
, "expected ':'") ||
7478 ParseUInt64(TTRes
.AlignLog2
))
7481 case lltok::kw_sizeM1
:
7483 if (ParseToken(lltok::colon
, "expected ':'") || ParseUInt64(TTRes
.SizeM1
))
7486 case lltok::kw_bitMask
: {
7489 if (ParseToken(lltok::colon
, "expected ':'") || ParseUInt32(Val
))
7491 assert(Val
<= 0xff);
7492 TTRes
.BitMask
= (uint8_t)Val
;
7495 case lltok::kw_inlineBits
:
7497 if (ParseToken(lltok::colon
, "expected ':'") ||
7498 ParseUInt64(TTRes
.InlineBits
))
7502 return Error(Lex
.getLoc(), "expected optional TypeTestResolution field");
7506 if (ParseToken(lltok::rparen
, "expected ')' here"))
7512 /// OptionalWpdResolutions
7513 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7514 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7515 bool LLParser::ParseOptionalWpdResolutions(
7516 std::map
<uint64_t, WholeProgramDevirtResolution
> &WPDResMap
) {
7517 if (ParseToken(lltok::kw_wpdResolutions
, "expected 'wpdResolutions' here") ||
7518 ParseToken(lltok::colon
, "expected ':' here") ||
7519 ParseToken(lltok::lparen
, "expected '(' here"))
7524 WholeProgramDevirtResolution WPDRes
;
7525 if (ParseToken(lltok::lparen
, "expected '(' here") ||
7526 ParseToken(lltok::kw_offset
, "expected 'offset' here") ||
7527 ParseToken(lltok::colon
, "expected ':' here") || ParseUInt64(Offset
) ||
7528 ParseToken(lltok::comma
, "expected ',' here") || ParseWpdRes(WPDRes
) ||
7529 ParseToken(lltok::rparen
, "expected ')' here"))
7531 WPDResMap
[Offset
] = WPDRes
;
7532 } while (EatIfPresent(lltok::comma
));
7534 if (ParseToken(lltok::rparen
, "expected ')' here"))
7541 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7542 /// [',' OptionalResByArg]? ')'
7543 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7544 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
7545 /// [',' OptionalResByArg]? ')'
7546 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7547 /// [',' OptionalResByArg]? ')'
7548 bool LLParser::ParseWpdRes(WholeProgramDevirtResolution
&WPDRes
) {
7549 if (ParseToken(lltok::kw_wpdRes
, "expected 'wpdRes' here") ||
7550 ParseToken(lltok::colon
, "expected ':' here") ||
7551 ParseToken(lltok::lparen
, "expected '(' here") ||
7552 ParseToken(lltok::kw_kind
, "expected 'kind' here") ||
7553 ParseToken(lltok::colon
, "expected ':' here"))
7556 switch (Lex
.getKind()) {
7557 case lltok::kw_indir
:
7558 WPDRes
.TheKind
= WholeProgramDevirtResolution::Indir
;
7560 case lltok::kw_singleImpl
:
7561 WPDRes
.TheKind
= WholeProgramDevirtResolution::SingleImpl
;
7563 case lltok::kw_branchFunnel
:
7564 WPDRes
.TheKind
= WholeProgramDevirtResolution::BranchFunnel
;
7567 return Error(Lex
.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7571 // Parse optional fields
7572 while (EatIfPresent(lltok::comma
)) {
7573 switch (Lex
.getKind()) {
7574 case lltok::kw_singleImplName
:
7576 if (ParseToken(lltok::colon
, "expected ':' here") ||
7577 ParseStringConstant(WPDRes
.SingleImplName
))
7580 case lltok::kw_resByArg
:
7581 if (ParseOptionalResByArg(WPDRes
.ResByArg
))
7585 return Error(Lex
.getLoc(),
7586 "expected optional WholeProgramDevirtResolution field");
7590 if (ParseToken(lltok::rparen
, "expected ')' here"))
7596 /// OptionalResByArg
7597 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7598 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7599 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7600 /// 'virtualConstProp' )
7601 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7602 /// [',' 'bit' ':' UInt32]? ')'
7603 bool LLParser::ParseOptionalResByArg(
7604 std::map
<std::vector
<uint64_t>, WholeProgramDevirtResolution::ByArg
>
7606 if (ParseToken(lltok::kw_resByArg
, "expected 'resByArg' here") ||
7607 ParseToken(lltok::colon
, "expected ':' here") ||
7608 ParseToken(lltok::lparen
, "expected '(' here"))
7612 std::vector
<uint64_t> Args
;
7613 if (ParseArgs(Args
) || ParseToken(lltok::comma
, "expected ',' here") ||
7614 ParseToken(lltok::kw_byArg
, "expected 'byArg here") ||
7615 ParseToken(lltok::colon
, "expected ':' here") ||
7616 ParseToken(lltok::lparen
, "expected '(' here") ||
7617 ParseToken(lltok::kw_kind
, "expected 'kind' here") ||
7618 ParseToken(lltok::colon
, "expected ':' here"))
7621 WholeProgramDevirtResolution::ByArg ByArg
;
7622 switch (Lex
.getKind()) {
7623 case lltok::kw_indir
:
7624 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::Indir
;
7626 case lltok::kw_uniformRetVal
:
7627 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::UniformRetVal
;
7629 case lltok::kw_uniqueRetVal
:
7630 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::UniqueRetVal
;
7632 case lltok::kw_virtualConstProp
:
7633 ByArg
.TheKind
= WholeProgramDevirtResolution::ByArg::VirtualConstProp
;
7636 return Error(Lex
.getLoc(),
7637 "unexpected WholeProgramDevirtResolution::ByArg kind");
7641 // Parse optional fields
7642 while (EatIfPresent(lltok::comma
)) {
7643 switch (Lex
.getKind()) {
7644 case lltok::kw_info
:
7646 if (ParseToken(lltok::colon
, "expected ':' here") ||
7647 ParseUInt64(ByArg
.Info
))
7650 case lltok::kw_byte
:
7652 if (ParseToken(lltok::colon
, "expected ':' here") ||
7653 ParseUInt32(ByArg
.Byte
))
7658 if (ParseToken(lltok::colon
, "expected ':' here") ||
7659 ParseUInt32(ByArg
.Bit
))
7663 return Error(Lex
.getLoc(),
7664 "expected optional whole program devirt field");
7668 if (ParseToken(lltok::rparen
, "expected ')' here"))
7671 ResByArg
[Args
] = ByArg
;
7672 } while (EatIfPresent(lltok::comma
));
7674 if (ParseToken(lltok::rparen
, "expected ')' here"))
7680 /// OptionalResByArg
7681 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7682 bool LLParser::ParseArgs(std::vector
<uint64_t> &Args
) {
7683 if (ParseToken(lltok::kw_args
, "expected 'args' here") ||
7684 ParseToken(lltok::colon
, "expected ':' here") ||
7685 ParseToken(lltok::lparen
, "expected '(' here"))
7690 if (ParseUInt64(Val
))
7692 Args
.push_back(Val
);
7693 } while (EatIfPresent(lltok::comma
));
7695 if (ParseToken(lltok::rparen
, "expected ')' here"))
7701 static const auto FwdVIRef
= (GlobalValueSummaryMapTy::value_type
*)-8;
7703 static void resolveFwdRef(ValueInfo
*Fwd
, ValueInfo
&Resolved
) {
7704 bool ReadOnly
= Fwd
->isReadOnly();
7710 /// Stores the given Name/GUID and associated summary into the Index.
7711 /// Also updates any forward references to the associated entry ID.
7712 void LLParser::AddGlobalValueToIndex(
7713 std::string Name
, GlobalValue::GUID GUID
, GlobalValue::LinkageTypes Linkage
,
7714 unsigned ID
, std::unique_ptr
<GlobalValueSummary
> Summary
) {
7715 // First create the ValueInfo utilizing the Name or GUID.
7718 assert(Name
.empty());
7719 VI
= Index
->getOrInsertValueInfo(GUID
);
7721 assert(!Name
.empty());
7723 auto *GV
= M
->getNamedValue(Name
);
7725 VI
= Index
->getOrInsertValueInfo(GV
);
7728 (!GlobalValue::isLocalLinkage(Linkage
) || !SourceFileName
.empty()) &&
7729 "Need a source_filename to compute GUID for local");
7730 GUID
= GlobalValue::getGUID(
7731 GlobalValue::getGlobalIdentifier(Name
, Linkage
, SourceFileName
));
7732 VI
= Index
->getOrInsertValueInfo(GUID
, Index
->saveString(Name
));
7736 // Resolve forward references from calls/refs
7737 auto FwdRefVIs
= ForwardRefValueInfos
.find(ID
);
7738 if (FwdRefVIs
!= ForwardRefValueInfos
.end()) {
7739 for (auto VIRef
: FwdRefVIs
->second
) {
7740 assert(VIRef
.first
->getRef() == FwdVIRef
&&
7741 "Forward referenced ValueInfo expected to be empty");
7742 resolveFwdRef(VIRef
.first
, VI
);
7744 ForwardRefValueInfos
.erase(FwdRefVIs
);
7747 // Resolve forward references from aliases
7748 auto FwdRefAliasees
= ForwardRefAliasees
.find(ID
);
7749 if (FwdRefAliasees
!= ForwardRefAliasees
.end()) {
7750 for (auto AliaseeRef
: FwdRefAliasees
->second
) {
7751 assert(!AliaseeRef
.first
->hasAliasee() &&
7752 "Forward referencing alias already has aliasee");
7753 assert(Summary
&& "Aliasee must be a definition");
7754 AliaseeRef
.first
->setAliasee(VI
, Summary
.get());
7756 ForwardRefAliasees
.erase(FwdRefAliasees
);
7759 // Add the summary if one was provided.
7761 Index
->addGlobalValueSummary(VI
, std::move(Summary
));
7763 // Save the associated ValueInfo for use in later references by ID.
7764 if (ID
== NumberedValueInfos
.size())
7765 NumberedValueInfos
.push_back(VI
);
7767 // Handle non-continuous numbers (to make test simplification easier).
7768 if (ID
> NumberedValueInfos
.size())
7769 NumberedValueInfos
.resize(ID
+ 1);
7770 NumberedValueInfos
[ID
] = VI
;
7775 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7776 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7777 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7778 bool LLParser::ParseGVEntry(unsigned ID
) {
7779 assert(Lex
.getKind() == lltok::kw_gv
);
7782 if (ParseToken(lltok::colon
, "expected ':' here") ||
7783 ParseToken(lltok::lparen
, "expected '(' here"))
7787 GlobalValue::GUID GUID
= 0;
7788 switch (Lex
.getKind()) {
7789 case lltok::kw_name
:
7791 if (ParseToken(lltok::colon
, "expected ':' here") ||
7792 ParseStringConstant(Name
))
7794 // Can't create GUID/ValueInfo until we have the linkage.
7796 case lltok::kw_guid
:
7798 if (ParseToken(lltok::colon
, "expected ':' here") || ParseUInt64(GUID
))
7802 return Error(Lex
.getLoc(), "expected name or guid tag");
7805 if (!EatIfPresent(lltok::comma
)) {
7806 // No summaries. Wrap up.
7807 if (ParseToken(lltok::rparen
, "expected ')' here"))
7809 // This was created for a call to an external or indirect target.
7810 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
7811 // created for indirect calls with VP. A Name with no GUID came from
7812 // an external definition. We pass ExternalLinkage since that is only
7813 // used when the GUID must be computed from Name, and in that case
7814 // the symbol must have external linkage.
7815 AddGlobalValueToIndex(Name
, GUID
, GlobalValue::ExternalLinkage
, ID
,
7820 // Have a list of summaries
7821 if (ParseToken(lltok::kw_summaries
, "expected 'summaries' here") ||
7822 ParseToken(lltok::colon
, "expected ':' here"))
7826 if (ParseToken(lltok::lparen
, "expected '(' here"))
7828 switch (Lex
.getKind()) {
7829 case lltok::kw_function
:
7830 if (ParseFunctionSummary(Name
, GUID
, ID
))
7833 case lltok::kw_variable
:
7834 if (ParseVariableSummary(Name
, GUID
, ID
))
7837 case lltok::kw_alias
:
7838 if (ParseAliasSummary(Name
, GUID
, ID
))
7842 return Error(Lex
.getLoc(), "expected summary type");
7844 if (ParseToken(lltok::rparen
, "expected ')' here"))
7846 } while (EatIfPresent(lltok::comma
));
7848 if (ParseToken(lltok::rparen
, "expected ')' here"))
7855 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7856 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
7857 /// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
7858 bool LLParser::ParseFunctionSummary(std::string Name
, GlobalValue::GUID GUID
,
7860 assert(Lex
.getKind() == lltok::kw_function
);
7863 StringRef ModulePath
;
7864 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
7865 /*Linkage=*/GlobalValue::ExternalLinkage
, /*NotEligibleToImport=*/false,
7866 /*Live=*/false, /*IsLocal=*/false);
7868 std::vector
<FunctionSummary::EdgeTy
> Calls
;
7869 FunctionSummary::TypeIdInfo TypeIdInfo
;
7870 std::vector
<ValueInfo
> Refs
;
7871 // Default is all-zeros (conservative values).
7872 FunctionSummary::FFlags FFlags
= {};
7873 if (ParseToken(lltok::colon
, "expected ':' here") ||
7874 ParseToken(lltok::lparen
, "expected '(' here") ||
7875 ParseModuleReference(ModulePath
) ||
7876 ParseToken(lltok::comma
, "expected ',' here") || ParseGVFlags(GVFlags
) ||
7877 ParseToken(lltok::comma
, "expected ',' here") ||
7878 ParseToken(lltok::kw_insts
, "expected 'insts' here") ||
7879 ParseToken(lltok::colon
, "expected ':' here") || ParseUInt32(InstCount
))
7882 // Parse optional fields
7883 while (EatIfPresent(lltok::comma
)) {
7884 switch (Lex
.getKind()) {
7885 case lltok::kw_funcFlags
:
7886 if (ParseOptionalFFlags(FFlags
))
7889 case lltok::kw_calls
:
7890 if (ParseOptionalCalls(Calls
))
7893 case lltok::kw_typeIdInfo
:
7894 if (ParseOptionalTypeIdInfo(TypeIdInfo
))
7897 case lltok::kw_refs
:
7898 if (ParseOptionalRefs(Refs
))
7902 return Error(Lex
.getLoc(), "expected optional function summary field");
7906 if (ParseToken(lltok::rparen
, "expected ')' here"))
7909 auto FS
= llvm::make_unique
<FunctionSummary
>(
7910 GVFlags
, InstCount
, FFlags
, /*EntryCount=*/0, std::move(Refs
),
7911 std::move(Calls
), std::move(TypeIdInfo
.TypeTests
),
7912 std::move(TypeIdInfo
.TypeTestAssumeVCalls
),
7913 std::move(TypeIdInfo
.TypeCheckedLoadVCalls
),
7914 std::move(TypeIdInfo
.TypeTestAssumeConstVCalls
),
7915 std::move(TypeIdInfo
.TypeCheckedLoadConstVCalls
));
7917 FS
->setModulePath(ModulePath
);
7919 AddGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
7926 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7927 /// [',' OptionalRefs]? ')'
7928 bool LLParser::ParseVariableSummary(std::string Name
, GlobalValue::GUID GUID
,
7930 assert(Lex
.getKind() == lltok::kw_variable
);
7933 StringRef ModulePath
;
7934 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
7935 /*Linkage=*/GlobalValue::ExternalLinkage
, /*NotEligibleToImport=*/false,
7936 /*Live=*/false, /*IsLocal=*/false);
7937 GlobalVarSummary::GVarFlags
GVarFlags(/*ReadOnly*/ false);
7938 std::vector
<ValueInfo
> Refs
;
7939 if (ParseToken(lltok::colon
, "expected ':' here") ||
7940 ParseToken(lltok::lparen
, "expected '(' here") ||
7941 ParseModuleReference(ModulePath
) ||
7942 ParseToken(lltok::comma
, "expected ',' here") || ParseGVFlags(GVFlags
) ||
7943 ParseToken(lltok::comma
, "expected ',' here") ||
7944 ParseGVarFlags(GVarFlags
))
7947 // Parse optional refs field
7948 if (EatIfPresent(lltok::comma
)) {
7949 if (ParseOptionalRefs(Refs
))
7953 if (ParseToken(lltok::rparen
, "expected ')' here"))
7957 llvm::make_unique
<GlobalVarSummary
>(GVFlags
, GVarFlags
, std::move(Refs
));
7959 GS
->setModulePath(ModulePath
);
7961 AddGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
7968 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
7969 /// 'aliasee' ':' GVReference ')'
7970 bool LLParser::ParseAliasSummary(std::string Name
, GlobalValue::GUID GUID
,
7972 assert(Lex
.getKind() == lltok::kw_alias
);
7973 LocTy Loc
= Lex
.getLoc();
7976 StringRef ModulePath
;
7977 GlobalValueSummary::GVFlags GVFlags
= GlobalValueSummary::GVFlags(
7978 /*Linkage=*/GlobalValue::ExternalLinkage
, /*NotEligibleToImport=*/false,
7979 /*Live=*/false, /*IsLocal=*/false);
7980 if (ParseToken(lltok::colon
, "expected ':' here") ||
7981 ParseToken(lltok::lparen
, "expected '(' here") ||
7982 ParseModuleReference(ModulePath
) ||
7983 ParseToken(lltok::comma
, "expected ',' here") || ParseGVFlags(GVFlags
) ||
7984 ParseToken(lltok::comma
, "expected ',' here") ||
7985 ParseToken(lltok::kw_aliasee
, "expected 'aliasee' here") ||
7986 ParseToken(lltok::colon
, "expected ':' here"))
7989 ValueInfo AliaseeVI
;
7991 if (ParseGVReference(AliaseeVI
, GVId
))
7994 if (ParseToken(lltok::rparen
, "expected ')' here"))
7997 auto AS
= llvm::make_unique
<AliasSummary
>(GVFlags
);
7999 AS
->setModulePath(ModulePath
);
8001 // Record forward reference if the aliasee is not parsed yet.
8002 if (AliaseeVI
.getRef() == FwdVIRef
) {
8003 auto FwdRef
= ForwardRefAliasees
.insert(
8004 std::make_pair(GVId
, std::vector
<std::pair
<AliasSummary
*, LocTy
>>()));
8005 FwdRef
.first
->second
.push_back(std::make_pair(AS
.get(), Loc
));
8007 auto Summary
= Index
->findSummaryInModule(AliaseeVI
, ModulePath
);
8008 assert(Summary
&& "Aliasee must be a definition");
8009 AS
->setAliasee(AliaseeVI
, Summary
);
8012 AddGlobalValueToIndex(Name
, GUID
, (GlobalValue::LinkageTypes
)GVFlags
.Linkage
,
8020 bool LLParser::ParseFlag(unsigned &Val
) {
8021 if (Lex
.getKind() != lltok::APSInt
|| Lex
.getAPSIntVal().isSigned())
8022 return TokError("expected integer");
8023 Val
= (unsigned)Lex
.getAPSIntVal().getBoolValue();
8029 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8030 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8031 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
8032 /// [',' 'noInline' ':' Flag]? ')'
8033 bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags
&FFlags
) {
8034 assert(Lex
.getKind() == lltok::kw_funcFlags
);
8037 if (ParseToken(lltok::colon
, "expected ':' in funcFlags") |
8038 ParseToken(lltok::lparen
, "expected '(' in funcFlags"))
8043 switch (Lex
.getKind()) {
8044 case lltok::kw_readNone
:
8046 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
8048 FFlags
.ReadNone
= Val
;
8050 case lltok::kw_readOnly
:
8052 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
8054 FFlags
.ReadOnly
= Val
;
8056 case lltok::kw_noRecurse
:
8058 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
8060 FFlags
.NoRecurse
= Val
;
8062 case lltok::kw_returnDoesNotAlias
:
8064 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
8066 FFlags
.ReturnDoesNotAlias
= Val
;
8068 case lltok::kw_noInline
:
8070 if (ParseToken(lltok::colon
, "expected ':'") || ParseFlag(Val
))
8072 FFlags
.NoInline
= Val
;
8075 return Error(Lex
.getLoc(), "expected function flag type");
8077 } while (EatIfPresent(lltok::comma
));
8079 if (ParseToken(lltok::rparen
, "expected ')' in funcFlags"))
8086 /// := 'calls' ':' '(' Call [',' Call]* ')'
8087 /// Call ::= '(' 'callee' ':' GVReference
8088 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8089 bool LLParser::ParseOptionalCalls(std::vector
<FunctionSummary::EdgeTy
> &Calls
) {
8090 assert(Lex
.getKind() == lltok::kw_calls
);
8093 if (ParseToken(lltok::colon
, "expected ':' in calls") |
8094 ParseToken(lltok::lparen
, "expected '(' in calls"))
8097 IdToIndexMapType IdToIndexMap
;
8098 // Parse each call edge
8101 if (ParseToken(lltok::lparen
, "expected '(' in call") ||
8102 ParseToken(lltok::kw_callee
, "expected 'callee' in call") ||
8103 ParseToken(lltok::colon
, "expected ':'"))
8106 LocTy Loc
= Lex
.getLoc();
8108 if (ParseGVReference(VI
, GVId
))
8111 CalleeInfo::HotnessType Hotness
= CalleeInfo::HotnessType::Unknown
;
8113 if (EatIfPresent(lltok::comma
)) {
8114 // Expect either hotness or relbf
8115 if (EatIfPresent(lltok::kw_hotness
)) {
8116 if (ParseToken(lltok::colon
, "expected ':'") || ParseHotness(Hotness
))
8119 if (ParseToken(lltok::kw_relbf
, "expected relbf") ||
8120 ParseToken(lltok::colon
, "expected ':'") || ParseUInt32(RelBF
))
8124 // Keep track of the Call array index needing a forward reference.
8125 // We will save the location of the ValueInfo needing an update, but
8126 // can only do so once the std::vector is finalized.
8127 if (VI
.getRef() == FwdVIRef
)
8128 IdToIndexMap
[GVId
].push_back(std::make_pair(Calls
.size(), Loc
));
8129 Calls
.push_back(FunctionSummary::EdgeTy
{VI
, CalleeInfo(Hotness
, RelBF
)});
8131 if (ParseToken(lltok::rparen
, "expected ')' in call"))
8133 } while (EatIfPresent(lltok::comma
));
8135 // Now that the Calls vector is finalized, it is safe to save the locations
8136 // of any forward GV references that need updating later.
8137 for (auto I
: IdToIndexMap
) {
8138 for (auto P
: I
.second
) {
8139 assert(Calls
[P
.first
].first
.getRef() == FwdVIRef
&&
8140 "Forward referenced ValueInfo expected to be empty");
8141 auto FwdRef
= ForwardRefValueInfos
.insert(std::make_pair(
8142 I
.first
, std::vector
<std::pair
<ValueInfo
*, LocTy
>>()));
8143 FwdRef
.first
->second
.push_back(
8144 std::make_pair(&Calls
[P
.first
].first
, P
.second
));
8148 if (ParseToken(lltok::rparen
, "expected ')' in calls"))
8155 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
8156 bool LLParser::ParseHotness(CalleeInfo::HotnessType
&Hotness
) {
8157 switch (Lex
.getKind()) {
8158 case lltok::kw_unknown
:
8159 Hotness
= CalleeInfo::HotnessType::Unknown
;
8161 case lltok::kw_cold
:
8162 Hotness
= CalleeInfo::HotnessType::Cold
;
8164 case lltok::kw_none
:
8165 Hotness
= CalleeInfo::HotnessType::None
;
8168 Hotness
= CalleeInfo::HotnessType::Hot
;
8170 case lltok::kw_critical
:
8171 Hotness
= CalleeInfo::HotnessType::Critical
;
8174 return Error(Lex
.getLoc(), "invalid call edge hotness");
8181 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8182 bool LLParser::ParseOptionalRefs(std::vector
<ValueInfo
> &Refs
) {
8183 assert(Lex
.getKind() == lltok::kw_refs
);
8186 if (ParseToken(lltok::colon
, "expected ':' in refs") |
8187 ParseToken(lltok::lparen
, "expected '(' in refs"))
8190 struct ValueContext
{
8195 std::vector
<ValueContext
> VContexts
;
8196 // Parse each ref edge
8199 VC
.Loc
= Lex
.getLoc();
8200 if (ParseGVReference(VC
.VI
, VC
.GVId
))
8202 VContexts
.push_back(VC
);
8203 } while (EatIfPresent(lltok::comma
));
8205 // Sort value contexts so that ones with readonly ValueInfo are at the end
8206 // of VContexts vector. This is needed to match immutableRefCount() behavior.
8207 llvm::sort(VContexts
, [](const ValueContext
&VC1
, const ValueContext
&VC2
) {
8208 return VC1
.VI
.isReadOnly() < VC2
.VI
.isReadOnly();
8211 IdToIndexMapType IdToIndexMap
;
8212 for (auto &VC
: VContexts
) {
8213 // Keep track of the Refs array index needing a forward reference.
8214 // We will save the location of the ValueInfo needing an update, but
8215 // can only do so once the std::vector is finalized.
8216 if (VC
.VI
.getRef() == FwdVIRef
)
8217 IdToIndexMap
[VC
.GVId
].push_back(std::make_pair(Refs
.size(), VC
.Loc
));
8218 Refs
.push_back(VC
.VI
);
8221 // Now that the Refs vector is finalized, it is safe to save the locations
8222 // of any forward GV references that need updating later.
8223 for (auto I
: IdToIndexMap
) {
8224 for (auto P
: I
.second
) {
8225 assert(Refs
[P
.first
].getRef() == FwdVIRef
&&
8226 "Forward referenced ValueInfo expected to be empty");
8227 auto FwdRef
= ForwardRefValueInfos
.insert(std::make_pair(
8228 I
.first
, std::vector
<std::pair
<ValueInfo
*, LocTy
>>()));
8229 FwdRef
.first
->second
.push_back(std::make_pair(&Refs
[P
.first
], P
.second
));
8233 if (ParseToken(lltok::rparen
, "expected ')' in refs"))
8239 /// OptionalTypeIdInfo
8240 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8241 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8242 /// [',' TypeCheckedLoadConstVCalls]? ')'
8243 bool LLParser::ParseOptionalTypeIdInfo(
8244 FunctionSummary::TypeIdInfo
&TypeIdInfo
) {
8245 assert(Lex
.getKind() == lltok::kw_typeIdInfo
);
8248 if (ParseToken(lltok::colon
, "expected ':' here") ||
8249 ParseToken(lltok::lparen
, "expected '(' in typeIdInfo"))
8253 switch (Lex
.getKind()) {
8254 case lltok::kw_typeTests
:
8255 if (ParseTypeTests(TypeIdInfo
.TypeTests
))
8258 case lltok::kw_typeTestAssumeVCalls
:
8259 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls
,
8260 TypeIdInfo
.TypeTestAssumeVCalls
))
8263 case lltok::kw_typeCheckedLoadVCalls
:
8264 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls
,
8265 TypeIdInfo
.TypeCheckedLoadVCalls
))
8268 case lltok::kw_typeTestAssumeConstVCalls
:
8269 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls
,
8270 TypeIdInfo
.TypeTestAssumeConstVCalls
))
8273 case lltok::kw_typeCheckedLoadConstVCalls
:
8274 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls
,
8275 TypeIdInfo
.TypeCheckedLoadConstVCalls
))
8279 return Error(Lex
.getLoc(), "invalid typeIdInfo list type");
8281 } while (EatIfPresent(lltok::comma
));
8283 if (ParseToken(lltok::rparen
, "expected ')' in typeIdInfo"))
8290 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8291 /// [',' (SummaryID | UInt64)]* ')'
8292 bool LLParser::ParseTypeTests(std::vector
<GlobalValue::GUID
> &TypeTests
) {
8293 assert(Lex
.getKind() == lltok::kw_typeTests
);
8296 if (ParseToken(lltok::colon
, "expected ':' here") ||
8297 ParseToken(lltok::lparen
, "expected '(' in typeIdInfo"))
8300 IdToIndexMapType IdToIndexMap
;
8302 GlobalValue::GUID GUID
= 0;
8303 if (Lex
.getKind() == lltok::SummaryID
) {
8304 unsigned ID
= Lex
.getUIntVal();
8305 LocTy Loc
= Lex
.getLoc();
8306 // Keep track of the TypeTests array index needing a forward reference.
8307 // We will save the location of the GUID needing an update, but
8308 // can only do so once the std::vector is finalized.
8309 IdToIndexMap
[ID
].push_back(std::make_pair(TypeTests
.size(), Loc
));
8311 } else if (ParseUInt64(GUID
))
8313 TypeTests
.push_back(GUID
);
8314 } while (EatIfPresent(lltok::comma
));
8316 // Now that the TypeTests vector is finalized, it is safe to save the
8317 // locations of any forward GV references that need updating later.
8318 for (auto I
: IdToIndexMap
) {
8319 for (auto P
: I
.second
) {
8320 assert(TypeTests
[P
.first
] == 0 &&
8321 "Forward referenced type id GUID expected to be 0");
8322 auto FwdRef
= ForwardRefTypeIds
.insert(std::make_pair(
8323 I
.first
, std::vector
<std::pair
<GlobalValue::GUID
*, LocTy
>>()));
8324 FwdRef
.first
->second
.push_back(
8325 std::make_pair(&TypeTests
[P
.first
], P
.second
));
8329 if (ParseToken(lltok::rparen
, "expected ')' in typeIdInfo"))
8336 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
8337 bool LLParser::ParseVFuncIdList(
8338 lltok::Kind Kind
, std::vector
<FunctionSummary::VFuncId
> &VFuncIdList
) {
8339 assert(Lex
.getKind() == Kind
);
8342 if (ParseToken(lltok::colon
, "expected ':' here") ||
8343 ParseToken(lltok::lparen
, "expected '(' here"))
8346 IdToIndexMapType IdToIndexMap
;
8348 FunctionSummary::VFuncId VFuncId
;
8349 if (ParseVFuncId(VFuncId
, IdToIndexMap
, VFuncIdList
.size()))
8351 VFuncIdList
.push_back(VFuncId
);
8352 } while (EatIfPresent(lltok::comma
));
8354 if (ParseToken(lltok::rparen
, "expected ')' here"))
8357 // Now that the VFuncIdList vector is finalized, it is safe to save the
8358 // locations of any forward GV references that need updating later.
8359 for (auto I
: IdToIndexMap
) {
8360 for (auto P
: I
.second
) {
8361 assert(VFuncIdList
[P
.first
].GUID
== 0 &&
8362 "Forward referenced type id GUID expected to be 0");
8363 auto FwdRef
= ForwardRefTypeIds
.insert(std::make_pair(
8364 I
.first
, std::vector
<std::pair
<GlobalValue::GUID
*, LocTy
>>()));
8365 FwdRef
.first
->second
.push_back(
8366 std::make_pair(&VFuncIdList
[P
.first
].GUID
, P
.second
));
8374 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8375 bool LLParser::ParseConstVCallList(
8377 std::vector
<FunctionSummary::ConstVCall
> &ConstVCallList
) {
8378 assert(Lex
.getKind() == Kind
);
8381 if (ParseToken(lltok::colon
, "expected ':' here") ||
8382 ParseToken(lltok::lparen
, "expected '(' here"))
8385 IdToIndexMapType IdToIndexMap
;
8387 FunctionSummary::ConstVCall ConstVCall
;
8388 if (ParseConstVCall(ConstVCall
, IdToIndexMap
, ConstVCallList
.size()))
8390 ConstVCallList
.push_back(ConstVCall
);
8391 } while (EatIfPresent(lltok::comma
));
8393 if (ParseToken(lltok::rparen
, "expected ')' here"))
8396 // Now that the ConstVCallList vector is finalized, it is safe to save the
8397 // locations of any forward GV references that need updating later.
8398 for (auto I
: IdToIndexMap
) {
8399 for (auto P
: I
.second
) {
8400 assert(ConstVCallList
[P
.first
].VFunc
.GUID
== 0 &&
8401 "Forward referenced type id GUID expected to be 0");
8402 auto FwdRef
= ForwardRefTypeIds
.insert(std::make_pair(
8403 I
.first
, std::vector
<std::pair
<GlobalValue::GUID
*, LocTy
>>()));
8404 FwdRef
.first
->second
.push_back(
8405 std::make_pair(&ConstVCallList
[P
.first
].VFunc
.GUID
, P
.second
));
8413 /// ::= '(' VFuncId ',' Args ')'
8414 bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall
&ConstVCall
,
8415 IdToIndexMapType
&IdToIndexMap
, unsigned Index
) {
8416 if (ParseToken(lltok::lparen
, "expected '(' here") ||
8417 ParseVFuncId(ConstVCall
.VFunc
, IdToIndexMap
, Index
))
8420 if (EatIfPresent(lltok::comma
))
8421 if (ParseArgs(ConstVCall
.Args
))
8424 if (ParseToken(lltok::rparen
, "expected ')' here"))
8431 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8432 /// 'offset' ':' UInt64 ')'
8433 bool LLParser::ParseVFuncId(FunctionSummary::VFuncId
&VFuncId
,
8434 IdToIndexMapType
&IdToIndexMap
, unsigned Index
) {
8435 assert(Lex
.getKind() == lltok::kw_vFuncId
);
8438 if (ParseToken(lltok::colon
, "expected ':' here") ||
8439 ParseToken(lltok::lparen
, "expected '(' here"))
8442 if (Lex
.getKind() == lltok::SummaryID
) {
8444 unsigned ID
= Lex
.getUIntVal();
8445 LocTy Loc
= Lex
.getLoc();
8446 // Keep track of the array index needing a forward reference.
8447 // We will save the location of the GUID needing an update, but
8448 // can only do so once the caller's std::vector is finalized.
8449 IdToIndexMap
[ID
].push_back(std::make_pair(Index
, Loc
));
8451 } else if (ParseToken(lltok::kw_guid
, "expected 'guid' here") ||
8452 ParseToken(lltok::colon
, "expected ':' here") ||
8453 ParseUInt64(VFuncId
.GUID
))
8456 if (ParseToken(lltok::comma
, "expected ',' here") ||
8457 ParseToken(lltok::kw_offset
, "expected 'offset' here") ||
8458 ParseToken(lltok::colon
, "expected ':' here") ||
8459 ParseUInt64(VFuncId
.Offset
) ||
8460 ParseToken(lltok::rparen
, "expected ')' here"))
8467 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8468 /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8469 /// 'dsoLocal' ':' Flag ')'
8470 bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags
&GVFlags
) {
8471 assert(Lex
.getKind() == lltok::kw_flags
);
8475 if (ParseToken(lltok::colon
, "expected ':' here") ||
8476 ParseToken(lltok::lparen
, "expected '(' here") ||
8477 ParseToken(lltok::kw_linkage
, "expected 'linkage' here") ||
8478 ParseToken(lltok::colon
, "expected ':' here"))
8481 GVFlags
.Linkage
= parseOptionalLinkageAux(Lex
.getKind(), HasLinkage
);
8482 assert(HasLinkage
&& "Linkage not optional in summary entry");
8486 if (ParseToken(lltok::comma
, "expected ',' here") ||
8487 ParseToken(lltok::kw_notEligibleToImport
,
8488 "expected 'notEligibleToImport' here") ||
8489 ParseToken(lltok::colon
, "expected ':' here") || ParseFlag(Flag
))
8491 GVFlags
.NotEligibleToImport
= Flag
;
8493 if (ParseToken(lltok::comma
, "expected ',' here") ||
8494 ParseToken(lltok::kw_live
, "expected 'live' here") ||
8495 ParseToken(lltok::colon
, "expected ':' here") || ParseFlag(Flag
))
8497 GVFlags
.Live
= Flag
;
8499 if (ParseToken(lltok::comma
, "expected ',' here") ||
8500 ParseToken(lltok::kw_dsoLocal
, "expected 'dsoLocal' here") ||
8501 ParseToken(lltok::colon
, "expected ':' here") || ParseFlag(Flag
))
8503 GVFlags
.DSOLocal
= Flag
;
8505 if (ParseToken(lltok::rparen
, "expected ')' here"))
8512 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag ')'
8513 bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags
&GVarFlags
) {
8514 assert(Lex
.getKind() == lltok::kw_varFlags
);
8518 if (ParseToken(lltok::colon
, "expected ':' here") ||
8519 ParseToken(lltok::lparen
, "expected '(' here") ||
8520 ParseToken(lltok::kw_readonly
, "expected 'readonly' here") ||
8521 ParseToken(lltok::colon
, "expected ':' here"))
8525 GVarFlags
.ReadOnly
= Flag
;
8527 if (ParseToken(lltok::rparen
, "expected ')' here"))
8533 /// ::= 'module' ':' UInt
8534 bool LLParser::ParseModuleReference(StringRef
&ModulePath
) {
8536 if (ParseToken(lltok::kw_module
, "expected 'module' here") ||
8537 ParseToken(lltok::colon
, "expected ':' here") ||
8538 ParseToken(lltok::SummaryID
, "expected module ID"))
8541 unsigned ModuleID
= Lex
.getUIntVal();
8542 auto I
= ModuleIdMap
.find(ModuleID
);
8543 // We should have already parsed all module IDs
8544 assert(I
!= ModuleIdMap
.end());
8545 ModulePath
= I
->second
;
8551 bool LLParser::ParseGVReference(ValueInfo
&VI
, unsigned &GVId
) {
8552 bool ReadOnly
= EatIfPresent(lltok::kw_readonly
);
8553 if (ParseToken(lltok::SummaryID
, "expected GV ID"))
8556 GVId
= Lex
.getUIntVal();
8557 // Check if we already have a VI for this GV
8558 if (GVId
< NumberedValueInfos
.size()) {
8559 assert(NumberedValueInfos
[GVId
].getRef() != FwdVIRef
);
8560 VI
= NumberedValueInfos
[GVId
];
8562 // We will create a forward reference to the stored location.
8563 VI
= ValueInfo(false, FwdVIRef
);