[llvm-exegesis] [NFC] Fixing typo.
[llvm-complete.git] / lib / AsmParser / LLParser.cpp
blob2a36bb189840964e1fcd3975412dfc6997aeb4be
1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the parser class for .ll files.
11 //===----------------------------------------------------------------------===//
13 #include "LLParser.h"
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"
48 #include <algorithm>
49 #include <cassert>
50 #include <cstring>
51 #include <iterator>
52 #include <vector>
54 using namespace llvm;
56 static std::string getTypeString(Type *T) {
57 std::string Result;
58 raw_string_ostream Tmp(Result);
59 Tmp << *T;
60 return Tmp.str();
63 /// Run: module ::= toplevelentity*
64 bool LLParser::Run() {
65 // Prime the lexer.
66 Lex.Lex();
68 if (Context.shouldDiscardValueNames())
69 return Error(
70 Lex.getLoc(),
71 "Can't read textual IR with a Context that discards named Values");
73 return ParseTopLevelEntities() || ValidateEndOfModule() ||
74 ValidateEndOfIndex();
77 bool LLParser::parseStandaloneConstantValue(Constant *&C,
78 const SlotMapping *Slots) {
79 restoreParsingState(Slots);
80 Lex.Lex();
82 Type *Ty = nullptr;
83 if (ParseType(Ty) || parseConstantValue(Ty, C))
84 return true;
85 if (Lex.getKind() != lltok::Eof)
86 return Error(Lex.getLoc(), "expected end of string");
87 return false;
90 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
91 const SlotMapping *Slots) {
92 restoreParsingState(Slots);
93 Lex.Lex();
95 Read = 0;
96 SMLoc Start = Lex.getLoc();
97 Ty = nullptr;
98 if (ParseType(Ty))
99 return true;
100 SMLoc End = Lex.getLoc();
101 Read = End.getPointer() - Start.getPointer();
103 return false;
106 void LLParser::restoreParsingState(const SlotMapping *Slots) {
107 if (!Slots)
108 return;
109 NumberedVals = Slots->GlobalValues;
110 NumberedMetadata = Slots->MetadataNodes;
111 for (const auto &I : Slots->NamedTypes)
112 NamedTypes.insert(
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
120 /// module.
121 bool LLParser::ValidateEndOfModule() {
122 if (!M)
123 return false;
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;
128 AttrBuilder B;
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);
138 FnAttrs.merge(B);
140 // If the alignment was parsed as an attribute, move to the alignment
141 // field.
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);
154 FnAttrs.merge(B);
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);
162 FnAttrs.merge(B);
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);
170 FnAttrs.merge(B);
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());
176 Attrs.merge(B);
177 GV->setAttributes(AttributeSet::get(Context,Attrs));
178 } else {
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 +
208 "'");
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);
255 if (!Slots)
256 return false;
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));
267 return false;
270 /// Do final validity and sanity checks at the end of the index.
271 bool LLParser::ValidateEndOfIndex() {
272 if (!Index)
273 return false;
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) + "'");
290 return false;
293 //===----------------------------------------------------------------------===//
294 // Top-Level Entities
295 //===----------------------------------------------------------------------===//
297 bool LLParser::ParseTopLevelEntities() {
298 // If there is no Module, then parse just the summary index entries.
299 if (!M) {
300 while (true) {
301 switch (Lex.getKind()) {
302 case lltok::Eof:
303 return false;
304 case lltok::SummaryID:
305 if (ParseSummaryEntry())
306 return true;
307 break;
308 case lltok::kw_source_filename:
309 if (ParseSourceFileName())
310 return true;
311 break;
312 default:
313 // Skip everything else
314 Lex.Lex();
318 while (true) {
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())
328 return true;
329 break;
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())
339 return true;
340 break;
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())
346 return true;
347 break;
352 /// toplevelentity
353 /// ::= 'module' 'asm' STRINGCONSTANT
354 bool LLParser::ParseModuleAsm() {
355 assert(Lex.getKind() == lltok::kw_module);
356 Lex.Lex();
358 std::string AsmStr;
359 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
360 ParseStringConstant(AsmStr)) return true;
362 M->appendModuleInlineAsm(AsmStr);
363 return false;
366 /// toplevelentity
367 /// ::= 'target' 'triple' '=' STRINGCONSTANT
368 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
369 bool LLParser::ParseTargetDefinition() {
370 assert(Lex.getKind() == lltok::kw_target);
371 std::string Str;
372 switch (Lex.Lex()) {
373 default: return TokError("unknown target property");
374 case lltok::kw_triple:
375 Lex.Lex();
376 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
377 ParseStringConstant(Str))
378 return true;
379 M->setTargetTriple(Str);
380 return false;
381 case lltok::kw_datalayout:
382 Lex.Lex();
383 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
384 ParseStringConstant(Str))
385 return true;
386 if (DataLayoutStr.empty())
387 M->setDataLayout(Str);
388 return false;
392 /// toplevelentity
393 /// ::= 'source_filename' '=' STRINGCONSTANT
394 bool LLParser::ParseSourceFileName() {
395 assert(Lex.getKind() == lltok::kw_source_filename);
396 Lex.Lex();
397 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
398 ParseStringConstant(SourceFileName))
399 return true;
400 if (M)
401 M->setSourceFileName(SourceFileName);
402 return false;
405 /// toplevelentity
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);
411 Lex.Lex();
412 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
413 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
414 return true;
416 if (EatIfPresent(lltok::rsquare))
417 return false;
419 do {
420 std::string Str;
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 '='"))
436 return true;
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];
444 if (Entry.first)
445 return Error(TypeLoc, "non-struct types may not be recursive");
446 Entry.first = Result;
447 Entry.second = SMLoc();
450 return false;
453 /// toplevelentity
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"))
462 return true;
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];
470 if (Entry.first)
471 return Error(NameLoc, "non-struct types may not be recursive");
472 Entry.first = Result;
473 Entry.second = SMLoc();
476 return false;
479 /// toplevelentity
480 /// ::= 'declare' FunctionHeader
481 bool LLParser::ParseDeclare() {
482 assert(Lex.getKind() == lltok::kw_declare);
483 Lex.Lex();
485 std::vector<std::pair<unsigned, MDNode *>> MDs;
486 while (Lex.getKind() == lltok::MetadataVar) {
487 unsigned MDK;
488 MDNode *N;
489 if (ParseMetadataAttachment(MDK, N))
490 return true;
491 MDs.push_back({MDK, N});
494 Function *F;
495 if (ParseFunctionHeader(F, false))
496 return true;
497 for (auto &MD : MDs)
498 F->addMetadata(MD.first, *MD.second);
499 return false;
502 /// toplevelentity
503 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
504 bool LLParser::ParseDefine() {
505 assert(Lex.getKind() == lltok::kw_define);
506 Lex.Lex();
508 Function *F;
509 return ParseFunctionHeader(F, true) ||
510 ParseOptionalFunctionMetadata(*F) ||
511 ParseFunctionBody(*F);
514 /// ParseGlobalType
515 /// ::= 'constant'
516 /// ::= 'global'
517 bool LLParser::ParseGlobalType(bool &IsConstant) {
518 if (Lex.getKind() == lltok::kw_constant)
519 IsConstant = true;
520 else if (Lex.getKind() == lltok::kw_global)
521 IsConstant = false;
522 else {
523 IsConstant = false;
524 return TokError("expected 'global' or 'constant'");
526 Lex.Lex();
527 return false;
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;
536 else
537 UnnamedAddr = GlobalValue::UnnamedAddr::None;
538 return false;
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();
552 std::string Name;
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 '%" +
559 Twine(VarID) + "'");
560 Lex.Lex(); // eat GlobalID;
562 if (ParseToken(lltok::equal, "expected '=' after name"))
563 return true;
566 bool HasLinkage;
567 unsigned Linkage, Visibility, DLLStorageClass;
568 bool DSOLocal;
569 GlobalVariable::ThreadLocalMode TLM;
570 GlobalVariable::UnnamedAddr UnnamedAddr;
571 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
572 DSOLocal) ||
573 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
574 return true;
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();
593 Lex.Lex();
595 bool HasLinkage;
596 unsigned Linkage, Visibility, DLLStorageClass;
597 bool DSOLocal;
598 GlobalVariable::ThreadLocalMode TLM;
599 GlobalVariable::UnnamedAddr UnnamedAddr;
600 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
601 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
602 DSOLocal) ||
603 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
604 return true;
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();
618 Lex.Lex();
620 if (ParseToken(lltok::equal, "expected '=' here"))
621 return true;
623 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
624 return TokError("expected comdat type");
626 Comdat::SelectionKind SK;
627 switch (Lex.getKind()) {
628 default:
629 return TokError("unknown selection kind");
630 case lltok::kw_any:
631 SK = Comdat::Any;
632 break;
633 case lltok::kw_exactmatch:
634 SK = Comdat::ExactMatch;
635 break;
636 case lltok::kw_largest:
637 SK = Comdat::Largest;
638 break;
639 case lltok::kw_noduplicates:
640 SK = Comdat::NoDuplicates;
641 break;
642 case lltok::kw_samesize:
643 SK = Comdat::SameSize;
644 break;
646 Lex.Lex();
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 + "'");
654 Comdat *C;
655 if (I != ComdatSymTab.end())
656 C = &I->second;
657 else
658 C = M->getOrInsertComdat(Name);
659 C->setSelectionKind(SK);
661 return false;
664 // MDString:
665 // ::= '!' STRINGCONSTANT
666 bool LLParser::ParseMDString(MDString *&Result) {
667 std::string Str;
668 if (ParseStringConstant(Str)) return true;
669 Result = MDString::get(Context, Str);
670 return false;
673 // MDNode:
674 // ::= '!' MDNodeNumber
675 bool LLParser::ParseMDNodeID(MDNode *&Result) {
676 // !{ ..., !42, ... }
677 LocTy IDLoc = Lex.getLoc();
678 unsigned MID = 0;
679 if (ParseUInt32(MID))
680 return true;
682 // If not a forward reference, just return it now.
683 if (NumberedMetadata.count(MID)) {
684 Result = NumberedMetadata[MID];
685 return false;
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);
694 return false;
697 /// ParseNamedMetadata:
698 /// !foo = !{ !1, !2 }
699 bool LLParser::ParseNamedMetadata() {
700 assert(Lex.getKind() == lltok::MetadataVar);
701 std::string Name = Lex.getStrVal();
702 Lex.Lex();
704 if (ParseToken(lltok::equal, "expected '=' here") ||
705 ParseToken(lltok::exclaim, "Expected '!' here") ||
706 ParseToken(lltok::lbrace, "Expected '{' here"))
707 return true;
709 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
710 if (Lex.getKind() != lltok::rbrace)
711 do {
712 MDNode *N = nullptr;
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))
719 return true;
720 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
721 ParseMDNodeID(N)) {
722 return true;
724 NMD->addOperand(N);
725 } while (EatIfPresent(lltok::comma));
727 return ParseToken(lltok::rbrace, "expected end of metadata node");
730 /// ParseStandaloneMetadata:
731 /// !42 = !{...}
732 bool LLParser::ParseStandaloneMetadata() {
733 assert(Lex.getKind() == lltok::exclaim);
734 Lex.Lex();
735 unsigned MetadataID = 0;
737 MDNode *Init;
738 if (ParseUInt32(MetadataID) ||
739 ParseToken(lltok::equal, "expected '=' here"))
740 return true;
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))
749 return true;
750 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
751 ParseMDTuple(Init, IsDistinct))
752 return true;
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");
761 } else {
762 if (NumberedMetadata.count(MetadataID))
763 return TokError("Metadata id is already used");
764 NumberedMetadata[MetadataID].reset(Init);
767 return false;
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)
778 return TokError(
779 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
780 Lex.Lex();
781 if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
782 ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
783 return true;
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;
787 do {
788 switch (Lex.getKind()) {
789 case lltok::lparen:
790 NumOpenParen++;
791 break;
792 case lltok::rparen:
793 NumOpenParen--;
794 break;
795 case lltok::Eof:
796 return TokError("found end of file while parsing summary entry");
797 default:
798 // Skip everything in between parentheses.
799 break;
801 Lex.Lex();
802 } while (NumOpenParen > 0);
803 return false;
806 /// SummaryEntry
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);
816 Lex.Lex();
817 if (ParseToken(lltok::equal, "expected '=' here"))
818 return true;
820 // If we don't have an index object, skip the summary entry.
821 if (!Index)
822 return SkipModuleSummaryEntry();
824 switch (Lex.getKind()) {
825 case lltok::kw_gv:
826 return ParseGVEntry(SummaryID);
827 case lltok::kw_module:
828 return ParseModuleEntry(SummaryID);
829 case lltok::kw_typeid:
830 return ParseTypeIdEntry(SummaryID);
831 break;
832 default:
833 return Error(Lex.getLoc(), "unexpected summary kind");
835 Lex.setIgnoreColonInIdentifiers(false);
836 return 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) {
847 if (DSOLocal)
848 GV.setDSOLocal(true);
851 /// parseIndirectSymbol:
852 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
853 /// OptionalVisibility OptionalDLLStorageClass
854 /// OptionalThreadLocal OptionalUnnamedAddr
855 // 'alias|ifunc' IndirectSymbol
857 /// IndirectSymbol
858 /// ::= TypeAndValue
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) {
867 bool IsAlias;
868 if (Lex.getKind() == lltok::kw_alias)
869 IsAlias = true;
870 else if (Lex.getKind() == lltok::kw_ifunc)
871 IsAlias = false;
872 else
873 llvm_unreachable("Not an alias or ifunc!");
874 Lex.Lex();
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");
885 Type *Ty;
886 LocTy ExplicitTypeLoc = Lex.getLoc();
887 if (ParseType(Ty) ||
888 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
889 return true;
891 Constant *Aliasee;
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))
898 return true;
899 } else {
900 // The bitcast dest type is not present, it is implied by the dest type.
901 ValID ID;
902 if (ParseValID(ID))
903 return true;
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);
911 if (!PTy)
912 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
913 unsigned AddrSpace = PTy->getAddressSpace();
915 if (IsAlias && Ty != PTy->getElementType())
916 return Error(
917 ExplicitTypeLoc,
918 "explicit pointee type doesn't match operand's pointee type");
920 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
921 return Error(
922 ExplicitTypeLoc,
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.
929 if (!Name.empty()) {
930 GVal = M->getNamedValue(Name);
931 if (GVal) {
932 if (!ForwardRefVals.erase(Name))
933 return Error(NameLoc, "redefinition of global '@" + Name + "'");
935 } else {
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;
945 if (IsAlias)
946 GA.reset(GlobalAlias::create(Ty, AddrSpace,
947 (GlobalValue::LinkageTypes)Linkage, Name,
948 Aliasee, /*Parent*/ nullptr));
949 else
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);
959 if (Name.empty())
960 NumberedVals.push_back(GA.get());
962 if (GVal) {
963 // Verify that types agree.
964 if (GVal->getType() != GA->getType())
965 return Error(
966 ExplicitTypeLoc,
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
970 // forward ref info.
971 GVal->replaceAllUsesWith(GA.get());
972 GVal->eraseFromParent();
975 // Insert into the module, we know its name won't collide now.
976 if (IsAlias)
977 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
978 else
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
983 GA.release();
985 return false;
988 /// ParseGlobal
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
999 /// already.
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");
1010 unsigned AddrSpace;
1011 bool IsConstant, IsExternallyInitialized;
1012 LocTy IsExternallyInitializedLoc;
1013 LocTy TyLoc;
1015 Type *Ty = nullptr;
1016 if (ParseOptionalAddrSpace(AddrSpace) ||
1017 ParseOptionalToken(lltok::kw_externally_initialized,
1018 IsExternallyInitialized,
1019 &IsExternallyInitializedLoc) ||
1020 ParseGlobalType(IsConstant) ||
1021 ParseType(Ty, TyLoc))
1022 return true;
1024 // If the linkage is specified and is external, then no initializer is
1025 // present.
1026 Constant *Init = nullptr;
1027 if (!HasLinkage ||
1028 !GlobalValue::isValidDeclarationLinkage(
1029 (GlobalValue::LinkageTypes)Linkage)) {
1030 if (ParseGlobalValue(Ty, Init))
1031 return true;
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);
1042 if (GVal) {
1043 if (!ForwardRefVals.erase(Name))
1044 return Error(NameLoc, "redefinition of global '@" + Name + "'");
1046 } else {
1047 auto I = ForwardRefValIDs.find(NumberedVals.size());
1048 if (I != ForwardRefValIDs.end()) {
1049 GVal = I->second.first;
1050 ForwardRefValIDs.erase(I);
1054 GlobalVariable *GV;
1055 if (!GVal) {
1056 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1057 Name, nullptr, GlobalVariable::NotThreadLocal,
1058 AddrSpace);
1059 } else {
1060 if (GVal->getValueType() != Ty)
1061 return Error(TyLoc,
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);
1070 if (Name.empty())
1071 NumberedVals.push_back(GV);
1073 // Set the parsed properties on the global.
1074 if (Init)
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) {
1087 Lex.Lex();
1089 if (Lex.getKind() == lltok::kw_section) {
1090 Lex.Lex();
1091 GV->setSection(Lex.getStrVal());
1092 if (ParseToken(lltok::StringConstant, "expected global section string"))
1093 return true;
1094 } else if (Lex.getKind() == lltok::kw_align) {
1095 unsigned Alignment;
1096 if (ParseOptionalAlignment(Alignment)) return true;
1097 GV->setAlignment(Alignment);
1098 } else if (Lex.getKind() == lltok::MetadataVar) {
1099 if (ParseGlobalObjectMetadataAttachment(*GV))
1100 return true;
1101 } else {
1102 Comdat *C;
1103 if (parseOptionalComdat(Name, C))
1104 return true;
1105 if (C)
1106 GV->setComdat(C);
1107 else
1108 return TokError("unknown global variable property!");
1112 AttrBuilder Attrs;
1113 LocTy BuiltinLoc;
1114 std::vector<unsigned> FwdRefAttrGrps;
1115 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1116 return true;
1117 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1118 GV->setAttributes(AttributeSet::get(Context, Attrs));
1119 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1122 return false;
1125 /// ParseUnnamedAttrGrp
1126 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1127 bool LLParser::ParseUnnamedAttrGrp() {
1128 assert(Lex.getKind() == lltok::kw_attributes);
1129 LocTy AttrGrpLoc = Lex.getLoc();
1130 Lex.Lex();
1132 if (Lex.getKind() != lltok::AttrGrpID)
1133 return TokError("expected attribute group id");
1135 unsigned VarID = Lex.getUIntVal();
1136 std::vector<unsigned> unused;
1137 LocTy BuiltinLoc;
1138 Lex.Lex();
1140 if (ParseToken(lltok::equal, "expected '=' here") ||
1141 ParseToken(lltok::lbrace, "expected '{' here") ||
1142 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1143 BuiltinLoc) ||
1144 ParseToken(lltok::rbrace, "expected end of attribute group"))
1145 return true;
1147 if (!NumberedAttrBuilders[VarID].hasAttributes())
1148 return Error(AttrGrpLoc, "attribute group has no attributes");
1150 return false;
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;
1160 B.clear();
1162 while (true) {
1163 lltok::Kind Token = Lex.getKind();
1164 if (Token == lltok::kw_builtin)
1165 BuiltinLoc = Lex.getLoc();
1166 switch (Token) {
1167 default:
1168 if (!inAttrGrp) return HaveError;
1169 return Error(Lex.getLoc(), "unterminated attribute group");
1170 case lltok::rbrace:
1171 // Finished.
1172 return false;
1174 case lltok::AttrGrpID: {
1175 // Allow a function to reference an attribute group:
1177 // define void @foo() #1 { ... }
1178 if (inAttrGrp)
1179 HaveError |=
1180 Error(Lex.getLoc(),
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);
1188 break;
1190 // Target-dependent attributes:
1191 case lltok::StringConstant: {
1192 if (ParseStringAttribute(B))
1193 return true;
1194 continue;
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.
1202 unsigned Alignment;
1203 if (inAttrGrp) {
1204 Lex.Lex();
1205 if (ParseToken(lltok::equal, "expected '=' here") ||
1206 ParseUInt32(Alignment))
1207 return true;
1208 } else {
1209 if (ParseOptionalAlignment(Alignment))
1210 return true;
1212 B.addAlignmentAttr(Alignment);
1213 continue;
1215 case lltok::kw_alignstack: {
1216 unsigned Alignment;
1217 if (inAttrGrp) {
1218 Lex.Lex();
1219 if (ParseToken(lltok::equal, "expected '=' here") ||
1220 ParseUInt32(Alignment))
1221 return true;
1222 } else {
1223 if (ParseOptionalStackAlignment(Alignment))
1224 return true;
1226 B.addStackAlignmentAttr(Alignment);
1227 continue;
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))
1234 return true;
1235 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1236 continue;
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);
1288 break;
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;
1293 // Error handling.
1294 case lltok::kw_inreg:
1295 case lltok::kw_signext:
1296 case lltok::kw_zeroext:
1297 HaveError |=
1298 Error(Lex.getLoc(),
1299 "invalid use of attribute on a function");
1300 break;
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 HaveError |=
1314 Error(Lex.getLoc(),
1315 "invalid use of parameter-only attribute on a function");
1316 break;
1319 Lex.Lex();
1323 //===----------------------------------------------------------------------===//
1324 // GlobalValue Reference/Resolution Routines.
1325 //===----------------------------------------------------------------------===//
1327 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1328 const std::string &Name) {
1329 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1330 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1331 PTy->getAddressSpace(), Name, M);
1332 else
1333 return new GlobalVariable(*M, PTy->getElementType(), false,
1334 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1335 nullptr, GlobalVariable::NotThreadLocal,
1336 PTy->getAddressSpace());
1339 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1340 Value *Val, bool IsCall) {
1341 if (Val->getType() == Ty)
1342 return Val;
1343 // For calls we also accept variables in the program address space.
1344 Type *SuggestedTy = Ty;
1345 if (IsCall && isa<PointerType>(Ty)) {
1346 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1347 M->getDataLayout().getProgramAddressSpace());
1348 SuggestedTy = TyInProgAS;
1349 if (Val->getType() == TyInProgAS)
1350 return Val;
1352 if (Ty->isLabelTy())
1353 Error(Loc, "'" + Name + "' is not a basic block");
1354 else
1355 Error(Loc, "'" + Name + "' defined with type '" +
1356 getTypeString(Val->getType()) + "' but expected '" +
1357 getTypeString(SuggestedTy) + "'");
1358 return nullptr;
1361 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1362 /// forward reference record if needed. This can return null if the value
1363 /// exists but does not have the right type.
1364 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1365 LocTy Loc, bool IsCall) {
1366 PointerType *PTy = dyn_cast<PointerType>(Ty);
1367 if (!PTy) {
1368 Error(Loc, "global variable reference must have pointer type");
1369 return nullptr;
1372 // Look this name up in the normal function symbol table.
1373 GlobalValue *Val =
1374 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1376 // If this is a forward reference for the value, see if we already created a
1377 // forward ref record.
1378 if (!Val) {
1379 auto I = ForwardRefVals.find(Name);
1380 if (I != ForwardRefVals.end())
1381 Val = I->second.first;
1384 // If we have the value in the symbol table or fwd-ref table, return it.
1385 if (Val)
1386 return cast_or_null<GlobalValue>(
1387 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1389 // Otherwise, create a new forward reference for this value and remember it.
1390 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1391 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1392 return FwdVal;
1395 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1396 bool IsCall) {
1397 PointerType *PTy = dyn_cast<PointerType>(Ty);
1398 if (!PTy) {
1399 Error(Loc, "global variable reference must have pointer type");
1400 return nullptr;
1403 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1405 // If this is a forward reference for the value, see if we already created a
1406 // forward ref record.
1407 if (!Val) {
1408 auto I = ForwardRefValIDs.find(ID);
1409 if (I != ForwardRefValIDs.end())
1410 Val = I->second.first;
1413 // If we have the value in the symbol table or fwd-ref table, return it.
1414 if (Val)
1415 return cast_or_null<GlobalValue>(
1416 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1418 // Otherwise, create a new forward reference for this value and remember it.
1419 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1420 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1421 return FwdVal;
1424 //===----------------------------------------------------------------------===//
1425 // Comdat Reference/Resolution Routines.
1426 //===----------------------------------------------------------------------===//
1428 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1429 // Look this name up in the comdat symbol table.
1430 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1431 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1432 if (I != ComdatSymTab.end())
1433 return &I->second;
1435 // Otherwise, create a new forward reference for this value and remember it.
1436 Comdat *C = M->getOrInsertComdat(Name);
1437 ForwardRefComdats[Name] = Loc;
1438 return C;
1441 //===----------------------------------------------------------------------===//
1442 // Helper Routines.
1443 //===----------------------------------------------------------------------===//
1445 /// ParseToken - If the current token has the specified kind, eat it and return
1446 /// success. Otherwise, emit the specified error and return failure.
1447 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1448 if (Lex.getKind() != T)
1449 return TokError(ErrMsg);
1450 Lex.Lex();
1451 return false;
1454 /// ParseStringConstant
1455 /// ::= StringConstant
1456 bool LLParser::ParseStringConstant(std::string &Result) {
1457 if (Lex.getKind() != lltok::StringConstant)
1458 return TokError("expected string constant");
1459 Result = Lex.getStrVal();
1460 Lex.Lex();
1461 return false;
1464 /// ParseUInt32
1465 /// ::= uint32
1466 bool LLParser::ParseUInt32(uint32_t &Val) {
1467 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1468 return TokError("expected integer");
1469 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1470 if (Val64 != unsigned(Val64))
1471 return TokError("expected 32-bit integer (too large)");
1472 Val = Val64;
1473 Lex.Lex();
1474 return false;
1477 /// ParseUInt64
1478 /// ::= uint64
1479 bool LLParser::ParseUInt64(uint64_t &Val) {
1480 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1481 return TokError("expected integer");
1482 Val = Lex.getAPSIntVal().getLimitedValue();
1483 Lex.Lex();
1484 return false;
1487 /// ParseTLSModel
1488 /// := 'localdynamic'
1489 /// := 'initialexec'
1490 /// := 'localexec'
1491 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1492 switch (Lex.getKind()) {
1493 default:
1494 return TokError("expected localdynamic, initialexec or localexec");
1495 case lltok::kw_localdynamic:
1496 TLM = GlobalVariable::LocalDynamicTLSModel;
1497 break;
1498 case lltok::kw_initialexec:
1499 TLM = GlobalVariable::InitialExecTLSModel;
1500 break;
1501 case lltok::kw_localexec:
1502 TLM = GlobalVariable::LocalExecTLSModel;
1503 break;
1506 Lex.Lex();
1507 return false;
1510 /// ParseOptionalThreadLocal
1511 /// := /*empty*/
1512 /// := 'thread_local'
1513 /// := 'thread_local' '(' tlsmodel ')'
1514 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1515 TLM = GlobalVariable::NotThreadLocal;
1516 if (!EatIfPresent(lltok::kw_thread_local))
1517 return false;
1519 TLM = GlobalVariable::GeneralDynamicTLSModel;
1520 if (Lex.getKind() == lltok::lparen) {
1521 Lex.Lex();
1522 return ParseTLSModel(TLM) ||
1523 ParseToken(lltok::rparen, "expected ')' after thread local model");
1525 return false;
1528 /// ParseOptionalAddrSpace
1529 /// := /*empty*/
1530 /// := 'addrspace' '(' uint32 ')'
1531 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1532 AddrSpace = DefaultAS;
1533 if (!EatIfPresent(lltok::kw_addrspace))
1534 return false;
1535 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1536 ParseUInt32(AddrSpace) ||
1537 ParseToken(lltok::rparen, "expected ')' in address space");
1540 /// ParseStringAttribute
1541 /// := StringConstant
1542 /// := StringConstant '=' StringConstant
1543 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1544 std::string Attr = Lex.getStrVal();
1545 Lex.Lex();
1546 std::string Val;
1547 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1548 return true;
1549 B.addAttribute(Attr, Val);
1550 return false;
1553 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1554 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1555 bool HaveError = false;
1557 B.clear();
1559 while (true) {
1560 lltok::Kind Token = Lex.getKind();
1561 switch (Token) {
1562 default: // End of attributes.
1563 return HaveError;
1564 case lltok::StringConstant: {
1565 if (ParseStringAttribute(B))
1566 return true;
1567 continue;
1569 case lltok::kw_align: {
1570 unsigned Alignment;
1571 if (ParseOptionalAlignment(Alignment))
1572 return true;
1573 B.addAlignmentAttr(Alignment);
1574 continue;
1576 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1577 case lltok::kw_dereferenceable: {
1578 uint64_t Bytes;
1579 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1580 return true;
1581 B.addDereferenceableAttr(Bytes);
1582 continue;
1584 case lltok::kw_dereferenceable_or_null: {
1585 uint64_t Bytes;
1586 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1587 return true;
1588 B.addDereferenceableOrNullAttr(Bytes);
1589 continue;
1591 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1592 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1593 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1594 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1595 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1596 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1597 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1598 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1599 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1600 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1601 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1602 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1603 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1604 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1605 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1607 case lltok::kw_alignstack:
1608 case lltok::kw_alwaysinline:
1609 case lltok::kw_argmemonly:
1610 case lltok::kw_builtin:
1611 case lltok::kw_inlinehint:
1612 case lltok::kw_jumptable:
1613 case lltok::kw_minsize:
1614 case lltok::kw_naked:
1615 case lltok::kw_nobuiltin:
1616 case lltok::kw_noduplicate:
1617 case lltok::kw_noimplicitfloat:
1618 case lltok::kw_noinline:
1619 case lltok::kw_nonlazybind:
1620 case lltok::kw_noredzone:
1621 case lltok::kw_noreturn:
1622 case lltok::kw_nocf_check:
1623 case lltok::kw_nounwind:
1624 case lltok::kw_optforfuzzing:
1625 case lltok::kw_optnone:
1626 case lltok::kw_optsize:
1627 case lltok::kw_returns_twice:
1628 case lltok::kw_sanitize_address:
1629 case lltok::kw_sanitize_hwaddress:
1630 case lltok::kw_sanitize_memory:
1631 case lltok::kw_sanitize_thread:
1632 case lltok::kw_speculative_load_hardening:
1633 case lltok::kw_ssp:
1634 case lltok::kw_sspreq:
1635 case lltok::kw_sspstrong:
1636 case lltok::kw_safestack:
1637 case lltok::kw_shadowcallstack:
1638 case lltok::kw_strictfp:
1639 case lltok::kw_uwtable:
1640 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1641 break;
1644 Lex.Lex();
1648 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1649 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1650 bool HaveError = false;
1652 B.clear();
1654 while (true) {
1655 lltok::Kind Token = Lex.getKind();
1656 switch (Token) {
1657 default: // End of attributes.
1658 return HaveError;
1659 case lltok::StringConstant: {
1660 if (ParseStringAttribute(B))
1661 return true;
1662 continue;
1664 case lltok::kw_dereferenceable: {
1665 uint64_t Bytes;
1666 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1667 return true;
1668 B.addDereferenceableAttr(Bytes);
1669 continue;
1671 case lltok::kw_dereferenceable_or_null: {
1672 uint64_t Bytes;
1673 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1674 return true;
1675 B.addDereferenceableOrNullAttr(Bytes);
1676 continue;
1678 case lltok::kw_align: {
1679 unsigned Alignment;
1680 if (ParseOptionalAlignment(Alignment))
1681 return true;
1682 B.addAlignmentAttr(Alignment);
1683 continue;
1685 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1686 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1687 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1688 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1689 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1691 // Error handling.
1692 case lltok::kw_byval:
1693 case lltok::kw_inalloca:
1694 case lltok::kw_nest:
1695 case lltok::kw_nocapture:
1696 case lltok::kw_returned:
1697 case lltok::kw_sret:
1698 case lltok::kw_swifterror:
1699 case lltok::kw_swiftself:
1700 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1701 break;
1703 case lltok::kw_alignstack:
1704 case lltok::kw_alwaysinline:
1705 case lltok::kw_argmemonly:
1706 case lltok::kw_builtin:
1707 case lltok::kw_cold:
1708 case lltok::kw_inlinehint:
1709 case lltok::kw_jumptable:
1710 case lltok::kw_minsize:
1711 case lltok::kw_naked:
1712 case lltok::kw_nobuiltin:
1713 case lltok::kw_noduplicate:
1714 case lltok::kw_noimplicitfloat:
1715 case lltok::kw_noinline:
1716 case lltok::kw_nonlazybind:
1717 case lltok::kw_noredzone:
1718 case lltok::kw_noreturn:
1719 case lltok::kw_nocf_check:
1720 case lltok::kw_nounwind:
1721 case lltok::kw_optforfuzzing:
1722 case lltok::kw_optnone:
1723 case lltok::kw_optsize:
1724 case lltok::kw_returns_twice:
1725 case lltok::kw_sanitize_address:
1726 case lltok::kw_sanitize_hwaddress:
1727 case lltok::kw_sanitize_memory:
1728 case lltok::kw_sanitize_thread:
1729 case lltok::kw_speculative_load_hardening:
1730 case lltok::kw_ssp:
1731 case lltok::kw_sspreq:
1732 case lltok::kw_sspstrong:
1733 case lltok::kw_safestack:
1734 case lltok::kw_shadowcallstack:
1735 case lltok::kw_strictfp:
1736 case lltok::kw_uwtable:
1737 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1738 break;
1740 case lltok::kw_readnone:
1741 case lltok::kw_readonly:
1742 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1745 Lex.Lex();
1749 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1750 HasLinkage = true;
1751 switch (Kind) {
1752 default:
1753 HasLinkage = false;
1754 return GlobalValue::ExternalLinkage;
1755 case lltok::kw_private:
1756 return GlobalValue::PrivateLinkage;
1757 case lltok::kw_internal:
1758 return GlobalValue::InternalLinkage;
1759 case lltok::kw_weak:
1760 return GlobalValue::WeakAnyLinkage;
1761 case lltok::kw_weak_odr:
1762 return GlobalValue::WeakODRLinkage;
1763 case lltok::kw_linkonce:
1764 return GlobalValue::LinkOnceAnyLinkage;
1765 case lltok::kw_linkonce_odr:
1766 return GlobalValue::LinkOnceODRLinkage;
1767 case lltok::kw_available_externally:
1768 return GlobalValue::AvailableExternallyLinkage;
1769 case lltok::kw_appending:
1770 return GlobalValue::AppendingLinkage;
1771 case lltok::kw_common:
1772 return GlobalValue::CommonLinkage;
1773 case lltok::kw_extern_weak:
1774 return GlobalValue::ExternalWeakLinkage;
1775 case lltok::kw_external:
1776 return GlobalValue::ExternalLinkage;
1780 /// ParseOptionalLinkage
1781 /// ::= /*empty*/
1782 /// ::= 'private'
1783 /// ::= 'internal'
1784 /// ::= 'weak'
1785 /// ::= 'weak_odr'
1786 /// ::= 'linkonce'
1787 /// ::= 'linkonce_odr'
1788 /// ::= 'available_externally'
1789 /// ::= 'appending'
1790 /// ::= 'common'
1791 /// ::= 'extern_weak'
1792 /// ::= 'external'
1793 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1794 unsigned &Visibility,
1795 unsigned &DLLStorageClass,
1796 bool &DSOLocal) {
1797 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1798 if (HasLinkage)
1799 Lex.Lex();
1800 ParseOptionalDSOLocal(DSOLocal);
1801 ParseOptionalVisibility(Visibility);
1802 ParseOptionalDLLStorageClass(DLLStorageClass);
1804 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1805 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1808 return false;
1811 void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1812 switch (Lex.getKind()) {
1813 default:
1814 DSOLocal = false;
1815 break;
1816 case lltok::kw_dso_local:
1817 DSOLocal = true;
1818 Lex.Lex();
1819 break;
1820 case lltok::kw_dso_preemptable:
1821 DSOLocal = false;
1822 Lex.Lex();
1823 break;
1827 /// ParseOptionalVisibility
1828 /// ::= /*empty*/
1829 /// ::= 'default'
1830 /// ::= 'hidden'
1831 /// ::= 'protected'
1833 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1834 switch (Lex.getKind()) {
1835 default:
1836 Res = GlobalValue::DefaultVisibility;
1837 return;
1838 case lltok::kw_default:
1839 Res = GlobalValue::DefaultVisibility;
1840 break;
1841 case lltok::kw_hidden:
1842 Res = GlobalValue::HiddenVisibility;
1843 break;
1844 case lltok::kw_protected:
1845 Res = GlobalValue::ProtectedVisibility;
1846 break;
1848 Lex.Lex();
1851 /// ParseOptionalDLLStorageClass
1852 /// ::= /*empty*/
1853 /// ::= 'dllimport'
1854 /// ::= 'dllexport'
1856 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1857 switch (Lex.getKind()) {
1858 default:
1859 Res = GlobalValue::DefaultStorageClass;
1860 return;
1861 case lltok::kw_dllimport:
1862 Res = GlobalValue::DLLImportStorageClass;
1863 break;
1864 case lltok::kw_dllexport:
1865 Res = GlobalValue::DLLExportStorageClass;
1866 break;
1868 Lex.Lex();
1871 /// ParseOptionalCallingConv
1872 /// ::= /*empty*/
1873 /// ::= 'ccc'
1874 /// ::= 'fastcc'
1875 /// ::= 'intel_ocl_bicc'
1876 /// ::= 'coldcc'
1877 /// ::= 'x86_stdcallcc'
1878 /// ::= 'x86_fastcallcc'
1879 /// ::= 'x86_thiscallcc'
1880 /// ::= 'x86_vectorcallcc'
1881 /// ::= 'arm_apcscc'
1882 /// ::= 'arm_aapcscc'
1883 /// ::= 'arm_aapcs_vfpcc'
1884 /// ::= 'aarch64_vector_pcs'
1885 /// ::= 'msp430_intrcc'
1886 /// ::= 'avr_intrcc'
1887 /// ::= 'avr_signalcc'
1888 /// ::= 'ptx_kernel'
1889 /// ::= 'ptx_device'
1890 /// ::= 'spir_func'
1891 /// ::= 'spir_kernel'
1892 /// ::= 'x86_64_sysvcc'
1893 /// ::= 'win64cc'
1894 /// ::= 'webkit_jscc'
1895 /// ::= 'anyregcc'
1896 /// ::= 'preserve_mostcc'
1897 /// ::= 'preserve_allcc'
1898 /// ::= 'ghccc'
1899 /// ::= 'swiftcc'
1900 /// ::= 'x86_intrcc'
1901 /// ::= 'hhvmcc'
1902 /// ::= 'hhvm_ccc'
1903 /// ::= 'cxx_fast_tlscc'
1904 /// ::= 'amdgpu_vs'
1905 /// ::= 'amdgpu_ls'
1906 /// ::= 'amdgpu_hs'
1907 /// ::= 'amdgpu_es'
1908 /// ::= 'amdgpu_gs'
1909 /// ::= 'amdgpu_ps'
1910 /// ::= 'amdgpu_cs'
1911 /// ::= 'amdgpu_kernel'
1912 /// ::= 'cc' UINT
1914 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1915 switch (Lex.getKind()) {
1916 default: CC = CallingConv::C; return false;
1917 case lltok::kw_ccc: CC = CallingConv::C; break;
1918 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1919 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1920 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1921 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1922 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1923 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1924 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1925 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1926 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1927 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1928 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
1929 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1930 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1931 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1932 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1933 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1934 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1935 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1936 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1937 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1938 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1939 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1940 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1941 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1942 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1943 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1944 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1945 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1946 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1947 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1948 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1949 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1950 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
1951 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
1952 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
1953 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1954 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1955 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1956 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1957 case lltok::kw_cc: {
1958 Lex.Lex();
1959 return ParseUInt32(CC);
1963 Lex.Lex();
1964 return false;
1967 /// ParseMetadataAttachment
1968 /// ::= !dbg !42
1969 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1970 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1972 std::string Name = Lex.getStrVal();
1973 Kind = M->getMDKindID(Name);
1974 Lex.Lex();
1976 return ParseMDNode(MD);
1979 /// ParseInstructionMetadata
1980 /// ::= !dbg !42 (',' !dbg !57)*
1981 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1982 do {
1983 if (Lex.getKind() != lltok::MetadataVar)
1984 return TokError("expected metadata after comma");
1986 unsigned MDK;
1987 MDNode *N;
1988 if (ParseMetadataAttachment(MDK, N))
1989 return true;
1991 Inst.setMetadata(MDK, N);
1992 if (MDK == LLVMContext::MD_tbaa)
1993 InstsWithTBAATag.push_back(&Inst);
1995 // If this is the end of the list, we're done.
1996 } while (EatIfPresent(lltok::comma));
1997 return false;
2000 /// ParseGlobalObjectMetadataAttachment
2001 /// ::= !dbg !57
2002 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2003 unsigned MDK;
2004 MDNode *N;
2005 if (ParseMetadataAttachment(MDK, N))
2006 return true;
2008 GO.addMetadata(MDK, *N);
2009 return false;
2012 /// ParseOptionalFunctionMetadata
2013 /// ::= (!dbg !57)*
2014 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
2015 while (Lex.getKind() == lltok::MetadataVar)
2016 if (ParseGlobalObjectMetadataAttachment(F))
2017 return true;
2018 return false;
2021 /// ParseOptionalAlignment
2022 /// ::= /* empty */
2023 /// ::= 'align' 4
2024 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
2025 Alignment = 0;
2026 if (!EatIfPresent(lltok::kw_align))
2027 return false;
2028 LocTy AlignLoc = Lex.getLoc();
2029 if (ParseUInt32(Alignment)) return true;
2030 if (!isPowerOf2_32(Alignment))
2031 return Error(AlignLoc, "alignment is not a power of two");
2032 if (Alignment > Value::MaximumAlignment)
2033 return Error(AlignLoc, "huge alignments are not supported yet");
2034 return false;
2037 /// ParseOptionalDerefAttrBytes
2038 /// ::= /* empty */
2039 /// ::= AttrKind '(' 4 ')'
2041 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2042 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2043 uint64_t &Bytes) {
2044 assert((AttrKind == lltok::kw_dereferenceable ||
2045 AttrKind == lltok::kw_dereferenceable_or_null) &&
2046 "contract!");
2048 Bytes = 0;
2049 if (!EatIfPresent(AttrKind))
2050 return false;
2051 LocTy ParenLoc = Lex.getLoc();
2052 if (!EatIfPresent(lltok::lparen))
2053 return Error(ParenLoc, "expected '('");
2054 LocTy DerefLoc = Lex.getLoc();
2055 if (ParseUInt64(Bytes)) return true;
2056 ParenLoc = Lex.getLoc();
2057 if (!EatIfPresent(lltok::rparen))
2058 return Error(ParenLoc, "expected ')'");
2059 if (!Bytes)
2060 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2061 return false;
2064 /// ParseOptionalCommaAlign
2065 /// ::=
2066 /// ::= ',' align 4
2068 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2069 /// end.
2070 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
2071 bool &AteExtraComma) {
2072 AteExtraComma = false;
2073 while (EatIfPresent(lltok::comma)) {
2074 // Metadata at the end is an early exit.
2075 if (Lex.getKind() == lltok::MetadataVar) {
2076 AteExtraComma = true;
2077 return false;
2080 if (Lex.getKind() != lltok::kw_align)
2081 return Error(Lex.getLoc(), "expected metadata or 'align'");
2083 if (ParseOptionalAlignment(Alignment)) return true;
2086 return false;
2089 /// ParseOptionalCommaAddrSpace
2090 /// ::=
2091 /// ::= ',' addrspace(1)
2093 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2094 /// end.
2095 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2096 LocTy &Loc,
2097 bool &AteExtraComma) {
2098 AteExtraComma = false;
2099 while (EatIfPresent(lltok::comma)) {
2100 // Metadata at the end is an early exit.
2101 if (Lex.getKind() == lltok::MetadataVar) {
2102 AteExtraComma = true;
2103 return false;
2106 Loc = Lex.getLoc();
2107 if (Lex.getKind() != lltok::kw_addrspace)
2108 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2110 if (ParseOptionalAddrSpace(AddrSpace))
2111 return true;
2114 return false;
2117 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2118 Optional<unsigned> &HowManyArg) {
2119 Lex.Lex();
2121 auto StartParen = Lex.getLoc();
2122 if (!EatIfPresent(lltok::lparen))
2123 return Error(StartParen, "expected '('");
2125 if (ParseUInt32(BaseSizeArg))
2126 return true;
2128 if (EatIfPresent(lltok::comma)) {
2129 auto HowManyAt = Lex.getLoc();
2130 unsigned HowMany;
2131 if (ParseUInt32(HowMany))
2132 return true;
2133 if (HowMany == BaseSizeArg)
2134 return Error(HowManyAt,
2135 "'allocsize' indices can't refer to the same parameter");
2136 HowManyArg = HowMany;
2137 } else
2138 HowManyArg = None;
2140 auto EndParen = Lex.getLoc();
2141 if (!EatIfPresent(lltok::rparen))
2142 return Error(EndParen, "expected ')'");
2143 return false;
2146 /// ParseScopeAndOrdering
2147 /// if isAtomic: ::= SyncScope? AtomicOrdering
2148 /// else: ::=
2150 /// This sets Scope and Ordering to the parsed values.
2151 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
2152 AtomicOrdering &Ordering) {
2153 if (!isAtomic)
2154 return false;
2156 return ParseScope(SSID) || ParseOrdering(Ordering);
2159 /// ParseScope
2160 /// ::= syncscope("singlethread" | "<target scope>")?
2162 /// This sets synchronization scope ID to the ID of the parsed value.
2163 bool LLParser::ParseScope(SyncScope::ID &SSID) {
2164 SSID = SyncScope::System;
2165 if (EatIfPresent(lltok::kw_syncscope)) {
2166 auto StartParenAt = Lex.getLoc();
2167 if (!EatIfPresent(lltok::lparen))
2168 return Error(StartParenAt, "Expected '(' in syncscope");
2170 std::string SSN;
2171 auto SSNAt = Lex.getLoc();
2172 if (ParseStringConstant(SSN))
2173 return Error(SSNAt, "Expected synchronization scope name");
2175 auto EndParenAt = Lex.getLoc();
2176 if (!EatIfPresent(lltok::rparen))
2177 return Error(EndParenAt, "Expected ')' in syncscope");
2179 SSID = Context.getOrInsertSyncScopeID(SSN);
2182 return false;
2185 /// ParseOrdering
2186 /// ::= AtomicOrdering
2188 /// This sets Ordering to the parsed value.
2189 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
2190 switch (Lex.getKind()) {
2191 default: return TokError("Expected ordering on atomic instruction");
2192 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2193 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2194 // Not specified yet:
2195 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2196 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2197 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2198 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2199 case lltok::kw_seq_cst:
2200 Ordering = AtomicOrdering::SequentiallyConsistent;
2201 break;
2203 Lex.Lex();
2204 return false;
2207 /// ParseOptionalStackAlignment
2208 /// ::= /* empty */
2209 /// ::= 'alignstack' '(' 4 ')'
2210 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2211 Alignment = 0;
2212 if (!EatIfPresent(lltok::kw_alignstack))
2213 return false;
2214 LocTy ParenLoc = Lex.getLoc();
2215 if (!EatIfPresent(lltok::lparen))
2216 return Error(ParenLoc, "expected '('");
2217 LocTy AlignLoc = Lex.getLoc();
2218 if (ParseUInt32(Alignment)) return true;
2219 ParenLoc = Lex.getLoc();
2220 if (!EatIfPresent(lltok::rparen))
2221 return Error(ParenLoc, "expected ')'");
2222 if (!isPowerOf2_32(Alignment))
2223 return Error(AlignLoc, "stack alignment is not a power of two");
2224 return false;
2227 /// ParseIndexList - This parses the index list for an insert/extractvalue
2228 /// instruction. This sets AteExtraComma in the case where we eat an extra
2229 /// comma at the end of the line and find that it is followed by metadata.
2230 /// Clients that don't allow metadata can call the version of this function that
2231 /// only takes one argument.
2233 /// ParseIndexList
2234 /// ::= (',' uint32)+
2236 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2237 bool &AteExtraComma) {
2238 AteExtraComma = false;
2240 if (Lex.getKind() != lltok::comma)
2241 return TokError("expected ',' as start of index list");
2243 while (EatIfPresent(lltok::comma)) {
2244 if (Lex.getKind() == lltok::MetadataVar) {
2245 if (Indices.empty()) return TokError("expected index");
2246 AteExtraComma = true;
2247 return false;
2249 unsigned Idx = 0;
2250 if (ParseUInt32(Idx)) return true;
2251 Indices.push_back(Idx);
2254 return false;
2257 //===----------------------------------------------------------------------===//
2258 // Type Parsing.
2259 //===----------------------------------------------------------------------===//
2261 /// ParseType - Parse a type.
2262 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2263 SMLoc TypeLoc = Lex.getLoc();
2264 switch (Lex.getKind()) {
2265 default:
2266 return TokError(Msg);
2267 case lltok::Type:
2268 // Type ::= 'float' | 'void' (etc)
2269 Result = Lex.getTyVal();
2270 Lex.Lex();
2271 break;
2272 case lltok::lbrace:
2273 // Type ::= StructType
2274 if (ParseAnonStructType(Result, false))
2275 return true;
2276 break;
2277 case lltok::lsquare:
2278 // Type ::= '[' ... ']'
2279 Lex.Lex(); // eat the lsquare.
2280 if (ParseArrayVectorType(Result, false))
2281 return true;
2282 break;
2283 case lltok::less: // Either vector or packed struct.
2284 // Type ::= '<' ... '>'
2285 Lex.Lex();
2286 if (Lex.getKind() == lltok::lbrace) {
2287 if (ParseAnonStructType(Result, true) ||
2288 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2289 return true;
2290 } else if (ParseArrayVectorType(Result, true))
2291 return true;
2292 break;
2293 case lltok::LocalVar: {
2294 // Type ::= %foo
2295 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2297 // If the type hasn't been defined yet, create a forward definition and
2298 // remember where that forward def'n was seen (in case it never is defined).
2299 if (!Entry.first) {
2300 Entry.first = StructType::create(Context, Lex.getStrVal());
2301 Entry.second = Lex.getLoc();
2303 Result = Entry.first;
2304 Lex.Lex();
2305 break;
2308 case lltok::LocalVarID: {
2309 // Type ::= %4
2310 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2312 // If the type hasn't been defined yet, create a forward definition and
2313 // remember where that forward def'n was seen (in case it never is defined).
2314 if (!Entry.first) {
2315 Entry.first = StructType::create(Context);
2316 Entry.second = Lex.getLoc();
2318 Result = Entry.first;
2319 Lex.Lex();
2320 break;
2324 // Parse the type suffixes.
2325 while (true) {
2326 switch (Lex.getKind()) {
2327 // End of type.
2328 default:
2329 if (!AllowVoid && Result->isVoidTy())
2330 return Error(TypeLoc, "void type only allowed for function results");
2331 return false;
2333 // Type ::= Type '*'
2334 case lltok::star:
2335 if (Result->isLabelTy())
2336 return TokError("basic block pointers are invalid");
2337 if (Result->isVoidTy())
2338 return TokError("pointers to void are invalid - use i8* instead");
2339 if (!PointerType::isValidElementType(Result))
2340 return TokError("pointer to this type is invalid");
2341 Result = PointerType::getUnqual(Result);
2342 Lex.Lex();
2343 break;
2345 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2346 case lltok::kw_addrspace: {
2347 if (Result->isLabelTy())
2348 return TokError("basic block pointers are invalid");
2349 if (Result->isVoidTy())
2350 return TokError("pointers to void are invalid; use i8* instead");
2351 if (!PointerType::isValidElementType(Result))
2352 return TokError("pointer to this type is invalid");
2353 unsigned AddrSpace;
2354 if (ParseOptionalAddrSpace(AddrSpace) ||
2355 ParseToken(lltok::star, "expected '*' in address space"))
2356 return true;
2358 Result = PointerType::get(Result, AddrSpace);
2359 break;
2362 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2363 case lltok::lparen:
2364 if (ParseFunctionType(Result))
2365 return true;
2366 break;
2371 /// ParseParameterList
2372 /// ::= '(' ')'
2373 /// ::= '(' Arg (',' Arg)* ')'
2374 /// Arg
2375 /// ::= Type OptionalAttributes Value OptionalAttributes
2376 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2377 PerFunctionState &PFS, bool IsMustTailCall,
2378 bool InVarArgsFunc) {
2379 if (ParseToken(lltok::lparen, "expected '(' in call"))
2380 return true;
2382 while (Lex.getKind() != lltok::rparen) {
2383 // If this isn't the first argument, we need a comma.
2384 if (!ArgList.empty() &&
2385 ParseToken(lltok::comma, "expected ',' in argument list"))
2386 return true;
2388 // Parse an ellipsis if this is a musttail call in a variadic function.
2389 if (Lex.getKind() == lltok::dotdotdot) {
2390 const char *Msg = "unexpected ellipsis in argument list for ";
2391 if (!IsMustTailCall)
2392 return TokError(Twine(Msg) + "non-musttail call");
2393 if (!InVarArgsFunc)
2394 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2395 Lex.Lex(); // Lex the '...', it is purely for readability.
2396 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2399 // Parse the argument.
2400 LocTy ArgLoc;
2401 Type *ArgTy = nullptr;
2402 AttrBuilder ArgAttrs;
2403 Value *V;
2404 if (ParseType(ArgTy, ArgLoc))
2405 return true;
2407 if (ArgTy->isMetadataTy()) {
2408 if (ParseMetadataAsValue(V, PFS))
2409 return true;
2410 } else {
2411 // Otherwise, handle normal operands.
2412 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2413 return true;
2415 ArgList.push_back(ParamInfo(
2416 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2419 if (IsMustTailCall && InVarArgsFunc)
2420 return TokError("expected '...' at end of argument list for musttail call "
2421 "in varargs function");
2423 Lex.Lex(); // Lex the ')'.
2424 return false;
2427 /// ParseOptionalOperandBundles
2428 /// ::= /*empty*/
2429 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2431 /// OperandBundle
2432 /// ::= bundle-tag '(' ')'
2433 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2435 /// bundle-tag ::= String Constant
2436 bool LLParser::ParseOptionalOperandBundles(
2437 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2438 LocTy BeginLoc = Lex.getLoc();
2439 if (!EatIfPresent(lltok::lsquare))
2440 return false;
2442 while (Lex.getKind() != lltok::rsquare) {
2443 // If this isn't the first operand bundle, we need a comma.
2444 if (!BundleList.empty() &&
2445 ParseToken(lltok::comma, "expected ',' in input list"))
2446 return true;
2448 std::string Tag;
2449 if (ParseStringConstant(Tag))
2450 return true;
2452 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2453 return true;
2455 std::vector<Value *> Inputs;
2456 while (Lex.getKind() != lltok::rparen) {
2457 // If this isn't the first input, we need a comma.
2458 if (!Inputs.empty() &&
2459 ParseToken(lltok::comma, "expected ',' in input list"))
2460 return true;
2462 Type *Ty = nullptr;
2463 Value *Input = nullptr;
2464 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2465 return true;
2466 Inputs.push_back(Input);
2469 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2471 Lex.Lex(); // Lex the ')'.
2474 if (BundleList.empty())
2475 return Error(BeginLoc, "operand bundle set must not be empty");
2477 Lex.Lex(); // Lex the ']'.
2478 return false;
2481 /// ParseArgumentList - Parse the argument list for a function type or function
2482 /// prototype.
2483 /// ::= '(' ArgTypeListI ')'
2484 /// ArgTypeListI
2485 /// ::= /*empty*/
2486 /// ::= '...'
2487 /// ::= ArgTypeList ',' '...'
2488 /// ::= ArgType (',' ArgType)*
2490 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2491 bool &isVarArg){
2492 isVarArg = false;
2493 assert(Lex.getKind() == lltok::lparen);
2494 Lex.Lex(); // eat the (.
2496 if (Lex.getKind() == lltok::rparen) {
2497 // empty
2498 } else if (Lex.getKind() == lltok::dotdotdot) {
2499 isVarArg = true;
2500 Lex.Lex();
2501 } else {
2502 LocTy TypeLoc = Lex.getLoc();
2503 Type *ArgTy = nullptr;
2504 AttrBuilder Attrs;
2505 std::string Name;
2507 if (ParseType(ArgTy) ||
2508 ParseOptionalParamAttrs(Attrs)) return true;
2510 if (ArgTy->isVoidTy())
2511 return Error(TypeLoc, "argument can not have void type");
2513 if (Lex.getKind() == lltok::LocalVar) {
2514 Name = Lex.getStrVal();
2515 Lex.Lex();
2518 if (!FunctionType::isValidArgumentType(ArgTy))
2519 return Error(TypeLoc, "invalid type for function argument");
2521 ArgList.emplace_back(TypeLoc, ArgTy,
2522 AttributeSet::get(ArgTy->getContext(), Attrs),
2523 std::move(Name));
2525 while (EatIfPresent(lltok::comma)) {
2526 // Handle ... at end of arg list.
2527 if (EatIfPresent(lltok::dotdotdot)) {
2528 isVarArg = true;
2529 break;
2532 // Otherwise must be an argument type.
2533 TypeLoc = Lex.getLoc();
2534 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2536 if (ArgTy->isVoidTy())
2537 return Error(TypeLoc, "argument can not have void type");
2539 if (Lex.getKind() == lltok::LocalVar) {
2540 Name = Lex.getStrVal();
2541 Lex.Lex();
2542 } else {
2543 Name = "";
2546 if (!ArgTy->isFirstClassType())
2547 return Error(TypeLoc, "invalid type for function argument");
2549 ArgList.emplace_back(TypeLoc, ArgTy,
2550 AttributeSet::get(ArgTy->getContext(), Attrs),
2551 std::move(Name));
2555 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2558 /// ParseFunctionType
2559 /// ::= Type ArgumentList OptionalAttrs
2560 bool LLParser::ParseFunctionType(Type *&Result) {
2561 assert(Lex.getKind() == lltok::lparen);
2563 if (!FunctionType::isValidReturnType(Result))
2564 return TokError("invalid function return type");
2566 SmallVector<ArgInfo, 8> ArgList;
2567 bool isVarArg;
2568 if (ParseArgumentList(ArgList, isVarArg))
2569 return true;
2571 // Reject names on the arguments lists.
2572 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2573 if (!ArgList[i].Name.empty())
2574 return Error(ArgList[i].Loc, "argument name invalid in function type");
2575 if (ArgList[i].Attrs.hasAttributes())
2576 return Error(ArgList[i].Loc,
2577 "argument attributes invalid in function type");
2580 SmallVector<Type*, 16> ArgListTy;
2581 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2582 ArgListTy.push_back(ArgList[i].Ty);
2584 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2585 return false;
2588 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2589 /// other structs.
2590 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2591 SmallVector<Type*, 8> Elts;
2592 if (ParseStructBody(Elts)) return true;
2594 Result = StructType::get(Context, Elts, Packed);
2595 return false;
2598 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2599 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2600 std::pair<Type*, LocTy> &Entry,
2601 Type *&ResultTy) {
2602 // If the type was already defined, diagnose the redefinition.
2603 if (Entry.first && !Entry.second.isValid())
2604 return Error(TypeLoc, "redefinition of type");
2606 // If we have opaque, just return without filling in the definition for the
2607 // struct. This counts as a definition as far as the .ll file goes.
2608 if (EatIfPresent(lltok::kw_opaque)) {
2609 // This type is being defined, so clear the location to indicate this.
2610 Entry.second = SMLoc();
2612 // If this type number has never been uttered, create it.
2613 if (!Entry.first)
2614 Entry.first = StructType::create(Context, Name);
2615 ResultTy = Entry.first;
2616 return false;
2619 // If the type starts with '<', then it is either a packed struct or a vector.
2620 bool isPacked = EatIfPresent(lltok::less);
2622 // If we don't have a struct, then we have a random type alias, which we
2623 // accept for compatibility with old files. These types are not allowed to be
2624 // forward referenced and not allowed to be recursive.
2625 if (Lex.getKind() != lltok::lbrace) {
2626 if (Entry.first)
2627 return Error(TypeLoc, "forward references to non-struct type");
2629 ResultTy = nullptr;
2630 if (isPacked)
2631 return ParseArrayVectorType(ResultTy, true);
2632 return ParseType(ResultTy);
2635 // This type is being defined, so clear the location to indicate this.
2636 Entry.second = SMLoc();
2638 // If this type number has never been uttered, create it.
2639 if (!Entry.first)
2640 Entry.first = StructType::create(Context, Name);
2642 StructType *STy = cast<StructType>(Entry.first);
2644 SmallVector<Type*, 8> Body;
2645 if (ParseStructBody(Body) ||
2646 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2647 return true;
2649 STy->setBody(Body, isPacked);
2650 ResultTy = STy;
2651 return false;
2654 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2655 /// StructType
2656 /// ::= '{' '}'
2657 /// ::= '{' Type (',' Type)* '}'
2658 /// ::= '<' '{' '}' '>'
2659 /// ::= '<' '{' Type (',' Type)* '}' '>'
2660 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2661 assert(Lex.getKind() == lltok::lbrace);
2662 Lex.Lex(); // Consume the '{'
2664 // Handle the empty struct.
2665 if (EatIfPresent(lltok::rbrace))
2666 return false;
2668 LocTy EltTyLoc = Lex.getLoc();
2669 Type *Ty = nullptr;
2670 if (ParseType(Ty)) return true;
2671 Body.push_back(Ty);
2673 if (!StructType::isValidElementType(Ty))
2674 return Error(EltTyLoc, "invalid element type for struct");
2676 while (EatIfPresent(lltok::comma)) {
2677 EltTyLoc = Lex.getLoc();
2678 if (ParseType(Ty)) return true;
2680 if (!StructType::isValidElementType(Ty))
2681 return Error(EltTyLoc, "invalid element type for struct");
2683 Body.push_back(Ty);
2686 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2689 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2690 /// token has already been consumed.
2691 /// Type
2692 /// ::= '[' APSINTVAL 'x' Types ']'
2693 /// ::= '<' APSINTVAL 'x' Types '>'
2694 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2695 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2696 Lex.getAPSIntVal().getBitWidth() > 64)
2697 return TokError("expected number in address space");
2699 LocTy SizeLoc = Lex.getLoc();
2700 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2701 Lex.Lex();
2703 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2704 return true;
2706 LocTy TypeLoc = Lex.getLoc();
2707 Type *EltTy = nullptr;
2708 if (ParseType(EltTy)) return true;
2710 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2711 "expected end of sequential type"))
2712 return true;
2714 if (isVector) {
2715 if (Size == 0)
2716 return Error(SizeLoc, "zero element vector is illegal");
2717 if ((unsigned)Size != Size)
2718 return Error(SizeLoc, "size too large for vector");
2719 if (!VectorType::isValidElementType(EltTy))
2720 return Error(TypeLoc, "invalid vector element type");
2721 Result = VectorType::get(EltTy, unsigned(Size));
2722 } else {
2723 if (!ArrayType::isValidElementType(EltTy))
2724 return Error(TypeLoc, "invalid array element type");
2725 Result = ArrayType::get(EltTy, Size);
2727 return false;
2730 //===----------------------------------------------------------------------===//
2731 // Function Semantic Analysis.
2732 //===----------------------------------------------------------------------===//
2734 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2735 int functionNumber)
2736 : P(p), F(f), FunctionNumber(functionNumber) {
2738 // Insert unnamed arguments into the NumberedVals list.
2739 for (Argument &A : F.args())
2740 if (!A.hasName())
2741 NumberedVals.push_back(&A);
2744 LLParser::PerFunctionState::~PerFunctionState() {
2745 // If there were any forward referenced non-basicblock values, delete them.
2747 for (const auto &P : ForwardRefVals) {
2748 if (isa<BasicBlock>(P.second.first))
2749 continue;
2750 P.second.first->replaceAllUsesWith(
2751 UndefValue::get(P.second.first->getType()));
2752 P.second.first->deleteValue();
2755 for (const auto &P : ForwardRefValIDs) {
2756 if (isa<BasicBlock>(P.second.first))
2757 continue;
2758 P.second.first->replaceAllUsesWith(
2759 UndefValue::get(P.second.first->getType()));
2760 P.second.first->deleteValue();
2764 bool LLParser::PerFunctionState::FinishFunction() {
2765 if (!ForwardRefVals.empty())
2766 return P.Error(ForwardRefVals.begin()->second.second,
2767 "use of undefined value '%" + ForwardRefVals.begin()->first +
2768 "'");
2769 if (!ForwardRefValIDs.empty())
2770 return P.Error(ForwardRefValIDs.begin()->second.second,
2771 "use of undefined value '%" +
2772 Twine(ForwardRefValIDs.begin()->first) + "'");
2773 return false;
2776 /// GetVal - Get a value with the specified name or ID, creating a
2777 /// forward reference record if needed. This can return null if the value
2778 /// exists but does not have the right type.
2779 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2780 LocTy Loc, bool IsCall) {
2781 // Look this name up in the normal function symbol table.
2782 Value *Val = F.getValueSymbolTable()->lookup(Name);
2784 // If this is a forward reference for the value, see if we already created a
2785 // forward ref record.
2786 if (!Val) {
2787 auto I = ForwardRefVals.find(Name);
2788 if (I != ForwardRefVals.end())
2789 Val = I->second.first;
2792 // If we have the value in the symbol table or fwd-ref table, return it.
2793 if (Val)
2794 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
2796 // Don't make placeholders with invalid type.
2797 if (!Ty->isFirstClassType()) {
2798 P.Error(Loc, "invalid use of a non-first-class type");
2799 return nullptr;
2802 // Otherwise, create a new forward reference for this value and remember it.
2803 Value *FwdVal;
2804 if (Ty->isLabelTy()) {
2805 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2806 } else {
2807 FwdVal = new Argument(Ty, Name);
2810 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2811 return FwdVal;
2814 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2815 bool IsCall) {
2816 // Look this name up in the normal function symbol table.
2817 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2819 // If this is a forward reference for the value, see if we already created a
2820 // forward ref record.
2821 if (!Val) {
2822 auto I = ForwardRefValIDs.find(ID);
2823 if (I != ForwardRefValIDs.end())
2824 Val = I->second.first;
2827 // If we have the value in the symbol table or fwd-ref table, return it.
2828 if (Val)
2829 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
2831 if (!Ty->isFirstClassType()) {
2832 P.Error(Loc, "invalid use of a non-first-class type");
2833 return nullptr;
2836 // Otherwise, create a new forward reference for this value and remember it.
2837 Value *FwdVal;
2838 if (Ty->isLabelTy()) {
2839 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2840 } else {
2841 FwdVal = new Argument(Ty);
2844 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2845 return FwdVal;
2848 /// SetInstName - After an instruction is parsed and inserted into its
2849 /// basic block, this installs its name.
2850 bool LLParser::PerFunctionState::SetInstName(int NameID,
2851 const std::string &NameStr,
2852 LocTy NameLoc, Instruction *Inst) {
2853 // If this instruction has void type, it cannot have a name or ID specified.
2854 if (Inst->getType()->isVoidTy()) {
2855 if (NameID != -1 || !NameStr.empty())
2856 return P.Error(NameLoc, "instructions returning void cannot have a name");
2857 return false;
2860 // If this was a numbered instruction, verify that the instruction is the
2861 // expected value and resolve any forward references.
2862 if (NameStr.empty()) {
2863 // If neither a name nor an ID was specified, just use the next ID.
2864 if (NameID == -1)
2865 NameID = NumberedVals.size();
2867 if (unsigned(NameID) != NumberedVals.size())
2868 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2869 Twine(NumberedVals.size()) + "'");
2871 auto FI = ForwardRefValIDs.find(NameID);
2872 if (FI != ForwardRefValIDs.end()) {
2873 Value *Sentinel = FI->second.first;
2874 if (Sentinel->getType() != Inst->getType())
2875 return P.Error(NameLoc, "instruction forward referenced with type '" +
2876 getTypeString(FI->second.first->getType()) + "'");
2878 Sentinel->replaceAllUsesWith(Inst);
2879 Sentinel->deleteValue();
2880 ForwardRefValIDs.erase(FI);
2883 NumberedVals.push_back(Inst);
2884 return false;
2887 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2888 auto FI = ForwardRefVals.find(NameStr);
2889 if (FI != ForwardRefVals.end()) {
2890 Value *Sentinel = FI->second.first;
2891 if (Sentinel->getType() != Inst->getType())
2892 return P.Error(NameLoc, "instruction forward referenced with type '" +
2893 getTypeString(FI->second.first->getType()) + "'");
2895 Sentinel->replaceAllUsesWith(Inst);
2896 Sentinel->deleteValue();
2897 ForwardRefVals.erase(FI);
2900 // Set the name on the instruction.
2901 Inst->setName(NameStr);
2903 if (Inst->getName() != NameStr)
2904 return P.Error(NameLoc, "multiple definition of local value named '" +
2905 NameStr + "'");
2906 return false;
2909 /// GetBB - Get a basic block with the specified name or ID, creating a
2910 /// forward reference record if needed.
2911 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2912 LocTy Loc) {
2913 return dyn_cast_or_null<BasicBlock>(
2914 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2917 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2918 return dyn_cast_or_null<BasicBlock>(
2919 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
2922 /// DefineBB - Define the specified basic block, which is either named or
2923 /// unnamed. If there is an error, this returns null otherwise it returns
2924 /// the block being defined.
2925 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2926 LocTy Loc) {
2927 BasicBlock *BB;
2928 if (Name.empty())
2929 BB = GetBB(NumberedVals.size(), Loc);
2930 else
2931 BB = GetBB(Name, Loc);
2932 if (!BB) return nullptr; // Already diagnosed error.
2934 // Move the block to the end of the function. Forward ref'd blocks are
2935 // inserted wherever they happen to be referenced.
2936 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2938 // Remove the block from forward ref sets.
2939 if (Name.empty()) {
2940 ForwardRefValIDs.erase(NumberedVals.size());
2941 NumberedVals.push_back(BB);
2942 } else {
2943 // BB forward references are already in the function symbol table.
2944 ForwardRefVals.erase(Name);
2947 return BB;
2950 //===----------------------------------------------------------------------===//
2951 // Constants.
2952 //===----------------------------------------------------------------------===//
2954 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2955 /// type implied. For example, if we parse "4" we don't know what integer type
2956 /// it has. The value will later be combined with its type and checked for
2957 /// sanity. PFS is used to convert function-local operands of metadata (since
2958 /// metadata operands are not just parsed here but also converted to values).
2959 /// PFS can be null when we are not parsing metadata values inside a function.
2960 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2961 ID.Loc = Lex.getLoc();
2962 switch (Lex.getKind()) {
2963 default: return TokError("expected value token");
2964 case lltok::GlobalID: // @42
2965 ID.UIntVal = Lex.getUIntVal();
2966 ID.Kind = ValID::t_GlobalID;
2967 break;
2968 case lltok::GlobalVar: // @foo
2969 ID.StrVal = Lex.getStrVal();
2970 ID.Kind = ValID::t_GlobalName;
2971 break;
2972 case lltok::LocalVarID: // %42
2973 ID.UIntVal = Lex.getUIntVal();
2974 ID.Kind = ValID::t_LocalID;
2975 break;
2976 case lltok::LocalVar: // %foo
2977 ID.StrVal = Lex.getStrVal();
2978 ID.Kind = ValID::t_LocalName;
2979 break;
2980 case lltok::APSInt:
2981 ID.APSIntVal = Lex.getAPSIntVal();
2982 ID.Kind = ValID::t_APSInt;
2983 break;
2984 case lltok::APFloat:
2985 ID.APFloatVal = Lex.getAPFloatVal();
2986 ID.Kind = ValID::t_APFloat;
2987 break;
2988 case lltok::kw_true:
2989 ID.ConstantVal = ConstantInt::getTrue(Context);
2990 ID.Kind = ValID::t_Constant;
2991 break;
2992 case lltok::kw_false:
2993 ID.ConstantVal = ConstantInt::getFalse(Context);
2994 ID.Kind = ValID::t_Constant;
2995 break;
2996 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2997 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2998 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2999 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3001 case lltok::lbrace: {
3002 // ValID ::= '{' ConstVector '}'
3003 Lex.Lex();
3004 SmallVector<Constant*, 16> Elts;
3005 if (ParseGlobalValueVector(Elts) ||
3006 ParseToken(lltok::rbrace, "expected end of struct constant"))
3007 return true;
3009 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3010 ID.UIntVal = Elts.size();
3011 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3012 Elts.size() * sizeof(Elts[0]));
3013 ID.Kind = ValID::t_ConstantStruct;
3014 return false;
3016 case lltok::less: {
3017 // ValID ::= '<' ConstVector '>' --> Vector.
3018 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3019 Lex.Lex();
3020 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3022 SmallVector<Constant*, 16> Elts;
3023 LocTy FirstEltLoc = Lex.getLoc();
3024 if (ParseGlobalValueVector(Elts) ||
3025 (isPackedStruct &&
3026 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3027 ParseToken(lltok::greater, "expected end of constant"))
3028 return true;
3030 if (isPackedStruct) {
3031 ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
3032 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3033 Elts.size() * sizeof(Elts[0]));
3034 ID.UIntVal = Elts.size();
3035 ID.Kind = ValID::t_PackedConstantStruct;
3036 return false;
3039 if (Elts.empty())
3040 return Error(ID.Loc, "constant vector must not be empty");
3042 if (!Elts[0]->getType()->isIntegerTy() &&
3043 !Elts[0]->getType()->isFloatingPointTy() &&
3044 !Elts[0]->getType()->isPointerTy())
3045 return Error(FirstEltLoc,
3046 "vector elements must have integer, pointer or floating point type");
3048 // Verify that all the vector elements have the same type.
3049 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3050 if (Elts[i]->getType() != Elts[0]->getType())
3051 return Error(FirstEltLoc,
3052 "vector element #" + Twine(i) +
3053 " is not of type '" + getTypeString(Elts[0]->getType()));
3055 ID.ConstantVal = ConstantVector::get(Elts);
3056 ID.Kind = ValID::t_Constant;
3057 return false;
3059 case lltok::lsquare: { // Array Constant
3060 Lex.Lex();
3061 SmallVector<Constant*, 16> Elts;
3062 LocTy FirstEltLoc = Lex.getLoc();
3063 if (ParseGlobalValueVector(Elts) ||
3064 ParseToken(lltok::rsquare, "expected end of array constant"))
3065 return true;
3067 // Handle empty element.
3068 if (Elts.empty()) {
3069 // Use undef instead of an array because it's inconvenient to determine
3070 // the element type at this point, there being no elements to examine.
3071 ID.Kind = ValID::t_EmptyArray;
3072 return false;
3075 if (!Elts[0]->getType()->isFirstClassType())
3076 return Error(FirstEltLoc, "invalid array element type: " +
3077 getTypeString(Elts[0]->getType()));
3079 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3081 // Verify all elements are correct type!
3082 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3083 if (Elts[i]->getType() != Elts[0]->getType())
3084 return Error(FirstEltLoc,
3085 "array element #" + Twine(i) +
3086 " is not of type '" + getTypeString(Elts[0]->getType()));
3089 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3090 ID.Kind = ValID::t_Constant;
3091 return false;
3093 case lltok::kw_c: // c "foo"
3094 Lex.Lex();
3095 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3096 false);
3097 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3098 ID.Kind = ValID::t_Constant;
3099 return false;
3101 case lltok::kw_asm: {
3102 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3103 // STRINGCONSTANT
3104 bool HasSideEffect, AlignStack, AsmDialect;
3105 Lex.Lex();
3106 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3107 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3108 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3109 ParseStringConstant(ID.StrVal) ||
3110 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
3111 ParseToken(lltok::StringConstant, "expected constraint string"))
3112 return true;
3113 ID.StrVal2 = Lex.getStrVal();
3114 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
3115 (unsigned(AsmDialect)<<2);
3116 ID.Kind = ValID::t_InlineAsm;
3117 return false;
3120 case lltok::kw_blockaddress: {
3121 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3122 Lex.Lex();
3124 ValID Fn, Label;
3126 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3127 ParseValID(Fn) ||
3128 ParseToken(lltok::comma, "expected comma in block address expression")||
3129 ParseValID(Label) ||
3130 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3131 return true;
3133 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3134 return Error(Fn.Loc, "expected function name in blockaddress");
3135 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3136 return Error(Label.Loc, "expected basic block name in blockaddress");
3138 // Try to find the function (but skip it if it's forward-referenced).
3139 GlobalValue *GV = nullptr;
3140 if (Fn.Kind == ValID::t_GlobalID) {
3141 if (Fn.UIntVal < NumberedVals.size())
3142 GV = NumberedVals[Fn.UIntVal];
3143 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3144 GV = M->getNamedValue(Fn.StrVal);
3146 Function *F = nullptr;
3147 if (GV) {
3148 // Confirm that it's actually a function with a definition.
3149 if (!isa<Function>(GV))
3150 return Error(Fn.Loc, "expected function name in blockaddress");
3151 F = cast<Function>(GV);
3152 if (F->isDeclaration())
3153 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3156 if (!F) {
3157 // Make a global variable as a placeholder for this reference.
3158 GlobalValue *&FwdRef =
3159 ForwardRefBlockAddresses.insert(std::make_pair(
3160 std::move(Fn),
3161 std::map<ValID, GlobalValue *>()))
3162 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3163 .first->second;
3164 if (!FwdRef)
3165 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3166 GlobalValue::InternalLinkage, nullptr, "");
3167 ID.ConstantVal = FwdRef;
3168 ID.Kind = ValID::t_Constant;
3169 return false;
3172 // We found the function; now find the basic block. Don't use PFS, since we
3173 // might be inside a constant expression.
3174 BasicBlock *BB;
3175 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3176 if (Label.Kind == ValID::t_LocalID)
3177 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3178 else
3179 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3180 if (!BB)
3181 return Error(Label.Loc, "referenced value is not a basic block");
3182 } else {
3183 if (Label.Kind == ValID::t_LocalID)
3184 return Error(Label.Loc, "cannot take address of numeric label after "
3185 "the function is defined");
3186 BB = dyn_cast_or_null<BasicBlock>(
3187 F->getValueSymbolTable()->lookup(Label.StrVal));
3188 if (!BB)
3189 return Error(Label.Loc, "referenced value is not a basic block");
3192 ID.ConstantVal = BlockAddress::get(F, BB);
3193 ID.Kind = ValID::t_Constant;
3194 return false;
3197 case lltok::kw_trunc:
3198 case lltok::kw_zext:
3199 case lltok::kw_sext:
3200 case lltok::kw_fptrunc:
3201 case lltok::kw_fpext:
3202 case lltok::kw_bitcast:
3203 case lltok::kw_addrspacecast:
3204 case lltok::kw_uitofp:
3205 case lltok::kw_sitofp:
3206 case lltok::kw_fptoui:
3207 case lltok::kw_fptosi:
3208 case lltok::kw_inttoptr:
3209 case lltok::kw_ptrtoint: {
3210 unsigned Opc = Lex.getUIntVal();
3211 Type *DestTy = nullptr;
3212 Constant *SrcVal;
3213 Lex.Lex();
3214 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3215 ParseGlobalTypeAndValue(SrcVal) ||
3216 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3217 ParseType(DestTy) ||
3218 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3219 return true;
3220 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3221 return Error(ID.Loc, "invalid cast opcode for cast from '" +
3222 getTypeString(SrcVal->getType()) + "' to '" +
3223 getTypeString(DestTy) + "'");
3224 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3225 SrcVal, DestTy);
3226 ID.Kind = ValID::t_Constant;
3227 return false;
3229 case lltok::kw_extractvalue: {
3230 Lex.Lex();
3231 Constant *Val;
3232 SmallVector<unsigned, 4> Indices;
3233 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3234 ParseGlobalTypeAndValue(Val) ||
3235 ParseIndexList(Indices) ||
3236 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3237 return true;
3239 if (!Val->getType()->isAggregateType())
3240 return Error(ID.Loc, "extractvalue operand must be aggregate type");
3241 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3242 return Error(ID.Loc, "invalid indices for extractvalue");
3243 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3244 ID.Kind = ValID::t_Constant;
3245 return false;
3247 case lltok::kw_insertvalue: {
3248 Lex.Lex();
3249 Constant *Val0, *Val1;
3250 SmallVector<unsigned, 4> Indices;
3251 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3252 ParseGlobalTypeAndValue(Val0) ||
3253 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3254 ParseGlobalTypeAndValue(Val1) ||
3255 ParseIndexList(Indices) ||
3256 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3257 return true;
3258 if (!Val0->getType()->isAggregateType())
3259 return Error(ID.Loc, "insertvalue operand must be aggregate type");
3260 Type *IndexedType =
3261 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3262 if (!IndexedType)
3263 return Error(ID.Loc, "invalid indices for insertvalue");
3264 if (IndexedType != Val1->getType())
3265 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3266 getTypeString(Val1->getType()) +
3267 "' instead of '" + getTypeString(IndexedType) +
3268 "'");
3269 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3270 ID.Kind = ValID::t_Constant;
3271 return false;
3273 case lltok::kw_icmp:
3274 case lltok::kw_fcmp: {
3275 unsigned PredVal, Opc = Lex.getUIntVal();
3276 Constant *Val0, *Val1;
3277 Lex.Lex();
3278 if (ParseCmpPredicate(PredVal, Opc) ||
3279 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3280 ParseGlobalTypeAndValue(Val0) ||
3281 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3282 ParseGlobalTypeAndValue(Val1) ||
3283 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3284 return true;
3286 if (Val0->getType() != Val1->getType())
3287 return Error(ID.Loc, "compare operands must have the same type");
3289 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3291 if (Opc == Instruction::FCmp) {
3292 if (!Val0->getType()->isFPOrFPVectorTy())
3293 return Error(ID.Loc, "fcmp requires floating point operands");
3294 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3295 } else {
3296 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3297 if (!Val0->getType()->isIntOrIntVectorTy() &&
3298 !Val0->getType()->isPtrOrPtrVectorTy())
3299 return Error(ID.Loc, "icmp requires pointer or integer operands");
3300 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3302 ID.Kind = ValID::t_Constant;
3303 return false;
3306 // Unary Operators.
3307 case lltok::kw_fneg: {
3308 unsigned Opc = Lex.getUIntVal();
3309 Constant *Val;
3310 Lex.Lex();
3311 if (ParseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3312 ParseGlobalTypeAndValue(Val) ||
3313 ParseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3314 return true;
3316 // Check that the type is valid for the operator.
3317 switch (Opc) {
3318 case Instruction::FNeg:
3319 if (!Val->getType()->isFPOrFPVectorTy())
3320 return Error(ID.Loc, "constexpr requires fp operands");
3321 break;
3322 default: llvm_unreachable("Unknown unary operator!");
3324 unsigned Flags = 0;
3325 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3326 ID.ConstantVal = C;
3327 ID.Kind = ValID::t_Constant;
3328 return false;
3330 // Binary Operators.
3331 case lltok::kw_add:
3332 case lltok::kw_fadd:
3333 case lltok::kw_sub:
3334 case lltok::kw_fsub:
3335 case lltok::kw_mul:
3336 case lltok::kw_fmul:
3337 case lltok::kw_udiv:
3338 case lltok::kw_sdiv:
3339 case lltok::kw_fdiv:
3340 case lltok::kw_urem:
3341 case lltok::kw_srem:
3342 case lltok::kw_frem:
3343 case lltok::kw_shl:
3344 case lltok::kw_lshr:
3345 case lltok::kw_ashr: {
3346 bool NUW = false;
3347 bool NSW = false;
3348 bool Exact = false;
3349 unsigned Opc = Lex.getUIntVal();
3350 Constant *Val0, *Val1;
3351 Lex.Lex();
3352 LocTy ModifierLoc = Lex.getLoc();
3353 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3354 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3355 if (EatIfPresent(lltok::kw_nuw))
3356 NUW = true;
3357 if (EatIfPresent(lltok::kw_nsw)) {
3358 NSW = true;
3359 if (EatIfPresent(lltok::kw_nuw))
3360 NUW = true;
3362 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3363 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3364 if (EatIfPresent(lltok::kw_exact))
3365 Exact = true;
3367 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3368 ParseGlobalTypeAndValue(Val0) ||
3369 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3370 ParseGlobalTypeAndValue(Val1) ||
3371 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3372 return true;
3373 if (Val0->getType() != Val1->getType())
3374 return Error(ID.Loc, "operands of constexpr must have same type");
3375 if (!Val0->getType()->isIntOrIntVectorTy()) {
3376 if (NUW)
3377 return Error(ModifierLoc, "nuw only applies to integer operations");
3378 if (NSW)
3379 return Error(ModifierLoc, "nsw only applies to integer operations");
3381 // Check that the type is valid for the operator.
3382 switch (Opc) {
3383 case Instruction::Add:
3384 case Instruction::Sub:
3385 case Instruction::Mul:
3386 case Instruction::UDiv:
3387 case Instruction::SDiv:
3388 case Instruction::URem:
3389 case Instruction::SRem:
3390 case Instruction::Shl:
3391 case Instruction::AShr:
3392 case Instruction::LShr:
3393 if (!Val0->getType()->isIntOrIntVectorTy())
3394 return Error(ID.Loc, "constexpr requires integer operands");
3395 break;
3396 case Instruction::FAdd:
3397 case Instruction::FSub:
3398 case Instruction::FMul:
3399 case Instruction::FDiv:
3400 case Instruction::FRem:
3401 if (!Val0->getType()->isFPOrFPVectorTy())
3402 return Error(ID.Loc, "constexpr requires fp operands");
3403 break;
3404 default: llvm_unreachable("Unknown binary operator!");
3406 unsigned Flags = 0;
3407 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3408 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3409 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3410 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3411 ID.ConstantVal = C;
3412 ID.Kind = ValID::t_Constant;
3413 return false;
3416 // Logical Operations
3417 case lltok::kw_and:
3418 case lltok::kw_or:
3419 case lltok::kw_xor: {
3420 unsigned Opc = Lex.getUIntVal();
3421 Constant *Val0, *Val1;
3422 Lex.Lex();
3423 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3424 ParseGlobalTypeAndValue(Val0) ||
3425 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3426 ParseGlobalTypeAndValue(Val1) ||
3427 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3428 return true;
3429 if (Val0->getType() != Val1->getType())
3430 return Error(ID.Loc, "operands of constexpr must have same type");
3431 if (!Val0->getType()->isIntOrIntVectorTy())
3432 return Error(ID.Loc,
3433 "constexpr requires integer or integer vector operands");
3434 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3435 ID.Kind = ValID::t_Constant;
3436 return false;
3439 case lltok::kw_getelementptr:
3440 case lltok::kw_shufflevector:
3441 case lltok::kw_insertelement:
3442 case lltok::kw_extractelement:
3443 case lltok::kw_select: {
3444 unsigned Opc = Lex.getUIntVal();
3445 SmallVector<Constant*, 16> Elts;
3446 bool InBounds = false;
3447 Type *Ty;
3448 Lex.Lex();
3450 if (Opc == Instruction::GetElementPtr)
3451 InBounds = EatIfPresent(lltok::kw_inbounds);
3453 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3454 return true;
3456 LocTy ExplicitTypeLoc = Lex.getLoc();
3457 if (Opc == Instruction::GetElementPtr) {
3458 if (ParseType(Ty) ||
3459 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3460 return true;
3463 Optional<unsigned> InRangeOp;
3464 if (ParseGlobalValueVector(
3465 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3466 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3467 return true;
3469 if (Opc == Instruction::GetElementPtr) {
3470 if (Elts.size() == 0 ||
3471 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3472 return Error(ID.Loc, "base of getelementptr must be a pointer");
3474 Type *BaseType = Elts[0]->getType();
3475 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3476 if (Ty != BasePointerType->getElementType())
3477 return Error(
3478 ExplicitTypeLoc,
3479 "explicit pointee type doesn't match operand's pointee type");
3481 unsigned GEPWidth =
3482 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3484 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3485 for (Constant *Val : Indices) {
3486 Type *ValTy = Val->getType();
3487 if (!ValTy->isIntOrIntVectorTy())
3488 return Error(ID.Loc, "getelementptr index must be an integer");
3489 if (ValTy->isVectorTy()) {
3490 unsigned ValNumEl = ValTy->getVectorNumElements();
3491 if (GEPWidth && (ValNumEl != GEPWidth))
3492 return Error(
3493 ID.Loc,
3494 "getelementptr vector index has a wrong number of elements");
3495 // GEPWidth may have been unknown because the base is a scalar,
3496 // but it is known now.
3497 GEPWidth = ValNumEl;
3501 SmallPtrSet<Type*, 4> Visited;
3502 if (!Indices.empty() && !Ty->isSized(&Visited))
3503 return Error(ID.Loc, "base element of getelementptr must be sized");
3505 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3506 return Error(ID.Loc, "invalid getelementptr indices");
3508 if (InRangeOp) {
3509 if (*InRangeOp == 0)
3510 return Error(ID.Loc,
3511 "inrange keyword may not appear on pointer operand");
3512 --*InRangeOp;
3515 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3516 InBounds, InRangeOp);
3517 } else if (Opc == Instruction::Select) {
3518 if (Elts.size() != 3)
3519 return Error(ID.Loc, "expected three operands to select");
3520 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3521 Elts[2]))
3522 return Error(ID.Loc, Reason);
3523 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3524 } else if (Opc == Instruction::ShuffleVector) {
3525 if (Elts.size() != 3)
3526 return Error(ID.Loc, "expected three operands to shufflevector");
3527 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3528 return Error(ID.Loc, "invalid operands to shufflevector");
3529 ID.ConstantVal =
3530 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3531 } else if (Opc == Instruction::ExtractElement) {
3532 if (Elts.size() != 2)
3533 return Error(ID.Loc, "expected two operands to extractelement");
3534 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3535 return Error(ID.Loc, "invalid extractelement operands");
3536 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3537 } else {
3538 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3539 if (Elts.size() != 3)
3540 return Error(ID.Loc, "expected three operands to insertelement");
3541 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3542 return Error(ID.Loc, "invalid insertelement operands");
3543 ID.ConstantVal =
3544 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3547 ID.Kind = ValID::t_Constant;
3548 return false;
3552 Lex.Lex();
3553 return false;
3556 /// ParseGlobalValue - Parse a global value with the specified type.
3557 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3558 C = nullptr;
3559 ValID ID;
3560 Value *V = nullptr;
3561 bool Parsed = ParseValID(ID) ||
3562 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3563 if (V && !(C = dyn_cast<Constant>(V)))
3564 return Error(ID.Loc, "global values must be constants");
3565 return Parsed;
3568 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3569 Type *Ty = nullptr;
3570 return ParseType(Ty) ||
3571 ParseGlobalValue(Ty, V);
3574 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3575 C = nullptr;
3577 LocTy KwLoc = Lex.getLoc();
3578 if (!EatIfPresent(lltok::kw_comdat))
3579 return false;
3581 if (EatIfPresent(lltok::lparen)) {
3582 if (Lex.getKind() != lltok::ComdatVar)
3583 return TokError("expected comdat variable");
3584 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3585 Lex.Lex();
3586 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3587 return true;
3588 } else {
3589 if (GlobalName.empty())
3590 return TokError("comdat cannot be unnamed");
3591 C = getComdat(GlobalName, KwLoc);
3594 return false;
3597 /// ParseGlobalValueVector
3598 /// ::= /*empty*/
3599 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3600 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3601 Optional<unsigned> *InRangeOp) {
3602 // Empty list.
3603 if (Lex.getKind() == lltok::rbrace ||
3604 Lex.getKind() == lltok::rsquare ||
3605 Lex.getKind() == lltok::greater ||
3606 Lex.getKind() == lltok::rparen)
3607 return false;
3609 do {
3610 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3611 *InRangeOp = Elts.size();
3613 Constant *C;
3614 if (ParseGlobalTypeAndValue(C)) return true;
3615 Elts.push_back(C);
3616 } while (EatIfPresent(lltok::comma));
3618 return false;
3621 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3622 SmallVector<Metadata *, 16> Elts;
3623 if (ParseMDNodeVector(Elts))
3624 return true;
3626 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3627 return false;
3630 /// MDNode:
3631 /// ::= !{ ... }
3632 /// ::= !7
3633 /// ::= !DILocation(...)
3634 bool LLParser::ParseMDNode(MDNode *&N) {
3635 if (Lex.getKind() == lltok::MetadataVar)
3636 return ParseSpecializedMDNode(N);
3638 return ParseToken(lltok::exclaim, "expected '!' here") ||
3639 ParseMDNodeTail(N);
3642 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3643 // !{ ... }
3644 if (Lex.getKind() == lltok::lbrace)
3645 return ParseMDTuple(N);
3647 // !42
3648 return ParseMDNodeID(N);
3651 namespace {
3653 /// Structure to represent an optional metadata field.
3654 template <class FieldTy> struct MDFieldImpl {
3655 typedef MDFieldImpl ImplTy;
3656 FieldTy Val;
3657 bool Seen;
3659 void assign(FieldTy Val) {
3660 Seen = true;
3661 this->Val = std::move(Val);
3664 explicit MDFieldImpl(FieldTy Default)
3665 : Val(std::move(Default)), Seen(false) {}
3668 /// Structure to represent an optional metadata field that
3669 /// can be of either type (A or B) and encapsulates the
3670 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3671 /// to reimplement the specifics for representing each Field.
3672 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3673 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3674 FieldTypeA A;
3675 FieldTypeB B;
3676 bool Seen;
3678 enum {
3679 IsInvalid = 0,
3680 IsTypeA = 1,
3681 IsTypeB = 2
3682 } WhatIs;
3684 void assign(FieldTypeA A) {
3685 Seen = true;
3686 this->A = std::move(A);
3687 WhatIs = IsTypeA;
3690 void assign(FieldTypeB B) {
3691 Seen = true;
3692 this->B = std::move(B);
3693 WhatIs = IsTypeB;
3696 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3697 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3698 WhatIs(IsInvalid) {}
3701 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3702 uint64_t Max;
3704 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3705 : ImplTy(Default), Max(Max) {}
3708 struct LineField : public MDUnsignedField {
3709 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3712 struct ColumnField : public MDUnsignedField {
3713 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3716 struct DwarfTagField : public MDUnsignedField {
3717 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3718 DwarfTagField(dwarf::Tag DefaultTag)
3719 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3722 struct DwarfMacinfoTypeField : public MDUnsignedField {
3723 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3724 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3725 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3728 struct DwarfAttEncodingField : public MDUnsignedField {
3729 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3732 struct DwarfVirtualityField : public MDUnsignedField {
3733 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3736 struct DwarfLangField : public MDUnsignedField {
3737 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3740 struct DwarfCCField : public MDUnsignedField {
3741 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3744 struct EmissionKindField : public MDUnsignedField {
3745 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3748 struct NameTableKindField : public MDUnsignedField {
3749 NameTableKindField()
3750 : MDUnsignedField(
3751 0, (unsigned)
3752 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3755 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3756 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3759 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3760 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3763 struct MDSignedField : public MDFieldImpl<int64_t> {
3764 int64_t Min;
3765 int64_t Max;
3767 MDSignedField(int64_t Default = 0)
3768 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3769 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3770 : ImplTy(Default), Min(Min), Max(Max) {}
3773 struct MDBoolField : public MDFieldImpl<bool> {
3774 MDBoolField(bool Default = false) : ImplTy(Default) {}
3777 struct MDField : public MDFieldImpl<Metadata *> {
3778 bool AllowNull;
3780 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3783 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3784 MDConstant() : ImplTy(nullptr) {}
3787 struct MDStringField : public MDFieldImpl<MDString *> {
3788 bool AllowEmpty;
3789 MDStringField(bool AllowEmpty = true)
3790 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3793 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3794 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3797 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3798 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3801 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3802 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3803 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3805 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3806 bool AllowNull = true)
3807 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3809 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3810 bool isMDField() const { return WhatIs == IsTypeB; }
3811 int64_t getMDSignedValue() const {
3812 assert(isMDSignedField() && "Wrong field type");
3813 return A.Val;
3815 Metadata *getMDFieldValue() const {
3816 assert(isMDField() && "Wrong field type");
3817 return B.Val;
3821 struct MDSignedOrUnsignedField
3822 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3823 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3825 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3826 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3827 int64_t getMDSignedValue() const {
3828 assert(isMDSignedField() && "Wrong field type");
3829 return A.Val;
3831 uint64_t getMDUnsignedValue() const {
3832 assert(isMDUnsignedField() && "Wrong field type");
3833 return B.Val;
3837 } // end anonymous namespace
3839 namespace llvm {
3841 template <>
3842 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3843 MDUnsignedField &Result) {
3844 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3845 return TokError("expected unsigned integer");
3847 auto &U = Lex.getAPSIntVal();
3848 if (U.ugt(Result.Max))
3849 return TokError("value for '" + Name + "' too large, limit is " +
3850 Twine(Result.Max));
3851 Result.assign(U.getZExtValue());
3852 assert(Result.Val <= Result.Max && "Expected value in range");
3853 Lex.Lex();
3854 return false;
3857 template <>
3858 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3859 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3861 template <>
3862 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3863 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3866 template <>
3867 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3868 if (Lex.getKind() == lltok::APSInt)
3869 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3871 if (Lex.getKind() != lltok::DwarfTag)
3872 return TokError("expected DWARF tag");
3874 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3875 if (Tag == dwarf::DW_TAG_invalid)
3876 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3877 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3879 Result.assign(Tag);
3880 Lex.Lex();
3881 return false;
3884 template <>
3885 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3886 DwarfMacinfoTypeField &Result) {
3887 if (Lex.getKind() == lltok::APSInt)
3888 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3890 if (Lex.getKind() != lltok::DwarfMacinfo)
3891 return TokError("expected DWARF macinfo type");
3893 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3894 if (Macinfo == dwarf::DW_MACINFO_invalid)
3895 return TokError(
3896 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3897 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3899 Result.assign(Macinfo);
3900 Lex.Lex();
3901 return false;
3904 template <>
3905 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3906 DwarfVirtualityField &Result) {
3907 if (Lex.getKind() == lltok::APSInt)
3908 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3910 if (Lex.getKind() != lltok::DwarfVirtuality)
3911 return TokError("expected DWARF virtuality code");
3913 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3914 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
3915 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3916 Lex.getStrVal() + "'");
3917 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3918 Result.assign(Virtuality);
3919 Lex.Lex();
3920 return false;
3923 template <>
3924 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3925 if (Lex.getKind() == lltok::APSInt)
3926 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3928 if (Lex.getKind() != lltok::DwarfLang)
3929 return TokError("expected DWARF language");
3931 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3932 if (!Lang)
3933 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3934 "'");
3935 assert(Lang <= Result.Max && "Expected valid DWARF language");
3936 Result.assign(Lang);
3937 Lex.Lex();
3938 return false;
3941 template <>
3942 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
3943 if (Lex.getKind() == lltok::APSInt)
3944 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3946 if (Lex.getKind() != lltok::DwarfCC)
3947 return TokError("expected DWARF calling convention");
3949 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
3950 if (!CC)
3951 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
3952 "'");
3953 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
3954 Result.assign(CC);
3955 Lex.Lex();
3956 return false;
3959 template <>
3960 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
3961 if (Lex.getKind() == lltok::APSInt)
3962 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3964 if (Lex.getKind() != lltok::EmissionKind)
3965 return TokError("expected emission kind");
3967 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
3968 if (!Kind)
3969 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
3970 "'");
3971 assert(*Kind <= Result.Max && "Expected valid emission kind");
3972 Result.assign(*Kind);
3973 Lex.Lex();
3974 return false;
3977 template <>
3978 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3979 NameTableKindField &Result) {
3980 if (Lex.getKind() == lltok::APSInt)
3981 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3983 if (Lex.getKind() != lltok::NameTableKind)
3984 return TokError("expected nameTable kind");
3986 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
3987 if (!Kind)
3988 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
3989 "'");
3990 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
3991 Result.assign((unsigned)*Kind);
3992 Lex.Lex();
3993 return false;
3996 template <>
3997 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3998 DwarfAttEncodingField &Result) {
3999 if (Lex.getKind() == lltok::APSInt)
4000 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4002 if (Lex.getKind() != lltok::DwarfAttEncoding)
4003 return TokError("expected DWARF type attribute encoding");
4005 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4006 if (!Encoding)
4007 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4008 Lex.getStrVal() + "'");
4009 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4010 Result.assign(Encoding);
4011 Lex.Lex();
4012 return false;
4015 /// DIFlagField
4016 /// ::= uint32
4017 /// ::= DIFlagVector
4018 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4019 template <>
4020 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4022 // Parser for a single flag.
4023 auto parseFlag = [&](DINode::DIFlags &Val) {
4024 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4025 uint32_t TempVal = static_cast<uint32_t>(Val);
4026 bool Res = ParseUInt32(TempVal);
4027 Val = static_cast<DINode::DIFlags>(TempVal);
4028 return Res;
4031 if (Lex.getKind() != lltok::DIFlag)
4032 return TokError("expected debug info flag");
4034 Val = DINode::getFlag(Lex.getStrVal());
4035 if (!Val)
4036 return TokError(Twine("invalid debug info flag flag '") +
4037 Lex.getStrVal() + "'");
4038 Lex.Lex();
4039 return false;
4042 // Parse the flags and combine them together.
4043 DINode::DIFlags Combined = DINode::FlagZero;
4044 do {
4045 DINode::DIFlags Val;
4046 if (parseFlag(Val))
4047 return true;
4048 Combined |= Val;
4049 } while (EatIfPresent(lltok::bar));
4051 Result.assign(Combined);
4052 return false;
4055 /// DISPFlagField
4056 /// ::= uint32
4057 /// ::= DISPFlagVector
4058 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4059 template <>
4060 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4062 // Parser for a single flag.
4063 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4064 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4065 uint32_t TempVal = static_cast<uint32_t>(Val);
4066 bool Res = ParseUInt32(TempVal);
4067 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4068 return Res;
4071 if (Lex.getKind() != lltok::DISPFlag)
4072 return TokError("expected debug info flag");
4074 Val = DISubprogram::getFlag(Lex.getStrVal());
4075 if (!Val)
4076 return TokError(Twine("invalid subprogram debug info flag '") +
4077 Lex.getStrVal() + "'");
4078 Lex.Lex();
4079 return false;
4082 // Parse the flags and combine them together.
4083 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4084 do {
4085 DISubprogram::DISPFlags Val;
4086 if (parseFlag(Val))
4087 return true;
4088 Combined |= Val;
4089 } while (EatIfPresent(lltok::bar));
4091 Result.assign(Combined);
4092 return false;
4095 template <>
4096 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4097 MDSignedField &Result) {
4098 if (Lex.getKind() != lltok::APSInt)
4099 return TokError("expected signed integer");
4101 auto &S = Lex.getAPSIntVal();
4102 if (S < Result.Min)
4103 return TokError("value for '" + Name + "' too small, limit is " +
4104 Twine(Result.Min));
4105 if (S > Result.Max)
4106 return TokError("value for '" + Name + "' too large, limit is " +
4107 Twine(Result.Max));
4108 Result.assign(S.getExtValue());
4109 assert(Result.Val >= Result.Min && "Expected value in range");
4110 assert(Result.Val <= Result.Max && "Expected value in range");
4111 Lex.Lex();
4112 return false;
4115 template <>
4116 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4117 switch (Lex.getKind()) {
4118 default:
4119 return TokError("expected 'true' or 'false'");
4120 case lltok::kw_true:
4121 Result.assign(true);
4122 break;
4123 case lltok::kw_false:
4124 Result.assign(false);
4125 break;
4127 Lex.Lex();
4128 return false;
4131 template <>
4132 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4133 if (Lex.getKind() == lltok::kw_null) {
4134 if (!Result.AllowNull)
4135 return TokError("'" + Name + "' cannot be null");
4136 Lex.Lex();
4137 Result.assign(nullptr);
4138 return false;
4141 Metadata *MD;
4142 if (ParseMetadata(MD, nullptr))
4143 return true;
4145 Result.assign(MD);
4146 return false;
4149 template <>
4150 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4151 MDSignedOrMDField &Result) {
4152 // Try to parse a signed int.
4153 if (Lex.getKind() == lltok::APSInt) {
4154 MDSignedField Res = Result.A;
4155 if (!ParseMDField(Loc, Name, Res)) {
4156 Result.assign(Res);
4157 return false;
4159 return true;
4162 // Otherwise, try to parse as an MDField.
4163 MDField Res = Result.B;
4164 if (!ParseMDField(Loc, Name, Res)) {
4165 Result.assign(Res);
4166 return false;
4169 return true;
4172 template <>
4173 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4174 MDSignedOrUnsignedField &Result) {
4175 if (Lex.getKind() != lltok::APSInt)
4176 return false;
4178 if (Lex.getAPSIntVal().isSigned()) {
4179 MDSignedField Res = Result.A;
4180 if (ParseMDField(Loc, Name, Res))
4181 return true;
4182 Result.assign(Res);
4183 return false;
4186 MDUnsignedField Res = Result.B;
4187 if (ParseMDField(Loc, Name, Res))
4188 return true;
4189 Result.assign(Res);
4190 return false;
4193 template <>
4194 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4195 LocTy ValueLoc = Lex.getLoc();
4196 std::string S;
4197 if (ParseStringConstant(S))
4198 return true;
4200 if (!Result.AllowEmpty && S.empty())
4201 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4203 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4204 return false;
4207 template <>
4208 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4209 SmallVector<Metadata *, 4> MDs;
4210 if (ParseMDNodeVector(MDs))
4211 return true;
4213 Result.assign(std::move(MDs));
4214 return false;
4217 template <>
4218 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4219 ChecksumKindField &Result) {
4220 Optional<DIFile::ChecksumKind> CSKind =
4221 DIFile::getChecksumKind(Lex.getStrVal());
4223 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4224 return TokError(
4225 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4227 Result.assign(*CSKind);
4228 Lex.Lex();
4229 return false;
4232 } // end namespace llvm
4234 template <class ParserTy>
4235 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
4236 do {
4237 if (Lex.getKind() != lltok::LabelStr)
4238 return TokError("expected field label here");
4240 if (parseField())
4241 return true;
4242 } while (EatIfPresent(lltok::comma));
4244 return false;
4247 template <class ParserTy>
4248 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4249 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4250 Lex.Lex();
4252 if (ParseToken(lltok::lparen, "expected '(' here"))
4253 return true;
4254 if (Lex.getKind() != lltok::rparen)
4255 if (ParseMDFieldsImplBody(parseField))
4256 return true;
4258 ClosingLoc = Lex.getLoc();
4259 return ParseToken(lltok::rparen, "expected ')' here");
4262 template <class FieldTy>
4263 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4264 if (Result.Seen)
4265 return TokError("field '" + Name + "' cannot be specified more than once");
4267 LocTy Loc = Lex.getLoc();
4268 Lex.Lex();
4269 return ParseMDField(Loc, Name, Result);
4272 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4273 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4275 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4276 if (Lex.getStrVal() == #CLASS) \
4277 return Parse##CLASS(N, IsDistinct);
4278 #include "llvm/IR/Metadata.def"
4280 return TokError("expected metadata type");
4283 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4284 #define NOP_FIELD(NAME, TYPE, INIT)
4285 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4286 if (!NAME.Seen) \
4287 return Error(ClosingLoc, "missing required field '" #NAME "'");
4288 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4289 if (Lex.getStrVal() == #NAME) \
4290 return ParseMDField(#NAME, NAME);
4291 #define PARSE_MD_FIELDS() \
4292 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4293 do { \
4294 LocTy ClosingLoc; \
4295 if (ParseMDFieldsImpl([&]() -> bool { \
4296 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4297 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4298 }, ClosingLoc)) \
4299 return true; \
4300 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4301 } while (false)
4302 #define GET_OR_DISTINCT(CLASS, ARGS) \
4303 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4305 /// ParseDILocationFields:
4306 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4307 /// isImplicitCode: true)
4308 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
4309 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4310 OPTIONAL(line, LineField, ); \
4311 OPTIONAL(column, ColumnField, ); \
4312 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4313 OPTIONAL(inlinedAt, MDField, ); \
4314 OPTIONAL(isImplicitCode, MDBoolField, (false));
4315 PARSE_MD_FIELDS();
4316 #undef VISIT_MD_FIELDS
4318 Result =
4319 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4320 inlinedAt.Val, isImplicitCode.Val));
4321 return false;
4324 /// ParseGenericDINode:
4325 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4326 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
4327 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4328 REQUIRED(tag, DwarfTagField, ); \
4329 OPTIONAL(header, MDStringField, ); \
4330 OPTIONAL(operands, MDFieldList, );
4331 PARSE_MD_FIELDS();
4332 #undef VISIT_MD_FIELDS
4334 Result = GET_OR_DISTINCT(GenericDINode,
4335 (Context, tag.Val, header.Val, operands.Val));
4336 return false;
4339 /// ParseDISubrange:
4340 /// ::= !DISubrange(count: 30, lowerBound: 2)
4341 /// ::= !DISubrange(count: !node, lowerBound: 2)
4342 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
4343 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4344 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4345 OPTIONAL(lowerBound, MDSignedField, );
4346 PARSE_MD_FIELDS();
4347 #undef VISIT_MD_FIELDS
4349 if (count.isMDSignedField())
4350 Result = GET_OR_DISTINCT(
4351 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4352 else if (count.isMDField())
4353 Result = GET_OR_DISTINCT(
4354 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4355 else
4356 return true;
4358 return false;
4361 /// ParseDIEnumerator:
4362 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4363 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4364 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4365 REQUIRED(name, MDStringField, ); \
4366 REQUIRED(value, MDSignedOrUnsignedField, ); \
4367 OPTIONAL(isUnsigned, MDBoolField, (false));
4368 PARSE_MD_FIELDS();
4369 #undef VISIT_MD_FIELDS
4371 if (isUnsigned.Val && value.isMDSignedField())
4372 return TokError("unsigned enumerator with negative value");
4374 int64_t Value = value.isMDSignedField()
4375 ? value.getMDSignedValue()
4376 : static_cast<int64_t>(value.getMDUnsignedValue());
4377 Result =
4378 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4380 return false;
4383 /// ParseDIBasicType:
4384 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4385 /// encoding: DW_ATE_encoding, flags: 0)
4386 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
4387 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4388 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4389 OPTIONAL(name, MDStringField, ); \
4390 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4391 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4392 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4393 OPTIONAL(flags, DIFlagField, );
4394 PARSE_MD_FIELDS();
4395 #undef VISIT_MD_FIELDS
4397 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4398 align.Val, encoding.Val, flags.Val));
4399 return false;
4402 /// ParseDIDerivedType:
4403 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4404 /// line: 7, scope: !1, baseType: !2, size: 32,
4405 /// align: 32, offset: 0, flags: 0, extraData: !3,
4406 /// dwarfAddressSpace: 3)
4407 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4408 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4409 REQUIRED(tag, DwarfTagField, ); \
4410 OPTIONAL(name, MDStringField, ); \
4411 OPTIONAL(file, MDField, ); \
4412 OPTIONAL(line, LineField, ); \
4413 OPTIONAL(scope, MDField, ); \
4414 REQUIRED(baseType, MDField, ); \
4415 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4416 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4417 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4418 OPTIONAL(flags, DIFlagField, ); \
4419 OPTIONAL(extraData, MDField, ); \
4420 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4421 PARSE_MD_FIELDS();
4422 #undef VISIT_MD_FIELDS
4424 Optional<unsigned> DWARFAddressSpace;
4425 if (dwarfAddressSpace.Val != UINT32_MAX)
4426 DWARFAddressSpace = dwarfAddressSpace.Val;
4428 Result = GET_OR_DISTINCT(DIDerivedType,
4429 (Context, tag.Val, name.Val, file.Val, line.Val,
4430 scope.Val, baseType.Val, size.Val, align.Val,
4431 offset.Val, DWARFAddressSpace, flags.Val,
4432 extraData.Val));
4433 return false;
4436 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
4437 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4438 REQUIRED(tag, DwarfTagField, ); \
4439 OPTIONAL(name, MDStringField, ); \
4440 OPTIONAL(file, MDField, ); \
4441 OPTIONAL(line, LineField, ); \
4442 OPTIONAL(scope, MDField, ); \
4443 OPTIONAL(baseType, MDField, ); \
4444 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4445 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4446 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4447 OPTIONAL(flags, DIFlagField, ); \
4448 OPTIONAL(elements, MDField, ); \
4449 OPTIONAL(runtimeLang, DwarfLangField, ); \
4450 OPTIONAL(vtableHolder, MDField, ); \
4451 OPTIONAL(templateParams, MDField, ); \
4452 OPTIONAL(identifier, MDStringField, ); \
4453 OPTIONAL(discriminator, MDField, );
4454 PARSE_MD_FIELDS();
4455 #undef VISIT_MD_FIELDS
4457 // If this has an identifier try to build an ODR type.
4458 if (identifier.Val)
4459 if (auto *CT = DICompositeType::buildODRType(
4460 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4461 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4462 elements.Val, runtimeLang.Val, vtableHolder.Val,
4463 templateParams.Val, discriminator.Val)) {
4464 Result = CT;
4465 return false;
4468 // Create a new node, and save it in the context if it belongs in the type
4469 // map.
4470 Result = GET_OR_DISTINCT(
4471 DICompositeType,
4472 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4473 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4474 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4475 discriminator.Val));
4476 return false;
4479 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4480 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4481 OPTIONAL(flags, DIFlagField, ); \
4482 OPTIONAL(cc, DwarfCCField, ); \
4483 REQUIRED(types, MDField, );
4484 PARSE_MD_FIELDS();
4485 #undef VISIT_MD_FIELDS
4487 Result = GET_OR_DISTINCT(DISubroutineType,
4488 (Context, flags.Val, cc.Val, types.Val));
4489 return false;
4492 /// ParseDIFileType:
4493 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4494 /// checksumkind: CSK_MD5,
4495 /// checksum: "000102030405060708090a0b0c0d0e0f",
4496 /// source: "source file contents")
4497 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
4498 // The default constructed value for checksumkind is required, but will never
4499 // be used, as the parser checks if the field was actually Seen before using
4500 // the Val.
4501 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4502 REQUIRED(filename, MDStringField, ); \
4503 REQUIRED(directory, MDStringField, ); \
4504 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4505 OPTIONAL(checksum, MDStringField, ); \
4506 OPTIONAL(source, MDStringField, );
4507 PARSE_MD_FIELDS();
4508 #undef VISIT_MD_FIELDS
4510 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4511 if (checksumkind.Seen && checksum.Seen)
4512 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4513 else if (checksumkind.Seen || checksum.Seen)
4514 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4516 Optional<MDString *> OptSource;
4517 if (source.Seen)
4518 OptSource = source.Val;
4519 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4520 OptChecksum, OptSource));
4521 return false;
4524 /// ParseDICompileUnit:
4525 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4526 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4527 /// splitDebugFilename: "abc.debug",
4528 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4529 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4530 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4531 if (!IsDistinct)
4532 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4534 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4535 REQUIRED(language, DwarfLangField, ); \
4536 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4537 OPTIONAL(producer, MDStringField, ); \
4538 OPTIONAL(isOptimized, MDBoolField, ); \
4539 OPTIONAL(flags, MDStringField, ); \
4540 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4541 OPTIONAL(splitDebugFilename, MDStringField, ); \
4542 OPTIONAL(emissionKind, EmissionKindField, ); \
4543 OPTIONAL(enums, MDField, ); \
4544 OPTIONAL(retainedTypes, MDField, ); \
4545 OPTIONAL(globals, MDField, ); \
4546 OPTIONAL(imports, MDField, ); \
4547 OPTIONAL(macros, MDField, ); \
4548 OPTIONAL(dwoId, MDUnsignedField, ); \
4549 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4550 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4551 OPTIONAL(nameTableKind, NameTableKindField, ); \
4552 OPTIONAL(debugBaseAddress, MDBoolField, = false);
4553 PARSE_MD_FIELDS();
4554 #undef VISIT_MD_FIELDS
4556 Result = DICompileUnit::getDistinct(
4557 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4558 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4559 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4560 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4561 debugBaseAddress.Val);
4562 return false;
4565 /// ParseDISubprogram:
4566 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4567 /// file: !1, line: 7, type: !2, isLocal: false,
4568 /// isDefinition: true, scopeLine: 8, containingType: !3,
4569 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4570 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4571 /// spFlags: 10, isOptimized: false, templateParams: !4,
4572 /// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4573 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4574 auto Loc = Lex.getLoc();
4575 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4576 OPTIONAL(scope, MDField, ); \
4577 OPTIONAL(name, MDStringField, ); \
4578 OPTIONAL(linkageName, MDStringField, ); \
4579 OPTIONAL(file, MDField, ); \
4580 OPTIONAL(line, LineField, ); \
4581 OPTIONAL(type, MDField, ); \
4582 OPTIONAL(isLocal, MDBoolField, ); \
4583 OPTIONAL(isDefinition, MDBoolField, (true)); \
4584 OPTIONAL(scopeLine, LineField, ); \
4585 OPTIONAL(containingType, MDField, ); \
4586 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4587 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4588 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4589 OPTIONAL(flags, DIFlagField, ); \
4590 OPTIONAL(spFlags, DISPFlagField, ); \
4591 OPTIONAL(isOptimized, MDBoolField, ); \
4592 OPTIONAL(unit, MDField, ); \
4593 OPTIONAL(templateParams, MDField, ); \
4594 OPTIONAL(declaration, MDField, ); \
4595 OPTIONAL(retainedNodes, MDField, ); \
4596 OPTIONAL(thrownTypes, MDField, );
4597 PARSE_MD_FIELDS();
4598 #undef VISIT_MD_FIELDS
4600 // An explicit spFlags field takes precedence over individual fields in
4601 // older IR versions.
4602 DISubprogram::DISPFlags SPFlags =
4603 spFlags.Seen ? spFlags.Val
4604 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4605 isOptimized.Val, virtuality.Val);
4606 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4607 return Lex.Error(
4608 Loc,
4609 "missing 'distinct', required for !DISubprogram that is a Definition");
4610 Result = GET_OR_DISTINCT(
4611 DISubprogram,
4612 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4613 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4614 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
4615 declaration.Val, retainedNodes.Val, thrownTypes.Val));
4616 return false;
4619 /// ParseDILexicalBlock:
4620 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4621 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4622 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4623 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4624 OPTIONAL(file, MDField, ); \
4625 OPTIONAL(line, LineField, ); \
4626 OPTIONAL(column, ColumnField, );
4627 PARSE_MD_FIELDS();
4628 #undef VISIT_MD_FIELDS
4630 Result = GET_OR_DISTINCT(
4631 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4632 return false;
4635 /// ParseDILexicalBlockFile:
4636 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4637 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4638 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4639 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4640 OPTIONAL(file, MDField, ); \
4641 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4642 PARSE_MD_FIELDS();
4643 #undef VISIT_MD_FIELDS
4645 Result = GET_OR_DISTINCT(DILexicalBlockFile,
4646 (Context, scope.Val, file.Val, discriminator.Val));
4647 return false;
4650 /// ParseDINamespace:
4651 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4652 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4653 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4654 REQUIRED(scope, MDField, ); \
4655 OPTIONAL(name, MDStringField, ); \
4656 OPTIONAL(exportSymbols, MDBoolField, );
4657 PARSE_MD_FIELDS();
4658 #undef VISIT_MD_FIELDS
4660 Result = GET_OR_DISTINCT(DINamespace,
4661 (Context, scope.Val, name.Val, exportSymbols.Val));
4662 return false;
4665 /// ParseDIMacro:
4666 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4667 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4668 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4669 REQUIRED(type, DwarfMacinfoTypeField, ); \
4670 OPTIONAL(line, LineField, ); \
4671 REQUIRED(name, MDStringField, ); \
4672 OPTIONAL(value, MDStringField, );
4673 PARSE_MD_FIELDS();
4674 #undef VISIT_MD_FIELDS
4676 Result = GET_OR_DISTINCT(DIMacro,
4677 (Context, type.Val, line.Val, name.Val, value.Val));
4678 return false;
4681 /// ParseDIMacroFile:
4682 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4683 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4684 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4685 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4686 OPTIONAL(line, LineField, ); \
4687 REQUIRED(file, MDField, ); \
4688 OPTIONAL(nodes, MDField, );
4689 PARSE_MD_FIELDS();
4690 #undef VISIT_MD_FIELDS
4692 Result = GET_OR_DISTINCT(DIMacroFile,
4693 (Context, type.Val, line.Val, file.Val, nodes.Val));
4694 return false;
4697 /// ParseDIModule:
4698 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4699 /// includePath: "/usr/include", isysroot: "/")
4700 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4701 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4702 REQUIRED(scope, MDField, ); \
4703 REQUIRED(name, MDStringField, ); \
4704 OPTIONAL(configMacros, MDStringField, ); \
4705 OPTIONAL(includePath, MDStringField, ); \
4706 OPTIONAL(isysroot, MDStringField, );
4707 PARSE_MD_FIELDS();
4708 #undef VISIT_MD_FIELDS
4710 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4711 configMacros.Val, includePath.Val, isysroot.Val));
4712 return false;
4715 /// ParseDITemplateTypeParameter:
4716 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4717 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4718 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4719 OPTIONAL(name, MDStringField, ); \
4720 REQUIRED(type, MDField, );
4721 PARSE_MD_FIELDS();
4722 #undef VISIT_MD_FIELDS
4724 Result =
4725 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4726 return false;
4729 /// ParseDITemplateValueParameter:
4730 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4731 /// name: "V", type: !1, value: i32 7)
4732 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4733 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4734 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4735 OPTIONAL(name, MDStringField, ); \
4736 OPTIONAL(type, MDField, ); \
4737 REQUIRED(value, MDField, );
4738 PARSE_MD_FIELDS();
4739 #undef VISIT_MD_FIELDS
4741 Result = GET_OR_DISTINCT(DITemplateValueParameter,
4742 (Context, tag.Val, name.Val, type.Val, value.Val));
4743 return false;
4746 /// ParseDIGlobalVariable:
4747 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4748 /// file: !1, line: 7, type: !2, isLocal: false,
4749 /// isDefinition: true, templateParams: !3,
4750 /// declaration: !4, align: 8)
4751 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4752 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4753 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4754 OPTIONAL(scope, MDField, ); \
4755 OPTIONAL(linkageName, MDStringField, ); \
4756 OPTIONAL(file, MDField, ); \
4757 OPTIONAL(line, LineField, ); \
4758 OPTIONAL(type, MDField, ); \
4759 OPTIONAL(isLocal, MDBoolField, ); \
4760 OPTIONAL(isDefinition, MDBoolField, (true)); \
4761 OPTIONAL(templateParams, MDField, ); \
4762 OPTIONAL(declaration, MDField, ); \
4763 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4764 PARSE_MD_FIELDS();
4765 #undef VISIT_MD_FIELDS
4767 Result =
4768 GET_OR_DISTINCT(DIGlobalVariable,
4769 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4770 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4771 declaration.Val, templateParams.Val, align.Val));
4772 return false;
4775 /// ParseDILocalVariable:
4776 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4777 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4778 /// align: 8)
4779 /// ::= !DILocalVariable(scope: !0, name: "foo",
4780 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4781 /// align: 8)
4782 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4783 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4784 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4785 OPTIONAL(name, MDStringField, ); \
4786 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4787 OPTIONAL(file, MDField, ); \
4788 OPTIONAL(line, LineField, ); \
4789 OPTIONAL(type, MDField, ); \
4790 OPTIONAL(flags, DIFlagField, ); \
4791 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4792 PARSE_MD_FIELDS();
4793 #undef VISIT_MD_FIELDS
4795 Result = GET_OR_DISTINCT(DILocalVariable,
4796 (Context, scope.Val, name.Val, file.Val, line.Val,
4797 type.Val, arg.Val, flags.Val, align.Val));
4798 return false;
4801 /// ParseDILabel:
4802 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4803 bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4804 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4805 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4806 REQUIRED(name, MDStringField, ); \
4807 REQUIRED(file, MDField, ); \
4808 REQUIRED(line, LineField, );
4809 PARSE_MD_FIELDS();
4810 #undef VISIT_MD_FIELDS
4812 Result = GET_OR_DISTINCT(DILabel,
4813 (Context, scope.Val, name.Val, file.Val, line.Val));
4814 return false;
4817 /// ParseDIExpression:
4818 /// ::= !DIExpression(0, 7, -1)
4819 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4820 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4821 Lex.Lex();
4823 if (ParseToken(lltok::lparen, "expected '(' here"))
4824 return true;
4826 SmallVector<uint64_t, 8> Elements;
4827 if (Lex.getKind() != lltok::rparen)
4828 do {
4829 if (Lex.getKind() == lltok::DwarfOp) {
4830 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4831 Lex.Lex();
4832 Elements.push_back(Op);
4833 continue;
4835 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4838 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4839 return TokError("expected unsigned integer");
4841 auto &U = Lex.getAPSIntVal();
4842 if (U.ugt(UINT64_MAX))
4843 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4844 Elements.push_back(U.getZExtValue());
4845 Lex.Lex();
4846 } while (EatIfPresent(lltok::comma));
4848 if (ParseToken(lltok::rparen, "expected ')' here"))
4849 return true;
4851 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4852 return false;
4855 /// ParseDIGlobalVariableExpression:
4856 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4857 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4858 bool IsDistinct) {
4859 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4860 REQUIRED(var, MDField, ); \
4861 REQUIRED(expr, MDField, );
4862 PARSE_MD_FIELDS();
4863 #undef VISIT_MD_FIELDS
4865 Result =
4866 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4867 return false;
4870 /// ParseDIObjCProperty:
4871 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4872 /// getter: "getFoo", attributes: 7, type: !2)
4873 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
4874 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4875 OPTIONAL(name, MDStringField, ); \
4876 OPTIONAL(file, MDField, ); \
4877 OPTIONAL(line, LineField, ); \
4878 OPTIONAL(setter, MDStringField, ); \
4879 OPTIONAL(getter, MDStringField, ); \
4880 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
4881 OPTIONAL(type, MDField, );
4882 PARSE_MD_FIELDS();
4883 #undef VISIT_MD_FIELDS
4885 Result = GET_OR_DISTINCT(DIObjCProperty,
4886 (Context, name.Val, file.Val, line.Val, setter.Val,
4887 getter.Val, attributes.Val, type.Val));
4888 return false;
4891 /// ParseDIImportedEntity:
4892 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
4893 /// line: 7, name: "foo")
4894 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
4895 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4896 REQUIRED(tag, DwarfTagField, ); \
4897 REQUIRED(scope, MDField, ); \
4898 OPTIONAL(entity, MDField, ); \
4899 OPTIONAL(file, MDField, ); \
4900 OPTIONAL(line, LineField, ); \
4901 OPTIONAL(name, MDStringField, );
4902 PARSE_MD_FIELDS();
4903 #undef VISIT_MD_FIELDS
4905 Result = GET_OR_DISTINCT(
4906 DIImportedEntity,
4907 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
4908 return false;
4911 #undef PARSE_MD_FIELD
4912 #undef NOP_FIELD
4913 #undef REQUIRE_FIELD
4914 #undef DECLARE_FIELD
4916 /// ParseMetadataAsValue
4917 /// ::= metadata i32 %local
4918 /// ::= metadata i32 @global
4919 /// ::= metadata i32 7
4920 /// ::= metadata !0
4921 /// ::= metadata !{...}
4922 /// ::= metadata !"string"
4923 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
4924 // Note: the type 'metadata' has already been parsed.
4925 Metadata *MD;
4926 if (ParseMetadata(MD, &PFS))
4927 return true;
4929 V = MetadataAsValue::get(Context, MD);
4930 return false;
4933 /// ParseValueAsMetadata
4934 /// ::= i32 %local
4935 /// ::= i32 @global
4936 /// ::= i32 7
4937 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
4938 PerFunctionState *PFS) {
4939 Type *Ty;
4940 LocTy Loc;
4941 if (ParseType(Ty, TypeMsg, Loc))
4942 return true;
4943 if (Ty->isMetadataTy())
4944 return Error(Loc, "invalid metadata-value-metadata roundtrip");
4946 Value *V;
4947 if (ParseValue(Ty, V, PFS))
4948 return true;
4950 MD = ValueAsMetadata::get(V);
4951 return false;
4954 /// ParseMetadata
4955 /// ::= i32 %local
4956 /// ::= i32 @global
4957 /// ::= i32 7
4958 /// ::= !42
4959 /// ::= !{...}
4960 /// ::= !"string"
4961 /// ::= !DILocation(...)
4962 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
4963 if (Lex.getKind() == lltok::MetadataVar) {
4964 MDNode *N;
4965 if (ParseSpecializedMDNode(N))
4966 return true;
4967 MD = N;
4968 return false;
4971 // ValueAsMetadata:
4972 // <type> <value>
4973 if (Lex.getKind() != lltok::exclaim)
4974 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
4976 // '!'.
4977 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
4978 Lex.Lex();
4980 // MDString:
4981 // ::= '!' STRINGCONSTANT
4982 if (Lex.getKind() == lltok::StringConstant) {
4983 MDString *S;
4984 if (ParseMDString(S))
4985 return true;
4986 MD = S;
4987 return false;
4990 // MDNode:
4991 // !{ ... }
4992 // !7
4993 MDNode *N;
4994 if (ParseMDNodeTail(N))
4995 return true;
4996 MD = N;
4997 return false;
5000 //===----------------------------------------------------------------------===//
5001 // Function Parsing.
5002 //===----------------------------------------------------------------------===//
5004 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5005 PerFunctionState *PFS, bool IsCall) {
5006 if (Ty->isFunctionTy())
5007 return Error(ID.Loc, "functions are not values, refer to them as pointers");
5009 switch (ID.Kind) {
5010 case ValID::t_LocalID:
5011 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5012 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5013 return V == nullptr;
5014 case ValID::t_LocalName:
5015 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5016 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
5017 return V == nullptr;
5018 case ValID::t_InlineAsm: {
5019 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5020 return Error(ID.Loc, "invalid type for inline asm constraint string");
5021 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
5022 (ID.UIntVal >> 1) & 1,
5023 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
5024 return false;
5026 case ValID::t_GlobalName:
5027 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
5028 return V == nullptr;
5029 case ValID::t_GlobalID:
5030 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5031 return V == nullptr;
5032 case ValID::t_APSInt:
5033 if (!Ty->isIntegerTy())
5034 return Error(ID.Loc, "integer constant must have integer type");
5035 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5036 V = ConstantInt::get(Context, ID.APSIntVal);
5037 return false;
5038 case ValID::t_APFloat:
5039 if (!Ty->isFloatingPointTy() ||
5040 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5041 return Error(ID.Loc, "floating point constant invalid for type");
5043 // The lexer has no type info, so builds all half, float, and double FP
5044 // constants as double. Fix this here. Long double does not need this.
5045 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5046 bool Ignored;
5047 if (Ty->isHalfTy())
5048 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5049 &Ignored);
5050 else if (Ty->isFloatTy())
5051 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5052 &Ignored);
5054 V = ConstantFP::get(Context, ID.APFloatVal);
5056 if (V->getType() != Ty)
5057 return Error(ID.Loc, "floating point constant does not have type '" +
5058 getTypeString(Ty) + "'");
5060 return false;
5061 case ValID::t_Null:
5062 if (!Ty->isPointerTy())
5063 return Error(ID.Loc, "null must be a pointer type");
5064 V = ConstantPointerNull::get(cast<PointerType>(Ty));
5065 return false;
5066 case ValID::t_Undef:
5067 // FIXME: LabelTy should not be a first-class type.
5068 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5069 return Error(ID.Loc, "invalid type for undef constant");
5070 V = UndefValue::get(Ty);
5071 return false;
5072 case ValID::t_EmptyArray:
5073 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5074 return Error(ID.Loc, "invalid empty array initializer");
5075 V = UndefValue::get(Ty);
5076 return false;
5077 case ValID::t_Zero:
5078 // FIXME: LabelTy should not be a first-class type.
5079 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5080 return Error(ID.Loc, "invalid type for null constant");
5081 V = Constant::getNullValue(Ty);
5082 return false;
5083 case ValID::t_None:
5084 if (!Ty->isTokenTy())
5085 return Error(ID.Loc, "invalid type for none constant");
5086 V = Constant::getNullValue(Ty);
5087 return false;
5088 case ValID::t_Constant:
5089 if (ID.ConstantVal->getType() != Ty)
5090 return Error(ID.Loc, "constant expression type mismatch");
5092 V = ID.ConstantVal;
5093 return false;
5094 case ValID::t_ConstantStruct:
5095 case ValID::t_PackedConstantStruct:
5096 if (StructType *ST = dyn_cast<StructType>(Ty)) {
5097 if (ST->getNumElements() != ID.UIntVal)
5098 return Error(ID.Loc,
5099 "initializer with struct type has wrong # elements");
5100 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5101 return Error(ID.Loc, "packed'ness of initializer and type don't match");
5103 // Verify that the elements are compatible with the structtype.
5104 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5105 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5106 return Error(ID.Loc, "element " + Twine(i) +
5107 " of struct initializer doesn't match struct element type");
5109 V = ConstantStruct::get(
5110 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5111 } else
5112 return Error(ID.Loc, "constant expression type mismatch");
5113 return false;
5115 llvm_unreachable("Invalid ValID");
5118 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5119 C = nullptr;
5120 ValID ID;
5121 auto Loc = Lex.getLoc();
5122 if (ParseValID(ID, /*PFS=*/nullptr))
5123 return true;
5124 switch (ID.Kind) {
5125 case ValID::t_APSInt:
5126 case ValID::t_APFloat:
5127 case ValID::t_Undef:
5128 case ValID::t_Constant:
5129 case ValID::t_ConstantStruct:
5130 case ValID::t_PackedConstantStruct: {
5131 Value *V;
5132 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
5133 return true;
5134 assert(isa<Constant>(V) && "Expected a constant value");
5135 C = cast<Constant>(V);
5136 return false;
5138 case ValID::t_Null:
5139 C = Constant::getNullValue(Ty);
5140 return false;
5141 default:
5142 return Error(Loc, "expected a constant value");
5146 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5147 V = nullptr;
5148 ValID ID;
5149 return ParseValID(ID, PFS) ||
5150 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
5153 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5154 Type *Ty = nullptr;
5155 return ParseType(Ty) ||
5156 ParseValue(Ty, V, PFS);
5159 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5160 PerFunctionState &PFS) {
5161 Value *V;
5162 Loc = Lex.getLoc();
5163 if (ParseTypeAndValue(V, PFS)) return true;
5164 if (!isa<BasicBlock>(V))
5165 return Error(Loc, "expected a basic block");
5166 BB = cast<BasicBlock>(V);
5167 return false;
5170 /// FunctionHeader
5171 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5172 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5173 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5174 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5175 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5176 // Parse the linkage.
5177 LocTy LinkageLoc = Lex.getLoc();
5178 unsigned Linkage;
5179 unsigned Visibility;
5180 unsigned DLLStorageClass;
5181 bool DSOLocal;
5182 AttrBuilder RetAttrs;
5183 unsigned CC;
5184 bool HasLinkage;
5185 Type *RetType = nullptr;
5186 LocTy RetTypeLoc = Lex.getLoc();
5187 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5188 DSOLocal) ||
5189 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5190 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
5191 return true;
5193 // Verify that the linkage is ok.
5194 switch ((GlobalValue::LinkageTypes)Linkage) {
5195 case GlobalValue::ExternalLinkage:
5196 break; // always ok.
5197 case GlobalValue::ExternalWeakLinkage:
5198 if (isDefine)
5199 return Error(LinkageLoc, "invalid linkage for function definition");
5200 break;
5201 case GlobalValue::PrivateLinkage:
5202 case GlobalValue::InternalLinkage:
5203 case GlobalValue::AvailableExternallyLinkage:
5204 case GlobalValue::LinkOnceAnyLinkage:
5205 case GlobalValue::LinkOnceODRLinkage:
5206 case GlobalValue::WeakAnyLinkage:
5207 case GlobalValue::WeakODRLinkage:
5208 if (!isDefine)
5209 return Error(LinkageLoc, "invalid linkage for function declaration");
5210 break;
5211 case GlobalValue::AppendingLinkage:
5212 case GlobalValue::CommonLinkage:
5213 return Error(LinkageLoc, "invalid function linkage type");
5216 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5217 return Error(LinkageLoc,
5218 "symbol with local linkage must have default visibility");
5220 if (!FunctionType::isValidReturnType(RetType))
5221 return Error(RetTypeLoc, "invalid function return type");
5223 LocTy NameLoc = Lex.getLoc();
5225 std::string FunctionName;
5226 if (Lex.getKind() == lltok::GlobalVar) {
5227 FunctionName = Lex.getStrVal();
5228 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5229 unsigned NameID = Lex.getUIntVal();
5231 if (NameID != NumberedVals.size())
5232 return TokError("function expected to be numbered '%" +
5233 Twine(NumberedVals.size()) + "'");
5234 } else {
5235 return TokError("expected function name");
5238 Lex.Lex();
5240 if (Lex.getKind() != lltok::lparen)
5241 return TokError("expected '(' in function argument list");
5243 SmallVector<ArgInfo, 8> ArgList;
5244 bool isVarArg;
5245 AttrBuilder FuncAttrs;
5246 std::vector<unsigned> FwdRefAttrGrps;
5247 LocTy BuiltinLoc;
5248 std::string Section;
5249 unsigned Alignment;
5250 std::string GC;
5251 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5252 unsigned AddrSpace = 0;
5253 Constant *Prefix = nullptr;
5254 Constant *Prologue = nullptr;
5255 Constant *PersonalityFn = nullptr;
5256 Comdat *C;
5258 if (ParseArgumentList(ArgList, isVarArg) ||
5259 ParseOptionalUnnamedAddr(UnnamedAddr) ||
5260 ParseOptionalProgramAddrSpace(AddrSpace) ||
5261 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5262 BuiltinLoc) ||
5263 (EatIfPresent(lltok::kw_section) &&
5264 ParseStringConstant(Section)) ||
5265 parseOptionalComdat(FunctionName, C) ||
5266 ParseOptionalAlignment(Alignment) ||
5267 (EatIfPresent(lltok::kw_gc) &&
5268 ParseStringConstant(GC)) ||
5269 (EatIfPresent(lltok::kw_prefix) &&
5270 ParseGlobalTypeAndValue(Prefix)) ||
5271 (EatIfPresent(lltok::kw_prologue) &&
5272 ParseGlobalTypeAndValue(Prologue)) ||
5273 (EatIfPresent(lltok::kw_personality) &&
5274 ParseGlobalTypeAndValue(PersonalityFn)))
5275 return true;
5277 if (FuncAttrs.contains(Attribute::Builtin))
5278 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
5280 // If the alignment was parsed as an attribute, move to the alignment field.
5281 if (FuncAttrs.hasAlignmentAttr()) {
5282 Alignment = FuncAttrs.getAlignment();
5283 FuncAttrs.removeAttribute(Attribute::Alignment);
5286 // Okay, if we got here, the function is syntactically valid. Convert types
5287 // and do semantic checks.
5288 std::vector<Type*> ParamTypeList;
5289 SmallVector<AttributeSet, 8> Attrs;
5291 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5292 ParamTypeList.push_back(ArgList[i].Ty);
5293 Attrs.push_back(ArgList[i].Attrs);
5296 AttributeList PAL =
5297 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5298 AttributeSet::get(Context, RetAttrs), Attrs);
5300 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
5301 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5303 FunctionType *FT =
5304 FunctionType::get(RetType, ParamTypeList, isVarArg);
5305 PointerType *PFT = PointerType::get(FT, AddrSpace);
5307 Fn = nullptr;
5308 if (!FunctionName.empty()) {
5309 // If this was a definition of a forward reference, remove the definition
5310 // from the forward reference table and fill in the forward ref.
5311 auto FRVI = ForwardRefVals.find(FunctionName);
5312 if (FRVI != ForwardRefVals.end()) {
5313 Fn = M->getFunction(FunctionName);
5314 if (!Fn)
5315 return Error(FRVI->second.second, "invalid forward reference to "
5316 "function as global value!");
5317 if (Fn->getType() != PFT)
5318 return Error(FRVI->second.second, "invalid forward reference to "
5319 "function '" + FunctionName + "' with wrong type: "
5320 "expected '" + getTypeString(PFT) + "' but was '" +
5321 getTypeString(Fn->getType()) + "'");
5322 ForwardRefVals.erase(FRVI);
5323 } else if ((Fn = M->getFunction(FunctionName))) {
5324 // Reject redefinitions.
5325 return Error(NameLoc, "invalid redefinition of function '" +
5326 FunctionName + "'");
5327 } else if (M->getNamedValue(FunctionName)) {
5328 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5331 } else {
5332 // If this is a definition of a forward referenced function, make sure the
5333 // types agree.
5334 auto I = ForwardRefValIDs.find(NumberedVals.size());
5335 if (I != ForwardRefValIDs.end()) {
5336 Fn = cast<Function>(I->second.first);
5337 if (Fn->getType() != PFT)
5338 return Error(NameLoc, "type of definition and forward reference of '@" +
5339 Twine(NumberedVals.size()) + "' disagree: "
5340 "expected '" + getTypeString(PFT) + "' but was '" +
5341 getTypeString(Fn->getType()) + "'");
5342 ForwardRefValIDs.erase(I);
5346 if (!Fn)
5347 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5348 FunctionName, M);
5349 else // Move the forward-reference to the correct spot in the module.
5350 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5352 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5354 if (FunctionName.empty())
5355 NumberedVals.push_back(Fn);
5357 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5358 maybeSetDSOLocal(DSOLocal, *Fn);
5359 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5360 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5361 Fn->setCallingConv(CC);
5362 Fn->setAttributes(PAL);
5363 Fn->setUnnamedAddr(UnnamedAddr);
5364 Fn->setAlignment(Alignment);
5365 Fn->setSection(Section);
5366 Fn->setComdat(C);
5367 Fn->setPersonalityFn(PersonalityFn);
5368 if (!GC.empty()) Fn->setGC(GC);
5369 Fn->setPrefixData(Prefix);
5370 Fn->setPrologueData(Prologue);
5371 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5373 // Add all of the arguments we parsed to the function.
5374 Function::arg_iterator ArgIt = Fn->arg_begin();
5375 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5376 // If the argument has a name, insert it into the argument symbol table.
5377 if (ArgList[i].Name.empty()) continue;
5379 // Set the name, if it conflicted, it will be auto-renamed.
5380 ArgIt->setName(ArgList[i].Name);
5382 if (ArgIt->getName() != ArgList[i].Name)
5383 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5384 ArgList[i].Name + "'");
5387 if (isDefine)
5388 return false;
5390 // Check the declaration has no block address forward references.
5391 ValID ID;
5392 if (FunctionName.empty()) {
5393 ID.Kind = ValID::t_GlobalID;
5394 ID.UIntVal = NumberedVals.size() - 1;
5395 } else {
5396 ID.Kind = ValID::t_GlobalName;
5397 ID.StrVal = FunctionName;
5399 auto Blocks = ForwardRefBlockAddresses.find(ID);
5400 if (Blocks != ForwardRefBlockAddresses.end())
5401 return Error(Blocks->first.Loc,
5402 "cannot take blockaddress inside a declaration");
5403 return false;
5406 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5407 ValID ID;
5408 if (FunctionNumber == -1) {
5409 ID.Kind = ValID::t_GlobalName;
5410 ID.StrVal = F.getName();
5411 } else {
5412 ID.Kind = ValID::t_GlobalID;
5413 ID.UIntVal = FunctionNumber;
5416 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5417 if (Blocks == P.ForwardRefBlockAddresses.end())
5418 return false;
5420 for (const auto &I : Blocks->second) {
5421 const ValID &BBID = I.first;
5422 GlobalValue *GV = I.second;
5424 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5425 "Expected local id or name");
5426 BasicBlock *BB;
5427 if (BBID.Kind == ValID::t_LocalName)
5428 BB = GetBB(BBID.StrVal, BBID.Loc);
5429 else
5430 BB = GetBB(BBID.UIntVal, BBID.Loc);
5431 if (!BB)
5432 return P.Error(BBID.Loc, "referenced value is not a basic block");
5434 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5435 GV->eraseFromParent();
5438 P.ForwardRefBlockAddresses.erase(Blocks);
5439 return false;
5442 /// ParseFunctionBody
5443 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5444 bool LLParser::ParseFunctionBody(Function &Fn) {
5445 if (Lex.getKind() != lltok::lbrace)
5446 return TokError("expected '{' in function body");
5447 Lex.Lex(); // eat the {.
5449 int FunctionNumber = -1;
5450 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5452 PerFunctionState PFS(*this, Fn, FunctionNumber);
5454 // Resolve block addresses and allow basic blocks to be forward-declared
5455 // within this function.
5456 if (PFS.resolveForwardRefBlockAddresses())
5457 return true;
5458 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5460 // We need at least one basic block.
5461 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5462 return TokError("function body requires at least one basic block");
5464 while (Lex.getKind() != lltok::rbrace &&
5465 Lex.getKind() != lltok::kw_uselistorder)
5466 if (ParseBasicBlock(PFS)) return true;
5468 while (Lex.getKind() != lltok::rbrace)
5469 if (ParseUseListOrder(&PFS))
5470 return true;
5472 // Eat the }.
5473 Lex.Lex();
5475 // Verify function is ok.
5476 return PFS.FinishFunction();
5479 /// ParseBasicBlock
5480 /// ::= LabelStr? Instruction*
5481 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5482 // If this basic block starts out with a name, remember it.
5483 std::string Name;
5484 LocTy NameLoc = Lex.getLoc();
5485 if (Lex.getKind() == lltok::LabelStr) {
5486 Name = Lex.getStrVal();
5487 Lex.Lex();
5490 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
5491 if (!BB)
5492 return Error(NameLoc,
5493 "unable to create block named '" + Name + "'");
5495 std::string NameStr;
5497 // Parse the instructions in this block until we get a terminator.
5498 Instruction *Inst;
5499 do {
5500 // This instruction may have three possibilities for a name: a) none
5501 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5502 LocTy NameLoc = Lex.getLoc();
5503 int NameID = -1;
5504 NameStr = "";
5506 if (Lex.getKind() == lltok::LocalVarID) {
5507 NameID = Lex.getUIntVal();
5508 Lex.Lex();
5509 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5510 return true;
5511 } else if (Lex.getKind() == lltok::LocalVar) {
5512 NameStr = Lex.getStrVal();
5513 Lex.Lex();
5514 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5515 return true;
5518 switch (ParseInstruction(Inst, BB, PFS)) {
5519 default: llvm_unreachable("Unknown ParseInstruction result!");
5520 case InstError: return true;
5521 case InstNormal:
5522 BB->getInstList().push_back(Inst);
5524 // With a normal result, we check to see if the instruction is followed by
5525 // a comma and metadata.
5526 if (EatIfPresent(lltok::comma))
5527 if (ParseInstructionMetadata(*Inst))
5528 return true;
5529 break;
5530 case InstExtraComma:
5531 BB->getInstList().push_back(Inst);
5533 // If the instruction parser ate an extra comma at the end of it, it
5534 // *must* be followed by metadata.
5535 if (ParseInstructionMetadata(*Inst))
5536 return true;
5537 break;
5540 // Set the name on the instruction.
5541 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5542 } while (!Inst->isTerminator());
5544 return false;
5547 //===----------------------------------------------------------------------===//
5548 // Instruction Parsing.
5549 //===----------------------------------------------------------------------===//
5551 /// ParseInstruction - Parse one of the many different instructions.
5553 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5554 PerFunctionState &PFS) {
5555 lltok::Kind Token = Lex.getKind();
5556 if (Token == lltok::Eof)
5557 return TokError("found end of file when expecting more instructions");
5558 LocTy Loc = Lex.getLoc();
5559 unsigned KeywordVal = Lex.getUIntVal();
5560 Lex.Lex(); // Eat the keyword.
5562 switch (Token) {
5563 default: return Error(Loc, "expected instruction opcode");
5564 // Terminator Instructions.
5565 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5566 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5567 case lltok::kw_br: return ParseBr(Inst, PFS);
5568 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
5569 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
5570 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
5571 case lltok::kw_resume: return ParseResume(Inst, PFS);
5572 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5573 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
5574 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5575 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
5576 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
5577 case lltok::kw_callbr: return ParseCallBr(Inst, PFS);
5578 // Unary Operators.
5579 case lltok::kw_fneg: {
5580 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5581 int Res = ParseUnaryOp(Inst, PFS, KeywordVal, 2);
5582 if (Res != 0)
5583 return Res;
5584 if (FMF.any())
5585 Inst->setFastMathFlags(FMF);
5586 return false;
5588 // Binary Operators.
5589 case lltok::kw_add:
5590 case lltok::kw_sub:
5591 case lltok::kw_mul:
5592 case lltok::kw_shl: {
5593 bool NUW = EatIfPresent(lltok::kw_nuw);
5594 bool NSW = EatIfPresent(lltok::kw_nsw);
5595 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5597 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5599 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5600 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5601 return false;
5603 case lltok::kw_fadd:
5604 case lltok::kw_fsub:
5605 case lltok::kw_fmul:
5606 case lltok::kw_fdiv:
5607 case lltok::kw_frem: {
5608 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5609 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
5610 if (Res != 0)
5611 return Res;
5612 if (FMF.any())
5613 Inst->setFastMathFlags(FMF);
5614 return 0;
5617 case lltok::kw_sdiv:
5618 case lltok::kw_udiv:
5619 case lltok::kw_lshr:
5620 case lltok::kw_ashr: {
5621 bool Exact = EatIfPresent(lltok::kw_exact);
5623 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
5624 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5625 return false;
5628 case lltok::kw_urem:
5629 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
5630 case lltok::kw_and:
5631 case lltok::kw_or:
5632 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
5633 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5634 case lltok::kw_fcmp: {
5635 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5636 int Res = ParseCompare(Inst, PFS, KeywordVal);
5637 if (Res != 0)
5638 return Res;
5639 if (FMF.any())
5640 Inst->setFastMathFlags(FMF);
5641 return 0;
5644 // Casts.
5645 case lltok::kw_trunc:
5646 case lltok::kw_zext:
5647 case lltok::kw_sext:
5648 case lltok::kw_fptrunc:
5649 case lltok::kw_fpext:
5650 case lltok::kw_bitcast:
5651 case lltok::kw_addrspacecast:
5652 case lltok::kw_uitofp:
5653 case lltok::kw_sitofp:
5654 case lltok::kw_fptoui:
5655 case lltok::kw_fptosi:
5656 case lltok::kw_inttoptr:
5657 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5658 // Other.
5659 case lltok::kw_select: return ParseSelect(Inst, PFS);
5660 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5661 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5662 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5663 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5664 case lltok::kw_phi: return ParsePHI(Inst, PFS);
5665 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5666 // Call.
5667 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5668 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5669 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5670 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5671 // Memory.
5672 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5673 case lltok::kw_load: return ParseLoad(Inst, PFS);
5674 case lltok::kw_store: return ParseStore(Inst, PFS);
5675 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5676 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5677 case lltok::kw_fence: return ParseFence(Inst, PFS);
5678 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5679 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5680 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5684 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5685 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5686 if (Opc == Instruction::FCmp) {
5687 switch (Lex.getKind()) {
5688 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5689 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5690 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5691 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5692 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5693 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5694 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5695 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5696 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5697 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5698 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5699 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5700 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5701 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5702 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5703 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5704 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5706 } else {
5707 switch (Lex.getKind()) {
5708 default: return TokError("expected icmp predicate (e.g. 'eq')");
5709 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5710 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5711 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5712 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5713 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5714 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5715 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5716 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5717 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5718 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5721 Lex.Lex();
5722 return false;
5725 //===----------------------------------------------------------------------===//
5726 // Terminator Instructions.
5727 //===----------------------------------------------------------------------===//
5729 /// ParseRet - Parse a return instruction.
5730 /// ::= 'ret' void (',' !dbg, !1)*
5731 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5732 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5733 PerFunctionState &PFS) {
5734 SMLoc TypeLoc = Lex.getLoc();
5735 Type *Ty = nullptr;
5736 if (ParseType(Ty, true /*void allowed*/)) return true;
5738 Type *ResType = PFS.getFunction().getReturnType();
5740 if (Ty->isVoidTy()) {
5741 if (!ResType->isVoidTy())
5742 return Error(TypeLoc, "value doesn't match function result type '" +
5743 getTypeString(ResType) + "'");
5745 Inst = ReturnInst::Create(Context);
5746 return false;
5749 Value *RV;
5750 if (ParseValue(Ty, RV, PFS)) return true;
5752 if (ResType != RV->getType())
5753 return Error(TypeLoc, "value doesn't match function result type '" +
5754 getTypeString(ResType) + "'");
5756 Inst = ReturnInst::Create(Context, RV);
5757 return false;
5760 /// ParseBr
5761 /// ::= 'br' TypeAndValue
5762 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5763 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5764 LocTy Loc, Loc2;
5765 Value *Op0;
5766 BasicBlock *Op1, *Op2;
5767 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5769 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5770 Inst = BranchInst::Create(BB);
5771 return false;
5774 if (Op0->getType() != Type::getInt1Ty(Context))
5775 return Error(Loc, "branch condition must have 'i1' type");
5777 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5778 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5779 ParseToken(lltok::comma, "expected ',' after true destination") ||
5780 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5781 return true;
5783 Inst = BranchInst::Create(Op1, Op2, Op0);
5784 return false;
5787 /// ParseSwitch
5788 /// Instruction
5789 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5790 /// JumpTable
5791 /// ::= (TypeAndValue ',' TypeAndValue)*
5792 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5793 LocTy CondLoc, BBLoc;
5794 Value *Cond;
5795 BasicBlock *DefaultBB;
5796 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5797 ParseToken(lltok::comma, "expected ',' after switch condition") ||
5798 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5799 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5800 return true;
5802 if (!Cond->getType()->isIntegerTy())
5803 return Error(CondLoc, "switch condition must have integer type");
5805 // Parse the jump table pairs.
5806 SmallPtrSet<Value*, 32> SeenCases;
5807 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5808 while (Lex.getKind() != lltok::rsquare) {
5809 Value *Constant;
5810 BasicBlock *DestBB;
5812 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5813 ParseToken(lltok::comma, "expected ',' after case value") ||
5814 ParseTypeAndBasicBlock(DestBB, PFS))
5815 return true;
5817 if (!SeenCases.insert(Constant).second)
5818 return Error(CondLoc, "duplicate case value in switch");
5819 if (!isa<ConstantInt>(Constant))
5820 return Error(CondLoc, "case value is not a constant integer");
5822 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5825 Lex.Lex(); // Eat the ']'.
5827 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5828 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5829 SI->addCase(Table[i].first, Table[i].second);
5830 Inst = SI;
5831 return false;
5834 /// ParseIndirectBr
5835 /// Instruction
5836 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5837 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5838 LocTy AddrLoc;
5839 Value *Address;
5840 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
5841 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
5842 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
5843 return true;
5845 if (!Address->getType()->isPointerTy())
5846 return Error(AddrLoc, "indirectbr address must have pointer type");
5848 // Parse the destination list.
5849 SmallVector<BasicBlock*, 16> DestList;
5851 if (Lex.getKind() != lltok::rsquare) {
5852 BasicBlock *DestBB;
5853 if (ParseTypeAndBasicBlock(DestBB, PFS))
5854 return true;
5855 DestList.push_back(DestBB);
5857 while (EatIfPresent(lltok::comma)) {
5858 if (ParseTypeAndBasicBlock(DestBB, PFS))
5859 return true;
5860 DestList.push_back(DestBB);
5864 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
5865 return true;
5867 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
5868 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
5869 IBI->addDestination(DestList[i]);
5870 Inst = IBI;
5871 return false;
5874 /// ParseInvoke
5875 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
5876 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
5877 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
5878 LocTy CallLoc = Lex.getLoc();
5879 AttrBuilder RetAttrs, FnAttrs;
5880 std::vector<unsigned> FwdRefAttrGrps;
5881 LocTy NoBuiltinLoc;
5882 unsigned CC;
5883 unsigned InvokeAddrSpace;
5884 Type *RetType = nullptr;
5885 LocTy RetTypeLoc;
5886 ValID CalleeID;
5887 SmallVector<ParamInfo, 16> ArgList;
5888 SmallVector<OperandBundleDef, 2> BundleList;
5890 BasicBlock *NormalBB, *UnwindBB;
5891 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5892 ParseOptionalProgramAddrSpace(InvokeAddrSpace) ||
5893 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5894 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
5895 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5896 NoBuiltinLoc) ||
5897 ParseOptionalOperandBundles(BundleList, PFS) ||
5898 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
5899 ParseTypeAndBasicBlock(NormalBB, PFS) ||
5900 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
5901 ParseTypeAndBasicBlock(UnwindBB, PFS))
5902 return true;
5904 // If RetType is a non-function pointer type, then this is the short syntax
5905 // for the call, which means that RetType is just the return type. Infer the
5906 // rest of the function argument types from the arguments that are present.
5907 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5908 if (!Ty) {
5909 // Pull out the types of all of the arguments...
5910 std::vector<Type*> ParamTypes;
5911 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5912 ParamTypes.push_back(ArgList[i].V->getType());
5914 if (!FunctionType::isValidReturnType(RetType))
5915 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5917 Ty = FunctionType::get(RetType, ParamTypes, false);
5920 CalleeID.FTy = Ty;
5922 // Look up the callee.
5923 Value *Callee;
5924 if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
5925 Callee, &PFS, /*IsCall=*/true))
5926 return true;
5928 // Set up the Attribute for the function.
5929 SmallVector<Value *, 8> Args;
5930 SmallVector<AttributeSet, 8> ArgAttrs;
5932 // Loop through FunctionType's arguments and ensure they are specified
5933 // correctly. Also, gather any parameter attributes.
5934 FunctionType::param_iterator I = Ty->param_begin();
5935 FunctionType::param_iterator E = Ty->param_end();
5936 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5937 Type *ExpectedTy = nullptr;
5938 if (I != E) {
5939 ExpectedTy = *I++;
5940 } else if (!Ty->isVarArg()) {
5941 return Error(ArgList[i].Loc, "too many arguments specified");
5944 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5945 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5946 getTypeString(ExpectedTy) + "'");
5947 Args.push_back(ArgList[i].V);
5948 ArgAttrs.push_back(ArgList[i].Attrs);
5951 if (I != E)
5952 return Error(CallLoc, "not enough parameters specified for call");
5954 if (FnAttrs.hasAlignmentAttr())
5955 return Error(CallLoc, "invoke instructions may not have an alignment");
5957 // Finish off the Attribute and check them
5958 AttributeList PAL =
5959 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
5960 AttributeSet::get(Context, RetAttrs), ArgAttrs);
5962 InvokeInst *II =
5963 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
5964 II->setCallingConv(CC);
5965 II->setAttributes(PAL);
5966 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
5967 Inst = II;
5968 return false;
5971 /// ParseResume
5972 /// ::= 'resume' TypeAndValue
5973 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
5974 Value *Exn; LocTy ExnLoc;
5975 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
5976 return true;
5978 ResumeInst *RI = ResumeInst::Create(Exn);
5979 Inst = RI;
5980 return false;
5983 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
5984 PerFunctionState &PFS) {
5985 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
5986 return true;
5988 while (Lex.getKind() != lltok::rsquare) {
5989 // If this isn't the first argument, we need a comma.
5990 if (!Args.empty() &&
5991 ParseToken(lltok::comma, "expected ',' in argument list"))
5992 return true;
5994 // Parse the argument.
5995 LocTy ArgLoc;
5996 Type *ArgTy = nullptr;
5997 if (ParseType(ArgTy, ArgLoc))
5998 return true;
6000 Value *V;
6001 if (ArgTy->isMetadataTy()) {
6002 if (ParseMetadataAsValue(V, PFS))
6003 return true;
6004 } else {
6005 if (ParseValue(ArgTy, V, PFS))
6006 return true;
6008 Args.push_back(V);
6011 Lex.Lex(); // Lex the ']'.
6012 return false;
6015 /// ParseCleanupRet
6016 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6017 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6018 Value *CleanupPad = nullptr;
6020 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6021 return true;
6023 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6024 return true;
6026 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6027 return true;
6029 BasicBlock *UnwindBB = nullptr;
6030 if (Lex.getKind() == lltok::kw_to) {
6031 Lex.Lex();
6032 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6033 return true;
6034 } else {
6035 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
6036 return true;
6040 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6041 return false;
6044 /// ParseCatchRet
6045 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6046 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6047 Value *CatchPad = nullptr;
6049 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
6050 return true;
6052 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
6053 return true;
6055 BasicBlock *BB;
6056 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
6057 ParseTypeAndBasicBlock(BB, PFS))
6058 return true;
6060 Inst = CatchReturnInst::Create(CatchPad, BB);
6061 return false;
6064 /// ParseCatchSwitch
6065 /// ::= 'catchswitch' within Parent
6066 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6067 Value *ParentPad;
6069 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6070 return true;
6072 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6073 Lex.getKind() != lltok::LocalVarID)
6074 return TokError("expected scope value for catchswitch");
6076 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6077 return true;
6079 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6080 return true;
6082 SmallVector<BasicBlock *, 32> Table;
6083 do {
6084 BasicBlock *DestBB;
6085 if (ParseTypeAndBasicBlock(DestBB, PFS))
6086 return true;
6087 Table.push_back(DestBB);
6088 } while (EatIfPresent(lltok::comma));
6090 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6091 return true;
6093 if (ParseToken(lltok::kw_unwind,
6094 "expected 'unwind' after catchswitch scope"))
6095 return true;
6097 BasicBlock *UnwindBB = nullptr;
6098 if (EatIfPresent(lltok::kw_to)) {
6099 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6100 return true;
6101 } else {
6102 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
6103 return true;
6106 auto *CatchSwitch =
6107 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6108 for (BasicBlock *DestBB : Table)
6109 CatchSwitch->addHandler(DestBB);
6110 Inst = CatchSwitch;
6111 return false;
6114 /// ParseCatchPad
6115 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6116 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6117 Value *CatchSwitch = nullptr;
6119 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
6120 return true;
6122 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6123 return TokError("expected scope value for catchpad");
6125 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6126 return true;
6128 SmallVector<Value *, 8> Args;
6129 if (ParseExceptionArgs(Args, PFS))
6130 return true;
6132 Inst = CatchPadInst::Create(CatchSwitch, Args);
6133 return false;
6136 /// ParseCleanupPad
6137 /// ::= 'cleanuppad' within Parent ParamList
6138 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6139 Value *ParentPad = nullptr;
6141 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6142 return true;
6144 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6145 Lex.getKind() != lltok::LocalVarID)
6146 return TokError("expected scope value for cleanuppad");
6148 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6149 return true;
6151 SmallVector<Value *, 8> Args;
6152 if (ParseExceptionArgs(Args, PFS))
6153 return true;
6155 Inst = CleanupPadInst::Create(ParentPad, Args);
6156 return false;
6159 //===----------------------------------------------------------------------===//
6160 // Unary Operators.
6161 //===----------------------------------------------------------------------===//
6163 /// ParseUnaryOp
6164 /// ::= UnaryOp TypeAndValue ',' Value
6166 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6167 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
6168 bool LLParser::ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6169 unsigned Opc, unsigned OperandType) {
6170 LocTy Loc; Value *LHS;
6171 if (ParseTypeAndValue(LHS, Loc, PFS))
6172 return true;
6174 bool Valid;
6175 switch (OperandType) {
6176 default: llvm_unreachable("Unknown operand type!");
6177 case 0: // int or FP.
6178 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6179 LHS->getType()->isFPOrFPVectorTy();
6180 break;
6181 case 1:
6182 Valid = LHS->getType()->isIntOrIntVectorTy();
6183 break;
6184 case 2:
6185 Valid = LHS->getType()->isFPOrFPVectorTy();
6186 break;
6189 if (!Valid)
6190 return Error(Loc, "invalid operand type for instruction");
6192 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6193 return false;
6196 /// ParseCallBr
6197 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6198 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6199 /// '[' LabelList ']'
6200 bool LLParser::ParseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6201 LocTy CallLoc = Lex.getLoc();
6202 AttrBuilder RetAttrs, FnAttrs;
6203 std::vector<unsigned> FwdRefAttrGrps;
6204 LocTy NoBuiltinLoc;
6205 unsigned CC;
6206 Type *RetType = nullptr;
6207 LocTy RetTypeLoc;
6208 ValID CalleeID;
6209 SmallVector<ParamInfo, 16> ArgList;
6210 SmallVector<OperandBundleDef, 2> BundleList;
6212 BasicBlock *DefaultDest;
6213 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6214 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6215 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
6216 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6217 NoBuiltinLoc) ||
6218 ParseOptionalOperandBundles(BundleList, PFS) ||
6219 ParseToken(lltok::kw_to, "expected 'to' in callbr") ||
6220 ParseTypeAndBasicBlock(DefaultDest, PFS) ||
6221 ParseToken(lltok::lsquare, "expected '[' in callbr"))
6222 return true;
6224 // Parse the destination list.
6225 SmallVector<BasicBlock *, 16> IndirectDests;
6227 if (Lex.getKind() != lltok::rsquare) {
6228 BasicBlock *DestBB;
6229 if (ParseTypeAndBasicBlock(DestBB, PFS))
6230 return true;
6231 IndirectDests.push_back(DestBB);
6233 while (EatIfPresent(lltok::comma)) {
6234 if (ParseTypeAndBasicBlock(DestBB, PFS))
6235 return true;
6236 IndirectDests.push_back(DestBB);
6240 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
6241 return true;
6243 // If RetType is a non-function pointer type, then this is the short syntax
6244 // for the call, which means that RetType is just the return type. Infer the
6245 // rest of the function argument types from the arguments that are present.
6246 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6247 if (!Ty) {
6248 // Pull out the types of all of the arguments...
6249 std::vector<Type *> ParamTypes;
6250 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6251 ParamTypes.push_back(ArgList[i].V->getType());
6253 if (!FunctionType::isValidReturnType(RetType))
6254 return Error(RetTypeLoc, "Invalid result type for LLVM function");
6256 Ty = FunctionType::get(RetType, ParamTypes, false);
6259 CalleeID.FTy = Ty;
6261 // Look up the callee.
6262 Value *Callee;
6263 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6264 /*IsCall=*/true))
6265 return true;
6267 if (isa<InlineAsm>(Callee) && !Ty->getReturnType()->isVoidTy())
6268 return Error(RetTypeLoc, "asm-goto outputs not supported");
6270 // Set up the Attribute for the function.
6271 SmallVector<Value *, 8> Args;
6272 SmallVector<AttributeSet, 8> ArgAttrs;
6274 // Loop through FunctionType's arguments and ensure they are specified
6275 // correctly. Also, gather any parameter attributes.
6276 FunctionType::param_iterator I = Ty->param_begin();
6277 FunctionType::param_iterator E = Ty->param_end();
6278 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6279 Type *ExpectedTy = nullptr;
6280 if (I != E) {
6281 ExpectedTy = *I++;
6282 } else if (!Ty->isVarArg()) {
6283 return Error(ArgList[i].Loc, "too many arguments specified");
6286 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6287 return Error(ArgList[i].Loc, "argument is not of expected type '" +
6288 getTypeString(ExpectedTy) + "'");
6289 Args.push_back(ArgList[i].V);
6290 ArgAttrs.push_back(ArgList[i].Attrs);
6293 if (I != E)
6294 return Error(CallLoc, "not enough parameters specified for call");
6296 if (FnAttrs.hasAlignmentAttr())
6297 return Error(CallLoc, "callbr instructions may not have an alignment");
6299 // Finish off the Attribute and check them
6300 AttributeList PAL =
6301 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6302 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6304 CallBrInst *CBI =
6305 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6306 BundleList);
6307 CBI->setCallingConv(CC);
6308 CBI->setAttributes(PAL);
6309 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6310 Inst = CBI;
6311 return false;
6314 //===----------------------------------------------------------------------===//
6315 // Binary Operators.
6316 //===----------------------------------------------------------------------===//
6318 /// ParseArithmetic
6319 /// ::= ArithmeticOps TypeAndValue ',' Value
6321 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
6322 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
6323 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6324 unsigned Opc, unsigned OperandType) {
6325 LocTy Loc; Value *LHS, *RHS;
6326 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6327 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6328 ParseValue(LHS->getType(), RHS, PFS))
6329 return true;
6331 bool Valid;
6332 switch (OperandType) {
6333 default: llvm_unreachable("Unknown operand type!");
6334 case 0: // int or FP.
6335 Valid = LHS->getType()->isIntOrIntVectorTy() ||
6336 LHS->getType()->isFPOrFPVectorTy();
6337 break;
6338 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
6339 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
6342 if (!Valid)
6343 return Error(Loc, "invalid operand type for instruction");
6345 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6346 return false;
6349 /// ParseLogical
6350 /// ::= ArithmeticOps TypeAndValue ',' Value {
6351 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
6352 unsigned Opc) {
6353 LocTy Loc; Value *LHS, *RHS;
6354 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6355 ParseToken(lltok::comma, "expected ',' in logical operation") ||
6356 ParseValue(LHS->getType(), RHS, PFS))
6357 return true;
6359 if (!LHS->getType()->isIntOrIntVectorTy())
6360 return Error(Loc,"instruction requires integer or integer vector operands");
6362 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6363 return false;
6366 /// ParseCompare
6367 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
6368 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
6369 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6370 unsigned Opc) {
6371 // Parse the integer/fp comparison predicate.
6372 LocTy Loc;
6373 unsigned Pred;
6374 Value *LHS, *RHS;
6375 if (ParseCmpPredicate(Pred, Opc) ||
6376 ParseTypeAndValue(LHS, Loc, PFS) ||
6377 ParseToken(lltok::comma, "expected ',' after compare value") ||
6378 ParseValue(LHS->getType(), RHS, PFS))
6379 return true;
6381 if (Opc == Instruction::FCmp) {
6382 if (!LHS->getType()->isFPOrFPVectorTy())
6383 return Error(Loc, "fcmp requires floating point operands");
6384 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6385 } else {
6386 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
6387 if (!LHS->getType()->isIntOrIntVectorTy() &&
6388 !LHS->getType()->isPtrOrPtrVectorTy())
6389 return Error(Loc, "icmp requires integer operands");
6390 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6392 return false;
6395 //===----------------------------------------------------------------------===//
6396 // Other Instructions.
6397 //===----------------------------------------------------------------------===//
6400 /// ParseCast
6401 /// ::= CastOpc TypeAndValue 'to' Type
6402 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6403 unsigned Opc) {
6404 LocTy Loc;
6405 Value *Op;
6406 Type *DestTy = nullptr;
6407 if (ParseTypeAndValue(Op, Loc, PFS) ||
6408 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6409 ParseType(DestTy))
6410 return true;
6412 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6413 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
6414 return Error(Loc, "invalid cast opcode for cast from '" +
6415 getTypeString(Op->getType()) + "' to '" +
6416 getTypeString(DestTy) + "'");
6418 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6419 return false;
6422 /// ParseSelect
6423 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6424 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6425 LocTy Loc;
6426 Value *Op0, *Op1, *Op2;
6427 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6428 ParseToken(lltok::comma, "expected ',' after select condition") ||
6429 ParseTypeAndValue(Op1, PFS) ||
6430 ParseToken(lltok::comma, "expected ',' after select value") ||
6431 ParseTypeAndValue(Op2, PFS))
6432 return true;
6434 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6435 return Error(Loc, Reason);
6437 Inst = SelectInst::Create(Op0, Op1, Op2);
6438 return false;
6441 /// ParseVA_Arg
6442 /// ::= 'va_arg' TypeAndValue ',' Type
6443 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
6444 Value *Op;
6445 Type *EltTy = nullptr;
6446 LocTy TypeLoc;
6447 if (ParseTypeAndValue(Op, PFS) ||
6448 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
6449 ParseType(EltTy, TypeLoc))
6450 return true;
6452 if (!EltTy->isFirstClassType())
6453 return Error(TypeLoc, "va_arg requires operand with first class type");
6455 Inst = new VAArgInst(Op, EltTy);
6456 return false;
6459 /// ParseExtractElement
6460 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6461 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6462 LocTy Loc;
6463 Value *Op0, *Op1;
6464 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6465 ParseToken(lltok::comma, "expected ',' after extract value") ||
6466 ParseTypeAndValue(Op1, PFS))
6467 return true;
6469 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6470 return Error(Loc, "invalid extractelement operands");
6472 Inst = ExtractElementInst::Create(Op0, Op1);
6473 return false;
6476 /// ParseInsertElement
6477 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6478 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6479 LocTy Loc;
6480 Value *Op0, *Op1, *Op2;
6481 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6482 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6483 ParseTypeAndValue(Op1, PFS) ||
6484 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6485 ParseTypeAndValue(Op2, PFS))
6486 return true;
6488 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
6489 return Error(Loc, "invalid insertelement operands");
6491 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6492 return false;
6495 /// ParseShuffleVector
6496 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6497 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6498 LocTy Loc;
6499 Value *Op0, *Op1, *Op2;
6500 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6501 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6502 ParseTypeAndValue(Op1, PFS) ||
6503 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6504 ParseTypeAndValue(Op2, PFS))
6505 return true;
6507 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
6508 return Error(Loc, "invalid shufflevector operands");
6510 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6511 return false;
6514 /// ParsePHI
6515 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6516 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
6517 Type *Ty = nullptr; LocTy TypeLoc;
6518 Value *Op0, *Op1;
6520 if (ParseType(Ty, TypeLoc) ||
6521 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6522 ParseValue(Ty, Op0, PFS) ||
6523 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6524 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
6525 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6526 return true;
6528 bool AteExtraComma = false;
6529 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
6531 while (true) {
6532 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
6534 if (!EatIfPresent(lltok::comma))
6535 break;
6537 if (Lex.getKind() == lltok::MetadataVar) {
6538 AteExtraComma = true;
6539 break;
6542 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6543 ParseValue(Ty, Op0, PFS) ||
6544 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6545 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
6546 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6547 return true;
6550 if (!Ty->isFirstClassType())
6551 return Error(TypeLoc, "phi node must have first class type");
6553 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
6554 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6555 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6556 Inst = PN;
6557 return AteExtraComma ? InstExtraComma : InstNormal;
6560 /// ParseLandingPad
6561 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6562 /// Clause
6563 /// ::= 'catch' TypeAndValue
6564 /// ::= 'filter'
6565 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6566 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
6567 Type *Ty = nullptr; LocTy TyLoc;
6569 if (ParseType(Ty, TyLoc))
6570 return true;
6572 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
6573 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6575 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6576 LandingPadInst::ClauseType CT;
6577 if (EatIfPresent(lltok::kw_catch))
6578 CT = LandingPadInst::Catch;
6579 else if (EatIfPresent(lltok::kw_filter))
6580 CT = LandingPadInst::Filter;
6581 else
6582 return TokError("expected 'catch' or 'filter' clause type");
6584 Value *V;
6585 LocTy VLoc;
6586 if (ParseTypeAndValue(V, VLoc, PFS))
6587 return true;
6589 // A 'catch' type expects a non-array constant. A filter clause expects an
6590 // array constant.
6591 if (CT == LandingPadInst::Catch) {
6592 if (isa<ArrayType>(V->getType()))
6593 Error(VLoc, "'catch' clause has an invalid type");
6594 } else {
6595 if (!isa<ArrayType>(V->getType()))
6596 Error(VLoc, "'filter' clause has an invalid type");
6599 Constant *CV = dyn_cast<Constant>(V);
6600 if (!CV)
6601 return Error(VLoc, "clause argument must be a constant");
6602 LP->addClause(CV);
6605 Inst = LP.release();
6606 return false;
6609 /// ParseCall
6610 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6611 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6612 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6613 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6614 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6615 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6616 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6617 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6618 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
6619 CallInst::TailCallKind TCK) {
6620 AttrBuilder RetAttrs, FnAttrs;
6621 std::vector<unsigned> FwdRefAttrGrps;
6622 LocTy BuiltinLoc;
6623 unsigned CallAddrSpace;
6624 unsigned CC;
6625 Type *RetType = nullptr;
6626 LocTy RetTypeLoc;
6627 ValID CalleeID;
6628 SmallVector<ParamInfo, 16> ArgList;
6629 SmallVector<OperandBundleDef, 2> BundleList;
6630 LocTy CallLoc = Lex.getLoc();
6632 if (TCK != CallInst::TCK_None &&
6633 ParseToken(lltok::kw_call,
6634 "expected 'tail call', 'musttail call', or 'notail call'"))
6635 return true;
6637 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6639 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6640 ParseOptionalProgramAddrSpace(CallAddrSpace) ||
6641 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6642 ParseValID(CalleeID) ||
6643 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6644 PFS.getFunction().isVarArg()) ||
6645 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6646 ParseOptionalOperandBundles(BundleList, PFS))
6647 return true;
6649 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6650 return Error(CallLoc, "fast-math-flags specified for call without "
6651 "floating-point scalar or vector return type");
6653 // If RetType is a non-function pointer type, then this is the short syntax
6654 // for the call, which means that RetType is just the return type. Infer the
6655 // rest of the function argument types from the arguments that are present.
6656 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6657 if (!Ty) {
6658 // Pull out the types of all of the arguments...
6659 std::vector<Type*> ParamTypes;
6660 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6661 ParamTypes.push_back(ArgList[i].V->getType());
6663 if (!FunctionType::isValidReturnType(RetType))
6664 return Error(RetTypeLoc, "Invalid result type for LLVM function");
6666 Ty = FunctionType::get(RetType, ParamTypes, false);
6669 CalleeID.FTy = Ty;
6671 // Look up the callee.
6672 Value *Callee;
6673 if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
6674 &PFS, /*IsCall=*/true))
6675 return true;
6677 // Set up the Attribute for the function.
6678 SmallVector<AttributeSet, 8> Attrs;
6680 SmallVector<Value*, 8> Args;
6682 // Loop through FunctionType's arguments and ensure they are specified
6683 // correctly. Also, gather any parameter attributes.
6684 FunctionType::param_iterator I = Ty->param_begin();
6685 FunctionType::param_iterator E = Ty->param_end();
6686 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6687 Type *ExpectedTy = nullptr;
6688 if (I != E) {
6689 ExpectedTy = *I++;
6690 } else if (!Ty->isVarArg()) {
6691 return Error(ArgList[i].Loc, "too many arguments specified");
6694 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6695 return Error(ArgList[i].Loc, "argument is not of expected type '" +
6696 getTypeString(ExpectedTy) + "'");
6697 Args.push_back(ArgList[i].V);
6698 Attrs.push_back(ArgList[i].Attrs);
6701 if (I != E)
6702 return Error(CallLoc, "not enough parameters specified for call");
6704 if (FnAttrs.hasAlignmentAttr())
6705 return Error(CallLoc, "call instructions may not have an alignment");
6707 // Finish off the Attribute and check them
6708 AttributeList PAL =
6709 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6710 AttributeSet::get(Context, RetAttrs), Attrs);
6712 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
6713 CI->setTailCallKind(TCK);
6714 CI->setCallingConv(CC);
6715 if (FMF.any())
6716 CI->setFastMathFlags(FMF);
6717 CI->setAttributes(PAL);
6718 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6719 Inst = CI;
6720 return false;
6723 //===----------------------------------------------------------------------===//
6724 // Memory Instructions.
6725 //===----------------------------------------------------------------------===//
6727 /// ParseAlloc
6728 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6729 /// (',' 'align' i32)? (',', 'addrspace(n))?
6730 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
6731 Value *Size = nullptr;
6732 LocTy SizeLoc, TyLoc, ASLoc;
6733 unsigned Alignment = 0;
6734 unsigned AddrSpace = 0;
6735 Type *Ty = nullptr;
6737 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
6738 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
6740 if (ParseType(Ty, TyLoc)) return true;
6742 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6743 return Error(TyLoc, "invalid type for alloca");
6745 bool AteExtraComma = false;
6746 if (EatIfPresent(lltok::comma)) {
6747 if (Lex.getKind() == lltok::kw_align) {
6748 if (ParseOptionalAlignment(Alignment))
6749 return true;
6750 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6751 return true;
6752 } else if (Lex.getKind() == lltok::kw_addrspace) {
6753 ASLoc = Lex.getLoc();
6754 if (ParseOptionalAddrSpace(AddrSpace))
6755 return true;
6756 } else if (Lex.getKind() == lltok::MetadataVar) {
6757 AteExtraComma = true;
6758 } else {
6759 if (ParseTypeAndValue(Size, SizeLoc, PFS))
6760 return true;
6761 if (EatIfPresent(lltok::comma)) {
6762 if (Lex.getKind() == lltok::kw_align) {
6763 if (ParseOptionalAlignment(Alignment))
6764 return true;
6765 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6766 return true;
6767 } else if (Lex.getKind() == lltok::kw_addrspace) {
6768 ASLoc = Lex.getLoc();
6769 if (ParseOptionalAddrSpace(AddrSpace))
6770 return true;
6771 } else if (Lex.getKind() == lltok::MetadataVar) {
6772 AteExtraComma = true;
6778 if (Size && !Size->getType()->isIntegerTy())
6779 return Error(SizeLoc, "element count must have integer type");
6781 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
6782 AI->setUsedWithInAlloca(IsInAlloca);
6783 AI->setSwiftError(IsSwiftError);
6784 Inst = AI;
6785 return AteExtraComma ? InstExtraComma : InstNormal;
6788 /// ParseLoad
6789 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6790 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6791 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6792 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6793 Value *Val; LocTy Loc;
6794 unsigned Alignment = 0;
6795 bool AteExtraComma = false;
6796 bool isAtomic = false;
6797 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6798 SyncScope::ID SSID = SyncScope::System;
6800 if (Lex.getKind() == lltok::kw_atomic) {
6801 isAtomic = true;
6802 Lex.Lex();
6805 bool isVolatile = false;
6806 if (Lex.getKind() == lltok::kw_volatile) {
6807 isVolatile = true;
6808 Lex.Lex();
6811 Type *Ty;
6812 LocTy ExplicitTypeLoc = Lex.getLoc();
6813 if (ParseType(Ty) ||
6814 ParseToken(lltok::comma, "expected comma after load's type") ||
6815 ParseTypeAndValue(Val, Loc, PFS) ||
6816 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6817 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6818 return true;
6820 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6821 return Error(Loc, "load operand must be a pointer to a first class type");
6822 if (isAtomic && !Alignment)
6823 return Error(Loc, "atomic load must have explicit non-zero alignment");
6824 if (Ordering == AtomicOrdering::Release ||
6825 Ordering == AtomicOrdering::AcquireRelease)
6826 return Error(Loc, "atomic load cannot use Release ordering");
6828 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6829 return Error(ExplicitTypeLoc,
6830 "explicit pointee type doesn't match operand's pointee type");
6832 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
6833 return AteExtraComma ? InstExtraComma : InstNormal;
6836 /// ParseStore
6838 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6839 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6840 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6841 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6842 Value *Val, *Ptr; LocTy Loc, PtrLoc;
6843 unsigned Alignment = 0;
6844 bool AteExtraComma = false;
6845 bool isAtomic = false;
6846 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6847 SyncScope::ID SSID = SyncScope::System;
6849 if (Lex.getKind() == lltok::kw_atomic) {
6850 isAtomic = true;
6851 Lex.Lex();
6854 bool isVolatile = false;
6855 if (Lex.getKind() == lltok::kw_volatile) {
6856 isVolatile = true;
6857 Lex.Lex();
6860 if (ParseTypeAndValue(Val, Loc, PFS) ||
6861 ParseToken(lltok::comma, "expected ',' after store operand") ||
6862 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6863 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6864 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6865 return true;
6867 if (!Ptr->getType()->isPointerTy())
6868 return Error(PtrLoc, "store operand must be a pointer");
6869 if (!Val->getType()->isFirstClassType())
6870 return Error(Loc, "store operand must be a first class value");
6871 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6872 return Error(Loc, "stored value and pointer type do not match");
6873 if (isAtomic && !Alignment)
6874 return Error(Loc, "atomic store must have explicit non-zero alignment");
6875 if (Ordering == AtomicOrdering::Acquire ||
6876 Ordering == AtomicOrdering::AcquireRelease)
6877 return Error(Loc, "atomic store cannot use Acquire ordering");
6879 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
6880 return AteExtraComma ? InstExtraComma : InstNormal;
6883 /// ParseCmpXchg
6884 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
6885 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
6886 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
6887 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
6888 bool AteExtraComma = false;
6889 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
6890 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
6891 SyncScope::ID SSID = SyncScope::System;
6892 bool isVolatile = false;
6893 bool isWeak = false;
6895 if (EatIfPresent(lltok::kw_weak))
6896 isWeak = true;
6898 if (EatIfPresent(lltok::kw_volatile))
6899 isVolatile = true;
6901 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6902 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
6903 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
6904 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
6905 ParseTypeAndValue(New, NewLoc, PFS) ||
6906 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
6907 ParseOrdering(FailureOrdering))
6908 return true;
6910 if (SuccessOrdering == AtomicOrdering::Unordered ||
6911 FailureOrdering == AtomicOrdering::Unordered)
6912 return TokError("cmpxchg cannot be unordered");
6913 if (isStrongerThan(FailureOrdering, SuccessOrdering))
6914 return TokError("cmpxchg failure argument shall be no stronger than the "
6915 "success argument");
6916 if (FailureOrdering == AtomicOrdering::Release ||
6917 FailureOrdering == AtomicOrdering::AcquireRelease)
6918 return TokError(
6919 "cmpxchg failure ordering cannot include release semantics");
6920 if (!Ptr->getType()->isPointerTy())
6921 return Error(PtrLoc, "cmpxchg operand must be a pointer");
6922 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
6923 return Error(CmpLoc, "compare value and pointer type do not match");
6924 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
6925 return Error(NewLoc, "new value and pointer type do not match");
6926 if (!New->getType()->isFirstClassType())
6927 return Error(NewLoc, "cmpxchg operand must be a first class value");
6928 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
6929 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
6930 CXI->setVolatile(isVolatile);
6931 CXI->setWeak(isWeak);
6932 Inst = CXI;
6933 return AteExtraComma ? InstExtraComma : InstNormal;
6936 /// ParseAtomicRMW
6937 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
6938 /// 'singlethread'? AtomicOrdering
6939 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
6940 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
6941 bool AteExtraComma = false;
6942 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6943 SyncScope::ID SSID = SyncScope::System;
6944 bool isVolatile = false;
6945 bool IsFP = false;
6946 AtomicRMWInst::BinOp Operation;
6948 if (EatIfPresent(lltok::kw_volatile))
6949 isVolatile = true;
6951 switch (Lex.getKind()) {
6952 default: return TokError("expected binary operation in atomicrmw");
6953 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
6954 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
6955 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
6956 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
6957 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
6958 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
6959 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
6960 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
6961 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
6962 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
6963 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
6964 case lltok::kw_fadd:
6965 Operation = AtomicRMWInst::FAdd;
6966 IsFP = true;
6967 break;
6968 case lltok::kw_fsub:
6969 Operation = AtomicRMWInst::FSub;
6970 IsFP = true;
6971 break;
6973 Lex.Lex(); // Eat the operation.
6975 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
6976 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
6977 ParseTypeAndValue(Val, ValLoc, PFS) ||
6978 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
6979 return true;
6981 if (Ordering == AtomicOrdering::Unordered)
6982 return TokError("atomicrmw cannot be unordered");
6983 if (!Ptr->getType()->isPointerTy())
6984 return Error(PtrLoc, "atomicrmw operand must be a pointer");
6985 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
6986 return Error(ValLoc, "atomicrmw value and pointer type do not match");
6988 if (Operation == AtomicRMWInst::Xchg) {
6989 if (!Val->getType()->isIntegerTy() &&
6990 !Val->getType()->isFloatingPointTy()) {
6991 return Error(ValLoc, "atomicrmw " +
6992 AtomicRMWInst::getOperationName(Operation) +
6993 " operand must be an integer or floating point type");
6995 } else if (IsFP) {
6996 if (!Val->getType()->isFloatingPointTy()) {
6997 return Error(ValLoc, "atomicrmw " +
6998 AtomicRMWInst::getOperationName(Operation) +
6999 " operand must be a floating point type");
7001 } else {
7002 if (!Val->getType()->isIntegerTy()) {
7003 return Error(ValLoc, "atomicrmw " +
7004 AtomicRMWInst::getOperationName(Operation) +
7005 " operand must be an integer");
7009 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
7010 if (Size < 8 || (Size & (Size - 1)))
7011 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7012 " integer");
7014 AtomicRMWInst *RMWI =
7015 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
7016 RMWI->setVolatile(isVolatile);
7017 Inst = RMWI;
7018 return AteExtraComma ? InstExtraComma : InstNormal;
7021 /// ParseFence
7022 /// ::= 'fence' 'singlethread'? AtomicOrdering
7023 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
7024 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7025 SyncScope::ID SSID = SyncScope::System;
7026 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7027 return true;
7029 if (Ordering == AtomicOrdering::Unordered)
7030 return TokError("fence cannot be unordered");
7031 if (Ordering == AtomicOrdering::Monotonic)
7032 return TokError("fence cannot be monotonic");
7034 Inst = new FenceInst(Context, Ordering, SSID);
7035 return InstNormal;
7038 /// ParseGetElementPtr
7039 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7040 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7041 Value *Ptr = nullptr;
7042 Value *Val = nullptr;
7043 LocTy Loc, EltLoc;
7045 bool InBounds = EatIfPresent(lltok::kw_inbounds);
7047 Type *Ty = nullptr;
7048 LocTy ExplicitTypeLoc = Lex.getLoc();
7049 if (ParseType(Ty) ||
7050 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
7051 ParseTypeAndValue(Ptr, Loc, PFS))
7052 return true;
7054 Type *BaseType = Ptr->getType();
7055 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7056 if (!BasePointerType)
7057 return Error(Loc, "base of getelementptr must be a pointer");
7059 if (Ty != BasePointerType->getElementType())
7060 return Error(ExplicitTypeLoc,
7061 "explicit pointee type doesn't match operand's pointee type");
7063 SmallVector<Value*, 16> Indices;
7064 bool AteExtraComma = false;
7065 // GEP returns a vector of pointers if at least one of parameters is a vector.
7066 // All vector parameters should have the same vector width.
7067 unsigned GEPWidth = BaseType->isVectorTy() ?
7068 BaseType->getVectorNumElements() : 0;
7070 while (EatIfPresent(lltok::comma)) {
7071 if (Lex.getKind() == lltok::MetadataVar) {
7072 AteExtraComma = true;
7073 break;
7075 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
7076 if (!Val->getType()->isIntOrIntVectorTy())
7077 return Error(EltLoc, "getelementptr index must be an integer");
7079 if (Val->getType()->isVectorTy()) {
7080 unsigned ValNumEl = Val->getType()->getVectorNumElements();
7081 if (GEPWidth && GEPWidth != ValNumEl)
7082 return Error(EltLoc,
7083 "getelementptr vector index has a wrong number of elements");
7084 GEPWidth = ValNumEl;
7086 Indices.push_back(Val);
7089 SmallPtrSet<Type*, 4> Visited;
7090 if (!Indices.empty() && !Ty->isSized(&Visited))
7091 return Error(Loc, "base element of getelementptr must be sized");
7093 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7094 return Error(Loc, "invalid getelementptr indices");
7095 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7096 if (InBounds)
7097 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7098 return AteExtraComma ? InstExtraComma : InstNormal;
7101 /// ParseExtractValue
7102 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
7103 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7104 Value *Val; LocTy Loc;
7105 SmallVector<unsigned, 4> Indices;
7106 bool AteExtraComma;
7107 if (ParseTypeAndValue(Val, Loc, PFS) ||
7108 ParseIndexList(Indices, AteExtraComma))
7109 return true;
7111 if (!Val->getType()->isAggregateType())
7112 return Error(Loc, "extractvalue operand must be aggregate type");
7114 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7115 return Error(Loc, "invalid indices for extractvalue");
7116 Inst = ExtractValueInst::Create(Val, Indices);
7117 return AteExtraComma ? InstExtraComma : InstNormal;
7120 /// ParseInsertValue
7121 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7122 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7123 Value *Val0, *Val1; LocTy Loc0, Loc1;
7124 SmallVector<unsigned, 4> Indices;
7125 bool AteExtraComma;
7126 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
7127 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
7128 ParseTypeAndValue(Val1, Loc1, PFS) ||
7129 ParseIndexList(Indices, AteExtraComma))
7130 return true;
7132 if (!Val0->getType()->isAggregateType())
7133 return Error(Loc0, "insertvalue operand must be aggregate type");
7135 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7136 if (!IndexedType)
7137 return Error(Loc0, "invalid indices for insertvalue");
7138 if (IndexedType != Val1->getType())
7139 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
7140 getTypeString(Val1->getType()) + "' instead of '" +
7141 getTypeString(IndexedType) + "'");
7142 Inst = InsertValueInst::Create(Val0, Val1, Indices);
7143 return AteExtraComma ? InstExtraComma : InstNormal;
7146 //===----------------------------------------------------------------------===//
7147 // Embedded metadata.
7148 //===----------------------------------------------------------------------===//
7150 /// ParseMDNodeVector
7151 /// ::= { Element (',' Element)* }
7152 /// Element
7153 /// ::= 'null' | TypeAndValue
7154 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7155 if (ParseToken(lltok::lbrace, "expected '{' here"))
7156 return true;
7158 // Check for an empty list.
7159 if (EatIfPresent(lltok::rbrace))
7160 return false;
7162 do {
7163 // Null is a special case since it is typeless.
7164 if (EatIfPresent(lltok::kw_null)) {
7165 Elts.push_back(nullptr);
7166 continue;
7169 Metadata *MD;
7170 if (ParseMetadata(MD, nullptr))
7171 return true;
7172 Elts.push_back(MD);
7173 } while (EatIfPresent(lltok::comma));
7175 return ParseToken(lltok::rbrace, "expected end of metadata node");
7178 //===----------------------------------------------------------------------===//
7179 // Use-list order directives.
7180 //===----------------------------------------------------------------------===//
7181 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7182 SMLoc Loc) {
7183 if (V->use_empty())
7184 return Error(Loc, "value has no uses");
7186 unsigned NumUses = 0;
7187 SmallDenseMap<const Use *, unsigned, 16> Order;
7188 for (const Use &U : V->uses()) {
7189 if (++NumUses > Indexes.size())
7190 break;
7191 Order[&U] = Indexes[NumUses - 1];
7193 if (NumUses < 2)
7194 return Error(Loc, "value only has one use");
7195 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7196 return Error(Loc,
7197 "wrong number of indexes, expected " + Twine(V->getNumUses()));
7199 V->sortUseList([&](const Use &L, const Use &R) {
7200 return Order.lookup(&L) < Order.lookup(&R);
7202 return false;
7205 /// ParseUseListOrderIndexes
7206 /// ::= '{' uint32 (',' uint32)+ '}'
7207 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7208 SMLoc Loc = Lex.getLoc();
7209 if (ParseToken(lltok::lbrace, "expected '{' here"))
7210 return true;
7211 if (Lex.getKind() == lltok::rbrace)
7212 return Lex.Error("expected non-empty list of uselistorder indexes");
7214 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7215 // indexes should be distinct numbers in the range [0, size-1], and should
7216 // not be in order.
7217 unsigned Offset = 0;
7218 unsigned Max = 0;
7219 bool IsOrdered = true;
7220 assert(Indexes.empty() && "Expected empty order vector");
7221 do {
7222 unsigned Index;
7223 if (ParseUInt32(Index))
7224 return true;
7226 // Update consistency checks.
7227 Offset += Index - Indexes.size();
7228 Max = std::max(Max, Index);
7229 IsOrdered &= Index == Indexes.size();
7231 Indexes.push_back(Index);
7232 } while (EatIfPresent(lltok::comma));
7234 if (ParseToken(lltok::rbrace, "expected '}' here"))
7235 return true;
7237 if (Indexes.size() < 2)
7238 return Error(Loc, "expected >= 2 uselistorder indexes");
7239 if (Offset != 0 || Max >= Indexes.size())
7240 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
7241 if (IsOrdered)
7242 return Error(Loc, "expected uselistorder indexes to change the order");
7244 return false;
7247 /// ParseUseListOrder
7248 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7249 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
7250 SMLoc Loc = Lex.getLoc();
7251 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7252 return true;
7254 Value *V;
7255 SmallVector<unsigned, 16> Indexes;
7256 if (ParseTypeAndValue(V, PFS) ||
7257 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
7258 ParseUseListOrderIndexes(Indexes))
7259 return true;
7261 return sortUseListOrder(V, Indexes, Loc);
7264 /// ParseUseListOrderBB
7265 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7266 bool LLParser::ParseUseListOrderBB() {
7267 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7268 SMLoc Loc = Lex.getLoc();
7269 Lex.Lex();
7271 ValID Fn, Label;
7272 SmallVector<unsigned, 16> Indexes;
7273 if (ParseValID(Fn) ||
7274 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7275 ParseValID(Label) ||
7276 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7277 ParseUseListOrderIndexes(Indexes))
7278 return true;
7280 // Check the function.
7281 GlobalValue *GV;
7282 if (Fn.Kind == ValID::t_GlobalName)
7283 GV = M->getNamedValue(Fn.StrVal);
7284 else if (Fn.Kind == ValID::t_GlobalID)
7285 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7286 else
7287 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7288 if (!GV)
7289 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
7290 auto *F = dyn_cast<Function>(GV);
7291 if (!F)
7292 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7293 if (F->isDeclaration())
7294 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
7296 // Check the basic block.
7297 if (Label.Kind == ValID::t_LocalID)
7298 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
7299 if (Label.Kind != ValID::t_LocalName)
7300 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
7301 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7302 if (!V)
7303 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
7304 if (!isa<BasicBlock>(V))
7305 return Error(Label.Loc, "expected basic block in uselistorder_bb");
7307 return sortUseListOrder(V, Indexes, Loc);
7310 /// ModuleEntry
7311 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7312 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7313 bool LLParser::ParseModuleEntry(unsigned ID) {
7314 assert(Lex.getKind() == lltok::kw_module);
7315 Lex.Lex();
7317 std::string Path;
7318 if (ParseToken(lltok::colon, "expected ':' here") ||
7319 ParseToken(lltok::lparen, "expected '(' here") ||
7320 ParseToken(lltok::kw_path, "expected 'path' here") ||
7321 ParseToken(lltok::colon, "expected ':' here") ||
7322 ParseStringConstant(Path) ||
7323 ParseToken(lltok::comma, "expected ',' here") ||
7324 ParseToken(lltok::kw_hash, "expected 'hash' here") ||
7325 ParseToken(lltok::colon, "expected ':' here") ||
7326 ParseToken(lltok::lparen, "expected '(' here"))
7327 return true;
7329 ModuleHash Hash;
7330 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
7331 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
7332 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
7333 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
7334 ParseUInt32(Hash[4]))
7335 return true;
7337 if (ParseToken(lltok::rparen, "expected ')' here") ||
7338 ParseToken(lltok::rparen, "expected ')' here"))
7339 return true;
7341 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7342 ModuleIdMap[ID] = ModuleEntry->first();
7344 return false;
7347 /// TypeIdEntry
7348 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7349 bool LLParser::ParseTypeIdEntry(unsigned ID) {
7350 assert(Lex.getKind() == lltok::kw_typeid);
7351 Lex.Lex();
7353 std::string Name;
7354 if (ParseToken(lltok::colon, "expected ':' here") ||
7355 ParseToken(lltok::lparen, "expected '(' here") ||
7356 ParseToken(lltok::kw_name, "expected 'name' here") ||
7357 ParseToken(lltok::colon, "expected ':' here") ||
7358 ParseStringConstant(Name))
7359 return true;
7361 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7362 if (ParseToken(lltok::comma, "expected ',' here") ||
7363 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
7364 return true;
7366 // Check if this ID was forward referenced, and if so, update the
7367 // corresponding GUIDs.
7368 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7369 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7370 for (auto TIDRef : FwdRefTIDs->second) {
7371 assert(!*TIDRef.first &&
7372 "Forward referenced type id GUID expected to be 0");
7373 *TIDRef.first = GlobalValue::getGUID(Name);
7375 ForwardRefTypeIds.erase(FwdRefTIDs);
7378 return false;
7381 /// TypeIdSummary
7382 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7383 bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
7384 if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7385 ParseToken(lltok::colon, "expected ':' here") ||
7386 ParseToken(lltok::lparen, "expected '(' here") ||
7387 ParseTypeTestResolution(TIS.TTRes))
7388 return true;
7390 if (EatIfPresent(lltok::comma)) {
7391 // Expect optional wpdResolutions field
7392 if (ParseOptionalWpdResolutions(TIS.WPDRes))
7393 return true;
7396 if (ParseToken(lltok::rparen, "expected ')' here"))
7397 return true;
7399 return false;
7402 /// TypeTestResolution
7403 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
7404 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7405 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7406 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7407 /// [',' 'inlinesBits' ':' UInt64]? ')'
7408 bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
7409 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7410 ParseToken(lltok::colon, "expected ':' here") ||
7411 ParseToken(lltok::lparen, "expected '(' here") ||
7412 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7413 ParseToken(lltok::colon, "expected ':' here"))
7414 return true;
7416 switch (Lex.getKind()) {
7417 case lltok::kw_unsat:
7418 TTRes.TheKind = TypeTestResolution::Unsat;
7419 break;
7420 case lltok::kw_byteArray:
7421 TTRes.TheKind = TypeTestResolution::ByteArray;
7422 break;
7423 case lltok::kw_inline:
7424 TTRes.TheKind = TypeTestResolution::Inline;
7425 break;
7426 case lltok::kw_single:
7427 TTRes.TheKind = TypeTestResolution::Single;
7428 break;
7429 case lltok::kw_allOnes:
7430 TTRes.TheKind = TypeTestResolution::AllOnes;
7431 break;
7432 default:
7433 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7435 Lex.Lex();
7437 if (ParseToken(lltok::comma, "expected ',' here") ||
7438 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7439 ParseToken(lltok::colon, "expected ':' here") ||
7440 ParseUInt32(TTRes.SizeM1BitWidth))
7441 return true;
7443 // Parse optional fields
7444 while (EatIfPresent(lltok::comma)) {
7445 switch (Lex.getKind()) {
7446 case lltok::kw_alignLog2:
7447 Lex.Lex();
7448 if (ParseToken(lltok::colon, "expected ':'") ||
7449 ParseUInt64(TTRes.AlignLog2))
7450 return true;
7451 break;
7452 case lltok::kw_sizeM1:
7453 Lex.Lex();
7454 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
7455 return true;
7456 break;
7457 case lltok::kw_bitMask: {
7458 unsigned Val;
7459 Lex.Lex();
7460 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
7461 return true;
7462 assert(Val <= 0xff);
7463 TTRes.BitMask = (uint8_t)Val;
7464 break;
7466 case lltok::kw_inlineBits:
7467 Lex.Lex();
7468 if (ParseToken(lltok::colon, "expected ':'") ||
7469 ParseUInt64(TTRes.InlineBits))
7470 return true;
7471 break;
7472 default:
7473 return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
7477 if (ParseToken(lltok::rparen, "expected ')' here"))
7478 return true;
7480 return false;
7483 /// OptionalWpdResolutions
7484 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7485 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7486 bool LLParser::ParseOptionalWpdResolutions(
7487 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7488 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7489 ParseToken(lltok::colon, "expected ':' here") ||
7490 ParseToken(lltok::lparen, "expected '(' here"))
7491 return true;
7493 do {
7494 uint64_t Offset;
7495 WholeProgramDevirtResolution WPDRes;
7496 if (ParseToken(lltok::lparen, "expected '(' here") ||
7497 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7498 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7499 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
7500 ParseToken(lltok::rparen, "expected ')' here"))
7501 return true;
7502 WPDResMap[Offset] = WPDRes;
7503 } while (EatIfPresent(lltok::comma));
7505 if (ParseToken(lltok::rparen, "expected ')' here"))
7506 return true;
7508 return false;
7511 /// WpdRes
7512 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7513 /// [',' OptionalResByArg]? ')'
7514 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7515 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
7516 /// [',' OptionalResByArg]? ')'
7517 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7518 /// [',' OptionalResByArg]? ')'
7519 bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7520 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7521 ParseToken(lltok::colon, "expected ':' here") ||
7522 ParseToken(lltok::lparen, "expected '(' here") ||
7523 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7524 ParseToken(lltok::colon, "expected ':' here"))
7525 return true;
7527 switch (Lex.getKind()) {
7528 case lltok::kw_indir:
7529 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
7530 break;
7531 case lltok::kw_singleImpl:
7532 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
7533 break;
7534 case lltok::kw_branchFunnel:
7535 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
7536 break;
7537 default:
7538 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7540 Lex.Lex();
7542 // Parse optional fields
7543 while (EatIfPresent(lltok::comma)) {
7544 switch (Lex.getKind()) {
7545 case lltok::kw_singleImplName:
7546 Lex.Lex();
7547 if (ParseToken(lltok::colon, "expected ':' here") ||
7548 ParseStringConstant(WPDRes.SingleImplName))
7549 return true;
7550 break;
7551 case lltok::kw_resByArg:
7552 if (ParseOptionalResByArg(WPDRes.ResByArg))
7553 return true;
7554 break;
7555 default:
7556 return Error(Lex.getLoc(),
7557 "expected optional WholeProgramDevirtResolution field");
7561 if (ParseToken(lltok::rparen, "expected ')' here"))
7562 return true;
7564 return false;
7567 /// OptionalResByArg
7568 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7569 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7570 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7571 /// 'virtualConstProp' )
7572 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7573 /// [',' 'bit' ':' UInt32]? ')'
7574 bool LLParser::ParseOptionalResByArg(
7575 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
7576 &ResByArg) {
7577 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
7578 ParseToken(lltok::colon, "expected ':' here") ||
7579 ParseToken(lltok::lparen, "expected '(' here"))
7580 return true;
7582 do {
7583 std::vector<uint64_t> Args;
7584 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
7585 ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
7586 ParseToken(lltok::colon, "expected ':' here") ||
7587 ParseToken(lltok::lparen, "expected '(' here") ||
7588 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7589 ParseToken(lltok::colon, "expected ':' here"))
7590 return true;
7592 WholeProgramDevirtResolution::ByArg ByArg;
7593 switch (Lex.getKind()) {
7594 case lltok::kw_indir:
7595 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
7596 break;
7597 case lltok::kw_uniformRetVal:
7598 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
7599 break;
7600 case lltok::kw_uniqueRetVal:
7601 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
7602 break;
7603 case lltok::kw_virtualConstProp:
7604 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
7605 break;
7606 default:
7607 return Error(Lex.getLoc(),
7608 "unexpected WholeProgramDevirtResolution::ByArg kind");
7610 Lex.Lex();
7612 // Parse optional fields
7613 while (EatIfPresent(lltok::comma)) {
7614 switch (Lex.getKind()) {
7615 case lltok::kw_info:
7616 Lex.Lex();
7617 if (ParseToken(lltok::colon, "expected ':' here") ||
7618 ParseUInt64(ByArg.Info))
7619 return true;
7620 break;
7621 case lltok::kw_byte:
7622 Lex.Lex();
7623 if (ParseToken(lltok::colon, "expected ':' here") ||
7624 ParseUInt32(ByArg.Byte))
7625 return true;
7626 break;
7627 case lltok::kw_bit:
7628 Lex.Lex();
7629 if (ParseToken(lltok::colon, "expected ':' here") ||
7630 ParseUInt32(ByArg.Bit))
7631 return true;
7632 break;
7633 default:
7634 return Error(Lex.getLoc(),
7635 "expected optional whole program devirt field");
7639 if (ParseToken(lltok::rparen, "expected ')' here"))
7640 return true;
7642 ResByArg[Args] = ByArg;
7643 } while (EatIfPresent(lltok::comma));
7645 if (ParseToken(lltok::rparen, "expected ')' here"))
7646 return true;
7648 return false;
7651 /// OptionalResByArg
7652 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7653 bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7654 if (ParseToken(lltok::kw_args, "expected 'args' here") ||
7655 ParseToken(lltok::colon, "expected ':' here") ||
7656 ParseToken(lltok::lparen, "expected '(' here"))
7657 return true;
7659 do {
7660 uint64_t Val;
7661 if (ParseUInt64(Val))
7662 return true;
7663 Args.push_back(Val);
7664 } while (EatIfPresent(lltok::comma));
7666 if (ParseToken(lltok::rparen, "expected ')' here"))
7667 return true;
7669 return false;
7672 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
7674 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
7675 bool ReadOnly = Fwd->isReadOnly();
7676 *Fwd = Resolved;
7677 if (ReadOnly)
7678 Fwd->setReadOnly();
7681 /// Stores the given Name/GUID and associated summary into the Index.
7682 /// Also updates any forward references to the associated entry ID.
7683 void LLParser::AddGlobalValueToIndex(
7684 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
7685 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7686 // First create the ValueInfo utilizing the Name or GUID.
7687 ValueInfo VI;
7688 if (GUID != 0) {
7689 assert(Name.empty());
7690 VI = Index->getOrInsertValueInfo(GUID);
7691 } else {
7692 assert(!Name.empty());
7693 if (M) {
7694 auto *GV = M->getNamedValue(Name);
7695 assert(GV);
7696 VI = Index->getOrInsertValueInfo(GV);
7697 } else {
7698 assert(
7699 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
7700 "Need a source_filename to compute GUID for local");
7701 GUID = GlobalValue::getGUID(
7702 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
7703 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7707 // Add the summary if one was provided.
7708 if (Summary)
7709 Index->addGlobalValueSummary(VI, std::move(Summary));
7711 // Resolve forward references from calls/refs
7712 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7713 if (FwdRefVIs != ForwardRefValueInfos.end()) {
7714 for (auto VIRef : FwdRefVIs->second) {
7715 assert(VIRef.first->getRef() == FwdVIRef &&
7716 "Forward referenced ValueInfo expected to be empty");
7717 resolveFwdRef(VIRef.first, VI);
7719 ForwardRefValueInfos.erase(FwdRefVIs);
7722 // Resolve forward references from aliases
7723 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7724 if (FwdRefAliasees != ForwardRefAliasees.end()) {
7725 for (auto AliaseeRef : FwdRefAliasees->second) {
7726 assert(!AliaseeRef.first->hasAliasee() &&
7727 "Forward referencing alias already has aliasee");
7728 AliaseeRef.first->setAliasee(VI.getSummaryList().front().get());
7730 ForwardRefAliasees.erase(FwdRefAliasees);
7733 // Save the associated ValueInfo for use in later references by ID.
7734 if (ID == NumberedValueInfos.size())
7735 NumberedValueInfos.push_back(VI);
7736 else {
7737 // Handle non-continuous numbers (to make test simplification easier).
7738 if (ID > NumberedValueInfos.size())
7739 NumberedValueInfos.resize(ID + 1);
7740 NumberedValueInfos[ID] = VI;
7744 /// ParseGVEntry
7745 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7746 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7747 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7748 bool LLParser::ParseGVEntry(unsigned ID) {
7749 assert(Lex.getKind() == lltok::kw_gv);
7750 Lex.Lex();
7752 if (ParseToken(lltok::colon, "expected ':' here") ||
7753 ParseToken(lltok::lparen, "expected '(' here"))
7754 return true;
7756 std::string Name;
7757 GlobalValue::GUID GUID = 0;
7758 switch (Lex.getKind()) {
7759 case lltok::kw_name:
7760 Lex.Lex();
7761 if (ParseToken(lltok::colon, "expected ':' here") ||
7762 ParseStringConstant(Name))
7763 return true;
7764 // Can't create GUID/ValueInfo until we have the linkage.
7765 break;
7766 case lltok::kw_guid:
7767 Lex.Lex();
7768 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
7769 return true;
7770 break;
7771 default:
7772 return Error(Lex.getLoc(), "expected name or guid tag");
7775 if (!EatIfPresent(lltok::comma)) {
7776 // No summaries. Wrap up.
7777 if (ParseToken(lltok::rparen, "expected ')' here"))
7778 return true;
7779 // This was created for a call to an external or indirect target.
7780 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
7781 // created for indirect calls with VP. A Name with no GUID came from
7782 // an external definition. We pass ExternalLinkage since that is only
7783 // used when the GUID must be computed from Name, and in that case
7784 // the symbol must have external linkage.
7785 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
7786 nullptr);
7787 return false;
7790 // Have a list of summaries
7791 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
7792 ParseToken(lltok::colon, "expected ':' here"))
7793 return true;
7795 do {
7796 if (ParseToken(lltok::lparen, "expected '(' here"))
7797 return true;
7798 switch (Lex.getKind()) {
7799 case lltok::kw_function:
7800 if (ParseFunctionSummary(Name, GUID, ID))
7801 return true;
7802 break;
7803 case lltok::kw_variable:
7804 if (ParseVariableSummary(Name, GUID, ID))
7805 return true;
7806 break;
7807 case lltok::kw_alias:
7808 if (ParseAliasSummary(Name, GUID, ID))
7809 return true;
7810 break;
7811 default:
7812 return Error(Lex.getLoc(), "expected summary type");
7814 if (ParseToken(lltok::rparen, "expected ')' here"))
7815 return true;
7816 } while (EatIfPresent(lltok::comma));
7818 if (ParseToken(lltok::rparen, "expected ')' here"))
7819 return true;
7821 return false;
7824 /// FunctionSummary
7825 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7826 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
7827 /// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
7828 bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
7829 unsigned ID) {
7830 assert(Lex.getKind() == lltok::kw_function);
7831 Lex.Lex();
7833 StringRef ModulePath;
7834 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7835 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7836 /*Live=*/false, /*IsLocal=*/false);
7837 unsigned InstCount;
7838 std::vector<FunctionSummary::EdgeTy> Calls;
7839 FunctionSummary::TypeIdInfo TypeIdInfo;
7840 std::vector<ValueInfo> Refs;
7841 // Default is all-zeros (conservative values).
7842 FunctionSummary::FFlags FFlags = {};
7843 if (ParseToken(lltok::colon, "expected ':' here") ||
7844 ParseToken(lltok::lparen, "expected '(' here") ||
7845 ParseModuleReference(ModulePath) ||
7846 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7847 ParseToken(lltok::comma, "expected ',' here") ||
7848 ParseToken(lltok::kw_insts, "expected 'insts' here") ||
7849 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
7850 return true;
7852 // Parse optional fields
7853 while (EatIfPresent(lltok::comma)) {
7854 switch (Lex.getKind()) {
7855 case lltok::kw_funcFlags:
7856 if (ParseOptionalFFlags(FFlags))
7857 return true;
7858 break;
7859 case lltok::kw_calls:
7860 if (ParseOptionalCalls(Calls))
7861 return true;
7862 break;
7863 case lltok::kw_typeIdInfo:
7864 if (ParseOptionalTypeIdInfo(TypeIdInfo))
7865 return true;
7866 break;
7867 case lltok::kw_refs:
7868 if (ParseOptionalRefs(Refs))
7869 return true;
7870 break;
7871 default:
7872 return Error(Lex.getLoc(), "expected optional function summary field");
7876 if (ParseToken(lltok::rparen, "expected ')' here"))
7877 return true;
7879 auto FS = llvm::make_unique<FunctionSummary>(
7880 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
7881 std::move(Calls), std::move(TypeIdInfo.TypeTests),
7882 std::move(TypeIdInfo.TypeTestAssumeVCalls),
7883 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
7884 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
7885 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
7887 FS->setModulePath(ModulePath);
7889 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7890 ID, std::move(FS));
7892 return false;
7895 /// VariableSummary
7896 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
7897 /// [',' OptionalRefs]? ')'
7898 bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
7899 unsigned ID) {
7900 assert(Lex.getKind() == lltok::kw_variable);
7901 Lex.Lex();
7903 StringRef ModulePath;
7904 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7905 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7906 /*Live=*/false, /*IsLocal=*/false);
7907 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false);
7908 std::vector<ValueInfo> Refs;
7909 if (ParseToken(lltok::colon, "expected ':' here") ||
7910 ParseToken(lltok::lparen, "expected '(' here") ||
7911 ParseModuleReference(ModulePath) ||
7912 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7913 ParseToken(lltok::comma, "expected ',' here") ||
7914 ParseGVarFlags(GVarFlags))
7915 return true;
7917 // Parse optional refs field
7918 if (EatIfPresent(lltok::comma)) {
7919 if (ParseOptionalRefs(Refs))
7920 return true;
7923 if (ParseToken(lltok::rparen, "expected ')' here"))
7924 return true;
7926 auto GS =
7927 llvm::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
7929 GS->setModulePath(ModulePath);
7931 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7932 ID, std::move(GS));
7934 return false;
7937 /// AliasSummary
7938 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
7939 /// 'aliasee' ':' GVReference ')'
7940 bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
7941 unsigned ID) {
7942 assert(Lex.getKind() == lltok::kw_alias);
7943 LocTy Loc = Lex.getLoc();
7944 Lex.Lex();
7946 StringRef ModulePath;
7947 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
7948 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
7949 /*Live=*/false, /*IsLocal=*/false);
7950 if (ParseToken(lltok::colon, "expected ':' here") ||
7951 ParseToken(lltok::lparen, "expected '(' here") ||
7952 ParseModuleReference(ModulePath) ||
7953 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
7954 ParseToken(lltok::comma, "expected ',' here") ||
7955 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
7956 ParseToken(lltok::colon, "expected ':' here"))
7957 return true;
7959 ValueInfo AliaseeVI;
7960 unsigned GVId;
7961 if (ParseGVReference(AliaseeVI, GVId))
7962 return true;
7964 if (ParseToken(lltok::rparen, "expected ')' here"))
7965 return true;
7967 auto AS = llvm::make_unique<AliasSummary>(GVFlags);
7969 AS->setModulePath(ModulePath);
7971 // Record forward reference if the aliasee is not parsed yet.
7972 if (AliaseeVI.getRef() == FwdVIRef) {
7973 auto FwdRef = ForwardRefAliasees.insert(
7974 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
7975 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
7976 } else
7977 AS->setAliasee(AliaseeVI.getSummaryList().front().get());
7979 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
7980 ID, std::move(AS));
7982 return false;
7985 /// Flag
7986 /// ::= [0|1]
7987 bool LLParser::ParseFlag(unsigned &Val) {
7988 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
7989 return TokError("expected integer");
7990 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
7991 Lex.Lex();
7992 return false;
7995 /// OptionalFFlags
7996 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
7997 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
7998 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
7999 /// [',' 'noInline' ':' Flag]? ')'
8000 bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8001 assert(Lex.getKind() == lltok::kw_funcFlags);
8002 Lex.Lex();
8004 if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
8005 ParseToken(lltok::lparen, "expected '(' in funcFlags"))
8006 return true;
8008 do {
8009 unsigned Val;
8010 switch (Lex.getKind()) {
8011 case lltok::kw_readNone:
8012 Lex.Lex();
8013 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8014 return true;
8015 FFlags.ReadNone = Val;
8016 break;
8017 case lltok::kw_readOnly:
8018 Lex.Lex();
8019 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8020 return true;
8021 FFlags.ReadOnly = Val;
8022 break;
8023 case lltok::kw_noRecurse:
8024 Lex.Lex();
8025 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8026 return true;
8027 FFlags.NoRecurse = Val;
8028 break;
8029 case lltok::kw_returnDoesNotAlias:
8030 Lex.Lex();
8031 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8032 return true;
8033 FFlags.ReturnDoesNotAlias = Val;
8034 break;
8035 case lltok::kw_noInline:
8036 Lex.Lex();
8037 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8038 return true;
8039 FFlags.NoInline = Val;
8040 break;
8041 default:
8042 return Error(Lex.getLoc(), "expected function flag type");
8044 } while (EatIfPresent(lltok::comma));
8046 if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
8047 return true;
8049 return false;
8052 /// OptionalCalls
8053 /// := 'calls' ':' '(' Call [',' Call]* ')'
8054 /// Call ::= '(' 'callee' ':' GVReference
8055 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8056 bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8057 assert(Lex.getKind() == lltok::kw_calls);
8058 Lex.Lex();
8060 if (ParseToken(lltok::colon, "expected ':' in calls") |
8061 ParseToken(lltok::lparen, "expected '(' in calls"))
8062 return true;
8064 IdToIndexMapType IdToIndexMap;
8065 // Parse each call edge
8066 do {
8067 ValueInfo VI;
8068 if (ParseToken(lltok::lparen, "expected '(' in call") ||
8069 ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
8070 ParseToken(lltok::colon, "expected ':'"))
8071 return true;
8073 LocTy Loc = Lex.getLoc();
8074 unsigned GVId;
8075 if (ParseGVReference(VI, GVId))
8076 return true;
8078 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8079 unsigned RelBF = 0;
8080 if (EatIfPresent(lltok::comma)) {
8081 // Expect either hotness or relbf
8082 if (EatIfPresent(lltok::kw_hotness)) {
8083 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
8084 return true;
8085 } else {
8086 if (ParseToken(lltok::kw_relbf, "expected relbf") ||
8087 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
8088 return true;
8091 // Keep track of the Call array index needing a forward reference.
8092 // We will save the location of the ValueInfo needing an update, but
8093 // can only do so once the std::vector is finalized.
8094 if (VI.getRef() == FwdVIRef)
8095 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8096 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8098 if (ParseToken(lltok::rparen, "expected ')' in call"))
8099 return true;
8100 } while (EatIfPresent(lltok::comma));
8102 // Now that the Calls vector is finalized, it is safe to save the locations
8103 // of any forward GV references that need updating later.
8104 for (auto I : IdToIndexMap) {
8105 for (auto P : I.second) {
8106 assert(Calls[P.first].first.getRef() == FwdVIRef &&
8107 "Forward referenced ValueInfo expected to be empty");
8108 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8109 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8110 FwdRef.first->second.push_back(
8111 std::make_pair(&Calls[P.first].first, P.second));
8115 if (ParseToken(lltok::rparen, "expected ')' in calls"))
8116 return true;
8118 return false;
8121 /// Hotness
8122 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
8123 bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
8124 switch (Lex.getKind()) {
8125 case lltok::kw_unknown:
8126 Hotness = CalleeInfo::HotnessType::Unknown;
8127 break;
8128 case lltok::kw_cold:
8129 Hotness = CalleeInfo::HotnessType::Cold;
8130 break;
8131 case lltok::kw_none:
8132 Hotness = CalleeInfo::HotnessType::None;
8133 break;
8134 case lltok::kw_hot:
8135 Hotness = CalleeInfo::HotnessType::Hot;
8136 break;
8137 case lltok::kw_critical:
8138 Hotness = CalleeInfo::HotnessType::Critical;
8139 break;
8140 default:
8141 return Error(Lex.getLoc(), "invalid call edge hotness");
8143 Lex.Lex();
8144 return false;
8147 /// OptionalRefs
8148 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8149 bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
8150 assert(Lex.getKind() == lltok::kw_refs);
8151 Lex.Lex();
8153 if (ParseToken(lltok::colon, "expected ':' in refs") |
8154 ParseToken(lltok::lparen, "expected '(' in refs"))
8155 return true;
8157 struct ValueContext {
8158 ValueInfo VI;
8159 unsigned GVId;
8160 LocTy Loc;
8162 std::vector<ValueContext> VContexts;
8163 // Parse each ref edge
8164 do {
8165 ValueContext VC;
8166 VC.Loc = Lex.getLoc();
8167 if (ParseGVReference(VC.VI, VC.GVId))
8168 return true;
8169 VContexts.push_back(VC);
8170 } while (EatIfPresent(lltok::comma));
8172 // Sort value contexts so that ones with readonly ValueInfo are at the end
8173 // of VContexts vector. This is needed to match immutableRefCount() behavior.
8174 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
8175 return VC1.VI.isReadOnly() < VC2.VI.isReadOnly();
8178 IdToIndexMapType IdToIndexMap;
8179 for (auto &VC : VContexts) {
8180 // Keep track of the Refs array index needing a forward reference.
8181 // We will save the location of the ValueInfo needing an update, but
8182 // can only do so once the std::vector is finalized.
8183 if (VC.VI.getRef() == FwdVIRef)
8184 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
8185 Refs.push_back(VC.VI);
8188 // Now that the Refs vector is finalized, it is safe to save the locations
8189 // of any forward GV references that need updating later.
8190 for (auto I : IdToIndexMap) {
8191 for (auto P : I.second) {
8192 assert(Refs[P.first].getRef() == FwdVIRef &&
8193 "Forward referenced ValueInfo expected to be empty");
8194 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8195 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8196 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
8200 if (ParseToken(lltok::rparen, "expected ')' in refs"))
8201 return true;
8203 return false;
8206 /// OptionalTypeIdInfo
8207 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8208 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8209 /// [',' TypeCheckedLoadConstVCalls]? ')'
8210 bool LLParser::ParseOptionalTypeIdInfo(
8211 FunctionSummary::TypeIdInfo &TypeIdInfo) {
8212 assert(Lex.getKind() == lltok::kw_typeIdInfo);
8213 Lex.Lex();
8215 if (ParseToken(lltok::colon, "expected ':' here") ||
8216 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8217 return true;
8219 do {
8220 switch (Lex.getKind()) {
8221 case lltok::kw_typeTests:
8222 if (ParseTypeTests(TypeIdInfo.TypeTests))
8223 return true;
8224 break;
8225 case lltok::kw_typeTestAssumeVCalls:
8226 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
8227 TypeIdInfo.TypeTestAssumeVCalls))
8228 return true;
8229 break;
8230 case lltok::kw_typeCheckedLoadVCalls:
8231 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
8232 TypeIdInfo.TypeCheckedLoadVCalls))
8233 return true;
8234 break;
8235 case lltok::kw_typeTestAssumeConstVCalls:
8236 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
8237 TypeIdInfo.TypeTestAssumeConstVCalls))
8238 return true;
8239 break;
8240 case lltok::kw_typeCheckedLoadConstVCalls:
8241 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
8242 TypeIdInfo.TypeCheckedLoadConstVCalls))
8243 return true;
8244 break;
8245 default:
8246 return Error(Lex.getLoc(), "invalid typeIdInfo list type");
8248 } while (EatIfPresent(lltok::comma));
8250 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8251 return true;
8253 return false;
8256 /// TypeTests
8257 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8258 /// [',' (SummaryID | UInt64)]* ')'
8259 bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
8260 assert(Lex.getKind() == lltok::kw_typeTests);
8261 Lex.Lex();
8263 if (ParseToken(lltok::colon, "expected ':' here") ||
8264 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8265 return true;
8267 IdToIndexMapType IdToIndexMap;
8268 do {
8269 GlobalValue::GUID GUID = 0;
8270 if (Lex.getKind() == lltok::SummaryID) {
8271 unsigned ID = Lex.getUIntVal();
8272 LocTy Loc = Lex.getLoc();
8273 // Keep track of the TypeTests array index needing a forward reference.
8274 // We will save the location of the GUID needing an update, but
8275 // can only do so once the std::vector is finalized.
8276 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
8277 Lex.Lex();
8278 } else if (ParseUInt64(GUID))
8279 return true;
8280 TypeTests.push_back(GUID);
8281 } while (EatIfPresent(lltok::comma));
8283 // Now that the TypeTests vector is finalized, it is safe to save the
8284 // locations of any forward GV references that need updating later.
8285 for (auto I : IdToIndexMap) {
8286 for (auto P : I.second) {
8287 assert(TypeTests[P.first] == 0 &&
8288 "Forward referenced type id GUID expected to be 0");
8289 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8290 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8291 FwdRef.first->second.push_back(
8292 std::make_pair(&TypeTests[P.first], P.second));
8296 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8297 return true;
8299 return false;
8302 /// VFuncIdList
8303 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
8304 bool LLParser::ParseVFuncIdList(
8305 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
8306 assert(Lex.getKind() == Kind);
8307 Lex.Lex();
8309 if (ParseToken(lltok::colon, "expected ':' here") ||
8310 ParseToken(lltok::lparen, "expected '(' here"))
8311 return true;
8313 IdToIndexMapType IdToIndexMap;
8314 do {
8315 FunctionSummary::VFuncId VFuncId;
8316 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
8317 return true;
8318 VFuncIdList.push_back(VFuncId);
8319 } while (EatIfPresent(lltok::comma));
8321 if (ParseToken(lltok::rparen, "expected ')' here"))
8322 return true;
8324 // Now that the VFuncIdList vector is finalized, it is safe to save the
8325 // locations of any forward GV references that need updating later.
8326 for (auto I : IdToIndexMap) {
8327 for (auto P : I.second) {
8328 assert(VFuncIdList[P.first].GUID == 0 &&
8329 "Forward referenced type id GUID expected to be 0");
8330 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8331 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8332 FwdRef.first->second.push_back(
8333 std::make_pair(&VFuncIdList[P.first].GUID, P.second));
8337 return false;
8340 /// ConstVCallList
8341 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8342 bool LLParser::ParseConstVCallList(
8343 lltok::Kind Kind,
8344 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8345 assert(Lex.getKind() == Kind);
8346 Lex.Lex();
8348 if (ParseToken(lltok::colon, "expected ':' here") ||
8349 ParseToken(lltok::lparen, "expected '(' here"))
8350 return true;
8352 IdToIndexMapType IdToIndexMap;
8353 do {
8354 FunctionSummary::ConstVCall ConstVCall;
8355 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8356 return true;
8357 ConstVCallList.push_back(ConstVCall);
8358 } while (EatIfPresent(lltok::comma));
8360 if (ParseToken(lltok::rparen, "expected ')' here"))
8361 return true;
8363 // Now that the ConstVCallList vector is finalized, it is safe to save the
8364 // locations of any forward GV references that need updating later.
8365 for (auto I : IdToIndexMap) {
8366 for (auto P : I.second) {
8367 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8368 "Forward referenced type id GUID expected to be 0");
8369 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8370 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8371 FwdRef.first->second.push_back(
8372 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8376 return false;
8379 /// ConstVCall
8380 /// ::= '(' VFuncId ',' Args ')'
8381 bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
8382 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8383 if (ParseToken(lltok::lparen, "expected '(' here") ||
8384 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
8385 return true;
8387 if (EatIfPresent(lltok::comma))
8388 if (ParseArgs(ConstVCall.Args))
8389 return true;
8391 if (ParseToken(lltok::rparen, "expected ')' here"))
8392 return true;
8394 return false;
8397 /// VFuncId
8398 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8399 /// 'offset' ':' UInt64 ')'
8400 bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
8401 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8402 assert(Lex.getKind() == lltok::kw_vFuncId);
8403 Lex.Lex();
8405 if (ParseToken(lltok::colon, "expected ':' here") ||
8406 ParseToken(lltok::lparen, "expected '(' here"))
8407 return true;
8409 if (Lex.getKind() == lltok::SummaryID) {
8410 VFuncId.GUID = 0;
8411 unsigned ID = Lex.getUIntVal();
8412 LocTy Loc = Lex.getLoc();
8413 // Keep track of the array index needing a forward reference.
8414 // We will save the location of the GUID needing an update, but
8415 // can only do so once the caller's std::vector is finalized.
8416 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
8417 Lex.Lex();
8418 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
8419 ParseToken(lltok::colon, "expected ':' here") ||
8420 ParseUInt64(VFuncId.GUID))
8421 return true;
8423 if (ParseToken(lltok::comma, "expected ',' here") ||
8424 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
8425 ParseToken(lltok::colon, "expected ':' here") ||
8426 ParseUInt64(VFuncId.Offset) ||
8427 ParseToken(lltok::rparen, "expected ')' here"))
8428 return true;
8430 return false;
8433 /// GVFlags
8434 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8435 /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8436 /// 'dsoLocal' ':' Flag ')'
8437 bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
8438 assert(Lex.getKind() == lltok::kw_flags);
8439 Lex.Lex();
8441 bool HasLinkage;
8442 if (ParseToken(lltok::colon, "expected ':' here") ||
8443 ParseToken(lltok::lparen, "expected '(' here") ||
8444 ParseToken(lltok::kw_linkage, "expected 'linkage' here") ||
8445 ParseToken(lltok::colon, "expected ':' here"))
8446 return true;
8448 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
8449 assert(HasLinkage && "Linkage not optional in summary entry");
8450 Lex.Lex();
8452 unsigned Flag;
8453 if (ParseToken(lltok::comma, "expected ',' here") ||
8454 ParseToken(lltok::kw_notEligibleToImport,
8455 "expected 'notEligibleToImport' here") ||
8456 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8457 return true;
8458 GVFlags.NotEligibleToImport = Flag;
8460 if (ParseToken(lltok::comma, "expected ',' here") ||
8461 ParseToken(lltok::kw_live, "expected 'live' here") ||
8462 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8463 return true;
8464 GVFlags.Live = Flag;
8466 if (ParseToken(lltok::comma, "expected ',' here") ||
8467 ParseToken(lltok::kw_dsoLocal, "expected 'dsoLocal' here") ||
8468 ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
8469 return true;
8470 GVFlags.DSOLocal = Flag;
8472 if (ParseToken(lltok::rparen, "expected ')' here"))
8473 return true;
8475 return false;
8478 /// GVarFlags
8479 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag ')'
8480 bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
8481 assert(Lex.getKind() == lltok::kw_varFlags);
8482 Lex.Lex();
8484 unsigned Flag;
8485 if (ParseToken(lltok::colon, "expected ':' here") ||
8486 ParseToken(lltok::lparen, "expected '(' here") ||
8487 ParseToken(lltok::kw_readonly, "expected 'readonly' here") ||
8488 ParseToken(lltok::colon, "expected ':' here"))
8489 return true;
8491 ParseFlag(Flag);
8492 GVarFlags.ReadOnly = Flag;
8494 if (ParseToken(lltok::rparen, "expected ')' here"))
8495 return true;
8496 return false;
8499 /// ModuleReference
8500 /// ::= 'module' ':' UInt
8501 bool LLParser::ParseModuleReference(StringRef &ModulePath) {
8502 // Parse module id.
8503 if (ParseToken(lltok::kw_module, "expected 'module' here") ||
8504 ParseToken(lltok::colon, "expected ':' here") ||
8505 ParseToken(lltok::SummaryID, "expected module ID"))
8506 return true;
8508 unsigned ModuleID = Lex.getUIntVal();
8509 auto I = ModuleIdMap.find(ModuleID);
8510 // We should have already parsed all module IDs
8511 assert(I != ModuleIdMap.end());
8512 ModulePath = I->second;
8513 return false;
8516 /// GVReference
8517 /// ::= SummaryID
8518 bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
8519 bool ReadOnly = EatIfPresent(lltok::kw_readonly);
8520 if (ParseToken(lltok::SummaryID, "expected GV ID"))
8521 return true;
8523 GVId = Lex.getUIntVal();
8524 // Check if we already have a VI for this GV
8525 if (GVId < NumberedValueInfos.size()) {
8526 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
8527 VI = NumberedValueInfos[GVId];
8528 } else
8529 // We will create a forward reference to the stored location.
8530 VI = ValueInfo(false, FwdVIRef);
8532 if (ReadOnly)
8533 VI.setReadOnly();
8534 return false;