[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / llvm / lib / AsmParser / LLParser.cpp
blobfd502eded0a0499e567d4afc21ee3ce2b3b94a1f
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 "llvm/AsmParser/LLParser.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/LLToken.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/BinaryFormat/Dwarf.h"
22 #include "llvm/IR/Argument.h"
23 #include "llvm/IR/AutoUpgrade.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/CallingConv.h"
26 #include "llvm/IR/Comdat.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DebugInfoMetadata.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalIFunc.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Operator.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 <vector>
53 using namespace llvm;
55 static std::string getTypeString(Type *T) {
56 std::string Result;
57 raw_string_ostream Tmp(Result);
58 Tmp << *T;
59 return Tmp.str();
62 static void setContextOpaquePointers(LLLexer &L, LLVMContext &C) {
63 while (true) {
64 lltok::Kind K = L.Lex();
65 // LLLexer will set the opaque pointers option in LLVMContext if it sees an
66 // explicit "ptr".
67 if (K == lltok::star || K == lltok::Error || K == lltok::Eof ||
68 isa_and_nonnull<PointerType>(L.getTyVal())) {
69 if (K == lltok::star)
70 C.setOpaquePointers(false);
71 return;
76 /// Run: module ::= toplevelentity*
77 bool LLParser::Run(bool UpgradeDebugInfo,
78 DataLayoutCallbackTy DataLayoutCallback) {
79 // If we haven't decided on whether or not we're using opaque pointers, do a
80 // quick lex over the tokens to see if we explicitly construct any typed or
81 // opaque pointer types.
82 // Don't bail out on an error so we do the same work in the parsing below
83 // regardless of if --opaque-pointers is set.
84 if (!Context.hasSetOpaquePointersValue())
85 setContextOpaquePointers(OPLex, Context);
87 // Prime the lexer.
88 Lex.Lex();
90 if (Context.shouldDiscardValueNames())
91 return error(
92 Lex.getLoc(),
93 "Can't read textual IR with a Context that discards named Values");
95 if (M) {
96 if (parseTargetDefinitions())
97 return true;
99 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple()))
100 M->setDataLayout(*LayoutOverride);
103 return parseTopLevelEntities() || validateEndOfModule(UpgradeDebugInfo) ||
104 validateEndOfIndex();
107 bool LLParser::parseStandaloneConstantValue(Constant *&C,
108 const SlotMapping *Slots) {
109 restoreParsingState(Slots);
110 Lex.Lex();
112 Type *Ty = nullptr;
113 if (parseType(Ty) || parseConstantValue(Ty, C))
114 return true;
115 if (Lex.getKind() != lltok::Eof)
116 return error(Lex.getLoc(), "expected end of string");
117 return false;
120 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
121 const SlotMapping *Slots) {
122 restoreParsingState(Slots);
123 Lex.Lex();
125 Read = 0;
126 SMLoc Start = Lex.getLoc();
127 Ty = nullptr;
128 if (parseType(Ty))
129 return true;
130 SMLoc End = Lex.getLoc();
131 Read = End.getPointer() - Start.getPointer();
133 return false;
136 void LLParser::restoreParsingState(const SlotMapping *Slots) {
137 if (!Slots)
138 return;
139 NumberedVals = Slots->GlobalValues;
140 NumberedMetadata = Slots->MetadataNodes;
141 for (const auto &I : Slots->NamedTypes)
142 NamedTypes.insert(
143 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
144 for (const auto &I : Slots->Types)
145 NumberedTypes.insert(
146 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
149 /// validateEndOfModule - Do final validity and basic correctness checks at the
150 /// end of the module.
151 bool LLParser::validateEndOfModule(bool UpgradeDebugInfo) {
152 if (!M)
153 return false;
154 // Handle any function attribute group forward references.
155 for (const auto &RAG : ForwardRefAttrGroups) {
156 Value *V = RAG.first;
157 const std::vector<unsigned> &Attrs = RAG.second;
158 AttrBuilder B(Context);
160 for (const auto &Attr : Attrs) {
161 auto R = NumberedAttrBuilders.find(Attr);
162 if (R != NumberedAttrBuilders.end())
163 B.merge(R->second);
166 if (Function *Fn = dyn_cast<Function>(V)) {
167 AttributeList AS = Fn->getAttributes();
168 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
169 AS = AS.removeFnAttributes(Context);
171 FnAttrs.merge(B);
173 // If the alignment was parsed as an attribute, move to the alignment
174 // field.
175 if (FnAttrs.hasAlignmentAttr()) {
176 Fn->setAlignment(FnAttrs.getAlignment());
177 FnAttrs.removeAttribute(Attribute::Alignment);
180 AS = AS.addFnAttributes(Context, FnAttrs);
181 Fn->setAttributes(AS);
182 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
183 AttributeList AS = CI->getAttributes();
184 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
185 AS = AS.removeFnAttributes(Context);
186 FnAttrs.merge(B);
187 AS = AS.addFnAttributes(Context, FnAttrs);
188 CI->setAttributes(AS);
189 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
190 AttributeList AS = II->getAttributes();
191 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
192 AS = AS.removeFnAttributes(Context);
193 FnAttrs.merge(B);
194 AS = AS.addFnAttributes(Context, FnAttrs);
195 II->setAttributes(AS);
196 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
197 AttributeList AS = CBI->getAttributes();
198 AttrBuilder FnAttrs(M->getContext(), AS.getFnAttrs());
199 AS = AS.removeFnAttributes(Context);
200 FnAttrs.merge(B);
201 AS = AS.addFnAttributes(Context, FnAttrs);
202 CBI->setAttributes(AS);
203 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
204 AttrBuilder Attrs(M->getContext(), GV->getAttributes());
205 Attrs.merge(B);
206 GV->setAttributes(AttributeSet::get(Context,Attrs));
207 } else {
208 llvm_unreachable("invalid object with forward attribute group reference");
212 // If there are entries in ForwardRefBlockAddresses at this point, the
213 // function was never defined.
214 if (!ForwardRefBlockAddresses.empty())
215 return error(ForwardRefBlockAddresses.begin()->first.Loc,
216 "expected function name in blockaddress");
218 for (const auto &NT : NumberedTypes)
219 if (NT.second.second.isValid())
220 return error(NT.second.second,
221 "use of undefined type '%" + Twine(NT.first) + "'");
223 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
224 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
225 if (I->second.second.isValid())
226 return error(I->second.second,
227 "use of undefined type named '" + I->getKey() + "'");
229 if (!ForwardRefComdats.empty())
230 return error(ForwardRefComdats.begin()->second,
231 "use of undefined comdat '$" +
232 ForwardRefComdats.begin()->first + "'");
234 if (!ForwardRefVals.empty())
235 return error(ForwardRefVals.begin()->second.second,
236 "use of undefined value '@" + ForwardRefVals.begin()->first +
237 "'");
239 if (!ForwardRefValIDs.empty())
240 return error(ForwardRefValIDs.begin()->second.second,
241 "use of undefined value '@" +
242 Twine(ForwardRefValIDs.begin()->first) + "'");
244 if (!ForwardRefMDNodes.empty())
245 return error(ForwardRefMDNodes.begin()->second.second,
246 "use of undefined metadata '!" +
247 Twine(ForwardRefMDNodes.begin()->first) + "'");
249 // Resolve metadata cycles.
250 for (auto &N : NumberedMetadata) {
251 if (N.second && !N.second->isResolved())
252 N.second->resolveCycles();
255 for (auto *Inst : InstsWithTBAATag) {
256 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
257 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
258 auto *UpgradedMD = UpgradeTBAANode(*MD);
259 if (MD != UpgradedMD)
260 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
263 // Look for intrinsic functions and CallInst that need to be upgraded. We use
264 // make_early_inc_range here because we may remove some functions.
265 for (Function &F : llvm::make_early_inc_range(*M))
266 UpgradeCallsToIntrinsic(&F);
268 // Some types could be renamed during loading if several modules are
269 // loaded in the same LLVMContext (LTO scenario). In this case we should
270 // remangle intrinsics names as well.
271 for (Function &F : llvm::make_early_inc_range(*M)) {
272 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F)) {
273 F.replaceAllUsesWith(*Remangled);
274 F.eraseFromParent();
278 if (UpgradeDebugInfo)
279 llvm::UpgradeDebugInfo(*M);
281 UpgradeModuleFlags(*M);
282 UpgradeSectionAttributes(*M);
284 if (!Slots)
285 return false;
286 // Initialize the slot mapping.
287 // Because by this point we've parsed and validated everything, we can "steal"
288 // the mapping from LLParser as it doesn't need it anymore.
289 Slots->GlobalValues = std::move(NumberedVals);
290 Slots->MetadataNodes = std::move(NumberedMetadata);
291 for (const auto &I : NamedTypes)
292 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
293 for (const auto &I : NumberedTypes)
294 Slots->Types.insert(std::make_pair(I.first, I.second.first));
296 return false;
299 /// Do final validity and basic correctness checks at the end of the index.
300 bool LLParser::validateEndOfIndex() {
301 if (!Index)
302 return false;
304 if (!ForwardRefValueInfos.empty())
305 return error(ForwardRefValueInfos.begin()->second.front().second,
306 "use of undefined summary '^" +
307 Twine(ForwardRefValueInfos.begin()->first) + "'");
309 if (!ForwardRefAliasees.empty())
310 return error(ForwardRefAliasees.begin()->second.front().second,
311 "use of undefined summary '^" +
312 Twine(ForwardRefAliasees.begin()->first) + "'");
314 if (!ForwardRefTypeIds.empty())
315 return error(ForwardRefTypeIds.begin()->second.front().second,
316 "use of undefined type id summary '^" +
317 Twine(ForwardRefTypeIds.begin()->first) + "'");
319 return false;
322 //===----------------------------------------------------------------------===//
323 // Top-Level Entities
324 //===----------------------------------------------------------------------===//
326 bool LLParser::parseTargetDefinitions() {
327 while (true) {
328 switch (Lex.getKind()) {
329 case lltok::kw_target:
330 if (parseTargetDefinition())
331 return true;
332 break;
333 case lltok::kw_source_filename:
334 if (parseSourceFileName())
335 return true;
336 break;
337 default:
338 return false;
343 bool LLParser::parseTopLevelEntities() {
344 // If there is no Module, then parse just the summary index entries.
345 if (!M) {
346 while (true) {
347 switch (Lex.getKind()) {
348 case lltok::Eof:
349 return false;
350 case lltok::SummaryID:
351 if (parseSummaryEntry())
352 return true;
353 break;
354 case lltok::kw_source_filename:
355 if (parseSourceFileName())
356 return true;
357 break;
358 default:
359 // Skip everything else
360 Lex.Lex();
364 while (true) {
365 switch (Lex.getKind()) {
366 default:
367 return tokError("expected top-level entity");
368 case lltok::Eof: return false;
369 case lltok::kw_declare:
370 if (parseDeclare())
371 return true;
372 break;
373 case lltok::kw_define:
374 if (parseDefine())
375 return true;
376 break;
377 case lltok::kw_module:
378 if (parseModuleAsm())
379 return true;
380 break;
381 case lltok::LocalVarID:
382 if (parseUnnamedType())
383 return true;
384 break;
385 case lltok::LocalVar:
386 if (parseNamedType())
387 return true;
388 break;
389 case lltok::GlobalID:
390 if (parseUnnamedGlobal())
391 return true;
392 break;
393 case lltok::GlobalVar:
394 if (parseNamedGlobal())
395 return true;
396 break;
397 case lltok::ComdatVar: if (parseComdat()) return true; break;
398 case lltok::exclaim:
399 if (parseStandaloneMetadata())
400 return true;
401 break;
402 case lltok::SummaryID:
403 if (parseSummaryEntry())
404 return true;
405 break;
406 case lltok::MetadataVar:
407 if (parseNamedMetadata())
408 return true;
409 break;
410 case lltok::kw_attributes:
411 if (parseUnnamedAttrGrp())
412 return true;
413 break;
414 case lltok::kw_uselistorder:
415 if (parseUseListOrder())
416 return true;
417 break;
418 case lltok::kw_uselistorder_bb:
419 if (parseUseListOrderBB())
420 return true;
421 break;
426 /// toplevelentity
427 /// ::= 'module' 'asm' STRINGCONSTANT
428 bool LLParser::parseModuleAsm() {
429 assert(Lex.getKind() == lltok::kw_module);
430 Lex.Lex();
432 std::string AsmStr;
433 if (parseToken(lltok::kw_asm, "expected 'module asm'") ||
434 parseStringConstant(AsmStr))
435 return true;
437 M->appendModuleInlineAsm(AsmStr);
438 return false;
441 /// toplevelentity
442 /// ::= 'target' 'triple' '=' STRINGCONSTANT
443 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
444 bool LLParser::parseTargetDefinition() {
445 assert(Lex.getKind() == lltok::kw_target);
446 std::string Str;
447 switch (Lex.Lex()) {
448 default:
449 return tokError("unknown target property");
450 case lltok::kw_triple:
451 Lex.Lex();
452 if (parseToken(lltok::equal, "expected '=' after target triple") ||
453 parseStringConstant(Str))
454 return true;
455 M->setTargetTriple(Str);
456 return false;
457 case lltok::kw_datalayout:
458 Lex.Lex();
459 if (parseToken(lltok::equal, "expected '=' after target datalayout"))
460 return true;
461 LocTy Loc = Lex.getLoc();
462 if (parseStringConstant(Str))
463 return true;
464 Expected<DataLayout> MaybeDL = DataLayout::parse(Str);
465 if (!MaybeDL)
466 return error(Loc, toString(MaybeDL.takeError()));
467 M->setDataLayout(MaybeDL.get());
468 return false;
472 /// toplevelentity
473 /// ::= 'source_filename' '=' STRINGCONSTANT
474 bool LLParser::parseSourceFileName() {
475 assert(Lex.getKind() == lltok::kw_source_filename);
476 Lex.Lex();
477 if (parseToken(lltok::equal, "expected '=' after source_filename") ||
478 parseStringConstant(SourceFileName))
479 return true;
480 if (M)
481 M->setSourceFileName(SourceFileName);
482 return false;
485 /// parseUnnamedType:
486 /// ::= LocalVarID '=' 'type' type
487 bool LLParser::parseUnnamedType() {
488 LocTy TypeLoc = Lex.getLoc();
489 unsigned TypeID = Lex.getUIntVal();
490 Lex.Lex(); // eat LocalVarID;
492 if (parseToken(lltok::equal, "expected '=' after name") ||
493 parseToken(lltok::kw_type, "expected 'type' after '='"))
494 return true;
496 Type *Result = nullptr;
497 if (parseStructDefinition(TypeLoc, "", NumberedTypes[TypeID], Result))
498 return true;
500 if (!isa<StructType>(Result)) {
501 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
502 if (Entry.first)
503 return error(TypeLoc, "non-struct types may not be recursive");
504 Entry.first = Result;
505 Entry.second = SMLoc();
508 return false;
511 /// toplevelentity
512 /// ::= LocalVar '=' 'type' type
513 bool LLParser::parseNamedType() {
514 std::string Name = Lex.getStrVal();
515 LocTy NameLoc = Lex.getLoc();
516 Lex.Lex(); // eat LocalVar.
518 if (parseToken(lltok::equal, "expected '=' after name") ||
519 parseToken(lltok::kw_type, "expected 'type' after name"))
520 return true;
522 Type *Result = nullptr;
523 if (parseStructDefinition(NameLoc, Name, NamedTypes[Name], Result))
524 return true;
526 if (!isa<StructType>(Result)) {
527 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
528 if (Entry.first)
529 return error(NameLoc, "non-struct types may not be recursive");
530 Entry.first = Result;
531 Entry.second = SMLoc();
534 return false;
537 /// toplevelentity
538 /// ::= 'declare' FunctionHeader
539 bool LLParser::parseDeclare() {
540 assert(Lex.getKind() == lltok::kw_declare);
541 Lex.Lex();
543 std::vector<std::pair<unsigned, MDNode *>> MDs;
544 while (Lex.getKind() == lltok::MetadataVar) {
545 unsigned MDK;
546 MDNode *N;
547 if (parseMetadataAttachment(MDK, N))
548 return true;
549 MDs.push_back({MDK, N});
552 Function *F;
553 if (parseFunctionHeader(F, false))
554 return true;
555 for (auto &MD : MDs)
556 F->addMetadata(MD.first, *MD.second);
557 return false;
560 /// toplevelentity
561 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
562 bool LLParser::parseDefine() {
563 assert(Lex.getKind() == lltok::kw_define);
564 Lex.Lex();
566 Function *F;
567 return parseFunctionHeader(F, true) || parseOptionalFunctionMetadata(*F) ||
568 parseFunctionBody(*F);
571 /// parseGlobalType
572 /// ::= 'constant'
573 /// ::= 'global'
574 bool LLParser::parseGlobalType(bool &IsConstant) {
575 if (Lex.getKind() == lltok::kw_constant)
576 IsConstant = true;
577 else if (Lex.getKind() == lltok::kw_global)
578 IsConstant = false;
579 else {
580 IsConstant = false;
581 return tokError("expected 'global' or 'constant'");
583 Lex.Lex();
584 return false;
587 bool LLParser::parseOptionalUnnamedAddr(
588 GlobalVariable::UnnamedAddr &UnnamedAddr) {
589 if (EatIfPresent(lltok::kw_unnamed_addr))
590 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
591 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
592 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
593 else
594 UnnamedAddr = GlobalValue::UnnamedAddr::None;
595 return false;
598 /// parseUnnamedGlobal:
599 /// OptionalVisibility (ALIAS | IFUNC) ...
600 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
601 /// OptionalDLLStorageClass
602 /// ... -> global variable
603 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
604 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier
605 /// OptionalVisibility
606 /// OptionalDLLStorageClass
607 /// ... -> global variable
608 bool LLParser::parseUnnamedGlobal() {
609 unsigned VarID = NumberedVals.size();
610 std::string Name;
611 LocTy NameLoc = Lex.getLoc();
613 // Handle the GlobalID form.
614 if (Lex.getKind() == lltok::GlobalID) {
615 if (Lex.getUIntVal() != VarID)
616 return error(Lex.getLoc(),
617 "variable expected to be numbered '%" + Twine(VarID) + "'");
618 Lex.Lex(); // eat GlobalID;
620 if (parseToken(lltok::equal, "expected '=' after name"))
621 return true;
624 bool HasLinkage;
625 unsigned Linkage, Visibility, DLLStorageClass;
626 bool DSOLocal;
627 GlobalVariable::ThreadLocalMode TLM;
628 GlobalVariable::UnnamedAddr UnnamedAddr;
629 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
630 DSOLocal) ||
631 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
632 return true;
634 switch (Lex.getKind()) {
635 default:
636 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
637 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
638 case lltok::kw_alias:
639 case lltok::kw_ifunc:
640 return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility,
641 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
645 /// parseNamedGlobal:
646 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
647 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
648 /// OptionalVisibility OptionalDLLStorageClass
649 /// ... -> global variable
650 bool LLParser::parseNamedGlobal() {
651 assert(Lex.getKind() == lltok::GlobalVar);
652 LocTy NameLoc = Lex.getLoc();
653 std::string Name = Lex.getStrVal();
654 Lex.Lex();
656 bool HasLinkage;
657 unsigned Linkage, Visibility, DLLStorageClass;
658 bool DSOLocal;
659 GlobalVariable::ThreadLocalMode TLM;
660 GlobalVariable::UnnamedAddr UnnamedAddr;
661 if (parseToken(lltok::equal, "expected '=' in global variable") ||
662 parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
663 DSOLocal) ||
664 parseOptionalThreadLocal(TLM) || parseOptionalUnnamedAddr(UnnamedAddr))
665 return true;
667 switch (Lex.getKind()) {
668 default:
669 return parseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
670 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
671 case lltok::kw_alias:
672 case lltok::kw_ifunc:
673 return parseAliasOrIFunc(Name, NameLoc, Linkage, Visibility,
674 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
678 bool LLParser::parseComdat() {
679 assert(Lex.getKind() == lltok::ComdatVar);
680 std::string Name = Lex.getStrVal();
681 LocTy NameLoc = Lex.getLoc();
682 Lex.Lex();
684 if (parseToken(lltok::equal, "expected '=' here"))
685 return true;
687 if (parseToken(lltok::kw_comdat, "expected comdat keyword"))
688 return tokError("expected comdat type");
690 Comdat::SelectionKind SK;
691 switch (Lex.getKind()) {
692 default:
693 return tokError("unknown selection kind");
694 case lltok::kw_any:
695 SK = Comdat::Any;
696 break;
697 case lltok::kw_exactmatch:
698 SK = Comdat::ExactMatch;
699 break;
700 case lltok::kw_largest:
701 SK = Comdat::Largest;
702 break;
703 case lltok::kw_nodeduplicate:
704 SK = Comdat::NoDeduplicate;
705 break;
706 case lltok::kw_samesize:
707 SK = Comdat::SameSize;
708 break;
710 Lex.Lex();
712 // See if the comdat was forward referenced, if so, use the comdat.
713 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
714 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
715 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
716 return error(NameLoc, "redefinition of comdat '$" + Name + "'");
718 Comdat *C;
719 if (I != ComdatSymTab.end())
720 C = &I->second;
721 else
722 C = M->getOrInsertComdat(Name);
723 C->setSelectionKind(SK);
725 return false;
728 // MDString:
729 // ::= '!' STRINGCONSTANT
730 bool LLParser::parseMDString(MDString *&Result) {
731 std::string Str;
732 if (parseStringConstant(Str))
733 return true;
734 Result = MDString::get(Context, Str);
735 return false;
738 // MDNode:
739 // ::= '!' MDNodeNumber
740 bool LLParser::parseMDNodeID(MDNode *&Result) {
741 // !{ ..., !42, ... }
742 LocTy IDLoc = Lex.getLoc();
743 unsigned MID = 0;
744 if (parseUInt32(MID))
745 return true;
747 // If not a forward reference, just return it now.
748 if (NumberedMetadata.count(MID)) {
749 Result = NumberedMetadata[MID];
750 return false;
753 // Otherwise, create MDNode forward reference.
754 auto &FwdRef = ForwardRefMDNodes[MID];
755 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
757 Result = FwdRef.first.get();
758 NumberedMetadata[MID].reset(Result);
759 return false;
762 /// parseNamedMetadata:
763 /// !foo = !{ !1, !2 }
764 bool LLParser::parseNamedMetadata() {
765 assert(Lex.getKind() == lltok::MetadataVar);
766 std::string Name = Lex.getStrVal();
767 Lex.Lex();
769 if (parseToken(lltok::equal, "expected '=' here") ||
770 parseToken(lltok::exclaim, "Expected '!' here") ||
771 parseToken(lltok::lbrace, "Expected '{' here"))
772 return true;
774 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
775 if (Lex.getKind() != lltok::rbrace)
776 do {
777 MDNode *N = nullptr;
778 // parse DIExpressions inline as a special case. They are still MDNodes,
779 // so they can still appear in named metadata. Remove this logic if they
780 // become plain Metadata.
781 if (Lex.getKind() == lltok::MetadataVar &&
782 Lex.getStrVal() == "DIExpression") {
783 if (parseDIExpression(N, /*IsDistinct=*/false))
784 return true;
785 // DIArgLists should only appear inline in a function, as they may
786 // contain LocalAsMetadata arguments which require a function context.
787 } else if (Lex.getKind() == lltok::MetadataVar &&
788 Lex.getStrVal() == "DIArgList") {
789 return tokError("found DIArgList outside of function");
790 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
791 parseMDNodeID(N)) {
792 return true;
794 NMD->addOperand(N);
795 } while (EatIfPresent(lltok::comma));
797 return parseToken(lltok::rbrace, "expected end of metadata node");
800 /// parseStandaloneMetadata:
801 /// !42 = !{...}
802 bool LLParser::parseStandaloneMetadata() {
803 assert(Lex.getKind() == lltok::exclaim);
804 Lex.Lex();
805 unsigned MetadataID = 0;
807 MDNode *Init;
808 if (parseUInt32(MetadataID) || parseToken(lltok::equal, "expected '=' here"))
809 return true;
811 // Detect common error, from old metadata syntax.
812 if (Lex.getKind() == lltok::Type)
813 return tokError("unexpected type in metadata definition");
815 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
816 if (Lex.getKind() == lltok::MetadataVar) {
817 if (parseSpecializedMDNode(Init, IsDistinct))
818 return true;
819 } else if (parseToken(lltok::exclaim, "Expected '!' here") ||
820 parseMDTuple(Init, IsDistinct))
821 return true;
823 // See if this was forward referenced, if so, handle it.
824 auto FI = ForwardRefMDNodes.find(MetadataID);
825 if (FI != ForwardRefMDNodes.end()) {
826 FI->second.first->replaceAllUsesWith(Init);
827 ForwardRefMDNodes.erase(FI);
829 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
830 } else {
831 if (NumberedMetadata.count(MetadataID))
832 return tokError("Metadata id is already used");
833 NumberedMetadata[MetadataID].reset(Init);
836 return false;
839 // Skips a single module summary entry.
840 bool LLParser::skipModuleSummaryEntry() {
841 // Each module summary entry consists of a tag for the entry
842 // type, followed by a colon, then the fields which may be surrounded by
843 // nested sets of parentheses. The "tag:" looks like a Label. Once parsing
844 // support is in place we will look for the tokens corresponding to the
845 // expected tags.
846 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
847 Lex.getKind() != lltok::kw_typeid && Lex.getKind() != lltok::kw_flags &&
848 Lex.getKind() != lltok::kw_blockcount)
849 return tokError(
850 "Expected 'gv', 'module', 'typeid', 'flags' or 'blockcount' at the "
851 "start of summary entry");
852 if (Lex.getKind() == lltok::kw_flags)
853 return parseSummaryIndexFlags();
854 if (Lex.getKind() == lltok::kw_blockcount)
855 return parseBlockCount();
856 Lex.Lex();
857 if (parseToken(lltok::colon, "expected ':' at start of summary entry") ||
858 parseToken(lltok::lparen, "expected '(' at start of summary entry"))
859 return true;
860 // Now walk through the parenthesized entry, until the number of open
861 // parentheses goes back down to 0 (the first '(' was parsed above).
862 unsigned NumOpenParen = 1;
863 do {
864 switch (Lex.getKind()) {
865 case lltok::lparen:
866 NumOpenParen++;
867 break;
868 case lltok::rparen:
869 NumOpenParen--;
870 break;
871 case lltok::Eof:
872 return tokError("found end of file while parsing summary entry");
873 default:
874 // Skip everything in between parentheses.
875 break;
877 Lex.Lex();
878 } while (NumOpenParen > 0);
879 return false;
882 /// SummaryEntry
883 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
884 bool LLParser::parseSummaryEntry() {
885 assert(Lex.getKind() == lltok::SummaryID);
886 unsigned SummaryID = Lex.getUIntVal();
888 // For summary entries, colons should be treated as distinct tokens,
889 // not an indication of the end of a label token.
890 Lex.setIgnoreColonInIdentifiers(true);
892 Lex.Lex();
893 if (parseToken(lltok::equal, "expected '=' here"))
894 return true;
896 // If we don't have an index object, skip the summary entry.
897 if (!Index)
898 return skipModuleSummaryEntry();
900 bool result = false;
901 switch (Lex.getKind()) {
902 case lltok::kw_gv:
903 result = parseGVEntry(SummaryID);
904 break;
905 case lltok::kw_module:
906 result = parseModuleEntry(SummaryID);
907 break;
908 case lltok::kw_typeid:
909 result = parseTypeIdEntry(SummaryID);
910 break;
911 case lltok::kw_typeidCompatibleVTable:
912 result = parseTypeIdCompatibleVtableEntry(SummaryID);
913 break;
914 case lltok::kw_flags:
915 result = parseSummaryIndexFlags();
916 break;
917 case lltok::kw_blockcount:
918 result = parseBlockCount();
919 break;
920 default:
921 result = error(Lex.getLoc(), "unexpected summary kind");
922 break;
924 Lex.setIgnoreColonInIdentifiers(false);
925 return result;
928 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
929 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
930 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
933 // If there was an explicit dso_local, update GV. In the absence of an explicit
934 // dso_local we keep the default value.
935 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
936 if (DSOLocal)
937 GV.setDSOLocal(true);
940 static std::string typeComparisonErrorMessage(StringRef Message, Type *Ty1,
941 Type *Ty2) {
942 std::string ErrString;
943 raw_string_ostream ErrOS(ErrString);
944 ErrOS << Message << " (" << *Ty1 << " vs " << *Ty2 << ")";
945 return ErrOS.str();
948 /// parseAliasOrIFunc:
949 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
950 /// OptionalVisibility OptionalDLLStorageClass
951 /// OptionalThreadLocal OptionalUnnamedAddr
952 /// 'alias|ifunc' AliaseeOrResolver SymbolAttrs*
954 /// AliaseeOrResolver
955 /// ::= TypeAndValue
957 /// SymbolAttrs
958 /// ::= ',' 'partition' StringConstant
960 /// Everything through OptionalUnnamedAddr has already been parsed.
962 bool LLParser::parseAliasOrIFunc(const std::string &Name, LocTy NameLoc,
963 unsigned L, unsigned Visibility,
964 unsigned DLLStorageClass, bool DSOLocal,
965 GlobalVariable::ThreadLocalMode TLM,
966 GlobalVariable::UnnamedAddr UnnamedAddr) {
967 bool IsAlias;
968 if (Lex.getKind() == lltok::kw_alias)
969 IsAlias = true;
970 else if (Lex.getKind() == lltok::kw_ifunc)
971 IsAlias = false;
972 else
973 llvm_unreachable("Not an alias or ifunc!");
974 Lex.Lex();
976 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
978 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
979 return error(NameLoc, "invalid linkage type for alias");
981 if (!isValidVisibilityForLinkage(Visibility, L))
982 return error(NameLoc,
983 "symbol with local linkage must have default visibility");
985 Type *Ty;
986 LocTy ExplicitTypeLoc = Lex.getLoc();
987 if (parseType(Ty) ||
988 parseToken(lltok::comma, "expected comma after alias or ifunc's type"))
989 return true;
991 Constant *Aliasee;
992 LocTy AliaseeLoc = Lex.getLoc();
993 if (Lex.getKind() != lltok::kw_bitcast &&
994 Lex.getKind() != lltok::kw_getelementptr &&
995 Lex.getKind() != lltok::kw_addrspacecast &&
996 Lex.getKind() != lltok::kw_inttoptr) {
997 if (parseGlobalTypeAndValue(Aliasee))
998 return true;
999 } else {
1000 // The bitcast dest type is not present, it is implied by the dest type.
1001 ValID ID;
1002 if (parseValID(ID, /*PFS=*/nullptr))
1003 return true;
1004 if (ID.Kind != ValID::t_Constant)
1005 return error(AliaseeLoc, "invalid aliasee");
1006 Aliasee = ID.ConstantVal;
1009 Type *AliaseeType = Aliasee->getType();
1010 auto *PTy = dyn_cast<PointerType>(AliaseeType);
1011 if (!PTy)
1012 return error(AliaseeLoc, "An alias or ifunc must have pointer type");
1013 unsigned AddrSpace = PTy->getAddressSpace();
1015 if (IsAlias) {
1016 if (!PTy->isOpaqueOrPointeeTypeMatches(Ty))
1017 return error(
1018 ExplicitTypeLoc,
1019 typeComparisonErrorMessage(
1020 "explicit pointee type doesn't match operand's pointee type", Ty,
1021 PTy->getNonOpaquePointerElementType()));
1022 } else {
1023 if (!PTy->isOpaque() &&
1024 !PTy->getNonOpaquePointerElementType()->isFunctionTy())
1025 return error(ExplicitTypeLoc,
1026 "explicit pointee type should be a function type");
1029 GlobalValue *GVal = nullptr;
1031 // See if the alias was forward referenced, if so, prepare to replace the
1032 // forward reference.
1033 if (!Name.empty()) {
1034 auto I = ForwardRefVals.find(Name);
1035 if (I != ForwardRefVals.end()) {
1036 GVal = I->second.first;
1037 ForwardRefVals.erase(Name);
1038 } else if (M->getNamedValue(Name)) {
1039 return error(NameLoc, "redefinition of global '@" + Name + "'");
1041 } else {
1042 auto I = ForwardRefValIDs.find(NumberedVals.size());
1043 if (I != ForwardRefValIDs.end()) {
1044 GVal = I->second.first;
1045 ForwardRefValIDs.erase(I);
1049 // Okay, create the alias/ifunc but do not insert it into the module yet.
1050 std::unique_ptr<GlobalAlias> GA;
1051 std::unique_ptr<GlobalIFunc> GI;
1052 GlobalValue *GV;
1053 if (IsAlias) {
1054 GA.reset(GlobalAlias::create(Ty, AddrSpace,
1055 (GlobalValue::LinkageTypes)Linkage, Name,
1056 Aliasee, /*Parent*/ nullptr));
1057 GV = GA.get();
1058 } else {
1059 GI.reset(GlobalIFunc::create(Ty, AddrSpace,
1060 (GlobalValue::LinkageTypes)Linkage, Name,
1061 Aliasee, /*Parent*/ nullptr));
1062 GV = GI.get();
1064 GV->setThreadLocalMode(TLM);
1065 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1066 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1067 GV->setUnnamedAddr(UnnamedAddr);
1068 maybeSetDSOLocal(DSOLocal, *GV);
1070 // At this point we've parsed everything except for the IndirectSymbolAttrs.
1071 // Now parse them if there are any.
1072 while (Lex.getKind() == lltok::comma) {
1073 Lex.Lex();
1075 if (Lex.getKind() == lltok::kw_partition) {
1076 Lex.Lex();
1077 GV->setPartition(Lex.getStrVal());
1078 if (parseToken(lltok::StringConstant, "expected partition string"))
1079 return true;
1080 } else {
1081 return tokError("unknown alias or ifunc property!");
1085 if (Name.empty())
1086 NumberedVals.push_back(GV);
1088 if (GVal) {
1089 // Verify that types agree.
1090 if (GVal->getType() != GV->getType())
1091 return error(
1092 ExplicitTypeLoc,
1093 "forward reference and definition of alias have different types");
1095 // If they agree, just RAUW the old value with the alias and remove the
1096 // forward ref info.
1097 GVal->replaceAllUsesWith(GV);
1098 GVal->eraseFromParent();
1101 // Insert into the module, we know its name won't collide now.
1102 if (IsAlias)
1103 M->getAliasList().push_back(GA.release());
1104 else
1105 M->getIFuncList().push_back(GI.release());
1106 assert(GV->getName() == Name && "Should not be a name conflict!");
1108 return false;
1111 static bool isSanitizer(lltok::Kind Kind) {
1112 switch (Kind) {
1113 case lltok::kw_no_sanitize_address:
1114 case lltok::kw_no_sanitize_hwaddress:
1115 case lltok::kw_sanitize_memtag:
1116 case lltok::kw_sanitize_address_dyninit:
1117 return true;
1118 default:
1119 return false;
1123 bool LLParser::parseSanitizer(GlobalVariable *GV) {
1124 using SanitizerMetadata = GlobalValue::SanitizerMetadata;
1125 SanitizerMetadata Meta;
1126 if (GV->hasSanitizerMetadata())
1127 Meta = GV->getSanitizerMetadata();
1129 switch (Lex.getKind()) {
1130 case lltok::kw_no_sanitize_address:
1131 Meta.NoAddress = true;
1132 break;
1133 case lltok::kw_no_sanitize_hwaddress:
1134 Meta.NoHWAddress = true;
1135 break;
1136 case lltok::kw_sanitize_memtag:
1137 Meta.Memtag = true;
1138 break;
1139 case lltok::kw_sanitize_address_dyninit:
1140 Meta.IsDynInit = true;
1141 break;
1142 default:
1143 return tokError("non-sanitizer token passed to LLParser::parseSanitizer()");
1145 GV->setSanitizerMetadata(Meta);
1146 Lex.Lex();
1147 return false;
1150 /// parseGlobal
1151 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1152 /// OptionalVisibility OptionalDLLStorageClass
1153 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1154 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1155 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1156 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1157 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1158 /// Const OptionalAttrs
1160 /// Everything up to and including OptionalUnnamedAddr has been parsed
1161 /// already.
1163 bool LLParser::parseGlobal(const std::string &Name, LocTy NameLoc,
1164 unsigned Linkage, bool HasLinkage,
1165 unsigned Visibility, unsigned DLLStorageClass,
1166 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1167 GlobalVariable::UnnamedAddr UnnamedAddr) {
1168 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1169 return error(NameLoc,
1170 "symbol with local linkage must have default visibility");
1172 unsigned AddrSpace;
1173 bool IsConstant, IsExternallyInitialized;
1174 LocTy IsExternallyInitializedLoc;
1175 LocTy TyLoc;
1177 Type *Ty = nullptr;
1178 if (parseOptionalAddrSpace(AddrSpace) ||
1179 parseOptionalToken(lltok::kw_externally_initialized,
1180 IsExternallyInitialized,
1181 &IsExternallyInitializedLoc) ||
1182 parseGlobalType(IsConstant) || parseType(Ty, TyLoc))
1183 return true;
1185 // If the linkage is specified and is external, then no initializer is
1186 // present.
1187 Constant *Init = nullptr;
1188 if (!HasLinkage ||
1189 !GlobalValue::isValidDeclarationLinkage(
1190 (GlobalValue::LinkageTypes)Linkage)) {
1191 if (parseGlobalValue(Ty, Init))
1192 return true;
1195 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1196 return error(TyLoc, "invalid type for global variable");
1198 GlobalValue *GVal = nullptr;
1200 // See if the global was forward referenced, if so, use the global.
1201 if (!Name.empty()) {
1202 auto I = ForwardRefVals.find(Name);
1203 if (I != ForwardRefVals.end()) {
1204 GVal = I->second.first;
1205 ForwardRefVals.erase(I);
1206 } else if (M->getNamedValue(Name)) {
1207 return error(NameLoc, "redefinition of global '@" + Name + "'");
1209 } else {
1210 auto I = ForwardRefValIDs.find(NumberedVals.size());
1211 if (I != ForwardRefValIDs.end()) {
1212 GVal = I->second.first;
1213 ForwardRefValIDs.erase(I);
1217 GlobalVariable *GV = new GlobalVariable(
1218 *M, Ty, false, GlobalValue::ExternalLinkage, nullptr, Name, nullptr,
1219 GlobalVariable::NotThreadLocal, AddrSpace);
1221 if (Name.empty())
1222 NumberedVals.push_back(GV);
1224 // Set the parsed properties on the global.
1225 if (Init)
1226 GV->setInitializer(Init);
1227 GV->setConstant(IsConstant);
1228 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1229 maybeSetDSOLocal(DSOLocal, *GV);
1230 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1231 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1232 GV->setExternallyInitialized(IsExternallyInitialized);
1233 GV->setThreadLocalMode(TLM);
1234 GV->setUnnamedAddr(UnnamedAddr);
1236 if (GVal) {
1237 if (GVal->getType() != Ty->getPointerTo(AddrSpace))
1238 return error(
1239 TyLoc,
1240 "forward reference and definition of global have different types");
1242 GVal->replaceAllUsesWith(GV);
1243 GVal->eraseFromParent();
1246 // parse attributes on the global.
1247 while (Lex.getKind() == lltok::comma) {
1248 Lex.Lex();
1250 if (Lex.getKind() == lltok::kw_section) {
1251 Lex.Lex();
1252 GV->setSection(Lex.getStrVal());
1253 if (parseToken(lltok::StringConstant, "expected global section string"))
1254 return true;
1255 } else if (Lex.getKind() == lltok::kw_partition) {
1256 Lex.Lex();
1257 GV->setPartition(Lex.getStrVal());
1258 if (parseToken(lltok::StringConstant, "expected partition string"))
1259 return true;
1260 } else if (Lex.getKind() == lltok::kw_align) {
1261 MaybeAlign Alignment;
1262 if (parseOptionalAlignment(Alignment))
1263 return true;
1264 GV->setAlignment(Alignment);
1265 } else if (Lex.getKind() == lltok::MetadataVar) {
1266 if (parseGlobalObjectMetadataAttachment(*GV))
1267 return true;
1268 } else if (isSanitizer(Lex.getKind())) {
1269 if (parseSanitizer(GV))
1270 return true;
1271 } else {
1272 Comdat *C;
1273 if (parseOptionalComdat(Name, C))
1274 return true;
1275 if (C)
1276 GV->setComdat(C);
1277 else
1278 return tokError("unknown global variable property!");
1282 AttrBuilder Attrs(M->getContext());
1283 LocTy BuiltinLoc;
1284 std::vector<unsigned> FwdRefAttrGrps;
1285 if (parseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1286 return true;
1287 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1288 GV->setAttributes(AttributeSet::get(Context, Attrs));
1289 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1292 return false;
1295 /// parseUnnamedAttrGrp
1296 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1297 bool LLParser::parseUnnamedAttrGrp() {
1298 assert(Lex.getKind() == lltok::kw_attributes);
1299 LocTy AttrGrpLoc = Lex.getLoc();
1300 Lex.Lex();
1302 if (Lex.getKind() != lltok::AttrGrpID)
1303 return tokError("expected attribute group id");
1305 unsigned VarID = Lex.getUIntVal();
1306 std::vector<unsigned> unused;
1307 LocTy BuiltinLoc;
1308 Lex.Lex();
1310 if (parseToken(lltok::equal, "expected '=' here") ||
1311 parseToken(lltok::lbrace, "expected '{' here"))
1312 return true;
1314 auto R = NumberedAttrBuilders.find(VarID);
1315 if (R == NumberedAttrBuilders.end())
1316 R = NumberedAttrBuilders.emplace(VarID, AttrBuilder(M->getContext())).first;
1318 if (parseFnAttributeValuePairs(R->second, unused, true, BuiltinLoc) ||
1319 parseToken(lltok::rbrace, "expected end of attribute group"))
1320 return true;
1322 if (!R->second.hasAttributes())
1323 return error(AttrGrpLoc, "attribute group has no attributes");
1325 return false;
1328 static Attribute::AttrKind tokenToAttribute(lltok::Kind Kind) {
1329 switch (Kind) {
1330 #define GET_ATTR_NAMES
1331 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \
1332 case lltok::kw_##DISPLAY_NAME: \
1333 return Attribute::ENUM_NAME;
1334 #include "llvm/IR/Attributes.inc"
1335 default:
1336 return Attribute::None;
1340 bool LLParser::parseEnumAttribute(Attribute::AttrKind Attr, AttrBuilder &B,
1341 bool InAttrGroup) {
1342 if (Attribute::isTypeAttrKind(Attr))
1343 return parseRequiredTypeAttr(B, Lex.getKind(), Attr);
1345 switch (Attr) {
1346 case Attribute::Alignment: {
1347 MaybeAlign Alignment;
1348 if (InAttrGroup) {
1349 uint32_t Value = 0;
1350 Lex.Lex();
1351 if (parseToken(lltok::equal, "expected '=' here") || parseUInt32(Value))
1352 return true;
1353 Alignment = Align(Value);
1354 } else {
1355 if (parseOptionalAlignment(Alignment, true))
1356 return true;
1358 B.addAlignmentAttr(Alignment);
1359 return false;
1361 case Attribute::StackAlignment: {
1362 unsigned Alignment;
1363 if (InAttrGroup) {
1364 Lex.Lex();
1365 if (parseToken(lltok::equal, "expected '=' here") ||
1366 parseUInt32(Alignment))
1367 return true;
1368 } else {
1369 if (parseOptionalStackAlignment(Alignment))
1370 return true;
1372 B.addStackAlignmentAttr(Alignment);
1373 return false;
1375 case Attribute::AllocSize: {
1376 unsigned ElemSizeArg;
1377 Optional<unsigned> NumElemsArg;
1378 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1379 return true;
1380 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1381 return false;
1383 case Attribute::VScaleRange: {
1384 unsigned MinValue, MaxValue;
1385 if (parseVScaleRangeArguments(MinValue, MaxValue))
1386 return true;
1387 B.addVScaleRangeAttr(MinValue,
1388 MaxValue > 0 ? MaxValue : Optional<unsigned>());
1389 return false;
1391 case Attribute::Dereferenceable: {
1392 uint64_t Bytes;
1393 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1394 return true;
1395 B.addDereferenceableAttr(Bytes);
1396 return false;
1398 case Attribute::DereferenceableOrNull: {
1399 uint64_t Bytes;
1400 if (parseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1401 return true;
1402 B.addDereferenceableOrNullAttr(Bytes);
1403 return false;
1405 case Attribute::UWTable: {
1406 UWTableKind Kind;
1407 if (parseOptionalUWTableKind(Kind))
1408 return true;
1409 B.addUWTableAttr(Kind);
1410 return false;
1412 case Attribute::AllocKind: {
1413 AllocFnKind Kind = AllocFnKind::Unknown;
1414 if (parseAllocKind(Kind))
1415 return true;
1416 B.addAllocKindAttr(Kind);
1417 return false;
1419 default:
1420 B.addAttribute(Attr);
1421 Lex.Lex();
1422 return false;
1426 /// parseFnAttributeValuePairs
1427 /// ::= <attr> | <attr> '=' <value>
1428 bool LLParser::parseFnAttributeValuePairs(AttrBuilder &B,
1429 std::vector<unsigned> &FwdRefAttrGrps,
1430 bool InAttrGrp, LocTy &BuiltinLoc) {
1431 bool HaveError = false;
1433 B.clear();
1435 while (true) {
1436 lltok::Kind Token = Lex.getKind();
1437 if (Token == lltok::rbrace)
1438 return HaveError; // Finished.
1440 if (Token == lltok::StringConstant) {
1441 if (parseStringAttribute(B))
1442 return true;
1443 continue;
1446 if (Token == lltok::AttrGrpID) {
1447 // Allow a function to reference an attribute group:
1449 // define void @foo() #1 { ... }
1450 if (InAttrGrp) {
1451 HaveError |= error(
1452 Lex.getLoc(),
1453 "cannot have an attribute group reference in an attribute group");
1454 } else {
1455 // Save the reference to the attribute group. We'll fill it in later.
1456 FwdRefAttrGrps.push_back(Lex.getUIntVal());
1458 Lex.Lex();
1459 continue;
1462 SMLoc Loc = Lex.getLoc();
1463 if (Token == lltok::kw_builtin)
1464 BuiltinLoc = Loc;
1466 Attribute::AttrKind Attr = tokenToAttribute(Token);
1467 if (Attr == Attribute::None) {
1468 if (!InAttrGrp)
1469 return HaveError;
1470 return error(Lex.getLoc(), "unterminated attribute group");
1473 if (parseEnumAttribute(Attr, B, InAttrGrp))
1474 return true;
1476 // As a hack, we allow function alignment to be initially parsed as an
1477 // attribute on a function declaration/definition or added to an attribute
1478 // group and later moved to the alignment field.
1479 if (!Attribute::canUseAsFnAttr(Attr) && Attr != Attribute::Alignment)
1480 HaveError |= error(Loc, "this attribute does not apply to functions");
1484 //===----------------------------------------------------------------------===//
1485 // GlobalValue Reference/Resolution Routines.
1486 //===----------------------------------------------------------------------===//
1488 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy) {
1489 // For opaque pointers, the used global type does not matter. We will later
1490 // RAUW it with a global/function of the correct type.
1491 if (PTy->isOpaque())
1492 return new GlobalVariable(*M, Type::getInt8Ty(M->getContext()), false,
1493 GlobalValue::ExternalWeakLinkage, nullptr, "",
1494 nullptr, GlobalVariable::NotThreadLocal,
1495 PTy->getAddressSpace());
1497 Type *ElemTy = PTy->getNonOpaquePointerElementType();
1498 if (auto *FT = dyn_cast<FunctionType>(ElemTy))
1499 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1500 PTy->getAddressSpace(), "", M);
1501 else
1502 return new GlobalVariable(
1503 *M, ElemTy, false, GlobalValue::ExternalWeakLinkage, nullptr, "",
1504 nullptr, GlobalVariable::NotThreadLocal, PTy->getAddressSpace());
1507 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1508 Value *Val) {
1509 Type *ValTy = Val->getType();
1510 if (ValTy == Ty)
1511 return Val;
1512 if (Ty->isLabelTy())
1513 error(Loc, "'" + Name + "' is not a basic block");
1514 else
1515 error(Loc, "'" + Name + "' defined with type '" +
1516 getTypeString(Val->getType()) + "' but expected '" +
1517 getTypeString(Ty) + "'");
1518 return nullptr;
1521 /// getGlobalVal - Get a value with the specified name or ID, creating a
1522 /// forward reference record if needed. This can return null if the value
1523 /// exists but does not have the right type.
1524 GlobalValue *LLParser::getGlobalVal(const std::string &Name, Type *Ty,
1525 LocTy Loc) {
1526 PointerType *PTy = dyn_cast<PointerType>(Ty);
1527 if (!PTy) {
1528 error(Loc, "global variable reference must have pointer type");
1529 return nullptr;
1532 // Look this name up in the normal function symbol table.
1533 GlobalValue *Val =
1534 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1536 // If this is a forward reference for the value, see if we already created a
1537 // forward ref record.
1538 if (!Val) {
1539 auto I = ForwardRefVals.find(Name);
1540 if (I != ForwardRefVals.end())
1541 Val = I->second.first;
1544 // If we have the value in the symbol table or fwd-ref table, return it.
1545 if (Val)
1546 return cast_or_null<GlobalValue>(
1547 checkValidVariableType(Loc, "@" + Name, Ty, Val));
1549 // Otherwise, create a new forward reference for this value and remember it.
1550 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1551 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1552 return FwdVal;
1555 GlobalValue *LLParser::getGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1556 PointerType *PTy = dyn_cast<PointerType>(Ty);
1557 if (!PTy) {
1558 error(Loc, "global variable reference must have pointer type");
1559 return nullptr;
1562 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1564 // If this is a forward reference for the value, see if we already created a
1565 // forward ref record.
1566 if (!Val) {
1567 auto I = ForwardRefValIDs.find(ID);
1568 if (I != ForwardRefValIDs.end())
1569 Val = I->second.first;
1572 // If we have the value in the symbol table or fwd-ref table, return it.
1573 if (Val)
1574 return cast_or_null<GlobalValue>(
1575 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val));
1577 // Otherwise, create a new forward reference for this value and remember it.
1578 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy);
1579 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1580 return FwdVal;
1583 //===----------------------------------------------------------------------===//
1584 // Comdat Reference/Resolution Routines.
1585 //===----------------------------------------------------------------------===//
1587 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1588 // Look this name up in the comdat symbol table.
1589 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1590 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1591 if (I != ComdatSymTab.end())
1592 return &I->second;
1594 // Otherwise, create a new forward reference for this value and remember it.
1595 Comdat *C = M->getOrInsertComdat(Name);
1596 ForwardRefComdats[Name] = Loc;
1597 return C;
1600 //===----------------------------------------------------------------------===//
1601 // Helper Routines.
1602 //===----------------------------------------------------------------------===//
1604 /// parseToken - If the current token has the specified kind, eat it and return
1605 /// success. Otherwise, emit the specified error and return failure.
1606 bool LLParser::parseToken(lltok::Kind T, const char *ErrMsg) {
1607 if (Lex.getKind() != T)
1608 return tokError(ErrMsg);
1609 Lex.Lex();
1610 return false;
1613 /// parseStringConstant
1614 /// ::= StringConstant
1615 bool LLParser::parseStringConstant(std::string &Result) {
1616 if (Lex.getKind() != lltok::StringConstant)
1617 return tokError("expected string constant");
1618 Result = Lex.getStrVal();
1619 Lex.Lex();
1620 return false;
1623 /// parseUInt32
1624 /// ::= uint32
1625 bool LLParser::parseUInt32(uint32_t &Val) {
1626 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1627 return tokError("expected integer");
1628 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1629 if (Val64 != unsigned(Val64))
1630 return tokError("expected 32-bit integer (too large)");
1631 Val = Val64;
1632 Lex.Lex();
1633 return false;
1636 /// parseUInt64
1637 /// ::= uint64
1638 bool LLParser::parseUInt64(uint64_t &Val) {
1639 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1640 return tokError("expected integer");
1641 Val = Lex.getAPSIntVal().getLimitedValue();
1642 Lex.Lex();
1643 return false;
1646 /// parseTLSModel
1647 /// := 'localdynamic'
1648 /// := 'initialexec'
1649 /// := 'localexec'
1650 bool LLParser::parseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1651 switch (Lex.getKind()) {
1652 default:
1653 return tokError("expected localdynamic, initialexec or localexec");
1654 case lltok::kw_localdynamic:
1655 TLM = GlobalVariable::LocalDynamicTLSModel;
1656 break;
1657 case lltok::kw_initialexec:
1658 TLM = GlobalVariable::InitialExecTLSModel;
1659 break;
1660 case lltok::kw_localexec:
1661 TLM = GlobalVariable::LocalExecTLSModel;
1662 break;
1665 Lex.Lex();
1666 return false;
1669 /// parseOptionalThreadLocal
1670 /// := /*empty*/
1671 /// := 'thread_local'
1672 /// := 'thread_local' '(' tlsmodel ')'
1673 bool LLParser::parseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1674 TLM = GlobalVariable::NotThreadLocal;
1675 if (!EatIfPresent(lltok::kw_thread_local))
1676 return false;
1678 TLM = GlobalVariable::GeneralDynamicTLSModel;
1679 if (Lex.getKind() == lltok::lparen) {
1680 Lex.Lex();
1681 return parseTLSModel(TLM) ||
1682 parseToken(lltok::rparen, "expected ')' after thread local model");
1684 return false;
1687 /// parseOptionalAddrSpace
1688 /// := /*empty*/
1689 /// := 'addrspace' '(' uint32 ')'
1690 bool LLParser::parseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1691 AddrSpace = DefaultAS;
1692 if (!EatIfPresent(lltok::kw_addrspace))
1693 return false;
1694 return parseToken(lltok::lparen, "expected '(' in address space") ||
1695 parseUInt32(AddrSpace) ||
1696 parseToken(lltok::rparen, "expected ')' in address space");
1699 /// parseStringAttribute
1700 /// := StringConstant
1701 /// := StringConstant '=' StringConstant
1702 bool LLParser::parseStringAttribute(AttrBuilder &B) {
1703 std::string Attr = Lex.getStrVal();
1704 Lex.Lex();
1705 std::string Val;
1706 if (EatIfPresent(lltok::equal) && parseStringConstant(Val))
1707 return true;
1708 B.addAttribute(Attr, Val);
1709 return false;
1712 /// Parse a potentially empty list of parameter or return attributes.
1713 bool LLParser::parseOptionalParamOrReturnAttrs(AttrBuilder &B, bool IsParam) {
1714 bool HaveError = false;
1716 B.clear();
1718 while (true) {
1719 lltok::Kind Token = Lex.getKind();
1720 if (Token == lltok::StringConstant) {
1721 if (parseStringAttribute(B))
1722 return true;
1723 continue;
1726 SMLoc Loc = Lex.getLoc();
1727 Attribute::AttrKind Attr = tokenToAttribute(Token);
1728 if (Attr == Attribute::None)
1729 return HaveError;
1731 if (parseEnumAttribute(Attr, B, /* InAttrGroup */ false))
1732 return true;
1734 if (IsParam && !Attribute::canUseAsParamAttr(Attr))
1735 HaveError |= error(Loc, "this attribute does not apply to parameters");
1736 if (!IsParam && !Attribute::canUseAsRetAttr(Attr))
1737 HaveError |= error(Loc, "this attribute does not apply to return values");
1741 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1742 HasLinkage = true;
1743 switch (Kind) {
1744 default:
1745 HasLinkage = false;
1746 return GlobalValue::ExternalLinkage;
1747 case lltok::kw_private:
1748 return GlobalValue::PrivateLinkage;
1749 case lltok::kw_internal:
1750 return GlobalValue::InternalLinkage;
1751 case lltok::kw_weak:
1752 return GlobalValue::WeakAnyLinkage;
1753 case lltok::kw_weak_odr:
1754 return GlobalValue::WeakODRLinkage;
1755 case lltok::kw_linkonce:
1756 return GlobalValue::LinkOnceAnyLinkage;
1757 case lltok::kw_linkonce_odr:
1758 return GlobalValue::LinkOnceODRLinkage;
1759 case lltok::kw_available_externally:
1760 return GlobalValue::AvailableExternallyLinkage;
1761 case lltok::kw_appending:
1762 return GlobalValue::AppendingLinkage;
1763 case lltok::kw_common:
1764 return GlobalValue::CommonLinkage;
1765 case lltok::kw_extern_weak:
1766 return GlobalValue::ExternalWeakLinkage;
1767 case lltok::kw_external:
1768 return GlobalValue::ExternalLinkage;
1772 /// parseOptionalLinkage
1773 /// ::= /*empty*/
1774 /// ::= 'private'
1775 /// ::= 'internal'
1776 /// ::= 'weak'
1777 /// ::= 'weak_odr'
1778 /// ::= 'linkonce'
1779 /// ::= 'linkonce_odr'
1780 /// ::= 'available_externally'
1781 /// ::= 'appending'
1782 /// ::= 'common'
1783 /// ::= 'extern_weak'
1784 /// ::= 'external'
1785 bool LLParser::parseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1786 unsigned &Visibility,
1787 unsigned &DLLStorageClass, bool &DSOLocal) {
1788 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1789 if (HasLinkage)
1790 Lex.Lex();
1791 parseOptionalDSOLocal(DSOLocal);
1792 parseOptionalVisibility(Visibility);
1793 parseOptionalDLLStorageClass(DLLStorageClass);
1795 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1796 return error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1799 return false;
1802 void LLParser::parseOptionalDSOLocal(bool &DSOLocal) {
1803 switch (Lex.getKind()) {
1804 default:
1805 DSOLocal = false;
1806 break;
1807 case lltok::kw_dso_local:
1808 DSOLocal = true;
1809 Lex.Lex();
1810 break;
1811 case lltok::kw_dso_preemptable:
1812 DSOLocal = false;
1813 Lex.Lex();
1814 break;
1818 /// parseOptionalVisibility
1819 /// ::= /*empty*/
1820 /// ::= 'default'
1821 /// ::= 'hidden'
1822 /// ::= 'protected'
1824 void LLParser::parseOptionalVisibility(unsigned &Res) {
1825 switch (Lex.getKind()) {
1826 default:
1827 Res = GlobalValue::DefaultVisibility;
1828 return;
1829 case lltok::kw_default:
1830 Res = GlobalValue::DefaultVisibility;
1831 break;
1832 case lltok::kw_hidden:
1833 Res = GlobalValue::HiddenVisibility;
1834 break;
1835 case lltok::kw_protected:
1836 Res = GlobalValue::ProtectedVisibility;
1837 break;
1839 Lex.Lex();
1842 /// parseOptionalDLLStorageClass
1843 /// ::= /*empty*/
1844 /// ::= 'dllimport'
1845 /// ::= 'dllexport'
1847 void LLParser::parseOptionalDLLStorageClass(unsigned &Res) {
1848 switch (Lex.getKind()) {
1849 default:
1850 Res = GlobalValue::DefaultStorageClass;
1851 return;
1852 case lltok::kw_dllimport:
1853 Res = GlobalValue::DLLImportStorageClass;
1854 break;
1855 case lltok::kw_dllexport:
1856 Res = GlobalValue::DLLExportStorageClass;
1857 break;
1859 Lex.Lex();
1862 /// parseOptionalCallingConv
1863 /// ::= /*empty*/
1864 /// ::= 'ccc'
1865 /// ::= 'fastcc'
1866 /// ::= 'intel_ocl_bicc'
1867 /// ::= 'coldcc'
1868 /// ::= 'cfguard_checkcc'
1869 /// ::= 'x86_stdcallcc'
1870 /// ::= 'x86_fastcallcc'
1871 /// ::= 'x86_thiscallcc'
1872 /// ::= 'x86_vectorcallcc'
1873 /// ::= 'arm_apcscc'
1874 /// ::= 'arm_aapcscc'
1875 /// ::= 'arm_aapcs_vfpcc'
1876 /// ::= 'aarch64_vector_pcs'
1877 /// ::= 'aarch64_sve_vector_pcs'
1878 /// ::= 'msp430_intrcc'
1879 /// ::= 'avr_intrcc'
1880 /// ::= 'avr_signalcc'
1881 /// ::= 'ptx_kernel'
1882 /// ::= 'ptx_device'
1883 /// ::= 'spir_func'
1884 /// ::= 'spir_kernel'
1885 /// ::= 'x86_64_sysvcc'
1886 /// ::= 'win64cc'
1887 /// ::= 'webkit_jscc'
1888 /// ::= 'anyregcc'
1889 /// ::= 'preserve_mostcc'
1890 /// ::= 'preserve_allcc'
1891 /// ::= 'ghccc'
1892 /// ::= 'swiftcc'
1893 /// ::= 'swifttailcc'
1894 /// ::= 'x86_intrcc'
1895 /// ::= 'hhvmcc'
1896 /// ::= 'hhvm_ccc'
1897 /// ::= 'cxx_fast_tlscc'
1898 /// ::= 'amdgpu_vs'
1899 /// ::= 'amdgpu_ls'
1900 /// ::= 'amdgpu_hs'
1901 /// ::= 'amdgpu_es'
1902 /// ::= 'amdgpu_gs'
1903 /// ::= 'amdgpu_ps'
1904 /// ::= 'amdgpu_cs'
1905 /// ::= 'amdgpu_kernel'
1906 /// ::= 'tailcc'
1907 /// ::= 'cc' UINT
1909 bool LLParser::parseOptionalCallingConv(unsigned &CC) {
1910 switch (Lex.getKind()) {
1911 default: CC = CallingConv::C; return false;
1912 case lltok::kw_ccc: CC = CallingConv::C; break;
1913 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1914 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1915 case lltok::kw_cfguard_checkcc: CC = CallingConv::CFGuard_Check; break;
1916 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1917 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1918 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1919 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1920 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1921 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1922 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1923 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1924 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
1925 case lltok::kw_aarch64_sve_vector_pcs:
1926 CC = CallingConv::AArch64_SVE_VectorCall;
1927 break;
1928 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1929 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1930 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1931 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1932 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1933 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1934 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1935 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1936 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1937 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1938 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1939 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1940 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1941 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1942 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1943 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1944 case lltok::kw_swifttailcc: CC = CallingConv::SwiftTail; 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_gfx: CC = CallingConv::AMDGPU_Gfx; break;
1951 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
1952 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
1953 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
1954 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
1955 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
1956 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
1957 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
1958 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
1959 case lltok::kw_cc: {
1960 Lex.Lex();
1961 return parseUInt32(CC);
1965 Lex.Lex();
1966 return false;
1969 /// parseMetadataAttachment
1970 /// ::= !dbg !42
1971 bool LLParser::parseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1972 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1974 std::string Name = Lex.getStrVal();
1975 Kind = M->getMDKindID(Name);
1976 Lex.Lex();
1978 return parseMDNode(MD);
1981 /// parseInstructionMetadata
1982 /// ::= !dbg !42 (',' !dbg !57)*
1983 bool LLParser::parseInstructionMetadata(Instruction &Inst) {
1984 do {
1985 if (Lex.getKind() != lltok::MetadataVar)
1986 return tokError("expected metadata after comma");
1988 unsigned MDK;
1989 MDNode *N;
1990 if (parseMetadataAttachment(MDK, N))
1991 return true;
1993 Inst.setMetadata(MDK, N);
1994 if (MDK == LLVMContext::MD_tbaa)
1995 InstsWithTBAATag.push_back(&Inst);
1997 // If this is the end of the list, we're done.
1998 } while (EatIfPresent(lltok::comma));
1999 return false;
2002 /// parseGlobalObjectMetadataAttachment
2003 /// ::= !dbg !57
2004 bool LLParser::parseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2005 unsigned MDK;
2006 MDNode *N;
2007 if (parseMetadataAttachment(MDK, N))
2008 return true;
2010 GO.addMetadata(MDK, *N);
2011 return false;
2014 /// parseOptionalFunctionMetadata
2015 /// ::= (!dbg !57)*
2016 bool LLParser::parseOptionalFunctionMetadata(Function &F) {
2017 while (Lex.getKind() == lltok::MetadataVar)
2018 if (parseGlobalObjectMetadataAttachment(F))
2019 return true;
2020 return false;
2023 /// parseOptionalAlignment
2024 /// ::= /* empty */
2025 /// ::= 'align' 4
2026 bool LLParser::parseOptionalAlignment(MaybeAlign &Alignment, bool AllowParens) {
2027 Alignment = None;
2028 if (!EatIfPresent(lltok::kw_align))
2029 return false;
2030 LocTy AlignLoc = Lex.getLoc();
2031 uint64_t Value = 0;
2033 LocTy ParenLoc = Lex.getLoc();
2034 bool HaveParens = false;
2035 if (AllowParens) {
2036 if (EatIfPresent(lltok::lparen))
2037 HaveParens = true;
2040 if (parseUInt64(Value))
2041 return true;
2043 if (HaveParens && !EatIfPresent(lltok::rparen))
2044 return error(ParenLoc, "expected ')'");
2046 if (!isPowerOf2_64(Value))
2047 return error(AlignLoc, "alignment is not a power of two");
2048 if (Value > Value::MaximumAlignment)
2049 return error(AlignLoc, "huge alignments are not supported yet");
2050 Alignment = Align(Value);
2051 return false;
2054 /// parseOptionalDerefAttrBytes
2055 /// ::= /* empty */
2056 /// ::= AttrKind '(' 4 ')'
2058 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2059 bool LLParser::parseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2060 uint64_t &Bytes) {
2061 assert((AttrKind == lltok::kw_dereferenceable ||
2062 AttrKind == lltok::kw_dereferenceable_or_null) &&
2063 "contract!");
2065 Bytes = 0;
2066 if (!EatIfPresent(AttrKind))
2067 return false;
2068 LocTy ParenLoc = Lex.getLoc();
2069 if (!EatIfPresent(lltok::lparen))
2070 return error(ParenLoc, "expected '('");
2071 LocTy DerefLoc = Lex.getLoc();
2072 if (parseUInt64(Bytes))
2073 return true;
2074 ParenLoc = Lex.getLoc();
2075 if (!EatIfPresent(lltok::rparen))
2076 return error(ParenLoc, "expected ')'");
2077 if (!Bytes)
2078 return error(DerefLoc, "dereferenceable bytes must be non-zero");
2079 return false;
2082 bool LLParser::parseOptionalUWTableKind(UWTableKind &Kind) {
2083 Lex.Lex();
2084 Kind = UWTableKind::Default;
2085 if (!EatIfPresent(lltok::lparen))
2086 return false;
2087 LocTy KindLoc = Lex.getLoc();
2088 if (Lex.getKind() == lltok::kw_sync)
2089 Kind = UWTableKind::Sync;
2090 else if (Lex.getKind() == lltok::kw_async)
2091 Kind = UWTableKind::Async;
2092 else
2093 return error(KindLoc, "expected unwind table kind");
2094 Lex.Lex();
2095 return parseToken(lltok::rparen, "expected ')'");
2098 bool LLParser::parseAllocKind(AllocFnKind &Kind) {
2099 Lex.Lex();
2100 LocTy ParenLoc = Lex.getLoc();
2101 if (!EatIfPresent(lltok::lparen))
2102 return error(ParenLoc, "expected '('");
2103 LocTy KindLoc = Lex.getLoc();
2104 std::string Arg;
2105 if (parseStringConstant(Arg))
2106 return error(KindLoc, "expected allockind value");
2107 for (StringRef A : llvm::split(Arg, ",")) {
2108 if (A == "alloc") {
2109 Kind |= AllocFnKind::Alloc;
2110 } else if (A == "realloc") {
2111 Kind |= AllocFnKind::Realloc;
2112 } else if (A == "free") {
2113 Kind |= AllocFnKind::Free;
2114 } else if (A == "uninitialized") {
2115 Kind |= AllocFnKind::Uninitialized;
2116 } else if (A == "zeroed") {
2117 Kind |= AllocFnKind::Zeroed;
2118 } else if (A == "aligned") {
2119 Kind |= AllocFnKind::Aligned;
2120 } else {
2121 return error(KindLoc, Twine("unknown allockind ") + A);
2124 ParenLoc = Lex.getLoc();
2125 if (!EatIfPresent(lltok::rparen))
2126 return error(ParenLoc, "expected ')'");
2127 if (Kind == AllocFnKind::Unknown)
2128 return error(KindLoc, "expected allockind value");
2129 return false;
2132 /// parseOptionalCommaAlign
2133 /// ::=
2134 /// ::= ',' align 4
2136 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2137 /// end.
2138 bool LLParser::parseOptionalCommaAlign(MaybeAlign &Alignment,
2139 bool &AteExtraComma) {
2140 AteExtraComma = false;
2141 while (EatIfPresent(lltok::comma)) {
2142 // Metadata at the end is an early exit.
2143 if (Lex.getKind() == lltok::MetadataVar) {
2144 AteExtraComma = true;
2145 return false;
2148 if (Lex.getKind() != lltok::kw_align)
2149 return error(Lex.getLoc(), "expected metadata or 'align'");
2151 if (parseOptionalAlignment(Alignment))
2152 return true;
2155 return false;
2158 /// parseOptionalCommaAddrSpace
2159 /// ::=
2160 /// ::= ',' addrspace(1)
2162 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2163 /// end.
2164 bool LLParser::parseOptionalCommaAddrSpace(unsigned &AddrSpace, LocTy &Loc,
2165 bool &AteExtraComma) {
2166 AteExtraComma = false;
2167 while (EatIfPresent(lltok::comma)) {
2168 // Metadata at the end is an early exit.
2169 if (Lex.getKind() == lltok::MetadataVar) {
2170 AteExtraComma = true;
2171 return false;
2174 Loc = Lex.getLoc();
2175 if (Lex.getKind() != lltok::kw_addrspace)
2176 return error(Lex.getLoc(), "expected metadata or 'addrspace'");
2178 if (parseOptionalAddrSpace(AddrSpace))
2179 return true;
2182 return false;
2185 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2186 Optional<unsigned> &HowManyArg) {
2187 Lex.Lex();
2189 auto StartParen = Lex.getLoc();
2190 if (!EatIfPresent(lltok::lparen))
2191 return error(StartParen, "expected '('");
2193 if (parseUInt32(BaseSizeArg))
2194 return true;
2196 if (EatIfPresent(lltok::comma)) {
2197 auto HowManyAt = Lex.getLoc();
2198 unsigned HowMany;
2199 if (parseUInt32(HowMany))
2200 return true;
2201 if (HowMany == BaseSizeArg)
2202 return error(HowManyAt,
2203 "'allocsize' indices can't refer to the same parameter");
2204 HowManyArg = HowMany;
2205 } else
2206 HowManyArg = None;
2208 auto EndParen = Lex.getLoc();
2209 if (!EatIfPresent(lltok::rparen))
2210 return error(EndParen, "expected ')'");
2211 return false;
2214 bool LLParser::parseVScaleRangeArguments(unsigned &MinValue,
2215 unsigned &MaxValue) {
2216 Lex.Lex();
2218 auto StartParen = Lex.getLoc();
2219 if (!EatIfPresent(lltok::lparen))
2220 return error(StartParen, "expected '('");
2222 if (parseUInt32(MinValue))
2223 return true;
2225 if (EatIfPresent(lltok::comma)) {
2226 if (parseUInt32(MaxValue))
2227 return true;
2228 } else
2229 MaxValue = MinValue;
2231 auto EndParen = Lex.getLoc();
2232 if (!EatIfPresent(lltok::rparen))
2233 return error(EndParen, "expected ')'");
2234 return false;
2237 /// parseScopeAndOrdering
2238 /// if isAtomic: ::= SyncScope? AtomicOrdering
2239 /// else: ::=
2241 /// This sets Scope and Ordering to the parsed values.
2242 bool LLParser::parseScopeAndOrdering(bool IsAtomic, SyncScope::ID &SSID,
2243 AtomicOrdering &Ordering) {
2244 if (!IsAtomic)
2245 return false;
2247 return parseScope(SSID) || parseOrdering(Ordering);
2250 /// parseScope
2251 /// ::= syncscope("singlethread" | "<target scope>")?
2253 /// This sets synchronization scope ID to the ID of the parsed value.
2254 bool LLParser::parseScope(SyncScope::ID &SSID) {
2255 SSID = SyncScope::System;
2256 if (EatIfPresent(lltok::kw_syncscope)) {
2257 auto StartParenAt = Lex.getLoc();
2258 if (!EatIfPresent(lltok::lparen))
2259 return error(StartParenAt, "Expected '(' in syncscope");
2261 std::string SSN;
2262 auto SSNAt = Lex.getLoc();
2263 if (parseStringConstant(SSN))
2264 return error(SSNAt, "Expected synchronization scope name");
2266 auto EndParenAt = Lex.getLoc();
2267 if (!EatIfPresent(lltok::rparen))
2268 return error(EndParenAt, "Expected ')' in syncscope");
2270 SSID = Context.getOrInsertSyncScopeID(SSN);
2273 return false;
2276 /// parseOrdering
2277 /// ::= AtomicOrdering
2279 /// This sets Ordering to the parsed value.
2280 bool LLParser::parseOrdering(AtomicOrdering &Ordering) {
2281 switch (Lex.getKind()) {
2282 default:
2283 return tokError("Expected ordering on atomic instruction");
2284 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2285 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2286 // Not specified yet:
2287 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2288 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2289 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2290 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2291 case lltok::kw_seq_cst:
2292 Ordering = AtomicOrdering::SequentiallyConsistent;
2293 break;
2295 Lex.Lex();
2296 return false;
2299 /// parseOptionalStackAlignment
2300 /// ::= /* empty */
2301 /// ::= 'alignstack' '(' 4 ')'
2302 bool LLParser::parseOptionalStackAlignment(unsigned &Alignment) {
2303 Alignment = 0;
2304 if (!EatIfPresent(lltok::kw_alignstack))
2305 return false;
2306 LocTy ParenLoc = Lex.getLoc();
2307 if (!EatIfPresent(lltok::lparen))
2308 return error(ParenLoc, "expected '('");
2309 LocTy AlignLoc = Lex.getLoc();
2310 if (parseUInt32(Alignment))
2311 return true;
2312 ParenLoc = Lex.getLoc();
2313 if (!EatIfPresent(lltok::rparen))
2314 return error(ParenLoc, "expected ')'");
2315 if (!isPowerOf2_32(Alignment))
2316 return error(AlignLoc, "stack alignment is not a power of two");
2317 return false;
2320 /// parseIndexList - This parses the index list for an insert/extractvalue
2321 /// instruction. This sets AteExtraComma in the case where we eat an extra
2322 /// comma at the end of the line and find that it is followed by metadata.
2323 /// Clients that don't allow metadata can call the version of this function that
2324 /// only takes one argument.
2326 /// parseIndexList
2327 /// ::= (',' uint32)+
2329 bool LLParser::parseIndexList(SmallVectorImpl<unsigned> &Indices,
2330 bool &AteExtraComma) {
2331 AteExtraComma = false;
2333 if (Lex.getKind() != lltok::comma)
2334 return tokError("expected ',' as start of index list");
2336 while (EatIfPresent(lltok::comma)) {
2337 if (Lex.getKind() == lltok::MetadataVar) {
2338 if (Indices.empty())
2339 return tokError("expected index");
2340 AteExtraComma = true;
2341 return false;
2343 unsigned Idx = 0;
2344 if (parseUInt32(Idx))
2345 return true;
2346 Indices.push_back(Idx);
2349 return false;
2352 //===----------------------------------------------------------------------===//
2353 // Type Parsing.
2354 //===----------------------------------------------------------------------===//
2356 /// parseType - parse a type.
2357 bool LLParser::parseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2358 SMLoc TypeLoc = Lex.getLoc();
2359 switch (Lex.getKind()) {
2360 default:
2361 return tokError(Msg);
2362 case lltok::Type:
2363 // Type ::= 'float' | 'void' (etc)
2364 Result = Lex.getTyVal();
2365 Lex.Lex();
2367 // Handle "ptr" opaque pointer type.
2369 // Type ::= ptr ('addrspace' '(' uint32 ')')?
2370 if (Result->isOpaquePointerTy()) {
2371 unsigned AddrSpace;
2372 if (parseOptionalAddrSpace(AddrSpace))
2373 return true;
2374 Result = PointerType::get(getContext(), AddrSpace);
2376 // Give a nice error for 'ptr*'.
2377 if (Lex.getKind() == lltok::star)
2378 return tokError("ptr* is invalid - use ptr instead");
2380 // Fall through to parsing the type suffixes only if this 'ptr' is a
2381 // function return. Otherwise, return success, implicitly rejecting other
2382 // suffixes.
2383 if (Lex.getKind() != lltok::lparen)
2384 return false;
2386 break;
2387 case lltok::lbrace:
2388 // Type ::= StructType
2389 if (parseAnonStructType(Result, false))
2390 return true;
2391 break;
2392 case lltok::lsquare:
2393 // Type ::= '[' ... ']'
2394 Lex.Lex(); // eat the lsquare.
2395 if (parseArrayVectorType(Result, false))
2396 return true;
2397 break;
2398 case lltok::less: // Either vector or packed struct.
2399 // Type ::= '<' ... '>'
2400 Lex.Lex();
2401 if (Lex.getKind() == lltok::lbrace) {
2402 if (parseAnonStructType(Result, true) ||
2403 parseToken(lltok::greater, "expected '>' at end of packed struct"))
2404 return true;
2405 } else if (parseArrayVectorType(Result, true))
2406 return true;
2407 break;
2408 case lltok::LocalVar: {
2409 // Type ::= %foo
2410 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2412 // If the type hasn't been defined yet, create a forward definition and
2413 // remember where that forward def'n was seen (in case it never is defined).
2414 if (!Entry.first) {
2415 Entry.first = StructType::create(Context, Lex.getStrVal());
2416 Entry.second = Lex.getLoc();
2418 Result = Entry.first;
2419 Lex.Lex();
2420 break;
2423 case lltok::LocalVarID: {
2424 // Type ::= %4
2425 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2427 // If the type hasn't been defined yet, create a forward definition and
2428 // remember where that forward def'n was seen (in case it never is defined).
2429 if (!Entry.first) {
2430 Entry.first = StructType::create(Context);
2431 Entry.second = Lex.getLoc();
2433 Result = Entry.first;
2434 Lex.Lex();
2435 break;
2439 // parse the type suffixes.
2440 while (true) {
2441 switch (Lex.getKind()) {
2442 // End of type.
2443 default:
2444 if (!AllowVoid && Result->isVoidTy())
2445 return error(TypeLoc, "void type only allowed for function results");
2446 return false;
2448 // Type ::= Type '*'
2449 case lltok::star:
2450 if (Result->isLabelTy())
2451 return tokError("basic block pointers are invalid");
2452 if (Result->isVoidTy())
2453 return tokError("pointers to void are invalid - use i8* instead");
2454 if (!PointerType::isValidElementType(Result))
2455 return tokError("pointer to this type is invalid");
2456 Result = PointerType::getUnqual(Result);
2457 Lex.Lex();
2458 break;
2460 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2461 case lltok::kw_addrspace: {
2462 if (Result->isLabelTy())
2463 return tokError("basic block pointers are invalid");
2464 if (Result->isVoidTy())
2465 return tokError("pointers to void are invalid; use i8* instead");
2466 if (!PointerType::isValidElementType(Result))
2467 return tokError("pointer to this type is invalid");
2468 unsigned AddrSpace;
2469 if (parseOptionalAddrSpace(AddrSpace) ||
2470 parseToken(lltok::star, "expected '*' in address space"))
2471 return true;
2473 Result = PointerType::get(Result, AddrSpace);
2474 break;
2477 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2478 case lltok::lparen:
2479 if (parseFunctionType(Result))
2480 return true;
2481 break;
2486 /// parseParameterList
2487 /// ::= '(' ')'
2488 /// ::= '(' Arg (',' Arg)* ')'
2489 /// Arg
2490 /// ::= Type OptionalAttributes Value OptionalAttributes
2491 bool LLParser::parseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2492 PerFunctionState &PFS, bool IsMustTailCall,
2493 bool InVarArgsFunc) {
2494 if (parseToken(lltok::lparen, "expected '(' in call"))
2495 return true;
2497 while (Lex.getKind() != lltok::rparen) {
2498 // If this isn't the first argument, we need a comma.
2499 if (!ArgList.empty() &&
2500 parseToken(lltok::comma, "expected ',' in argument list"))
2501 return true;
2503 // parse an ellipsis if this is a musttail call in a variadic function.
2504 if (Lex.getKind() == lltok::dotdotdot) {
2505 const char *Msg = "unexpected ellipsis in argument list for ";
2506 if (!IsMustTailCall)
2507 return tokError(Twine(Msg) + "non-musttail call");
2508 if (!InVarArgsFunc)
2509 return tokError(Twine(Msg) + "musttail call in non-varargs function");
2510 Lex.Lex(); // Lex the '...', it is purely for readability.
2511 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2514 // parse the argument.
2515 LocTy ArgLoc;
2516 Type *ArgTy = nullptr;
2517 Value *V;
2518 if (parseType(ArgTy, ArgLoc))
2519 return true;
2521 AttrBuilder ArgAttrs(M->getContext());
2523 if (ArgTy->isMetadataTy()) {
2524 if (parseMetadataAsValue(V, PFS))
2525 return true;
2526 } else {
2527 // Otherwise, handle normal operands.
2528 if (parseOptionalParamAttrs(ArgAttrs) || parseValue(ArgTy, V, PFS))
2529 return true;
2531 ArgList.push_back(ParamInfo(
2532 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2535 if (IsMustTailCall && InVarArgsFunc)
2536 return tokError("expected '...' at end of argument list for musttail call "
2537 "in varargs function");
2539 Lex.Lex(); // Lex the ')'.
2540 return false;
2543 /// parseRequiredTypeAttr
2544 /// ::= attrname(<ty>)
2545 bool LLParser::parseRequiredTypeAttr(AttrBuilder &B, lltok::Kind AttrToken,
2546 Attribute::AttrKind AttrKind) {
2547 Type *Ty = nullptr;
2548 if (!EatIfPresent(AttrToken))
2549 return true;
2550 if (!EatIfPresent(lltok::lparen))
2551 return error(Lex.getLoc(), "expected '('");
2552 if (parseType(Ty))
2553 return true;
2554 if (!EatIfPresent(lltok::rparen))
2555 return error(Lex.getLoc(), "expected ')'");
2557 B.addTypeAttr(AttrKind, Ty);
2558 return false;
2561 /// parseOptionalOperandBundles
2562 /// ::= /*empty*/
2563 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2565 /// OperandBundle
2566 /// ::= bundle-tag '(' ')'
2567 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2569 /// bundle-tag ::= String Constant
2570 bool LLParser::parseOptionalOperandBundles(
2571 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2572 LocTy BeginLoc = Lex.getLoc();
2573 if (!EatIfPresent(lltok::lsquare))
2574 return false;
2576 while (Lex.getKind() != lltok::rsquare) {
2577 // If this isn't the first operand bundle, we need a comma.
2578 if (!BundleList.empty() &&
2579 parseToken(lltok::comma, "expected ',' in input list"))
2580 return true;
2582 std::string Tag;
2583 if (parseStringConstant(Tag))
2584 return true;
2586 if (parseToken(lltok::lparen, "expected '(' in operand bundle"))
2587 return true;
2589 std::vector<Value *> Inputs;
2590 while (Lex.getKind() != lltok::rparen) {
2591 // If this isn't the first input, we need a comma.
2592 if (!Inputs.empty() &&
2593 parseToken(lltok::comma, "expected ',' in input list"))
2594 return true;
2596 Type *Ty = nullptr;
2597 Value *Input = nullptr;
2598 if (parseType(Ty) || parseValue(Ty, Input, PFS))
2599 return true;
2600 Inputs.push_back(Input);
2603 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2605 Lex.Lex(); // Lex the ')'.
2608 if (BundleList.empty())
2609 return error(BeginLoc, "operand bundle set must not be empty");
2611 Lex.Lex(); // Lex the ']'.
2612 return false;
2615 /// parseArgumentList - parse the argument list for a function type or function
2616 /// prototype.
2617 /// ::= '(' ArgTypeListI ')'
2618 /// ArgTypeListI
2619 /// ::= /*empty*/
2620 /// ::= '...'
2621 /// ::= ArgTypeList ',' '...'
2622 /// ::= ArgType (',' ArgType)*
2624 bool LLParser::parseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2625 bool &IsVarArg) {
2626 unsigned CurValID = 0;
2627 IsVarArg = false;
2628 assert(Lex.getKind() == lltok::lparen);
2629 Lex.Lex(); // eat the (.
2631 if (Lex.getKind() == lltok::rparen) {
2632 // empty
2633 } else if (Lex.getKind() == lltok::dotdotdot) {
2634 IsVarArg = true;
2635 Lex.Lex();
2636 } else {
2637 LocTy TypeLoc = Lex.getLoc();
2638 Type *ArgTy = nullptr;
2639 AttrBuilder Attrs(M->getContext());
2640 std::string Name;
2642 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2643 return true;
2645 if (ArgTy->isVoidTy())
2646 return error(TypeLoc, "argument can not have void type");
2648 if (Lex.getKind() == lltok::LocalVar) {
2649 Name = Lex.getStrVal();
2650 Lex.Lex();
2651 } else if (Lex.getKind() == lltok::LocalVarID) {
2652 if (Lex.getUIntVal() != CurValID)
2653 return error(TypeLoc, "argument expected to be numbered '%" +
2654 Twine(CurValID) + "'");
2655 ++CurValID;
2656 Lex.Lex();
2659 if (!FunctionType::isValidArgumentType(ArgTy))
2660 return error(TypeLoc, "invalid type for function argument");
2662 ArgList.emplace_back(TypeLoc, ArgTy,
2663 AttributeSet::get(ArgTy->getContext(), Attrs),
2664 std::move(Name));
2666 while (EatIfPresent(lltok::comma)) {
2667 // Handle ... at end of arg list.
2668 if (EatIfPresent(lltok::dotdotdot)) {
2669 IsVarArg = true;
2670 break;
2673 // Otherwise must be an argument type.
2674 TypeLoc = Lex.getLoc();
2675 if (parseType(ArgTy) || parseOptionalParamAttrs(Attrs))
2676 return true;
2678 if (ArgTy->isVoidTy())
2679 return error(TypeLoc, "argument can not have void type");
2681 if (Lex.getKind() == lltok::LocalVar) {
2682 Name = Lex.getStrVal();
2683 Lex.Lex();
2684 } else {
2685 if (Lex.getKind() == lltok::LocalVarID) {
2686 if (Lex.getUIntVal() != CurValID)
2687 return error(TypeLoc, "argument expected to be numbered '%" +
2688 Twine(CurValID) + "'");
2689 Lex.Lex();
2691 ++CurValID;
2692 Name = "";
2695 if (!ArgTy->isFirstClassType())
2696 return error(TypeLoc, "invalid type for function argument");
2698 ArgList.emplace_back(TypeLoc, ArgTy,
2699 AttributeSet::get(ArgTy->getContext(), Attrs),
2700 std::move(Name));
2704 return parseToken(lltok::rparen, "expected ')' at end of argument list");
2707 /// parseFunctionType
2708 /// ::= Type ArgumentList OptionalAttrs
2709 bool LLParser::parseFunctionType(Type *&Result) {
2710 assert(Lex.getKind() == lltok::lparen);
2712 if (!FunctionType::isValidReturnType(Result))
2713 return tokError("invalid function return type");
2715 SmallVector<ArgInfo, 8> ArgList;
2716 bool IsVarArg;
2717 if (parseArgumentList(ArgList, IsVarArg))
2718 return true;
2720 // Reject names on the arguments lists.
2721 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2722 if (!ArgList[i].Name.empty())
2723 return error(ArgList[i].Loc, "argument name invalid in function type");
2724 if (ArgList[i].Attrs.hasAttributes())
2725 return error(ArgList[i].Loc,
2726 "argument attributes invalid in function type");
2729 SmallVector<Type*, 16> ArgListTy;
2730 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2731 ArgListTy.push_back(ArgList[i].Ty);
2733 Result = FunctionType::get(Result, ArgListTy, IsVarArg);
2734 return false;
2737 /// parseAnonStructType - parse an anonymous struct type, which is inlined into
2738 /// other structs.
2739 bool LLParser::parseAnonStructType(Type *&Result, bool Packed) {
2740 SmallVector<Type*, 8> Elts;
2741 if (parseStructBody(Elts))
2742 return true;
2744 Result = StructType::get(Context, Elts, Packed);
2745 return false;
2748 /// parseStructDefinition - parse a struct in a 'type' definition.
2749 bool LLParser::parseStructDefinition(SMLoc TypeLoc, StringRef Name,
2750 std::pair<Type *, LocTy> &Entry,
2751 Type *&ResultTy) {
2752 // If the type was already defined, diagnose the redefinition.
2753 if (Entry.first && !Entry.second.isValid())
2754 return error(TypeLoc, "redefinition of type");
2756 // If we have opaque, just return without filling in the definition for the
2757 // struct. This counts as a definition as far as the .ll file goes.
2758 if (EatIfPresent(lltok::kw_opaque)) {
2759 // This type is being defined, so clear the location to indicate this.
2760 Entry.second = SMLoc();
2762 // If this type number has never been uttered, create it.
2763 if (!Entry.first)
2764 Entry.first = StructType::create(Context, Name);
2765 ResultTy = Entry.first;
2766 return false;
2769 // If the type starts with '<', then it is either a packed struct or a vector.
2770 bool isPacked = EatIfPresent(lltok::less);
2772 // If we don't have a struct, then we have a random type alias, which we
2773 // accept for compatibility with old files. These types are not allowed to be
2774 // forward referenced and not allowed to be recursive.
2775 if (Lex.getKind() != lltok::lbrace) {
2776 if (Entry.first)
2777 return error(TypeLoc, "forward references to non-struct type");
2779 ResultTy = nullptr;
2780 if (isPacked)
2781 return parseArrayVectorType(ResultTy, true);
2782 return parseType(ResultTy);
2785 // This type is being defined, so clear the location to indicate this.
2786 Entry.second = SMLoc();
2788 // If this type number has never been uttered, create it.
2789 if (!Entry.first)
2790 Entry.first = StructType::create(Context, Name);
2792 StructType *STy = cast<StructType>(Entry.first);
2794 SmallVector<Type*, 8> Body;
2795 if (parseStructBody(Body) ||
2796 (isPacked && parseToken(lltok::greater, "expected '>' in packed struct")))
2797 return true;
2799 STy->setBody(Body, isPacked);
2800 ResultTy = STy;
2801 return false;
2804 /// parseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2805 /// StructType
2806 /// ::= '{' '}'
2807 /// ::= '{' Type (',' Type)* '}'
2808 /// ::= '<' '{' '}' '>'
2809 /// ::= '<' '{' Type (',' Type)* '}' '>'
2810 bool LLParser::parseStructBody(SmallVectorImpl<Type *> &Body) {
2811 assert(Lex.getKind() == lltok::lbrace);
2812 Lex.Lex(); // Consume the '{'
2814 // Handle the empty struct.
2815 if (EatIfPresent(lltok::rbrace))
2816 return false;
2818 LocTy EltTyLoc = Lex.getLoc();
2819 Type *Ty = nullptr;
2820 if (parseType(Ty))
2821 return true;
2822 Body.push_back(Ty);
2824 if (!StructType::isValidElementType(Ty))
2825 return error(EltTyLoc, "invalid element type for struct");
2827 while (EatIfPresent(lltok::comma)) {
2828 EltTyLoc = Lex.getLoc();
2829 if (parseType(Ty))
2830 return true;
2832 if (!StructType::isValidElementType(Ty))
2833 return error(EltTyLoc, "invalid element type for struct");
2835 Body.push_back(Ty);
2838 return parseToken(lltok::rbrace, "expected '}' at end of struct");
2841 /// parseArrayVectorType - parse an array or vector type, assuming the first
2842 /// token has already been consumed.
2843 /// Type
2844 /// ::= '[' APSINTVAL 'x' Types ']'
2845 /// ::= '<' APSINTVAL 'x' Types '>'
2846 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
2847 bool LLParser::parseArrayVectorType(Type *&Result, bool IsVector) {
2848 bool Scalable = false;
2850 if (IsVector && Lex.getKind() == lltok::kw_vscale) {
2851 Lex.Lex(); // consume the 'vscale'
2852 if (parseToken(lltok::kw_x, "expected 'x' after vscale"))
2853 return true;
2855 Scalable = true;
2858 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2859 Lex.getAPSIntVal().getBitWidth() > 64)
2860 return tokError("expected number in address space");
2862 LocTy SizeLoc = Lex.getLoc();
2863 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2864 Lex.Lex();
2866 if (parseToken(lltok::kw_x, "expected 'x' after element count"))
2867 return true;
2869 LocTy TypeLoc = Lex.getLoc();
2870 Type *EltTy = nullptr;
2871 if (parseType(EltTy))
2872 return true;
2874 if (parseToken(IsVector ? lltok::greater : lltok::rsquare,
2875 "expected end of sequential type"))
2876 return true;
2878 if (IsVector) {
2879 if (Size == 0)
2880 return error(SizeLoc, "zero element vector is illegal");
2881 if ((unsigned)Size != Size)
2882 return error(SizeLoc, "size too large for vector");
2883 if (!VectorType::isValidElementType(EltTy))
2884 return error(TypeLoc, "invalid vector element type");
2885 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
2886 } else {
2887 if (!ArrayType::isValidElementType(EltTy))
2888 return error(TypeLoc, "invalid array element type");
2889 Result = ArrayType::get(EltTy, Size);
2891 return false;
2894 //===----------------------------------------------------------------------===//
2895 // Function Semantic Analysis.
2896 //===----------------------------------------------------------------------===//
2898 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2899 int functionNumber)
2900 : P(p), F(f), FunctionNumber(functionNumber) {
2902 // Insert unnamed arguments into the NumberedVals list.
2903 for (Argument &A : F.args())
2904 if (!A.hasName())
2905 NumberedVals.push_back(&A);
2908 LLParser::PerFunctionState::~PerFunctionState() {
2909 // If there were any forward referenced non-basicblock values, delete them.
2911 for (const auto &P : ForwardRefVals) {
2912 if (isa<BasicBlock>(P.second.first))
2913 continue;
2914 P.second.first->replaceAllUsesWith(
2915 UndefValue::get(P.second.first->getType()));
2916 P.second.first->deleteValue();
2919 for (const auto &P : ForwardRefValIDs) {
2920 if (isa<BasicBlock>(P.second.first))
2921 continue;
2922 P.second.first->replaceAllUsesWith(
2923 UndefValue::get(P.second.first->getType()));
2924 P.second.first->deleteValue();
2928 bool LLParser::PerFunctionState::finishFunction() {
2929 if (!ForwardRefVals.empty())
2930 return P.error(ForwardRefVals.begin()->second.second,
2931 "use of undefined value '%" + ForwardRefVals.begin()->first +
2932 "'");
2933 if (!ForwardRefValIDs.empty())
2934 return P.error(ForwardRefValIDs.begin()->second.second,
2935 "use of undefined value '%" +
2936 Twine(ForwardRefValIDs.begin()->first) + "'");
2937 return false;
2940 /// getVal - Get a value with the specified name or ID, creating a
2941 /// forward reference record if needed. This can return null if the value
2942 /// exists but does not have the right type.
2943 Value *LLParser::PerFunctionState::getVal(const std::string &Name, Type *Ty,
2944 LocTy Loc) {
2945 // Look this name up in the normal function symbol table.
2946 Value *Val = F.getValueSymbolTable()->lookup(Name);
2948 // If this is a forward reference for the value, see if we already created a
2949 // forward ref record.
2950 if (!Val) {
2951 auto I = ForwardRefVals.find(Name);
2952 if (I != ForwardRefVals.end())
2953 Val = I->second.first;
2956 // If we have the value in the symbol table or fwd-ref table, return it.
2957 if (Val)
2958 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val);
2960 // Don't make placeholders with invalid type.
2961 if (!Ty->isFirstClassType()) {
2962 P.error(Loc, "invalid use of a non-first-class type");
2963 return nullptr;
2966 // Otherwise, create a new forward reference for this value and remember it.
2967 Value *FwdVal;
2968 if (Ty->isLabelTy()) {
2969 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2970 } else {
2971 FwdVal = new Argument(Ty, Name);
2974 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2975 return FwdVal;
2978 Value *LLParser::PerFunctionState::getVal(unsigned ID, Type *Ty, LocTy Loc) {
2979 // Look this name up in the normal function symbol table.
2980 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2982 // If this is a forward reference for the value, see if we already created a
2983 // forward ref record.
2984 if (!Val) {
2985 auto I = ForwardRefValIDs.find(ID);
2986 if (I != ForwardRefValIDs.end())
2987 Val = I->second.first;
2990 // If we have the value in the symbol table or fwd-ref table, return it.
2991 if (Val)
2992 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val);
2994 if (!Ty->isFirstClassType()) {
2995 P.error(Loc, "invalid use of a non-first-class type");
2996 return nullptr;
2999 // Otherwise, create a new forward reference for this value and remember it.
3000 Value *FwdVal;
3001 if (Ty->isLabelTy()) {
3002 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
3003 } else {
3004 FwdVal = new Argument(Ty);
3007 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
3008 return FwdVal;
3011 /// setInstName - After an instruction is parsed and inserted into its
3012 /// basic block, this installs its name.
3013 bool LLParser::PerFunctionState::setInstName(int NameID,
3014 const std::string &NameStr,
3015 LocTy NameLoc, Instruction *Inst) {
3016 // If this instruction has void type, it cannot have a name or ID specified.
3017 if (Inst->getType()->isVoidTy()) {
3018 if (NameID != -1 || !NameStr.empty())
3019 return P.error(NameLoc, "instructions returning void cannot have a name");
3020 return false;
3023 // If this was a numbered instruction, verify that the instruction is the
3024 // expected value and resolve any forward references.
3025 if (NameStr.empty()) {
3026 // If neither a name nor an ID was specified, just use the next ID.
3027 if (NameID == -1)
3028 NameID = NumberedVals.size();
3030 if (unsigned(NameID) != NumberedVals.size())
3031 return P.error(NameLoc, "instruction expected to be numbered '%" +
3032 Twine(NumberedVals.size()) + "'");
3034 auto FI = ForwardRefValIDs.find(NameID);
3035 if (FI != ForwardRefValIDs.end()) {
3036 Value *Sentinel = FI->second.first;
3037 if (Sentinel->getType() != Inst->getType())
3038 return P.error(NameLoc, "instruction forward referenced with type '" +
3039 getTypeString(FI->second.first->getType()) +
3040 "'");
3042 Sentinel->replaceAllUsesWith(Inst);
3043 Sentinel->deleteValue();
3044 ForwardRefValIDs.erase(FI);
3047 NumberedVals.push_back(Inst);
3048 return false;
3051 // Otherwise, the instruction had a name. Resolve forward refs and set it.
3052 auto FI = ForwardRefVals.find(NameStr);
3053 if (FI != ForwardRefVals.end()) {
3054 Value *Sentinel = FI->second.first;
3055 if (Sentinel->getType() != Inst->getType())
3056 return P.error(NameLoc, "instruction forward referenced with type '" +
3057 getTypeString(FI->second.first->getType()) +
3058 "'");
3060 Sentinel->replaceAllUsesWith(Inst);
3061 Sentinel->deleteValue();
3062 ForwardRefVals.erase(FI);
3065 // Set the name on the instruction.
3066 Inst->setName(NameStr);
3068 if (Inst->getName() != NameStr)
3069 return P.error(NameLoc, "multiple definition of local value named '" +
3070 NameStr + "'");
3071 return false;
3074 /// getBB - Get a basic block with the specified name or ID, creating a
3075 /// forward reference record if needed.
3076 BasicBlock *LLParser::PerFunctionState::getBB(const std::string &Name,
3077 LocTy Loc) {
3078 return dyn_cast_or_null<BasicBlock>(
3079 getVal(Name, Type::getLabelTy(F.getContext()), Loc));
3082 BasicBlock *LLParser::PerFunctionState::getBB(unsigned ID, LocTy Loc) {
3083 return dyn_cast_or_null<BasicBlock>(
3084 getVal(ID, Type::getLabelTy(F.getContext()), Loc));
3087 /// defineBB - Define the specified basic block, which is either named or
3088 /// unnamed. If there is an error, this returns null otherwise it returns
3089 /// the block being defined.
3090 BasicBlock *LLParser::PerFunctionState::defineBB(const std::string &Name,
3091 int NameID, LocTy Loc) {
3092 BasicBlock *BB;
3093 if (Name.empty()) {
3094 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3095 P.error(Loc, "label expected to be numbered '" +
3096 Twine(NumberedVals.size()) + "'");
3097 return nullptr;
3099 BB = getBB(NumberedVals.size(), Loc);
3100 if (!BB) {
3101 P.error(Loc, "unable to create block numbered '" +
3102 Twine(NumberedVals.size()) + "'");
3103 return nullptr;
3105 } else {
3106 BB = getBB(Name, Loc);
3107 if (!BB) {
3108 P.error(Loc, "unable to create block named '" + Name + "'");
3109 return nullptr;
3113 // Move the block to the end of the function. Forward ref'd blocks are
3114 // inserted wherever they happen to be referenced.
3115 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
3117 // Remove the block from forward ref sets.
3118 if (Name.empty()) {
3119 ForwardRefValIDs.erase(NumberedVals.size());
3120 NumberedVals.push_back(BB);
3121 } else {
3122 // BB forward references are already in the function symbol table.
3123 ForwardRefVals.erase(Name);
3126 return BB;
3129 //===----------------------------------------------------------------------===//
3130 // Constants.
3131 //===----------------------------------------------------------------------===//
3133 /// parseValID - parse an abstract value that doesn't necessarily have a
3134 /// type implied. For example, if we parse "4" we don't know what integer type
3135 /// it has. The value will later be combined with its type and checked for
3136 /// basic correctness. PFS is used to convert function-local operands of
3137 /// metadata (since metadata operands are not just parsed here but also
3138 /// converted to values). PFS can be null when we are not parsing metadata
3139 /// values inside a function.
3140 bool LLParser::parseValID(ValID &ID, PerFunctionState *PFS, Type *ExpectedTy) {
3141 ID.Loc = Lex.getLoc();
3142 switch (Lex.getKind()) {
3143 default:
3144 return tokError("expected value token");
3145 case lltok::GlobalID: // @42
3146 ID.UIntVal = Lex.getUIntVal();
3147 ID.Kind = ValID::t_GlobalID;
3148 break;
3149 case lltok::GlobalVar: // @foo
3150 ID.StrVal = Lex.getStrVal();
3151 ID.Kind = ValID::t_GlobalName;
3152 break;
3153 case lltok::LocalVarID: // %42
3154 ID.UIntVal = Lex.getUIntVal();
3155 ID.Kind = ValID::t_LocalID;
3156 break;
3157 case lltok::LocalVar: // %foo
3158 ID.StrVal = Lex.getStrVal();
3159 ID.Kind = ValID::t_LocalName;
3160 break;
3161 case lltok::APSInt:
3162 ID.APSIntVal = Lex.getAPSIntVal();
3163 ID.Kind = ValID::t_APSInt;
3164 break;
3165 case lltok::APFloat:
3166 ID.APFloatVal = Lex.getAPFloatVal();
3167 ID.Kind = ValID::t_APFloat;
3168 break;
3169 case lltok::kw_true:
3170 ID.ConstantVal = ConstantInt::getTrue(Context);
3171 ID.Kind = ValID::t_Constant;
3172 break;
3173 case lltok::kw_false:
3174 ID.ConstantVal = ConstantInt::getFalse(Context);
3175 ID.Kind = ValID::t_Constant;
3176 break;
3177 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3178 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3179 case lltok::kw_poison: ID.Kind = ValID::t_Poison; break;
3180 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3181 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3183 case lltok::lbrace: {
3184 // ValID ::= '{' ConstVector '}'
3185 Lex.Lex();
3186 SmallVector<Constant*, 16> Elts;
3187 if (parseGlobalValueVector(Elts) ||
3188 parseToken(lltok::rbrace, "expected end of struct constant"))
3189 return true;
3191 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3192 ID.UIntVal = Elts.size();
3193 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3194 Elts.size() * sizeof(Elts[0]));
3195 ID.Kind = ValID::t_ConstantStruct;
3196 return false;
3198 case lltok::less: {
3199 // ValID ::= '<' ConstVector '>' --> Vector.
3200 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3201 Lex.Lex();
3202 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3204 SmallVector<Constant*, 16> Elts;
3205 LocTy FirstEltLoc = Lex.getLoc();
3206 if (parseGlobalValueVector(Elts) ||
3207 (isPackedStruct &&
3208 parseToken(lltok::rbrace, "expected end of packed struct")) ||
3209 parseToken(lltok::greater, "expected end of constant"))
3210 return true;
3212 if (isPackedStruct) {
3213 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3214 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3215 Elts.size() * sizeof(Elts[0]));
3216 ID.UIntVal = Elts.size();
3217 ID.Kind = ValID::t_PackedConstantStruct;
3218 return false;
3221 if (Elts.empty())
3222 return error(ID.Loc, "constant vector must not be empty");
3224 if (!Elts[0]->getType()->isIntegerTy() &&
3225 !Elts[0]->getType()->isFloatingPointTy() &&
3226 !Elts[0]->getType()->isPointerTy())
3227 return error(
3228 FirstEltLoc,
3229 "vector elements must have integer, pointer or floating point type");
3231 // Verify that all the vector elements have the same type.
3232 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3233 if (Elts[i]->getType() != Elts[0]->getType())
3234 return error(FirstEltLoc, "vector element #" + Twine(i) +
3235 " is not of type '" +
3236 getTypeString(Elts[0]->getType()));
3238 ID.ConstantVal = ConstantVector::get(Elts);
3239 ID.Kind = ValID::t_Constant;
3240 return false;
3242 case lltok::lsquare: { // Array Constant
3243 Lex.Lex();
3244 SmallVector<Constant*, 16> Elts;
3245 LocTy FirstEltLoc = Lex.getLoc();
3246 if (parseGlobalValueVector(Elts) ||
3247 parseToken(lltok::rsquare, "expected end of array constant"))
3248 return true;
3250 // Handle empty element.
3251 if (Elts.empty()) {
3252 // Use undef instead of an array because it's inconvenient to determine
3253 // the element type at this point, there being no elements to examine.
3254 ID.Kind = ValID::t_EmptyArray;
3255 return false;
3258 if (!Elts[0]->getType()->isFirstClassType())
3259 return error(FirstEltLoc, "invalid array element type: " +
3260 getTypeString(Elts[0]->getType()));
3262 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3264 // Verify all elements are correct type!
3265 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3266 if (Elts[i]->getType() != Elts[0]->getType())
3267 return error(FirstEltLoc, "array element #" + Twine(i) +
3268 " is not of type '" +
3269 getTypeString(Elts[0]->getType()));
3272 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3273 ID.Kind = ValID::t_Constant;
3274 return false;
3276 case lltok::kw_c: // c "foo"
3277 Lex.Lex();
3278 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3279 false);
3280 if (parseToken(lltok::StringConstant, "expected string"))
3281 return true;
3282 ID.Kind = ValID::t_Constant;
3283 return false;
3285 case lltok::kw_asm: {
3286 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3287 // STRINGCONSTANT
3288 bool HasSideEffect, AlignStack, AsmDialect, CanThrow;
3289 Lex.Lex();
3290 if (parseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3291 parseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3292 parseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3293 parseOptionalToken(lltok::kw_unwind, CanThrow) ||
3294 parseStringConstant(ID.StrVal) ||
3295 parseToken(lltok::comma, "expected comma in inline asm expression") ||
3296 parseToken(lltok::StringConstant, "expected constraint string"))
3297 return true;
3298 ID.StrVal2 = Lex.getStrVal();
3299 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack) << 1) |
3300 (unsigned(AsmDialect) << 2) | (unsigned(CanThrow) << 3);
3301 ID.Kind = ValID::t_InlineAsm;
3302 return false;
3305 case lltok::kw_blockaddress: {
3306 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3307 Lex.Lex();
3309 ValID Fn, Label;
3311 if (parseToken(lltok::lparen, "expected '(' in block address expression") ||
3312 parseValID(Fn, PFS) ||
3313 parseToken(lltok::comma,
3314 "expected comma in block address expression") ||
3315 parseValID(Label, PFS) ||
3316 parseToken(lltok::rparen, "expected ')' in block address expression"))
3317 return true;
3319 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3320 return error(Fn.Loc, "expected function name in blockaddress");
3321 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3322 return error(Label.Loc, "expected basic block name in blockaddress");
3324 // Try to find the function (but skip it if it's forward-referenced).
3325 GlobalValue *GV = nullptr;
3326 if (Fn.Kind == ValID::t_GlobalID) {
3327 if (Fn.UIntVal < NumberedVals.size())
3328 GV = NumberedVals[Fn.UIntVal];
3329 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3330 GV = M->getNamedValue(Fn.StrVal);
3332 Function *F = nullptr;
3333 if (GV) {
3334 // Confirm that it's actually a function with a definition.
3335 if (!isa<Function>(GV))
3336 return error(Fn.Loc, "expected function name in blockaddress");
3337 F = cast<Function>(GV);
3338 if (F->isDeclaration())
3339 return error(Fn.Loc, "cannot take blockaddress inside a declaration");
3342 if (!F) {
3343 // Make a global variable as a placeholder for this reference.
3344 GlobalValue *&FwdRef =
3345 ForwardRefBlockAddresses.insert(std::make_pair(
3346 std::move(Fn),
3347 std::map<ValID, GlobalValue *>()))
3348 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3349 .first->second;
3350 if (!FwdRef) {
3351 unsigned FwdDeclAS;
3352 if (ExpectedTy) {
3353 // If we know the type that the blockaddress is being assigned to,
3354 // we can use the address space of that type.
3355 if (!ExpectedTy->isPointerTy())
3356 return error(ID.Loc,
3357 "type of blockaddress must be a pointer and not '" +
3358 getTypeString(ExpectedTy) + "'");
3359 FwdDeclAS = ExpectedTy->getPointerAddressSpace();
3360 } else if (PFS) {
3361 // Otherwise, we default the address space of the current function.
3362 FwdDeclAS = PFS->getFunction().getAddressSpace();
3363 } else {
3364 llvm_unreachable("Unknown address space for blockaddress");
3366 FwdRef = new GlobalVariable(
3367 *M, Type::getInt8Ty(Context), false, GlobalValue::InternalLinkage,
3368 nullptr, "", nullptr, GlobalValue::NotThreadLocal, FwdDeclAS);
3371 ID.ConstantVal = FwdRef;
3372 ID.Kind = ValID::t_Constant;
3373 return false;
3376 // We found the function; now find the basic block. Don't use PFS, since we
3377 // might be inside a constant expression.
3378 BasicBlock *BB;
3379 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3380 if (Label.Kind == ValID::t_LocalID)
3381 BB = BlockAddressPFS->getBB(Label.UIntVal, Label.Loc);
3382 else
3383 BB = BlockAddressPFS->getBB(Label.StrVal, Label.Loc);
3384 if (!BB)
3385 return error(Label.Loc, "referenced value is not a basic block");
3386 } else {
3387 if (Label.Kind == ValID::t_LocalID)
3388 return error(Label.Loc, "cannot take address of numeric label after "
3389 "the function is defined");
3390 BB = dyn_cast_or_null<BasicBlock>(
3391 F->getValueSymbolTable()->lookup(Label.StrVal));
3392 if (!BB)
3393 return error(Label.Loc, "referenced value is not a basic block");
3396 ID.ConstantVal = BlockAddress::get(F, BB);
3397 ID.Kind = ValID::t_Constant;
3398 return false;
3401 case lltok::kw_dso_local_equivalent: {
3402 // ValID ::= 'dso_local_equivalent' @foo
3403 Lex.Lex();
3405 ValID Fn;
3407 if (parseValID(Fn, PFS))
3408 return true;
3410 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3411 return error(Fn.Loc,
3412 "expected global value name in dso_local_equivalent");
3414 // Try to find the function (but skip it if it's forward-referenced).
3415 GlobalValue *GV = nullptr;
3416 if (Fn.Kind == ValID::t_GlobalID) {
3417 if (Fn.UIntVal < NumberedVals.size())
3418 GV = NumberedVals[Fn.UIntVal];
3419 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3420 GV = M->getNamedValue(Fn.StrVal);
3423 assert(GV && "Could not find a corresponding global variable");
3425 if (!GV->getValueType()->isFunctionTy())
3426 return error(Fn.Loc, "expected a function, alias to function, or ifunc "
3427 "in dso_local_equivalent");
3429 ID.ConstantVal = DSOLocalEquivalent::get(GV);
3430 ID.Kind = ValID::t_Constant;
3431 return false;
3434 case lltok::kw_no_cfi: {
3435 // ValID ::= 'no_cfi' @foo
3436 Lex.Lex();
3438 if (parseValID(ID, PFS))
3439 return true;
3441 if (ID.Kind != ValID::t_GlobalID && ID.Kind != ValID::t_GlobalName)
3442 return error(ID.Loc, "expected global value name in no_cfi");
3444 ID.NoCFI = true;
3445 return false;
3448 case lltok::kw_trunc:
3449 case lltok::kw_zext:
3450 case lltok::kw_sext:
3451 case lltok::kw_fptrunc:
3452 case lltok::kw_fpext:
3453 case lltok::kw_bitcast:
3454 case lltok::kw_addrspacecast:
3455 case lltok::kw_uitofp:
3456 case lltok::kw_sitofp:
3457 case lltok::kw_fptoui:
3458 case lltok::kw_fptosi:
3459 case lltok::kw_inttoptr:
3460 case lltok::kw_ptrtoint: {
3461 unsigned Opc = Lex.getUIntVal();
3462 Type *DestTy = nullptr;
3463 Constant *SrcVal;
3464 Lex.Lex();
3465 if (parseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3466 parseGlobalTypeAndValue(SrcVal) ||
3467 parseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3468 parseType(DestTy) ||
3469 parseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3470 return true;
3471 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3472 return error(ID.Loc, "invalid cast opcode for cast from '" +
3473 getTypeString(SrcVal->getType()) + "' to '" +
3474 getTypeString(DestTy) + "'");
3475 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3476 SrcVal, DestTy);
3477 ID.Kind = ValID::t_Constant;
3478 return false;
3480 case lltok::kw_extractvalue:
3481 return error(ID.Loc, "extractvalue constexprs are no longer supported");
3482 case lltok::kw_insertvalue:
3483 return error(ID.Loc, "insertvalue constexprs are no longer supported");
3484 case lltok::kw_udiv:
3485 return error(ID.Loc, "udiv constexprs are no longer supported");
3486 case lltok::kw_sdiv:
3487 return error(ID.Loc, "sdiv constexprs are no longer supported");
3488 case lltok::kw_urem:
3489 return error(ID.Loc, "urem constexprs are no longer supported");
3490 case lltok::kw_srem:
3491 return error(ID.Loc, "srem constexprs are no longer supported");
3492 case lltok::kw_fadd:
3493 return error(ID.Loc, "fadd constexprs are no longer supported");
3494 case lltok::kw_fsub:
3495 return error(ID.Loc, "fsub constexprs are no longer supported");
3496 case lltok::kw_fmul:
3497 return error(ID.Loc, "fmul constexprs are no longer supported");
3498 case lltok::kw_fdiv:
3499 return error(ID.Loc, "fdiv constexprs are no longer supported");
3500 case lltok::kw_frem:
3501 return error(ID.Loc, "frem constexprs are no longer supported");
3502 case lltok::kw_icmp:
3503 case lltok::kw_fcmp: {
3504 unsigned PredVal, Opc = Lex.getUIntVal();
3505 Constant *Val0, *Val1;
3506 Lex.Lex();
3507 if (parseCmpPredicate(PredVal, Opc) ||
3508 parseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3509 parseGlobalTypeAndValue(Val0) ||
3510 parseToken(lltok::comma, "expected comma in compare constantexpr") ||
3511 parseGlobalTypeAndValue(Val1) ||
3512 parseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3513 return true;
3515 if (Val0->getType() != Val1->getType())
3516 return error(ID.Loc, "compare operands must have the same type");
3518 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3520 if (Opc == Instruction::FCmp) {
3521 if (!Val0->getType()->isFPOrFPVectorTy())
3522 return error(ID.Loc, "fcmp requires floating point operands");
3523 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3524 } else {
3525 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3526 if (!Val0->getType()->isIntOrIntVectorTy() &&
3527 !Val0->getType()->isPtrOrPtrVectorTy())
3528 return error(ID.Loc, "icmp requires pointer or integer operands");
3529 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3531 ID.Kind = ValID::t_Constant;
3532 return false;
3535 // Unary Operators.
3536 case lltok::kw_fneg: {
3537 unsigned Opc = Lex.getUIntVal();
3538 Constant *Val;
3539 Lex.Lex();
3540 if (parseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3541 parseGlobalTypeAndValue(Val) ||
3542 parseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3543 return true;
3545 // Check that the type is valid for the operator.
3546 switch (Opc) {
3547 case Instruction::FNeg:
3548 if (!Val->getType()->isFPOrFPVectorTy())
3549 return error(ID.Loc, "constexpr requires fp operands");
3550 break;
3551 default: llvm_unreachable("Unknown unary operator!");
3553 unsigned Flags = 0;
3554 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3555 ID.ConstantVal = C;
3556 ID.Kind = ValID::t_Constant;
3557 return false;
3559 // Binary Operators.
3560 case lltok::kw_add:
3561 case lltok::kw_sub:
3562 case lltok::kw_mul:
3563 case lltok::kw_shl:
3564 case lltok::kw_lshr:
3565 case lltok::kw_ashr: {
3566 bool NUW = false;
3567 bool NSW = false;
3568 bool Exact = false;
3569 unsigned Opc = Lex.getUIntVal();
3570 Constant *Val0, *Val1;
3571 Lex.Lex();
3572 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3573 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3574 if (EatIfPresent(lltok::kw_nuw))
3575 NUW = true;
3576 if (EatIfPresent(lltok::kw_nsw)) {
3577 NSW = true;
3578 if (EatIfPresent(lltok::kw_nuw))
3579 NUW = true;
3581 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3582 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3583 if (EatIfPresent(lltok::kw_exact))
3584 Exact = true;
3586 if (parseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3587 parseGlobalTypeAndValue(Val0) ||
3588 parseToken(lltok::comma, "expected comma in binary constantexpr") ||
3589 parseGlobalTypeAndValue(Val1) ||
3590 parseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3591 return true;
3592 if (Val0->getType() != Val1->getType())
3593 return error(ID.Loc, "operands of constexpr must have same type");
3594 // Check that the type is valid for the operator.
3595 switch (Opc) {
3596 case Instruction::Add:
3597 case Instruction::Sub:
3598 case Instruction::Mul:
3599 case Instruction::UDiv:
3600 case Instruction::SDiv:
3601 case Instruction::URem:
3602 case Instruction::SRem:
3603 case Instruction::Shl:
3604 case Instruction::AShr:
3605 case Instruction::LShr:
3606 if (!Val0->getType()->isIntOrIntVectorTy())
3607 return error(ID.Loc, "constexpr requires integer operands");
3608 break;
3609 case Instruction::FAdd:
3610 case Instruction::FSub:
3611 case Instruction::FMul:
3612 case Instruction::FDiv:
3613 case Instruction::FRem:
3614 if (!Val0->getType()->isFPOrFPVectorTy())
3615 return error(ID.Loc, "constexpr requires fp operands");
3616 break;
3617 default: llvm_unreachable("Unknown binary operator!");
3619 unsigned Flags = 0;
3620 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3621 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3622 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3623 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3624 ID.ConstantVal = C;
3625 ID.Kind = ValID::t_Constant;
3626 return false;
3629 // Logical Operations
3630 case lltok::kw_and:
3631 case lltok::kw_or:
3632 case lltok::kw_xor: {
3633 unsigned Opc = Lex.getUIntVal();
3634 Constant *Val0, *Val1;
3635 Lex.Lex();
3636 if (parseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3637 parseGlobalTypeAndValue(Val0) ||
3638 parseToken(lltok::comma, "expected comma in logical constantexpr") ||
3639 parseGlobalTypeAndValue(Val1) ||
3640 parseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3641 return true;
3642 if (Val0->getType() != Val1->getType())
3643 return error(ID.Loc, "operands of constexpr must have same type");
3644 if (!Val0->getType()->isIntOrIntVectorTy())
3645 return error(ID.Loc,
3646 "constexpr requires integer or integer vector operands");
3647 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3648 ID.Kind = ValID::t_Constant;
3649 return false;
3652 case lltok::kw_getelementptr:
3653 case lltok::kw_shufflevector:
3654 case lltok::kw_insertelement:
3655 case lltok::kw_extractelement:
3656 case lltok::kw_select: {
3657 unsigned Opc = Lex.getUIntVal();
3658 SmallVector<Constant*, 16> Elts;
3659 bool InBounds = false;
3660 Type *Ty;
3661 Lex.Lex();
3663 if (Opc == Instruction::GetElementPtr)
3664 InBounds = EatIfPresent(lltok::kw_inbounds);
3666 if (parseToken(lltok::lparen, "expected '(' in constantexpr"))
3667 return true;
3669 LocTy ExplicitTypeLoc = Lex.getLoc();
3670 if (Opc == Instruction::GetElementPtr) {
3671 if (parseType(Ty) ||
3672 parseToken(lltok::comma, "expected comma after getelementptr's type"))
3673 return true;
3676 Optional<unsigned> InRangeOp;
3677 if (parseGlobalValueVector(
3678 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3679 parseToken(lltok::rparen, "expected ')' in constantexpr"))
3680 return true;
3682 if (Opc == Instruction::GetElementPtr) {
3683 if (Elts.size() == 0 ||
3684 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3685 return error(ID.Loc, "base of getelementptr must be a pointer");
3687 Type *BaseType = Elts[0]->getType();
3688 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3689 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
3690 return error(
3691 ExplicitTypeLoc,
3692 typeComparisonErrorMessage(
3693 "explicit pointee type doesn't match operand's pointee type",
3694 Ty, BasePointerType->getNonOpaquePointerElementType()));
3697 unsigned GEPWidth =
3698 BaseType->isVectorTy()
3699 ? cast<FixedVectorType>(BaseType)->getNumElements()
3700 : 0;
3702 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3703 for (Constant *Val : Indices) {
3704 Type *ValTy = Val->getType();
3705 if (!ValTy->isIntOrIntVectorTy())
3706 return error(ID.Loc, "getelementptr index must be an integer");
3707 if (auto *ValVTy = dyn_cast<VectorType>(ValTy)) {
3708 unsigned ValNumEl = cast<FixedVectorType>(ValVTy)->getNumElements();
3709 if (GEPWidth && (ValNumEl != GEPWidth))
3710 return error(
3711 ID.Loc,
3712 "getelementptr vector index has a wrong number of elements");
3713 // GEPWidth may have been unknown because the base is a scalar,
3714 // but it is known now.
3715 GEPWidth = ValNumEl;
3719 SmallPtrSet<Type*, 4> Visited;
3720 if (!Indices.empty() && !Ty->isSized(&Visited))
3721 return error(ID.Loc, "base element of getelementptr must be sized");
3723 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3724 return error(ID.Loc, "invalid getelementptr indices");
3726 if (InRangeOp) {
3727 if (*InRangeOp == 0)
3728 return error(ID.Loc,
3729 "inrange keyword may not appear on pointer operand");
3730 --*InRangeOp;
3733 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3734 InBounds, InRangeOp);
3735 } else if (Opc == Instruction::Select) {
3736 if (Elts.size() != 3)
3737 return error(ID.Loc, "expected three operands to select");
3738 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3739 Elts[2]))
3740 return error(ID.Loc, Reason);
3741 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3742 } else if (Opc == Instruction::ShuffleVector) {
3743 if (Elts.size() != 3)
3744 return error(ID.Loc, "expected three operands to shufflevector");
3745 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3746 return error(ID.Loc, "invalid operands to shufflevector");
3747 SmallVector<int, 16> Mask;
3748 ShuffleVectorInst::getShuffleMask(cast<Constant>(Elts[2]), Mask);
3749 ID.ConstantVal = ConstantExpr::getShuffleVector(Elts[0], Elts[1], Mask);
3750 } else if (Opc == Instruction::ExtractElement) {
3751 if (Elts.size() != 2)
3752 return error(ID.Loc, "expected two operands to extractelement");
3753 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3754 return error(ID.Loc, "invalid extractelement operands");
3755 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3756 } else {
3757 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3758 if (Elts.size() != 3)
3759 return error(ID.Loc, "expected three operands to insertelement");
3760 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3761 return error(ID.Loc, "invalid insertelement operands");
3762 ID.ConstantVal =
3763 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3766 ID.Kind = ValID::t_Constant;
3767 return false;
3771 Lex.Lex();
3772 return false;
3775 /// parseGlobalValue - parse a global value with the specified type.
3776 bool LLParser::parseGlobalValue(Type *Ty, Constant *&C) {
3777 C = nullptr;
3778 ValID ID;
3779 Value *V = nullptr;
3780 bool Parsed = parseValID(ID, /*PFS=*/nullptr, Ty) ||
3781 convertValIDToValue(Ty, ID, V, nullptr);
3782 if (V && !(C = dyn_cast<Constant>(V)))
3783 return error(ID.Loc, "global values must be constants");
3784 return Parsed;
3787 bool LLParser::parseGlobalTypeAndValue(Constant *&V) {
3788 Type *Ty = nullptr;
3789 return parseType(Ty) || parseGlobalValue(Ty, V);
3792 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3793 C = nullptr;
3795 LocTy KwLoc = Lex.getLoc();
3796 if (!EatIfPresent(lltok::kw_comdat))
3797 return false;
3799 if (EatIfPresent(lltok::lparen)) {
3800 if (Lex.getKind() != lltok::ComdatVar)
3801 return tokError("expected comdat variable");
3802 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3803 Lex.Lex();
3804 if (parseToken(lltok::rparen, "expected ')' after comdat var"))
3805 return true;
3806 } else {
3807 if (GlobalName.empty())
3808 return tokError("comdat cannot be unnamed");
3809 C = getComdat(std::string(GlobalName), KwLoc);
3812 return false;
3815 /// parseGlobalValueVector
3816 /// ::= /*empty*/
3817 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3818 bool LLParser::parseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3819 Optional<unsigned> *InRangeOp) {
3820 // Empty list.
3821 if (Lex.getKind() == lltok::rbrace ||
3822 Lex.getKind() == lltok::rsquare ||
3823 Lex.getKind() == lltok::greater ||
3824 Lex.getKind() == lltok::rparen)
3825 return false;
3827 do {
3828 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3829 *InRangeOp = Elts.size();
3831 Constant *C;
3832 if (parseGlobalTypeAndValue(C))
3833 return true;
3834 Elts.push_back(C);
3835 } while (EatIfPresent(lltok::comma));
3837 return false;
3840 bool LLParser::parseMDTuple(MDNode *&MD, bool IsDistinct) {
3841 SmallVector<Metadata *, 16> Elts;
3842 if (parseMDNodeVector(Elts))
3843 return true;
3845 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3846 return false;
3849 /// MDNode:
3850 /// ::= !{ ... }
3851 /// ::= !7
3852 /// ::= !DILocation(...)
3853 bool LLParser::parseMDNode(MDNode *&N) {
3854 if (Lex.getKind() == lltok::MetadataVar)
3855 return parseSpecializedMDNode(N);
3857 return parseToken(lltok::exclaim, "expected '!' here") || parseMDNodeTail(N);
3860 bool LLParser::parseMDNodeTail(MDNode *&N) {
3861 // !{ ... }
3862 if (Lex.getKind() == lltok::lbrace)
3863 return parseMDTuple(N);
3865 // !42
3866 return parseMDNodeID(N);
3869 namespace {
3871 /// Structure to represent an optional metadata field.
3872 template <class FieldTy> struct MDFieldImpl {
3873 typedef MDFieldImpl ImplTy;
3874 FieldTy Val;
3875 bool Seen;
3877 void assign(FieldTy Val) {
3878 Seen = true;
3879 this->Val = std::move(Val);
3882 explicit MDFieldImpl(FieldTy Default)
3883 : Val(std::move(Default)), Seen(false) {}
3886 /// Structure to represent an optional metadata field that
3887 /// can be of either type (A or B) and encapsulates the
3888 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3889 /// to reimplement the specifics for representing each Field.
3890 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3891 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3892 FieldTypeA A;
3893 FieldTypeB B;
3894 bool Seen;
3896 enum {
3897 IsInvalid = 0,
3898 IsTypeA = 1,
3899 IsTypeB = 2
3900 } WhatIs;
3902 void assign(FieldTypeA A) {
3903 Seen = true;
3904 this->A = std::move(A);
3905 WhatIs = IsTypeA;
3908 void assign(FieldTypeB B) {
3909 Seen = true;
3910 this->B = std::move(B);
3911 WhatIs = IsTypeB;
3914 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3915 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3916 WhatIs(IsInvalid) {}
3919 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3920 uint64_t Max;
3922 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3923 : ImplTy(Default), Max(Max) {}
3926 struct LineField : public MDUnsignedField {
3927 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3930 struct ColumnField : public MDUnsignedField {
3931 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3934 struct DwarfTagField : public MDUnsignedField {
3935 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3936 DwarfTagField(dwarf::Tag DefaultTag)
3937 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3940 struct DwarfMacinfoTypeField : public MDUnsignedField {
3941 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3942 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3943 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3946 struct DwarfAttEncodingField : public MDUnsignedField {
3947 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3950 struct DwarfVirtualityField : public MDUnsignedField {
3951 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3954 struct DwarfLangField : public MDUnsignedField {
3955 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3958 struct DwarfCCField : public MDUnsignedField {
3959 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3962 struct EmissionKindField : public MDUnsignedField {
3963 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3966 struct NameTableKindField : public MDUnsignedField {
3967 NameTableKindField()
3968 : MDUnsignedField(
3969 0, (unsigned)
3970 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3973 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3974 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3977 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3978 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3981 struct MDAPSIntField : public MDFieldImpl<APSInt> {
3982 MDAPSIntField() : ImplTy(APSInt()) {}
3985 struct MDSignedField : public MDFieldImpl<int64_t> {
3986 int64_t Min = INT64_MIN;
3987 int64_t Max = INT64_MAX;
3989 MDSignedField(int64_t Default = 0)
3990 : ImplTy(Default) {}
3991 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3992 : ImplTy(Default), Min(Min), Max(Max) {}
3995 struct MDBoolField : public MDFieldImpl<bool> {
3996 MDBoolField(bool Default = false) : ImplTy(Default) {}
3999 struct MDField : public MDFieldImpl<Metadata *> {
4000 bool AllowNull;
4002 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
4005 struct MDStringField : public MDFieldImpl<MDString *> {
4006 bool AllowEmpty;
4007 MDStringField(bool AllowEmpty = true)
4008 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
4011 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
4012 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
4015 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
4016 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
4019 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
4020 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
4021 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
4023 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
4024 bool AllowNull = true)
4025 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
4027 bool isMDSignedField() const { return WhatIs == IsTypeA; }
4028 bool isMDField() const { return WhatIs == IsTypeB; }
4029 int64_t getMDSignedValue() const {
4030 assert(isMDSignedField() && "Wrong field type");
4031 return A.Val;
4033 Metadata *getMDFieldValue() const {
4034 assert(isMDField() && "Wrong field type");
4035 return B.Val;
4039 } // end anonymous namespace
4041 namespace llvm {
4043 template <>
4044 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDAPSIntField &Result) {
4045 if (Lex.getKind() != lltok::APSInt)
4046 return tokError("expected integer");
4048 Result.assign(Lex.getAPSIntVal());
4049 Lex.Lex();
4050 return false;
4053 template <>
4054 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4055 MDUnsignedField &Result) {
4056 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4057 return tokError("expected unsigned integer");
4059 auto &U = Lex.getAPSIntVal();
4060 if (U.ugt(Result.Max))
4061 return tokError("value for '" + Name + "' too large, limit is " +
4062 Twine(Result.Max));
4063 Result.assign(U.getZExtValue());
4064 assert(Result.Val <= Result.Max && "Expected value in range");
4065 Lex.Lex();
4066 return false;
4069 template <>
4070 bool LLParser::parseMDField(LocTy Loc, StringRef Name, LineField &Result) {
4071 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4073 template <>
4074 bool LLParser::parseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
4075 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4078 template <>
4079 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
4080 if (Lex.getKind() == lltok::APSInt)
4081 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4083 if (Lex.getKind() != lltok::DwarfTag)
4084 return tokError("expected DWARF tag");
4086 unsigned Tag = dwarf::getTag(Lex.getStrVal());
4087 if (Tag == dwarf::DW_TAG_invalid)
4088 return tokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
4089 assert(Tag <= Result.Max && "Expected valid DWARF tag");
4091 Result.assign(Tag);
4092 Lex.Lex();
4093 return false;
4096 template <>
4097 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4098 DwarfMacinfoTypeField &Result) {
4099 if (Lex.getKind() == lltok::APSInt)
4100 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4102 if (Lex.getKind() != lltok::DwarfMacinfo)
4103 return tokError("expected DWARF macinfo type");
4105 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
4106 if (Macinfo == dwarf::DW_MACINFO_invalid)
4107 return tokError("invalid DWARF macinfo type" + Twine(" '") +
4108 Lex.getStrVal() + "'");
4109 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
4111 Result.assign(Macinfo);
4112 Lex.Lex();
4113 return false;
4116 template <>
4117 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4118 DwarfVirtualityField &Result) {
4119 if (Lex.getKind() == lltok::APSInt)
4120 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4122 if (Lex.getKind() != lltok::DwarfVirtuality)
4123 return tokError("expected DWARF virtuality code");
4125 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4126 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4127 return tokError("invalid DWARF virtuality code" + Twine(" '") +
4128 Lex.getStrVal() + "'");
4129 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4130 Result.assign(Virtuality);
4131 Lex.Lex();
4132 return false;
4135 template <>
4136 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4137 if (Lex.getKind() == lltok::APSInt)
4138 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4140 if (Lex.getKind() != lltok::DwarfLang)
4141 return tokError("expected DWARF language");
4143 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4144 if (!Lang)
4145 return tokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4146 "'");
4147 assert(Lang <= Result.Max && "Expected valid DWARF language");
4148 Result.assign(Lang);
4149 Lex.Lex();
4150 return false;
4153 template <>
4154 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4155 if (Lex.getKind() == lltok::APSInt)
4156 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4158 if (Lex.getKind() != lltok::DwarfCC)
4159 return tokError("expected DWARF calling convention");
4161 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4162 if (!CC)
4163 return tokError("invalid DWARF calling convention" + Twine(" '") +
4164 Lex.getStrVal() + "'");
4165 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4166 Result.assign(CC);
4167 Lex.Lex();
4168 return false;
4171 template <>
4172 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4173 EmissionKindField &Result) {
4174 if (Lex.getKind() == lltok::APSInt)
4175 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4177 if (Lex.getKind() != lltok::EmissionKind)
4178 return tokError("expected emission kind");
4180 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4181 if (!Kind)
4182 return tokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4183 "'");
4184 assert(*Kind <= Result.Max && "Expected valid emission kind");
4185 Result.assign(*Kind);
4186 Lex.Lex();
4187 return false;
4190 template <>
4191 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4192 NameTableKindField &Result) {
4193 if (Lex.getKind() == lltok::APSInt)
4194 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4196 if (Lex.getKind() != lltok::NameTableKind)
4197 return tokError("expected nameTable kind");
4199 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4200 if (!Kind)
4201 return tokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4202 "'");
4203 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4204 Result.assign((unsigned)*Kind);
4205 Lex.Lex();
4206 return false;
4209 template <>
4210 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4211 DwarfAttEncodingField &Result) {
4212 if (Lex.getKind() == lltok::APSInt)
4213 return parseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4215 if (Lex.getKind() != lltok::DwarfAttEncoding)
4216 return tokError("expected DWARF type attribute encoding");
4218 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4219 if (!Encoding)
4220 return tokError("invalid DWARF type attribute encoding" + Twine(" '") +
4221 Lex.getStrVal() + "'");
4222 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4223 Result.assign(Encoding);
4224 Lex.Lex();
4225 return false;
4228 /// DIFlagField
4229 /// ::= uint32
4230 /// ::= DIFlagVector
4231 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4232 template <>
4233 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4235 // parser for a single flag.
4236 auto parseFlag = [&](DINode::DIFlags &Val) {
4237 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4238 uint32_t TempVal = static_cast<uint32_t>(Val);
4239 bool Res = parseUInt32(TempVal);
4240 Val = static_cast<DINode::DIFlags>(TempVal);
4241 return Res;
4244 if (Lex.getKind() != lltok::DIFlag)
4245 return tokError("expected debug info flag");
4247 Val = DINode::getFlag(Lex.getStrVal());
4248 if (!Val)
4249 return tokError(Twine("invalid debug info flag '") + Lex.getStrVal() +
4250 "'");
4251 Lex.Lex();
4252 return false;
4255 // parse the flags and combine them together.
4256 DINode::DIFlags Combined = DINode::FlagZero;
4257 do {
4258 DINode::DIFlags Val;
4259 if (parseFlag(Val))
4260 return true;
4261 Combined |= Val;
4262 } while (EatIfPresent(lltok::bar));
4264 Result.assign(Combined);
4265 return false;
4268 /// DISPFlagField
4269 /// ::= uint32
4270 /// ::= DISPFlagVector
4271 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4272 template <>
4273 bool LLParser::parseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4275 // parser for a single flag.
4276 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4277 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4278 uint32_t TempVal = static_cast<uint32_t>(Val);
4279 bool Res = parseUInt32(TempVal);
4280 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4281 return Res;
4284 if (Lex.getKind() != lltok::DISPFlag)
4285 return tokError("expected debug info flag");
4287 Val = DISubprogram::getFlag(Lex.getStrVal());
4288 if (!Val)
4289 return tokError(Twine("invalid subprogram debug info flag '") +
4290 Lex.getStrVal() + "'");
4291 Lex.Lex();
4292 return false;
4295 // parse the flags and combine them together.
4296 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4297 do {
4298 DISubprogram::DISPFlags Val;
4299 if (parseFlag(Val))
4300 return true;
4301 Combined |= Val;
4302 } while (EatIfPresent(lltok::bar));
4304 Result.assign(Combined);
4305 return false;
4308 template <>
4309 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDSignedField &Result) {
4310 if (Lex.getKind() != lltok::APSInt)
4311 return tokError("expected signed integer");
4313 auto &S = Lex.getAPSIntVal();
4314 if (S < Result.Min)
4315 return tokError("value for '" + Name + "' too small, limit is " +
4316 Twine(Result.Min));
4317 if (S > Result.Max)
4318 return tokError("value for '" + Name + "' too large, limit is " +
4319 Twine(Result.Max));
4320 Result.assign(S.getExtValue());
4321 assert(Result.Val >= Result.Min && "Expected value in range");
4322 assert(Result.Val <= Result.Max && "Expected value in range");
4323 Lex.Lex();
4324 return false;
4327 template <>
4328 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4329 switch (Lex.getKind()) {
4330 default:
4331 return tokError("expected 'true' or 'false'");
4332 case lltok::kw_true:
4333 Result.assign(true);
4334 break;
4335 case lltok::kw_false:
4336 Result.assign(false);
4337 break;
4339 Lex.Lex();
4340 return false;
4343 template <>
4344 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4345 if (Lex.getKind() == lltok::kw_null) {
4346 if (!Result.AllowNull)
4347 return tokError("'" + Name + "' cannot be null");
4348 Lex.Lex();
4349 Result.assign(nullptr);
4350 return false;
4353 Metadata *MD;
4354 if (parseMetadata(MD, nullptr))
4355 return true;
4357 Result.assign(MD);
4358 return false;
4361 template <>
4362 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4363 MDSignedOrMDField &Result) {
4364 // Try to parse a signed int.
4365 if (Lex.getKind() == lltok::APSInt) {
4366 MDSignedField Res = Result.A;
4367 if (!parseMDField(Loc, Name, Res)) {
4368 Result.assign(Res);
4369 return false;
4371 return true;
4374 // Otherwise, try to parse as an MDField.
4375 MDField Res = Result.B;
4376 if (!parseMDField(Loc, Name, Res)) {
4377 Result.assign(Res);
4378 return false;
4381 return true;
4384 template <>
4385 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4386 LocTy ValueLoc = Lex.getLoc();
4387 std::string S;
4388 if (parseStringConstant(S))
4389 return true;
4391 if (!Result.AllowEmpty && S.empty())
4392 return error(ValueLoc, "'" + Name + "' cannot be empty");
4394 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4395 return false;
4398 template <>
4399 bool LLParser::parseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4400 SmallVector<Metadata *, 4> MDs;
4401 if (parseMDNodeVector(MDs))
4402 return true;
4404 Result.assign(std::move(MDs));
4405 return false;
4408 template <>
4409 bool LLParser::parseMDField(LocTy Loc, StringRef Name,
4410 ChecksumKindField &Result) {
4411 Optional<DIFile::ChecksumKind> CSKind =
4412 DIFile::getChecksumKind(Lex.getStrVal());
4414 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4415 return tokError("invalid checksum kind" + Twine(" '") + Lex.getStrVal() +
4416 "'");
4418 Result.assign(*CSKind);
4419 Lex.Lex();
4420 return false;
4423 } // end namespace llvm
4425 template <class ParserTy>
4426 bool LLParser::parseMDFieldsImplBody(ParserTy ParseField) {
4427 do {
4428 if (Lex.getKind() != lltok::LabelStr)
4429 return tokError("expected field label here");
4431 if (ParseField())
4432 return true;
4433 } while (EatIfPresent(lltok::comma));
4435 return false;
4438 template <class ParserTy>
4439 bool LLParser::parseMDFieldsImpl(ParserTy ParseField, LocTy &ClosingLoc) {
4440 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4441 Lex.Lex();
4443 if (parseToken(lltok::lparen, "expected '(' here"))
4444 return true;
4445 if (Lex.getKind() != lltok::rparen)
4446 if (parseMDFieldsImplBody(ParseField))
4447 return true;
4449 ClosingLoc = Lex.getLoc();
4450 return parseToken(lltok::rparen, "expected ')' here");
4453 template <class FieldTy>
4454 bool LLParser::parseMDField(StringRef Name, FieldTy &Result) {
4455 if (Result.Seen)
4456 return tokError("field '" + Name + "' cannot be specified more than once");
4458 LocTy Loc = Lex.getLoc();
4459 Lex.Lex();
4460 return parseMDField(Loc, Name, Result);
4463 bool LLParser::parseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4464 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4466 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4467 if (Lex.getStrVal() == #CLASS) \
4468 return parse##CLASS(N, IsDistinct);
4469 #include "llvm/IR/Metadata.def"
4471 return tokError("expected metadata type");
4474 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4475 #define NOP_FIELD(NAME, TYPE, INIT)
4476 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4477 if (!NAME.Seen) \
4478 return error(ClosingLoc, "missing required field '" #NAME "'");
4479 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4480 if (Lex.getStrVal() == #NAME) \
4481 return parseMDField(#NAME, NAME);
4482 #define PARSE_MD_FIELDS() \
4483 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4484 do { \
4485 LocTy ClosingLoc; \
4486 if (parseMDFieldsImpl( \
4487 [&]() -> bool { \
4488 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4489 return tokError(Twine("invalid field '") + Lex.getStrVal() + \
4490 "'"); \
4491 }, \
4492 ClosingLoc)) \
4493 return true; \
4494 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4495 } while (false)
4496 #define GET_OR_DISTINCT(CLASS, ARGS) \
4497 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4499 /// parseDILocationFields:
4500 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4501 /// isImplicitCode: true)
4502 bool LLParser::parseDILocation(MDNode *&Result, bool IsDistinct) {
4503 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4504 OPTIONAL(line, LineField, ); \
4505 OPTIONAL(column, ColumnField, ); \
4506 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4507 OPTIONAL(inlinedAt, MDField, ); \
4508 OPTIONAL(isImplicitCode, MDBoolField, (false));
4509 PARSE_MD_FIELDS();
4510 #undef VISIT_MD_FIELDS
4512 Result =
4513 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4514 inlinedAt.Val, isImplicitCode.Val));
4515 return false;
4518 /// parseGenericDINode:
4519 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4520 bool LLParser::parseGenericDINode(MDNode *&Result, bool IsDistinct) {
4521 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4522 REQUIRED(tag, DwarfTagField, ); \
4523 OPTIONAL(header, MDStringField, ); \
4524 OPTIONAL(operands, MDFieldList, );
4525 PARSE_MD_FIELDS();
4526 #undef VISIT_MD_FIELDS
4528 Result = GET_OR_DISTINCT(GenericDINode,
4529 (Context, tag.Val, header.Val, operands.Val));
4530 return false;
4533 /// parseDISubrange:
4534 /// ::= !DISubrange(count: 30, lowerBound: 2)
4535 /// ::= !DISubrange(count: !node, lowerBound: 2)
4536 /// ::= !DISubrange(lowerBound: !node1, upperBound: !node2, stride: !node3)
4537 bool LLParser::parseDISubrange(MDNode *&Result, bool IsDistinct) {
4538 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4539 OPTIONAL(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4540 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4541 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4542 OPTIONAL(stride, MDSignedOrMDField, );
4543 PARSE_MD_FIELDS();
4544 #undef VISIT_MD_FIELDS
4546 Metadata *Count = nullptr;
4547 Metadata *LowerBound = nullptr;
4548 Metadata *UpperBound = nullptr;
4549 Metadata *Stride = nullptr;
4551 auto convToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4552 if (Bound.isMDSignedField())
4553 return ConstantAsMetadata::get(ConstantInt::getSigned(
4554 Type::getInt64Ty(Context), Bound.getMDSignedValue()));
4555 if (Bound.isMDField())
4556 return Bound.getMDFieldValue();
4557 return nullptr;
4560 Count = convToMetadata(count);
4561 LowerBound = convToMetadata(lowerBound);
4562 UpperBound = convToMetadata(upperBound);
4563 Stride = convToMetadata(stride);
4565 Result = GET_OR_DISTINCT(DISubrange,
4566 (Context, Count, LowerBound, UpperBound, Stride));
4568 return false;
4571 /// parseDIGenericSubrange:
4572 /// ::= !DIGenericSubrange(lowerBound: !node1, upperBound: !node2, stride:
4573 /// !node3)
4574 bool LLParser::parseDIGenericSubrange(MDNode *&Result, bool IsDistinct) {
4575 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4576 OPTIONAL(count, MDSignedOrMDField, ); \
4577 OPTIONAL(lowerBound, MDSignedOrMDField, ); \
4578 OPTIONAL(upperBound, MDSignedOrMDField, ); \
4579 OPTIONAL(stride, MDSignedOrMDField, );
4580 PARSE_MD_FIELDS();
4581 #undef VISIT_MD_FIELDS
4583 auto ConvToMetadata = [&](MDSignedOrMDField Bound) -> Metadata * {
4584 if (Bound.isMDSignedField())
4585 return DIExpression::get(
4586 Context, {dwarf::DW_OP_consts,
4587 static_cast<uint64_t>(Bound.getMDSignedValue())});
4588 if (Bound.isMDField())
4589 return Bound.getMDFieldValue();
4590 return nullptr;
4593 Metadata *Count = ConvToMetadata(count);
4594 Metadata *LowerBound = ConvToMetadata(lowerBound);
4595 Metadata *UpperBound = ConvToMetadata(upperBound);
4596 Metadata *Stride = ConvToMetadata(stride);
4598 Result = GET_OR_DISTINCT(DIGenericSubrange,
4599 (Context, Count, LowerBound, UpperBound, Stride));
4601 return false;
4604 /// parseDIEnumerator:
4605 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4606 bool LLParser::parseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4607 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4608 REQUIRED(name, MDStringField, ); \
4609 REQUIRED(value, MDAPSIntField, ); \
4610 OPTIONAL(isUnsigned, MDBoolField, (false));
4611 PARSE_MD_FIELDS();
4612 #undef VISIT_MD_FIELDS
4614 if (isUnsigned.Val && value.Val.isNegative())
4615 return tokError("unsigned enumerator with negative value");
4617 APSInt Value(value.Val);
4618 // Add a leading zero so that unsigned values with the msb set are not
4619 // mistaken for negative values when used for signed enumerators.
4620 if (!isUnsigned.Val && value.Val.isUnsigned() && value.Val.isSignBitSet())
4621 Value = Value.zext(Value.getBitWidth() + 1);
4623 Result =
4624 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4626 return false;
4629 /// parseDIBasicType:
4630 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4631 /// encoding: DW_ATE_encoding, flags: 0)
4632 bool LLParser::parseDIBasicType(MDNode *&Result, bool IsDistinct) {
4633 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4634 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4635 OPTIONAL(name, MDStringField, ); \
4636 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4637 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4638 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4639 OPTIONAL(flags, DIFlagField, );
4640 PARSE_MD_FIELDS();
4641 #undef VISIT_MD_FIELDS
4643 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4644 align.Val, encoding.Val, flags.Val));
4645 return false;
4648 /// parseDIStringType:
4649 /// ::= !DIStringType(name: "character(4)", size: 32, align: 32)
4650 bool LLParser::parseDIStringType(MDNode *&Result, bool IsDistinct) {
4651 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4652 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_string_type)); \
4653 OPTIONAL(name, MDStringField, ); \
4654 OPTIONAL(stringLength, MDField, ); \
4655 OPTIONAL(stringLengthExpression, MDField, ); \
4656 OPTIONAL(stringLocationExpression, MDField, ); \
4657 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4658 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4659 OPTIONAL(encoding, DwarfAttEncodingField, );
4660 PARSE_MD_FIELDS();
4661 #undef VISIT_MD_FIELDS
4663 Result = GET_OR_DISTINCT(
4664 DIStringType,
4665 (Context, tag.Val, name.Val, stringLength.Val, stringLengthExpression.Val,
4666 stringLocationExpression.Val, size.Val, align.Val, encoding.Val));
4667 return false;
4670 /// parseDIDerivedType:
4671 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4672 /// line: 7, scope: !1, baseType: !2, size: 32,
4673 /// align: 32, offset: 0, flags: 0, extraData: !3,
4674 /// dwarfAddressSpace: 3)
4675 bool LLParser::parseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4676 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4677 REQUIRED(tag, DwarfTagField, ); \
4678 OPTIONAL(name, MDStringField, ); \
4679 OPTIONAL(file, MDField, ); \
4680 OPTIONAL(line, LineField, ); \
4681 OPTIONAL(scope, MDField, ); \
4682 REQUIRED(baseType, MDField, ); \
4683 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4684 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4685 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4686 OPTIONAL(flags, DIFlagField, ); \
4687 OPTIONAL(extraData, MDField, ); \
4688 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX)); \
4689 OPTIONAL(annotations, MDField, );
4690 PARSE_MD_FIELDS();
4691 #undef VISIT_MD_FIELDS
4693 Optional<unsigned> DWARFAddressSpace;
4694 if (dwarfAddressSpace.Val != UINT32_MAX)
4695 DWARFAddressSpace = dwarfAddressSpace.Val;
4697 Result = GET_OR_DISTINCT(DIDerivedType,
4698 (Context, tag.Val, name.Val, file.Val, line.Val,
4699 scope.Val, baseType.Val, size.Val, align.Val,
4700 offset.Val, DWARFAddressSpace, flags.Val,
4701 extraData.Val, annotations.Val));
4702 return false;
4705 bool LLParser::parseDICompositeType(MDNode *&Result, bool IsDistinct) {
4706 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4707 REQUIRED(tag, DwarfTagField, ); \
4708 OPTIONAL(name, MDStringField, ); \
4709 OPTIONAL(file, MDField, ); \
4710 OPTIONAL(line, LineField, ); \
4711 OPTIONAL(scope, MDField, ); \
4712 OPTIONAL(baseType, MDField, ); \
4713 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4714 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4715 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4716 OPTIONAL(flags, DIFlagField, ); \
4717 OPTIONAL(elements, MDField, ); \
4718 OPTIONAL(runtimeLang, DwarfLangField, ); \
4719 OPTIONAL(vtableHolder, MDField, ); \
4720 OPTIONAL(templateParams, MDField, ); \
4721 OPTIONAL(identifier, MDStringField, ); \
4722 OPTIONAL(discriminator, MDField, ); \
4723 OPTIONAL(dataLocation, MDField, ); \
4724 OPTIONAL(associated, MDField, ); \
4725 OPTIONAL(allocated, MDField, ); \
4726 OPTIONAL(rank, MDSignedOrMDField, ); \
4727 OPTIONAL(annotations, MDField, );
4728 PARSE_MD_FIELDS();
4729 #undef VISIT_MD_FIELDS
4731 Metadata *Rank = nullptr;
4732 if (rank.isMDSignedField())
4733 Rank = ConstantAsMetadata::get(ConstantInt::getSigned(
4734 Type::getInt64Ty(Context), rank.getMDSignedValue()));
4735 else if (rank.isMDField())
4736 Rank = rank.getMDFieldValue();
4738 // If this has an identifier try to build an ODR type.
4739 if (identifier.Val)
4740 if (auto *CT = DICompositeType::buildODRType(
4741 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4742 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4743 elements.Val, runtimeLang.Val, vtableHolder.Val, templateParams.Val,
4744 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val,
4745 Rank, annotations.Val)) {
4746 Result = CT;
4747 return false;
4750 // Create a new node, and save it in the context if it belongs in the type
4751 // map.
4752 Result = GET_OR_DISTINCT(
4753 DICompositeType,
4754 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4755 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4756 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4757 discriminator.Val, dataLocation.Val, associated.Val, allocated.Val, Rank,
4758 annotations.Val));
4759 return false;
4762 bool LLParser::parseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4763 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4764 OPTIONAL(flags, DIFlagField, ); \
4765 OPTIONAL(cc, DwarfCCField, ); \
4766 REQUIRED(types, MDField, );
4767 PARSE_MD_FIELDS();
4768 #undef VISIT_MD_FIELDS
4770 Result = GET_OR_DISTINCT(DISubroutineType,
4771 (Context, flags.Val, cc.Val, types.Val));
4772 return false;
4775 /// parseDIFileType:
4776 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4777 /// checksumkind: CSK_MD5,
4778 /// checksum: "000102030405060708090a0b0c0d0e0f",
4779 /// source: "source file contents")
4780 bool LLParser::parseDIFile(MDNode *&Result, bool IsDistinct) {
4781 // The default constructed value for checksumkind is required, but will never
4782 // be used, as the parser checks if the field was actually Seen before using
4783 // the Val.
4784 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4785 REQUIRED(filename, MDStringField, ); \
4786 REQUIRED(directory, MDStringField, ); \
4787 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4788 OPTIONAL(checksum, MDStringField, ); \
4789 OPTIONAL(source, MDStringField, );
4790 PARSE_MD_FIELDS();
4791 #undef VISIT_MD_FIELDS
4793 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4794 if (checksumkind.Seen && checksum.Seen)
4795 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4796 else if (checksumkind.Seen || checksum.Seen)
4797 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4799 Optional<MDString *> OptSource;
4800 if (source.Seen)
4801 OptSource = source.Val;
4802 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4803 OptChecksum, OptSource));
4804 return false;
4807 /// parseDICompileUnit:
4808 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4809 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4810 /// splitDebugFilename: "abc.debug",
4811 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4812 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd,
4813 /// sysroot: "/", sdk: "MacOSX.sdk")
4814 bool LLParser::parseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4815 if (!IsDistinct)
4816 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4818 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4819 REQUIRED(language, DwarfLangField, ); \
4820 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4821 OPTIONAL(producer, MDStringField, ); \
4822 OPTIONAL(isOptimized, MDBoolField, ); \
4823 OPTIONAL(flags, MDStringField, ); \
4824 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4825 OPTIONAL(splitDebugFilename, MDStringField, ); \
4826 OPTIONAL(emissionKind, EmissionKindField, ); \
4827 OPTIONAL(enums, MDField, ); \
4828 OPTIONAL(retainedTypes, MDField, ); \
4829 OPTIONAL(globals, MDField, ); \
4830 OPTIONAL(imports, MDField, ); \
4831 OPTIONAL(macros, MDField, ); \
4832 OPTIONAL(dwoId, MDUnsignedField, ); \
4833 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4834 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4835 OPTIONAL(nameTableKind, NameTableKindField, ); \
4836 OPTIONAL(rangesBaseAddress, MDBoolField, = false); \
4837 OPTIONAL(sysroot, MDStringField, ); \
4838 OPTIONAL(sdk, MDStringField, );
4839 PARSE_MD_FIELDS();
4840 #undef VISIT_MD_FIELDS
4842 Result = DICompileUnit::getDistinct(
4843 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4844 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4845 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4846 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4847 rangesBaseAddress.Val, sysroot.Val, sdk.Val);
4848 return false;
4851 /// parseDISubprogram:
4852 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4853 /// file: !1, line: 7, type: !2, isLocal: false,
4854 /// isDefinition: true, scopeLine: 8, containingType: !3,
4855 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4856 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4857 /// spFlags: 10, isOptimized: false, templateParams: !4,
4858 /// declaration: !5, retainedNodes: !6, thrownTypes: !7,
4859 /// annotations: !8)
4860 bool LLParser::parseDISubprogram(MDNode *&Result, bool IsDistinct) {
4861 auto Loc = Lex.getLoc();
4862 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4863 OPTIONAL(scope, MDField, ); \
4864 OPTIONAL(name, MDStringField, ); \
4865 OPTIONAL(linkageName, MDStringField, ); \
4866 OPTIONAL(file, MDField, ); \
4867 OPTIONAL(line, LineField, ); \
4868 OPTIONAL(type, MDField, ); \
4869 OPTIONAL(isLocal, MDBoolField, ); \
4870 OPTIONAL(isDefinition, MDBoolField, (true)); \
4871 OPTIONAL(scopeLine, LineField, ); \
4872 OPTIONAL(containingType, MDField, ); \
4873 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4874 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4875 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4876 OPTIONAL(flags, DIFlagField, ); \
4877 OPTIONAL(spFlags, DISPFlagField, ); \
4878 OPTIONAL(isOptimized, MDBoolField, ); \
4879 OPTIONAL(unit, MDField, ); \
4880 OPTIONAL(templateParams, MDField, ); \
4881 OPTIONAL(declaration, MDField, ); \
4882 OPTIONAL(retainedNodes, MDField, ); \
4883 OPTIONAL(thrownTypes, MDField, ); \
4884 OPTIONAL(annotations, MDField, ); \
4885 OPTIONAL(targetFuncName, MDStringField, );
4886 PARSE_MD_FIELDS();
4887 #undef VISIT_MD_FIELDS
4889 // An explicit spFlags field takes precedence over individual fields in
4890 // older IR versions.
4891 DISubprogram::DISPFlags SPFlags =
4892 spFlags.Seen ? spFlags.Val
4893 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4894 isOptimized.Val, virtuality.Val);
4895 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4896 return Lex.Error(
4897 Loc,
4898 "missing 'distinct', required for !DISubprogram that is a Definition");
4899 Result = GET_OR_DISTINCT(
4900 DISubprogram,
4901 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4902 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4903 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
4904 declaration.Val, retainedNodes.Val, thrownTypes.Val, annotations.Val,
4905 targetFuncName.Val));
4906 return false;
4909 /// parseDILexicalBlock:
4910 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4911 bool LLParser::parseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4912 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4913 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4914 OPTIONAL(file, MDField, ); \
4915 OPTIONAL(line, LineField, ); \
4916 OPTIONAL(column, ColumnField, );
4917 PARSE_MD_FIELDS();
4918 #undef VISIT_MD_FIELDS
4920 Result = GET_OR_DISTINCT(
4921 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4922 return false;
4925 /// parseDILexicalBlockFile:
4926 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4927 bool LLParser::parseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4928 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4929 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4930 OPTIONAL(file, MDField, ); \
4931 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4932 PARSE_MD_FIELDS();
4933 #undef VISIT_MD_FIELDS
4935 Result = GET_OR_DISTINCT(DILexicalBlockFile,
4936 (Context, scope.Val, file.Val, discriminator.Val));
4937 return false;
4940 /// parseDICommonBlock:
4941 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4942 bool LLParser::parseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4943 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4944 REQUIRED(scope, MDField, ); \
4945 OPTIONAL(declaration, MDField, ); \
4946 OPTIONAL(name, MDStringField, ); \
4947 OPTIONAL(file, MDField, ); \
4948 OPTIONAL(line, LineField, );
4949 PARSE_MD_FIELDS();
4950 #undef VISIT_MD_FIELDS
4952 Result = GET_OR_DISTINCT(DICommonBlock,
4953 (Context, scope.Val, declaration.Val, name.Val,
4954 file.Val, line.Val));
4955 return false;
4958 /// parseDINamespace:
4959 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4960 bool LLParser::parseDINamespace(MDNode *&Result, bool IsDistinct) {
4961 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4962 REQUIRED(scope, MDField, ); \
4963 OPTIONAL(name, MDStringField, ); \
4964 OPTIONAL(exportSymbols, MDBoolField, );
4965 PARSE_MD_FIELDS();
4966 #undef VISIT_MD_FIELDS
4968 Result = GET_OR_DISTINCT(DINamespace,
4969 (Context, scope.Val, name.Val, exportSymbols.Val));
4970 return false;
4973 /// parseDIMacro:
4974 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value:
4975 /// "SomeValue")
4976 bool LLParser::parseDIMacro(MDNode *&Result, bool IsDistinct) {
4977 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4978 REQUIRED(type, DwarfMacinfoTypeField, ); \
4979 OPTIONAL(line, LineField, ); \
4980 REQUIRED(name, MDStringField, ); \
4981 OPTIONAL(value, MDStringField, );
4982 PARSE_MD_FIELDS();
4983 #undef VISIT_MD_FIELDS
4985 Result = GET_OR_DISTINCT(DIMacro,
4986 (Context, type.Val, line.Val, name.Val, value.Val));
4987 return false;
4990 /// parseDIMacroFile:
4991 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4992 bool LLParser::parseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4993 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4994 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4995 OPTIONAL(line, LineField, ); \
4996 REQUIRED(file, MDField, ); \
4997 OPTIONAL(nodes, MDField, );
4998 PARSE_MD_FIELDS();
4999 #undef VISIT_MD_FIELDS
5001 Result = GET_OR_DISTINCT(DIMacroFile,
5002 (Context, type.Val, line.Val, file.Val, nodes.Val));
5003 return false;
5006 /// parseDIModule:
5007 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros:
5008 /// "-DNDEBUG", includePath: "/usr/include", apinotes: "module.apinotes",
5009 /// file: !1, line: 4, isDecl: false)
5010 bool LLParser::parseDIModule(MDNode *&Result, bool IsDistinct) {
5011 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5012 REQUIRED(scope, MDField, ); \
5013 REQUIRED(name, MDStringField, ); \
5014 OPTIONAL(configMacros, MDStringField, ); \
5015 OPTIONAL(includePath, MDStringField, ); \
5016 OPTIONAL(apinotes, MDStringField, ); \
5017 OPTIONAL(file, MDField, ); \
5018 OPTIONAL(line, LineField, ); \
5019 OPTIONAL(isDecl, MDBoolField, );
5020 PARSE_MD_FIELDS();
5021 #undef VISIT_MD_FIELDS
5023 Result = GET_OR_DISTINCT(DIModule, (Context, file.Val, scope.Val, name.Val,
5024 configMacros.Val, includePath.Val,
5025 apinotes.Val, line.Val, isDecl.Val));
5026 return false;
5029 /// parseDITemplateTypeParameter:
5030 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1, defaulted: false)
5031 bool LLParser::parseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
5032 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5033 OPTIONAL(name, MDStringField, ); \
5034 REQUIRED(type, MDField, ); \
5035 OPTIONAL(defaulted, MDBoolField, );
5036 PARSE_MD_FIELDS();
5037 #undef VISIT_MD_FIELDS
5039 Result = GET_OR_DISTINCT(DITemplateTypeParameter,
5040 (Context, name.Val, type.Val, defaulted.Val));
5041 return false;
5044 /// parseDITemplateValueParameter:
5045 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
5046 /// name: "V", type: !1, defaulted: false,
5047 /// value: i32 7)
5048 bool LLParser::parseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
5049 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5050 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
5051 OPTIONAL(name, MDStringField, ); \
5052 OPTIONAL(type, MDField, ); \
5053 OPTIONAL(defaulted, MDBoolField, ); \
5054 REQUIRED(value, MDField, );
5056 PARSE_MD_FIELDS();
5057 #undef VISIT_MD_FIELDS
5059 Result = GET_OR_DISTINCT(
5060 DITemplateValueParameter,
5061 (Context, tag.Val, name.Val, type.Val, defaulted.Val, value.Val));
5062 return false;
5065 /// parseDIGlobalVariable:
5066 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
5067 /// file: !1, line: 7, type: !2, isLocal: false,
5068 /// isDefinition: true, templateParams: !3,
5069 /// declaration: !4, align: 8)
5070 bool LLParser::parseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
5071 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5072 OPTIONAL(name, MDStringField, (/* AllowEmpty */ false)); \
5073 OPTIONAL(scope, MDField, ); \
5074 OPTIONAL(linkageName, MDStringField, ); \
5075 OPTIONAL(file, MDField, ); \
5076 OPTIONAL(line, LineField, ); \
5077 OPTIONAL(type, MDField, ); \
5078 OPTIONAL(isLocal, MDBoolField, ); \
5079 OPTIONAL(isDefinition, MDBoolField, (true)); \
5080 OPTIONAL(templateParams, MDField, ); \
5081 OPTIONAL(declaration, MDField, ); \
5082 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5083 OPTIONAL(annotations, MDField, );
5084 PARSE_MD_FIELDS();
5085 #undef VISIT_MD_FIELDS
5087 Result =
5088 GET_OR_DISTINCT(DIGlobalVariable,
5089 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
5090 line.Val, type.Val, isLocal.Val, isDefinition.Val,
5091 declaration.Val, templateParams.Val, align.Val,
5092 annotations.Val));
5093 return false;
5096 /// parseDILocalVariable:
5097 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
5098 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5099 /// align: 8)
5100 /// ::= !DILocalVariable(scope: !0, name: "foo",
5101 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
5102 /// align: 8)
5103 bool LLParser::parseDILocalVariable(MDNode *&Result, bool IsDistinct) {
5104 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5105 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5106 OPTIONAL(name, MDStringField, ); \
5107 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
5108 OPTIONAL(file, MDField, ); \
5109 OPTIONAL(line, LineField, ); \
5110 OPTIONAL(type, MDField, ); \
5111 OPTIONAL(flags, DIFlagField, ); \
5112 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
5113 OPTIONAL(annotations, MDField, );
5114 PARSE_MD_FIELDS();
5115 #undef VISIT_MD_FIELDS
5117 Result = GET_OR_DISTINCT(DILocalVariable,
5118 (Context, scope.Val, name.Val, file.Val, line.Val,
5119 type.Val, arg.Val, flags.Val, align.Val,
5120 annotations.Val));
5121 return false;
5124 /// parseDILabel:
5125 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
5126 bool LLParser::parseDILabel(MDNode *&Result, bool IsDistinct) {
5127 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5128 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
5129 REQUIRED(name, MDStringField, ); \
5130 REQUIRED(file, MDField, ); \
5131 REQUIRED(line, LineField, );
5132 PARSE_MD_FIELDS();
5133 #undef VISIT_MD_FIELDS
5135 Result = GET_OR_DISTINCT(DILabel,
5136 (Context, scope.Val, name.Val, file.Val, line.Val));
5137 return false;
5140 /// parseDIExpression:
5141 /// ::= !DIExpression(0, 7, -1)
5142 bool LLParser::parseDIExpression(MDNode *&Result, bool IsDistinct) {
5143 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5144 Lex.Lex();
5146 if (parseToken(lltok::lparen, "expected '(' here"))
5147 return true;
5149 SmallVector<uint64_t, 8> Elements;
5150 if (Lex.getKind() != lltok::rparen)
5151 do {
5152 if (Lex.getKind() == lltok::DwarfOp) {
5153 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
5154 Lex.Lex();
5155 Elements.push_back(Op);
5156 continue;
5158 return tokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
5161 if (Lex.getKind() == lltok::DwarfAttEncoding) {
5162 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
5163 Lex.Lex();
5164 Elements.push_back(Op);
5165 continue;
5167 return tokError(Twine("invalid DWARF attribute encoding '") +
5168 Lex.getStrVal() + "'");
5171 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
5172 return tokError("expected unsigned integer");
5174 auto &U = Lex.getAPSIntVal();
5175 if (U.ugt(UINT64_MAX))
5176 return tokError("element too large, limit is " + Twine(UINT64_MAX));
5177 Elements.push_back(U.getZExtValue());
5178 Lex.Lex();
5179 } while (EatIfPresent(lltok::comma));
5181 if (parseToken(lltok::rparen, "expected ')' here"))
5182 return true;
5184 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
5185 return false;
5188 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct) {
5189 return parseDIArgList(Result, IsDistinct, nullptr);
5191 /// ParseDIArgList:
5192 /// ::= !DIArgList(i32 7, i64 %0)
5193 bool LLParser::parseDIArgList(MDNode *&Result, bool IsDistinct,
5194 PerFunctionState *PFS) {
5195 assert(PFS && "Expected valid function state");
5196 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
5197 Lex.Lex();
5199 if (parseToken(lltok::lparen, "expected '(' here"))
5200 return true;
5202 SmallVector<ValueAsMetadata *, 4> Args;
5203 if (Lex.getKind() != lltok::rparen)
5204 do {
5205 Metadata *MD;
5206 if (parseValueAsMetadata(MD, "expected value-as-metadata operand", PFS))
5207 return true;
5208 Args.push_back(dyn_cast<ValueAsMetadata>(MD));
5209 } while (EatIfPresent(lltok::comma));
5211 if (parseToken(lltok::rparen, "expected ')' here"))
5212 return true;
5214 Result = GET_OR_DISTINCT(DIArgList, (Context, Args));
5215 return false;
5218 /// parseDIGlobalVariableExpression:
5219 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
5220 bool LLParser::parseDIGlobalVariableExpression(MDNode *&Result,
5221 bool IsDistinct) {
5222 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5223 REQUIRED(var, MDField, ); \
5224 REQUIRED(expr, MDField, );
5225 PARSE_MD_FIELDS();
5226 #undef VISIT_MD_FIELDS
5228 Result =
5229 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
5230 return false;
5233 /// parseDIObjCProperty:
5234 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
5235 /// getter: "getFoo", attributes: 7, type: !2)
5236 bool LLParser::parseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5237 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5238 OPTIONAL(name, MDStringField, ); \
5239 OPTIONAL(file, MDField, ); \
5240 OPTIONAL(line, LineField, ); \
5241 OPTIONAL(setter, MDStringField, ); \
5242 OPTIONAL(getter, MDStringField, ); \
5243 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5244 OPTIONAL(type, MDField, );
5245 PARSE_MD_FIELDS();
5246 #undef VISIT_MD_FIELDS
5248 Result = GET_OR_DISTINCT(DIObjCProperty,
5249 (Context, name.Val, file.Val, line.Val, setter.Val,
5250 getter.Val, attributes.Val, type.Val));
5251 return false;
5254 /// parseDIImportedEntity:
5255 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5256 /// line: 7, name: "foo", elements: !2)
5257 bool LLParser::parseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5258 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5259 REQUIRED(tag, DwarfTagField, ); \
5260 REQUIRED(scope, MDField, ); \
5261 OPTIONAL(entity, MDField, ); \
5262 OPTIONAL(file, MDField, ); \
5263 OPTIONAL(line, LineField, ); \
5264 OPTIONAL(name, MDStringField, ); \
5265 OPTIONAL(elements, MDField, );
5266 PARSE_MD_FIELDS();
5267 #undef VISIT_MD_FIELDS
5269 Result = GET_OR_DISTINCT(DIImportedEntity,
5270 (Context, tag.Val, scope.Val, entity.Val, file.Val,
5271 line.Val, name.Val, elements.Val));
5272 return false;
5275 #undef PARSE_MD_FIELD
5276 #undef NOP_FIELD
5277 #undef REQUIRE_FIELD
5278 #undef DECLARE_FIELD
5280 /// parseMetadataAsValue
5281 /// ::= metadata i32 %local
5282 /// ::= metadata i32 @global
5283 /// ::= metadata i32 7
5284 /// ::= metadata !0
5285 /// ::= metadata !{...}
5286 /// ::= metadata !"string"
5287 bool LLParser::parseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5288 // Note: the type 'metadata' has already been parsed.
5289 Metadata *MD;
5290 if (parseMetadata(MD, &PFS))
5291 return true;
5293 V = MetadataAsValue::get(Context, MD);
5294 return false;
5297 /// parseValueAsMetadata
5298 /// ::= i32 %local
5299 /// ::= i32 @global
5300 /// ::= i32 7
5301 bool LLParser::parseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5302 PerFunctionState *PFS) {
5303 Type *Ty;
5304 LocTy Loc;
5305 if (parseType(Ty, TypeMsg, Loc))
5306 return true;
5307 if (Ty->isMetadataTy())
5308 return error(Loc, "invalid metadata-value-metadata roundtrip");
5310 Value *V;
5311 if (parseValue(Ty, V, PFS))
5312 return true;
5314 MD = ValueAsMetadata::get(V);
5315 return false;
5318 /// parseMetadata
5319 /// ::= i32 %local
5320 /// ::= i32 @global
5321 /// ::= i32 7
5322 /// ::= !42
5323 /// ::= !{...}
5324 /// ::= !"string"
5325 /// ::= !DILocation(...)
5326 bool LLParser::parseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5327 if (Lex.getKind() == lltok::MetadataVar) {
5328 MDNode *N;
5329 // DIArgLists are a special case, as they are a list of ValueAsMetadata and
5330 // so parsing this requires a Function State.
5331 if (Lex.getStrVal() == "DIArgList") {
5332 if (parseDIArgList(N, false, PFS))
5333 return true;
5334 } else if (parseSpecializedMDNode(N)) {
5335 return true;
5337 MD = N;
5338 return false;
5341 // ValueAsMetadata:
5342 // <type> <value>
5343 if (Lex.getKind() != lltok::exclaim)
5344 return parseValueAsMetadata(MD, "expected metadata operand", PFS);
5346 // '!'.
5347 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5348 Lex.Lex();
5350 // MDString:
5351 // ::= '!' STRINGCONSTANT
5352 if (Lex.getKind() == lltok::StringConstant) {
5353 MDString *S;
5354 if (parseMDString(S))
5355 return true;
5356 MD = S;
5357 return false;
5360 // MDNode:
5361 // !{ ... }
5362 // !7
5363 MDNode *N;
5364 if (parseMDNodeTail(N))
5365 return true;
5366 MD = N;
5367 return false;
5370 //===----------------------------------------------------------------------===//
5371 // Function Parsing.
5372 //===----------------------------------------------------------------------===//
5374 bool LLParser::convertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5375 PerFunctionState *PFS) {
5376 if (Ty->isFunctionTy())
5377 return error(ID.Loc, "functions are not values, refer to them as pointers");
5379 switch (ID.Kind) {
5380 case ValID::t_LocalID:
5381 if (!PFS)
5382 return error(ID.Loc, "invalid use of function-local name");
5383 V = PFS->getVal(ID.UIntVal, Ty, ID.Loc);
5384 return V == nullptr;
5385 case ValID::t_LocalName:
5386 if (!PFS)
5387 return error(ID.Loc, "invalid use of function-local name");
5388 V = PFS->getVal(ID.StrVal, Ty, ID.Loc);
5389 return V == nullptr;
5390 case ValID::t_InlineAsm: {
5391 if (!ID.FTy)
5392 return error(ID.Loc, "invalid type for inline asm constraint string");
5393 if (Error Err = InlineAsm::verify(ID.FTy, ID.StrVal2))
5394 return error(ID.Loc, toString(std::move(Err)));
5395 V = InlineAsm::get(
5396 ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1, (ID.UIntVal >> 1) & 1,
5397 InlineAsm::AsmDialect((ID.UIntVal >> 2) & 1), (ID.UIntVal >> 3) & 1);
5398 return false;
5400 case ValID::t_GlobalName:
5401 V = getGlobalVal(ID.StrVal, Ty, ID.Loc);
5402 if (V && ID.NoCFI)
5403 V = NoCFIValue::get(cast<GlobalValue>(V));
5404 return V == nullptr;
5405 case ValID::t_GlobalID:
5406 V = getGlobalVal(ID.UIntVal, Ty, ID.Loc);
5407 if (V && ID.NoCFI)
5408 V = NoCFIValue::get(cast<GlobalValue>(V));
5409 return V == nullptr;
5410 case ValID::t_APSInt:
5411 if (!Ty->isIntegerTy())
5412 return error(ID.Loc, "integer constant must have integer type");
5413 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5414 V = ConstantInt::get(Context, ID.APSIntVal);
5415 return false;
5416 case ValID::t_APFloat:
5417 if (!Ty->isFloatingPointTy() ||
5418 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5419 return error(ID.Loc, "floating point constant invalid for type");
5421 // The lexer has no type info, so builds all half, bfloat, float, and double
5422 // FP constants as double. Fix this here. Long double does not need this.
5423 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5424 // Check for signaling before potentially converting and losing that info.
5425 bool IsSNAN = ID.APFloatVal.isSignaling();
5426 bool Ignored;
5427 if (Ty->isHalfTy())
5428 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5429 &Ignored);
5430 else if (Ty->isBFloatTy())
5431 ID.APFloatVal.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven,
5432 &Ignored);
5433 else if (Ty->isFloatTy())
5434 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5435 &Ignored);
5436 if (IsSNAN) {
5437 // The convert call above may quiet an SNaN, so manufacture another
5438 // SNaN. The bitcast works because the payload (significand) parameter
5439 // is truncated to fit.
5440 APInt Payload = ID.APFloatVal.bitcastToAPInt();
5441 ID.APFloatVal = APFloat::getSNaN(ID.APFloatVal.getSemantics(),
5442 ID.APFloatVal.isNegative(), &Payload);
5445 V = ConstantFP::get(Context, ID.APFloatVal);
5447 if (V->getType() != Ty)
5448 return error(ID.Loc, "floating point constant does not have type '" +
5449 getTypeString(Ty) + "'");
5451 return false;
5452 case ValID::t_Null:
5453 if (!Ty->isPointerTy())
5454 return error(ID.Loc, "null must be a pointer type");
5455 V = ConstantPointerNull::get(cast<PointerType>(Ty));
5456 return false;
5457 case ValID::t_Undef:
5458 // FIXME: LabelTy should not be a first-class type.
5459 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5460 return error(ID.Loc, "invalid type for undef constant");
5461 V = UndefValue::get(Ty);
5462 return false;
5463 case ValID::t_EmptyArray:
5464 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5465 return error(ID.Loc, "invalid empty array initializer");
5466 V = UndefValue::get(Ty);
5467 return false;
5468 case ValID::t_Zero:
5469 // FIXME: LabelTy should not be a first-class type.
5470 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5471 return error(ID.Loc, "invalid type for null constant");
5472 V = Constant::getNullValue(Ty);
5473 return false;
5474 case ValID::t_None:
5475 if (!Ty->isTokenTy())
5476 return error(ID.Loc, "invalid type for none constant");
5477 V = Constant::getNullValue(Ty);
5478 return false;
5479 case ValID::t_Poison:
5480 // FIXME: LabelTy should not be a first-class type.
5481 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5482 return error(ID.Loc, "invalid type for poison constant");
5483 V = PoisonValue::get(Ty);
5484 return false;
5485 case ValID::t_Constant:
5486 if (ID.ConstantVal->getType() != Ty)
5487 return error(ID.Loc, "constant expression type mismatch: got type '" +
5488 getTypeString(ID.ConstantVal->getType()) +
5489 "' but expected '" + getTypeString(Ty) + "'");
5490 V = ID.ConstantVal;
5491 return false;
5492 case ValID::t_ConstantStruct:
5493 case ValID::t_PackedConstantStruct:
5494 if (StructType *ST = dyn_cast<StructType>(Ty)) {
5495 if (ST->getNumElements() != ID.UIntVal)
5496 return error(ID.Loc,
5497 "initializer with struct type has wrong # elements");
5498 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5499 return error(ID.Loc, "packed'ness of initializer and type don't match");
5501 // Verify that the elements are compatible with the structtype.
5502 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5503 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5504 return error(
5505 ID.Loc,
5506 "element " + Twine(i) +
5507 " of struct initializer doesn't match struct element type");
5509 V = ConstantStruct::get(
5510 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5511 } else
5512 return error(ID.Loc, "constant expression type mismatch");
5513 return false;
5515 llvm_unreachable("Invalid ValID");
5518 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5519 C = nullptr;
5520 ValID ID;
5521 auto Loc = Lex.getLoc();
5522 if (parseValID(ID, /*PFS=*/nullptr))
5523 return true;
5524 switch (ID.Kind) {
5525 case ValID::t_APSInt:
5526 case ValID::t_APFloat:
5527 case ValID::t_Undef:
5528 case ValID::t_Constant:
5529 case ValID::t_ConstantStruct:
5530 case ValID::t_PackedConstantStruct: {
5531 Value *V;
5532 if (convertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
5533 return true;
5534 assert(isa<Constant>(V) && "Expected a constant value");
5535 C = cast<Constant>(V);
5536 return false;
5538 case ValID::t_Null:
5539 C = Constant::getNullValue(Ty);
5540 return false;
5541 default:
5542 return error(Loc, "expected a constant value");
5546 bool LLParser::parseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5547 V = nullptr;
5548 ValID ID;
5549 return parseValID(ID, PFS, Ty) ||
5550 convertValIDToValue(Ty, ID, V, PFS);
5553 bool LLParser::parseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5554 Type *Ty = nullptr;
5555 return parseType(Ty) || parseValue(Ty, V, PFS);
5558 bool LLParser::parseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5559 PerFunctionState &PFS) {
5560 Value *V;
5561 Loc = Lex.getLoc();
5562 if (parseTypeAndValue(V, PFS))
5563 return true;
5564 if (!isa<BasicBlock>(V))
5565 return error(Loc, "expected a basic block");
5566 BB = cast<BasicBlock>(V);
5567 return false;
5570 /// FunctionHeader
5571 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5572 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5573 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5574 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5575 bool LLParser::parseFunctionHeader(Function *&Fn, bool IsDefine) {
5576 // parse the linkage.
5577 LocTy LinkageLoc = Lex.getLoc();
5578 unsigned Linkage;
5579 unsigned Visibility;
5580 unsigned DLLStorageClass;
5581 bool DSOLocal;
5582 AttrBuilder RetAttrs(M->getContext());
5583 unsigned CC;
5584 bool HasLinkage;
5585 Type *RetType = nullptr;
5586 LocTy RetTypeLoc = Lex.getLoc();
5587 if (parseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5588 DSOLocal) ||
5589 parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
5590 parseType(RetType, RetTypeLoc, true /*void allowed*/))
5591 return true;
5593 // Verify that the linkage is ok.
5594 switch ((GlobalValue::LinkageTypes)Linkage) {
5595 case GlobalValue::ExternalLinkage:
5596 break; // always ok.
5597 case GlobalValue::ExternalWeakLinkage:
5598 if (IsDefine)
5599 return error(LinkageLoc, "invalid linkage for function definition");
5600 break;
5601 case GlobalValue::PrivateLinkage:
5602 case GlobalValue::InternalLinkage:
5603 case GlobalValue::AvailableExternallyLinkage:
5604 case GlobalValue::LinkOnceAnyLinkage:
5605 case GlobalValue::LinkOnceODRLinkage:
5606 case GlobalValue::WeakAnyLinkage:
5607 case GlobalValue::WeakODRLinkage:
5608 if (!IsDefine)
5609 return error(LinkageLoc, "invalid linkage for function declaration");
5610 break;
5611 case GlobalValue::AppendingLinkage:
5612 case GlobalValue::CommonLinkage:
5613 return error(LinkageLoc, "invalid function linkage type");
5616 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5617 return error(LinkageLoc,
5618 "symbol with local linkage must have default visibility");
5620 if (!FunctionType::isValidReturnType(RetType))
5621 return error(RetTypeLoc, "invalid function return type");
5623 LocTy NameLoc = Lex.getLoc();
5625 std::string FunctionName;
5626 if (Lex.getKind() == lltok::GlobalVar) {
5627 FunctionName = Lex.getStrVal();
5628 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5629 unsigned NameID = Lex.getUIntVal();
5631 if (NameID != NumberedVals.size())
5632 return tokError("function expected to be numbered '%" +
5633 Twine(NumberedVals.size()) + "'");
5634 } else {
5635 return tokError("expected function name");
5638 Lex.Lex();
5640 if (Lex.getKind() != lltok::lparen)
5641 return tokError("expected '(' in function argument list");
5643 SmallVector<ArgInfo, 8> ArgList;
5644 bool IsVarArg;
5645 AttrBuilder FuncAttrs(M->getContext());
5646 std::vector<unsigned> FwdRefAttrGrps;
5647 LocTy BuiltinLoc;
5648 std::string Section;
5649 std::string Partition;
5650 MaybeAlign Alignment;
5651 std::string GC;
5652 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5653 unsigned AddrSpace = 0;
5654 Constant *Prefix = nullptr;
5655 Constant *Prologue = nullptr;
5656 Constant *PersonalityFn = nullptr;
5657 Comdat *C;
5659 if (parseArgumentList(ArgList, IsVarArg) ||
5660 parseOptionalUnnamedAddr(UnnamedAddr) ||
5661 parseOptionalProgramAddrSpace(AddrSpace) ||
5662 parseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5663 BuiltinLoc) ||
5664 (EatIfPresent(lltok::kw_section) && parseStringConstant(Section)) ||
5665 (EatIfPresent(lltok::kw_partition) && parseStringConstant(Partition)) ||
5666 parseOptionalComdat(FunctionName, C) ||
5667 parseOptionalAlignment(Alignment) ||
5668 (EatIfPresent(lltok::kw_gc) && parseStringConstant(GC)) ||
5669 (EatIfPresent(lltok::kw_prefix) && parseGlobalTypeAndValue(Prefix)) ||
5670 (EatIfPresent(lltok::kw_prologue) && parseGlobalTypeAndValue(Prologue)) ||
5671 (EatIfPresent(lltok::kw_personality) &&
5672 parseGlobalTypeAndValue(PersonalityFn)))
5673 return true;
5675 if (FuncAttrs.contains(Attribute::Builtin))
5676 return error(BuiltinLoc, "'builtin' attribute not valid on function");
5678 // If the alignment was parsed as an attribute, move to the alignment field.
5679 if (FuncAttrs.hasAlignmentAttr()) {
5680 Alignment = FuncAttrs.getAlignment();
5681 FuncAttrs.removeAttribute(Attribute::Alignment);
5684 // Okay, if we got here, the function is syntactically valid. Convert types
5685 // and do semantic checks.
5686 std::vector<Type*> ParamTypeList;
5687 SmallVector<AttributeSet, 8> Attrs;
5689 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5690 ParamTypeList.push_back(ArgList[i].Ty);
5691 Attrs.push_back(ArgList[i].Attrs);
5694 AttributeList PAL =
5695 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5696 AttributeSet::get(Context, RetAttrs), Attrs);
5698 if (PAL.hasParamAttr(0, Attribute::StructRet) && !RetType->isVoidTy())
5699 return error(RetTypeLoc, "functions with 'sret' argument must return void");
5701 FunctionType *FT = FunctionType::get(RetType, ParamTypeList, IsVarArg);
5702 PointerType *PFT = PointerType::get(FT, AddrSpace);
5704 Fn = nullptr;
5705 GlobalValue *FwdFn = nullptr;
5706 if (!FunctionName.empty()) {
5707 // If this was a definition of a forward reference, remove the definition
5708 // from the forward reference table and fill in the forward ref.
5709 auto FRVI = ForwardRefVals.find(FunctionName);
5710 if (FRVI != ForwardRefVals.end()) {
5711 FwdFn = FRVI->second.first;
5712 if (!FwdFn->getType()->isOpaque() &&
5713 !FwdFn->getType()->getNonOpaquePointerElementType()->isFunctionTy())
5714 return error(FRVI->second.second, "invalid forward reference to "
5715 "function as global value!");
5716 if (FwdFn->getType() != PFT)
5717 return error(FRVI->second.second,
5718 "invalid forward reference to "
5719 "function '" +
5720 FunctionName +
5721 "' with wrong type: "
5722 "expected '" +
5723 getTypeString(PFT) + "' but was '" +
5724 getTypeString(FwdFn->getType()) + "'");
5725 ForwardRefVals.erase(FRVI);
5726 } else if ((Fn = M->getFunction(FunctionName))) {
5727 // Reject redefinitions.
5728 return error(NameLoc,
5729 "invalid redefinition of function '" + FunctionName + "'");
5730 } else if (M->getNamedValue(FunctionName)) {
5731 return error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5734 } else {
5735 // If this is a definition of a forward referenced function, make sure the
5736 // types agree.
5737 auto I = ForwardRefValIDs.find(NumberedVals.size());
5738 if (I != ForwardRefValIDs.end()) {
5739 FwdFn = I->second.first;
5740 if (FwdFn->getType() != PFT)
5741 return error(NameLoc, "type of definition and forward reference of '@" +
5742 Twine(NumberedVals.size()) +
5743 "' disagree: "
5744 "expected '" +
5745 getTypeString(PFT) + "' but was '" +
5746 getTypeString(FwdFn->getType()) + "'");
5747 ForwardRefValIDs.erase(I);
5751 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5752 FunctionName, M);
5754 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5756 if (FunctionName.empty())
5757 NumberedVals.push_back(Fn);
5759 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5760 maybeSetDSOLocal(DSOLocal, *Fn);
5761 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5762 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5763 Fn->setCallingConv(CC);
5764 Fn->setAttributes(PAL);
5765 Fn->setUnnamedAddr(UnnamedAddr);
5766 Fn->setAlignment(MaybeAlign(Alignment));
5767 Fn->setSection(Section);
5768 Fn->setPartition(Partition);
5769 Fn->setComdat(C);
5770 Fn->setPersonalityFn(PersonalityFn);
5771 if (!GC.empty()) Fn->setGC(GC);
5772 Fn->setPrefixData(Prefix);
5773 Fn->setPrologueData(Prologue);
5774 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5776 // Add all of the arguments we parsed to the function.
5777 Function::arg_iterator ArgIt = Fn->arg_begin();
5778 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5779 // If the argument has a name, insert it into the argument symbol table.
5780 if (ArgList[i].Name.empty()) continue;
5782 // Set the name, if it conflicted, it will be auto-renamed.
5783 ArgIt->setName(ArgList[i].Name);
5785 if (ArgIt->getName() != ArgList[i].Name)
5786 return error(ArgList[i].Loc,
5787 "redefinition of argument '%" + ArgList[i].Name + "'");
5790 if (FwdFn) {
5791 FwdFn->replaceAllUsesWith(Fn);
5792 FwdFn->eraseFromParent();
5795 if (IsDefine)
5796 return false;
5798 // Check the declaration has no block address forward references.
5799 ValID ID;
5800 if (FunctionName.empty()) {
5801 ID.Kind = ValID::t_GlobalID;
5802 ID.UIntVal = NumberedVals.size() - 1;
5803 } else {
5804 ID.Kind = ValID::t_GlobalName;
5805 ID.StrVal = FunctionName;
5807 auto Blocks = ForwardRefBlockAddresses.find(ID);
5808 if (Blocks != ForwardRefBlockAddresses.end())
5809 return error(Blocks->first.Loc,
5810 "cannot take blockaddress inside a declaration");
5811 return false;
5814 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5815 ValID ID;
5816 if (FunctionNumber == -1) {
5817 ID.Kind = ValID::t_GlobalName;
5818 ID.StrVal = std::string(F.getName());
5819 } else {
5820 ID.Kind = ValID::t_GlobalID;
5821 ID.UIntVal = FunctionNumber;
5824 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5825 if (Blocks == P.ForwardRefBlockAddresses.end())
5826 return false;
5828 for (const auto &I : Blocks->second) {
5829 const ValID &BBID = I.first;
5830 GlobalValue *GV = I.second;
5832 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5833 "Expected local id or name");
5834 BasicBlock *BB;
5835 if (BBID.Kind == ValID::t_LocalName)
5836 BB = getBB(BBID.StrVal, BBID.Loc);
5837 else
5838 BB = getBB(BBID.UIntVal, BBID.Loc);
5839 if (!BB)
5840 return P.error(BBID.Loc, "referenced value is not a basic block");
5842 Value *ResolvedVal = BlockAddress::get(&F, BB);
5843 ResolvedVal = P.checkValidVariableType(BBID.Loc, BBID.StrVal, GV->getType(),
5844 ResolvedVal);
5845 if (!ResolvedVal)
5846 return true;
5847 GV->replaceAllUsesWith(ResolvedVal);
5848 GV->eraseFromParent();
5851 P.ForwardRefBlockAddresses.erase(Blocks);
5852 return false;
5855 /// parseFunctionBody
5856 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5857 bool LLParser::parseFunctionBody(Function &Fn) {
5858 if (Lex.getKind() != lltok::lbrace)
5859 return tokError("expected '{' in function body");
5860 Lex.Lex(); // eat the {.
5862 int FunctionNumber = -1;
5863 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5865 PerFunctionState PFS(*this, Fn, FunctionNumber);
5867 // Resolve block addresses and allow basic blocks to be forward-declared
5868 // within this function.
5869 if (PFS.resolveForwardRefBlockAddresses())
5870 return true;
5871 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5873 // We need at least one basic block.
5874 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5875 return tokError("function body requires at least one basic block");
5877 while (Lex.getKind() != lltok::rbrace &&
5878 Lex.getKind() != lltok::kw_uselistorder)
5879 if (parseBasicBlock(PFS))
5880 return true;
5882 while (Lex.getKind() != lltok::rbrace)
5883 if (parseUseListOrder(&PFS))
5884 return true;
5886 // Eat the }.
5887 Lex.Lex();
5889 // Verify function is ok.
5890 return PFS.finishFunction();
5893 /// parseBasicBlock
5894 /// ::= (LabelStr|LabelID)? Instruction*
5895 bool LLParser::parseBasicBlock(PerFunctionState &PFS) {
5896 // If this basic block starts out with a name, remember it.
5897 std::string Name;
5898 int NameID = -1;
5899 LocTy NameLoc = Lex.getLoc();
5900 if (Lex.getKind() == lltok::LabelStr) {
5901 Name = Lex.getStrVal();
5902 Lex.Lex();
5903 } else if (Lex.getKind() == lltok::LabelID) {
5904 NameID = Lex.getUIntVal();
5905 Lex.Lex();
5908 BasicBlock *BB = PFS.defineBB(Name, NameID, NameLoc);
5909 if (!BB)
5910 return true;
5912 std::string NameStr;
5914 // parse the instructions in this block until we get a terminator.
5915 Instruction *Inst;
5916 do {
5917 // This instruction may have three possibilities for a name: a) none
5918 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5919 LocTy NameLoc = Lex.getLoc();
5920 int NameID = -1;
5921 NameStr = "";
5923 if (Lex.getKind() == lltok::LocalVarID) {
5924 NameID = Lex.getUIntVal();
5925 Lex.Lex();
5926 if (parseToken(lltok::equal, "expected '=' after instruction id"))
5927 return true;
5928 } else if (Lex.getKind() == lltok::LocalVar) {
5929 NameStr = Lex.getStrVal();
5930 Lex.Lex();
5931 if (parseToken(lltok::equal, "expected '=' after instruction name"))
5932 return true;
5935 switch (parseInstruction(Inst, BB, PFS)) {
5936 default:
5937 llvm_unreachable("Unknown parseInstruction result!");
5938 case InstError: return true;
5939 case InstNormal:
5940 BB->getInstList().push_back(Inst);
5942 // With a normal result, we check to see if the instruction is followed by
5943 // a comma and metadata.
5944 if (EatIfPresent(lltok::comma))
5945 if (parseInstructionMetadata(*Inst))
5946 return true;
5947 break;
5948 case InstExtraComma:
5949 BB->getInstList().push_back(Inst);
5951 // If the instruction parser ate an extra comma at the end of it, it
5952 // *must* be followed by metadata.
5953 if (parseInstructionMetadata(*Inst))
5954 return true;
5955 break;
5958 // Set the name on the instruction.
5959 if (PFS.setInstName(NameID, NameStr, NameLoc, Inst))
5960 return true;
5961 } while (!Inst->isTerminator());
5963 return false;
5966 //===----------------------------------------------------------------------===//
5967 // Instruction Parsing.
5968 //===----------------------------------------------------------------------===//
5970 /// parseInstruction - parse one of the many different instructions.
5972 int LLParser::parseInstruction(Instruction *&Inst, BasicBlock *BB,
5973 PerFunctionState &PFS) {
5974 lltok::Kind Token = Lex.getKind();
5975 if (Token == lltok::Eof)
5976 return tokError("found end of file when expecting more instructions");
5977 LocTy Loc = Lex.getLoc();
5978 unsigned KeywordVal = Lex.getUIntVal();
5979 Lex.Lex(); // Eat the keyword.
5981 switch (Token) {
5982 default:
5983 return error(Loc, "expected instruction opcode");
5984 // Terminator Instructions.
5985 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5986 case lltok::kw_ret:
5987 return parseRet(Inst, BB, PFS);
5988 case lltok::kw_br:
5989 return parseBr(Inst, PFS);
5990 case lltok::kw_switch:
5991 return parseSwitch(Inst, PFS);
5992 case lltok::kw_indirectbr:
5993 return parseIndirectBr(Inst, PFS);
5994 case lltok::kw_invoke:
5995 return parseInvoke(Inst, PFS);
5996 case lltok::kw_resume:
5997 return parseResume(Inst, PFS);
5998 case lltok::kw_cleanupret:
5999 return parseCleanupRet(Inst, PFS);
6000 case lltok::kw_catchret:
6001 return parseCatchRet(Inst, PFS);
6002 case lltok::kw_catchswitch:
6003 return parseCatchSwitch(Inst, PFS);
6004 case lltok::kw_catchpad:
6005 return parseCatchPad(Inst, PFS);
6006 case lltok::kw_cleanuppad:
6007 return parseCleanupPad(Inst, PFS);
6008 case lltok::kw_callbr:
6009 return parseCallBr(Inst, PFS);
6010 // Unary Operators.
6011 case lltok::kw_fneg: {
6012 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6013 int Res = parseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/ true);
6014 if (Res != 0)
6015 return Res;
6016 if (FMF.any())
6017 Inst->setFastMathFlags(FMF);
6018 return false;
6020 // Binary Operators.
6021 case lltok::kw_add:
6022 case lltok::kw_sub:
6023 case lltok::kw_mul:
6024 case lltok::kw_shl: {
6025 bool NUW = EatIfPresent(lltok::kw_nuw);
6026 bool NSW = EatIfPresent(lltok::kw_nsw);
6027 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
6029 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6030 return true;
6032 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
6033 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
6034 return false;
6036 case lltok::kw_fadd:
6037 case lltok::kw_fsub:
6038 case lltok::kw_fmul:
6039 case lltok::kw_fdiv:
6040 case lltok::kw_frem: {
6041 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6042 int Res = parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ true);
6043 if (Res != 0)
6044 return Res;
6045 if (FMF.any())
6046 Inst->setFastMathFlags(FMF);
6047 return 0;
6050 case lltok::kw_sdiv:
6051 case lltok::kw_udiv:
6052 case lltok::kw_lshr:
6053 case lltok::kw_ashr: {
6054 bool Exact = EatIfPresent(lltok::kw_exact);
6056 if (parseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/ false))
6057 return true;
6058 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
6059 return false;
6062 case lltok::kw_urem:
6063 case lltok::kw_srem:
6064 return parseArithmetic(Inst, PFS, KeywordVal,
6065 /*IsFP*/ false);
6066 case lltok::kw_and:
6067 case lltok::kw_or:
6068 case lltok::kw_xor:
6069 return parseLogical(Inst, PFS, KeywordVal);
6070 case lltok::kw_icmp:
6071 return parseCompare(Inst, PFS, KeywordVal);
6072 case lltok::kw_fcmp: {
6073 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6074 int Res = parseCompare(Inst, PFS, KeywordVal);
6075 if (Res != 0)
6076 return Res;
6077 if (FMF.any())
6078 Inst->setFastMathFlags(FMF);
6079 return 0;
6082 // Casts.
6083 case lltok::kw_trunc:
6084 case lltok::kw_zext:
6085 case lltok::kw_sext:
6086 case lltok::kw_fptrunc:
6087 case lltok::kw_fpext:
6088 case lltok::kw_bitcast:
6089 case lltok::kw_addrspacecast:
6090 case lltok::kw_uitofp:
6091 case lltok::kw_sitofp:
6092 case lltok::kw_fptoui:
6093 case lltok::kw_fptosi:
6094 case lltok::kw_inttoptr:
6095 case lltok::kw_ptrtoint:
6096 return parseCast(Inst, PFS, KeywordVal);
6097 // Other.
6098 case lltok::kw_select: {
6099 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6100 int Res = parseSelect(Inst, PFS);
6101 if (Res != 0)
6102 return Res;
6103 if (FMF.any()) {
6104 if (!isa<FPMathOperator>(Inst))
6105 return error(Loc, "fast-math-flags specified for select without "
6106 "floating-point scalar or vector return type");
6107 Inst->setFastMathFlags(FMF);
6109 return 0;
6111 case lltok::kw_va_arg:
6112 return parseVAArg(Inst, PFS);
6113 case lltok::kw_extractelement:
6114 return parseExtractElement(Inst, PFS);
6115 case lltok::kw_insertelement:
6116 return parseInsertElement(Inst, PFS);
6117 case lltok::kw_shufflevector:
6118 return parseShuffleVector(Inst, PFS);
6119 case lltok::kw_phi: {
6120 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6121 int Res = parsePHI(Inst, PFS);
6122 if (Res != 0)
6123 return Res;
6124 if (FMF.any()) {
6125 if (!isa<FPMathOperator>(Inst))
6126 return error(Loc, "fast-math-flags specified for phi without "
6127 "floating-point scalar or vector return type");
6128 Inst->setFastMathFlags(FMF);
6130 return 0;
6132 case lltok::kw_landingpad:
6133 return parseLandingPad(Inst, PFS);
6134 case lltok::kw_freeze:
6135 return parseFreeze(Inst, PFS);
6136 // Call.
6137 case lltok::kw_call:
6138 return parseCall(Inst, PFS, CallInst::TCK_None);
6139 case lltok::kw_tail:
6140 return parseCall(Inst, PFS, CallInst::TCK_Tail);
6141 case lltok::kw_musttail:
6142 return parseCall(Inst, PFS, CallInst::TCK_MustTail);
6143 case lltok::kw_notail:
6144 return parseCall(Inst, PFS, CallInst::TCK_NoTail);
6145 // Memory.
6146 case lltok::kw_alloca:
6147 return parseAlloc(Inst, PFS);
6148 case lltok::kw_load:
6149 return parseLoad(Inst, PFS);
6150 case lltok::kw_store:
6151 return parseStore(Inst, PFS);
6152 case lltok::kw_cmpxchg:
6153 return parseCmpXchg(Inst, PFS);
6154 case lltok::kw_atomicrmw:
6155 return parseAtomicRMW(Inst, PFS);
6156 case lltok::kw_fence:
6157 return parseFence(Inst, PFS);
6158 case lltok::kw_getelementptr:
6159 return parseGetElementPtr(Inst, PFS);
6160 case lltok::kw_extractvalue:
6161 return parseExtractValue(Inst, PFS);
6162 case lltok::kw_insertvalue:
6163 return parseInsertValue(Inst, PFS);
6167 /// parseCmpPredicate - parse an integer or fp predicate, based on Kind.
6168 bool LLParser::parseCmpPredicate(unsigned &P, unsigned Opc) {
6169 if (Opc == Instruction::FCmp) {
6170 switch (Lex.getKind()) {
6171 default:
6172 return tokError("expected fcmp predicate (e.g. 'oeq')");
6173 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
6174 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
6175 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
6176 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
6177 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
6178 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
6179 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
6180 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
6181 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
6182 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
6183 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
6184 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
6185 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
6186 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
6187 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
6188 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
6190 } else {
6191 switch (Lex.getKind()) {
6192 default:
6193 return tokError("expected icmp predicate (e.g. 'eq')");
6194 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
6195 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
6196 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
6197 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
6198 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
6199 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
6200 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
6201 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
6202 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
6203 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
6206 Lex.Lex();
6207 return false;
6210 //===----------------------------------------------------------------------===//
6211 // Terminator Instructions.
6212 //===----------------------------------------------------------------------===//
6214 /// parseRet - parse a return instruction.
6215 /// ::= 'ret' void (',' !dbg, !1)*
6216 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
6217 bool LLParser::parseRet(Instruction *&Inst, BasicBlock *BB,
6218 PerFunctionState &PFS) {
6219 SMLoc TypeLoc = Lex.getLoc();
6220 Type *Ty = nullptr;
6221 if (parseType(Ty, true /*void allowed*/))
6222 return true;
6224 Type *ResType = PFS.getFunction().getReturnType();
6226 if (Ty->isVoidTy()) {
6227 if (!ResType->isVoidTy())
6228 return error(TypeLoc, "value doesn't match function result type '" +
6229 getTypeString(ResType) + "'");
6231 Inst = ReturnInst::Create(Context);
6232 return false;
6235 Value *RV;
6236 if (parseValue(Ty, RV, PFS))
6237 return true;
6239 if (ResType != RV->getType())
6240 return error(TypeLoc, "value doesn't match function result type '" +
6241 getTypeString(ResType) + "'");
6243 Inst = ReturnInst::Create(Context, RV);
6244 return false;
6247 /// parseBr
6248 /// ::= 'br' TypeAndValue
6249 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6250 bool LLParser::parseBr(Instruction *&Inst, PerFunctionState &PFS) {
6251 LocTy Loc, Loc2;
6252 Value *Op0;
6253 BasicBlock *Op1, *Op2;
6254 if (parseTypeAndValue(Op0, Loc, PFS))
6255 return true;
6257 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
6258 Inst = BranchInst::Create(BB);
6259 return false;
6262 if (Op0->getType() != Type::getInt1Ty(Context))
6263 return error(Loc, "branch condition must have 'i1' type");
6265 if (parseToken(lltok::comma, "expected ',' after branch condition") ||
6266 parseTypeAndBasicBlock(Op1, Loc, PFS) ||
6267 parseToken(lltok::comma, "expected ',' after true destination") ||
6268 parseTypeAndBasicBlock(Op2, Loc2, PFS))
6269 return true;
6271 Inst = BranchInst::Create(Op1, Op2, Op0);
6272 return false;
6275 /// parseSwitch
6276 /// Instruction
6277 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
6278 /// JumpTable
6279 /// ::= (TypeAndValue ',' TypeAndValue)*
6280 bool LLParser::parseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6281 LocTy CondLoc, BBLoc;
6282 Value *Cond;
6283 BasicBlock *DefaultBB;
6284 if (parseTypeAndValue(Cond, CondLoc, PFS) ||
6285 parseToken(lltok::comma, "expected ',' after switch condition") ||
6286 parseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
6287 parseToken(lltok::lsquare, "expected '[' with switch table"))
6288 return true;
6290 if (!Cond->getType()->isIntegerTy())
6291 return error(CondLoc, "switch condition must have integer type");
6293 // parse the jump table pairs.
6294 SmallPtrSet<Value*, 32> SeenCases;
6295 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
6296 while (Lex.getKind() != lltok::rsquare) {
6297 Value *Constant;
6298 BasicBlock *DestBB;
6300 if (parseTypeAndValue(Constant, CondLoc, PFS) ||
6301 parseToken(lltok::comma, "expected ',' after case value") ||
6302 parseTypeAndBasicBlock(DestBB, PFS))
6303 return true;
6305 if (!SeenCases.insert(Constant).second)
6306 return error(CondLoc, "duplicate case value in switch");
6307 if (!isa<ConstantInt>(Constant))
6308 return error(CondLoc, "case value is not a constant integer");
6310 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
6313 Lex.Lex(); // Eat the ']'.
6315 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
6316 for (unsigned i = 0, e = Table.size(); i != e; ++i)
6317 SI->addCase(Table[i].first, Table[i].second);
6318 Inst = SI;
6319 return false;
6322 /// parseIndirectBr
6323 /// Instruction
6324 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
6325 bool LLParser::parseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
6326 LocTy AddrLoc;
6327 Value *Address;
6328 if (parseTypeAndValue(Address, AddrLoc, PFS) ||
6329 parseToken(lltok::comma, "expected ',' after indirectbr address") ||
6330 parseToken(lltok::lsquare, "expected '[' with indirectbr"))
6331 return true;
6333 if (!Address->getType()->isPointerTy())
6334 return error(AddrLoc, "indirectbr address must have pointer type");
6336 // parse the destination list.
6337 SmallVector<BasicBlock*, 16> DestList;
6339 if (Lex.getKind() != lltok::rsquare) {
6340 BasicBlock *DestBB;
6341 if (parseTypeAndBasicBlock(DestBB, PFS))
6342 return true;
6343 DestList.push_back(DestBB);
6345 while (EatIfPresent(lltok::comma)) {
6346 if (parseTypeAndBasicBlock(DestBB, PFS))
6347 return true;
6348 DestList.push_back(DestBB);
6352 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6353 return true;
6355 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
6356 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6357 IBI->addDestination(DestList[i]);
6358 Inst = IBI;
6359 return false;
6362 /// parseInvoke
6363 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6364 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6365 bool LLParser::parseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6366 LocTy CallLoc = Lex.getLoc();
6367 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
6368 std::vector<unsigned> FwdRefAttrGrps;
6369 LocTy NoBuiltinLoc;
6370 unsigned CC;
6371 unsigned InvokeAddrSpace;
6372 Type *RetType = nullptr;
6373 LocTy RetTypeLoc;
6374 ValID CalleeID;
6375 SmallVector<ParamInfo, 16> ArgList;
6376 SmallVector<OperandBundleDef, 2> BundleList;
6378 BasicBlock *NormalBB, *UnwindBB;
6379 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6380 parseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6381 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6382 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
6383 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6384 NoBuiltinLoc) ||
6385 parseOptionalOperandBundles(BundleList, PFS) ||
6386 parseToken(lltok::kw_to, "expected 'to' in invoke") ||
6387 parseTypeAndBasicBlock(NormalBB, PFS) ||
6388 parseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6389 parseTypeAndBasicBlock(UnwindBB, PFS))
6390 return true;
6392 // If RetType is a non-function pointer type, then this is the short syntax
6393 // for the call, which means that RetType is just the return type. Infer the
6394 // rest of the function argument types from the arguments that are present.
6395 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6396 if (!Ty) {
6397 // Pull out the types of all of the arguments...
6398 std::vector<Type*> ParamTypes;
6399 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6400 ParamTypes.push_back(ArgList[i].V->getType());
6402 if (!FunctionType::isValidReturnType(RetType))
6403 return error(RetTypeLoc, "Invalid result type for LLVM function");
6405 Ty = FunctionType::get(RetType, ParamTypes, false);
6408 CalleeID.FTy = Ty;
6410 // Look up the callee.
6411 Value *Callee;
6412 if (convertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6413 Callee, &PFS))
6414 return true;
6416 // Set up the Attribute for the function.
6417 SmallVector<Value *, 8> Args;
6418 SmallVector<AttributeSet, 8> ArgAttrs;
6420 // Loop through FunctionType's arguments and ensure they are specified
6421 // correctly. Also, gather any parameter attributes.
6422 FunctionType::param_iterator I = Ty->param_begin();
6423 FunctionType::param_iterator E = Ty->param_end();
6424 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6425 Type *ExpectedTy = nullptr;
6426 if (I != E) {
6427 ExpectedTy = *I++;
6428 } else if (!Ty->isVarArg()) {
6429 return error(ArgList[i].Loc, "too many arguments specified");
6432 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6433 return error(ArgList[i].Loc, "argument is not of expected type '" +
6434 getTypeString(ExpectedTy) + "'");
6435 Args.push_back(ArgList[i].V);
6436 ArgAttrs.push_back(ArgList[i].Attrs);
6439 if (I != E)
6440 return error(CallLoc, "not enough parameters specified for call");
6442 if (FnAttrs.hasAlignmentAttr())
6443 return error(CallLoc, "invoke instructions may not have an alignment");
6445 // Finish off the Attribute and check them
6446 AttributeList PAL =
6447 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6448 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6450 InvokeInst *II =
6451 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6452 II->setCallingConv(CC);
6453 II->setAttributes(PAL);
6454 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6455 Inst = II;
6456 return false;
6459 /// parseResume
6460 /// ::= 'resume' TypeAndValue
6461 bool LLParser::parseResume(Instruction *&Inst, PerFunctionState &PFS) {
6462 Value *Exn; LocTy ExnLoc;
6463 if (parseTypeAndValue(Exn, ExnLoc, PFS))
6464 return true;
6466 ResumeInst *RI = ResumeInst::Create(Exn);
6467 Inst = RI;
6468 return false;
6471 bool LLParser::parseExceptionArgs(SmallVectorImpl<Value *> &Args,
6472 PerFunctionState &PFS) {
6473 if (parseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6474 return true;
6476 while (Lex.getKind() != lltok::rsquare) {
6477 // If this isn't the first argument, we need a comma.
6478 if (!Args.empty() &&
6479 parseToken(lltok::comma, "expected ',' in argument list"))
6480 return true;
6482 // parse the argument.
6483 LocTy ArgLoc;
6484 Type *ArgTy = nullptr;
6485 if (parseType(ArgTy, ArgLoc))
6486 return true;
6488 Value *V;
6489 if (ArgTy->isMetadataTy()) {
6490 if (parseMetadataAsValue(V, PFS))
6491 return true;
6492 } else {
6493 if (parseValue(ArgTy, V, PFS))
6494 return true;
6496 Args.push_back(V);
6499 Lex.Lex(); // Lex the ']'.
6500 return false;
6503 /// parseCleanupRet
6504 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6505 bool LLParser::parseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6506 Value *CleanupPad = nullptr;
6508 if (parseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6509 return true;
6511 if (parseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6512 return true;
6514 if (parseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6515 return true;
6517 BasicBlock *UnwindBB = nullptr;
6518 if (Lex.getKind() == lltok::kw_to) {
6519 Lex.Lex();
6520 if (parseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6521 return true;
6522 } else {
6523 if (parseTypeAndBasicBlock(UnwindBB, PFS)) {
6524 return true;
6528 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6529 return false;
6532 /// parseCatchRet
6533 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6534 bool LLParser::parseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6535 Value *CatchPad = nullptr;
6537 if (parseToken(lltok::kw_from, "expected 'from' after catchret"))
6538 return true;
6540 if (parseValue(Type::getTokenTy(Context), CatchPad, PFS))
6541 return true;
6543 BasicBlock *BB;
6544 if (parseToken(lltok::kw_to, "expected 'to' in catchret") ||
6545 parseTypeAndBasicBlock(BB, PFS))
6546 return true;
6548 Inst = CatchReturnInst::Create(CatchPad, BB);
6549 return false;
6552 /// parseCatchSwitch
6553 /// ::= 'catchswitch' within Parent
6554 bool LLParser::parseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6555 Value *ParentPad;
6557 if (parseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6558 return true;
6560 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6561 Lex.getKind() != lltok::LocalVarID)
6562 return tokError("expected scope value for catchswitch");
6564 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6565 return true;
6567 if (parseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6568 return true;
6570 SmallVector<BasicBlock *, 32> Table;
6571 do {
6572 BasicBlock *DestBB;
6573 if (parseTypeAndBasicBlock(DestBB, PFS))
6574 return true;
6575 Table.push_back(DestBB);
6576 } while (EatIfPresent(lltok::comma));
6578 if (parseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6579 return true;
6581 if (parseToken(lltok::kw_unwind, "expected 'unwind' after catchswitch scope"))
6582 return true;
6584 BasicBlock *UnwindBB = nullptr;
6585 if (EatIfPresent(lltok::kw_to)) {
6586 if (parseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6587 return true;
6588 } else {
6589 if (parseTypeAndBasicBlock(UnwindBB, PFS))
6590 return true;
6593 auto *CatchSwitch =
6594 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6595 for (BasicBlock *DestBB : Table)
6596 CatchSwitch->addHandler(DestBB);
6597 Inst = CatchSwitch;
6598 return false;
6601 /// parseCatchPad
6602 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6603 bool LLParser::parseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6604 Value *CatchSwitch = nullptr;
6606 if (parseToken(lltok::kw_within, "expected 'within' after catchpad"))
6607 return true;
6609 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6610 return tokError("expected scope value for catchpad");
6612 if (parseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6613 return true;
6615 SmallVector<Value *, 8> Args;
6616 if (parseExceptionArgs(Args, PFS))
6617 return true;
6619 Inst = CatchPadInst::Create(CatchSwitch, Args);
6620 return false;
6623 /// parseCleanupPad
6624 /// ::= 'cleanuppad' within Parent ParamList
6625 bool LLParser::parseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6626 Value *ParentPad = nullptr;
6628 if (parseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6629 return true;
6631 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6632 Lex.getKind() != lltok::LocalVarID)
6633 return tokError("expected scope value for cleanuppad");
6635 if (parseValue(Type::getTokenTy(Context), ParentPad, PFS))
6636 return true;
6638 SmallVector<Value *, 8> Args;
6639 if (parseExceptionArgs(Args, PFS))
6640 return true;
6642 Inst = CleanupPadInst::Create(ParentPad, Args);
6643 return false;
6646 //===----------------------------------------------------------------------===//
6647 // Unary Operators.
6648 //===----------------------------------------------------------------------===//
6650 /// parseUnaryOp
6651 /// ::= UnaryOp TypeAndValue ',' Value
6653 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6654 /// operand is allowed.
6655 bool LLParser::parseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6656 unsigned Opc, bool IsFP) {
6657 LocTy Loc; Value *LHS;
6658 if (parseTypeAndValue(LHS, Loc, PFS))
6659 return true;
6661 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6662 : LHS->getType()->isIntOrIntVectorTy();
6664 if (!Valid)
6665 return error(Loc, "invalid operand type for instruction");
6667 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6668 return false;
6671 /// parseCallBr
6672 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6673 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6674 /// '[' LabelList ']'
6675 bool LLParser::parseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6676 LocTy CallLoc = Lex.getLoc();
6677 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
6678 std::vector<unsigned> FwdRefAttrGrps;
6679 LocTy NoBuiltinLoc;
6680 unsigned CC;
6681 Type *RetType = nullptr;
6682 LocTy RetTypeLoc;
6683 ValID CalleeID;
6684 SmallVector<ParamInfo, 16> ArgList;
6685 SmallVector<OperandBundleDef, 2> BundleList;
6687 BasicBlock *DefaultDest;
6688 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
6689 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6690 parseValID(CalleeID, &PFS) || parseParameterList(ArgList, PFS) ||
6691 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6692 NoBuiltinLoc) ||
6693 parseOptionalOperandBundles(BundleList, PFS) ||
6694 parseToken(lltok::kw_to, "expected 'to' in callbr") ||
6695 parseTypeAndBasicBlock(DefaultDest, PFS) ||
6696 parseToken(lltok::lsquare, "expected '[' in callbr"))
6697 return true;
6699 // parse the destination list.
6700 SmallVector<BasicBlock *, 16> IndirectDests;
6702 if (Lex.getKind() != lltok::rsquare) {
6703 BasicBlock *DestBB;
6704 if (parseTypeAndBasicBlock(DestBB, PFS))
6705 return true;
6706 IndirectDests.push_back(DestBB);
6708 while (EatIfPresent(lltok::comma)) {
6709 if (parseTypeAndBasicBlock(DestBB, PFS))
6710 return true;
6711 IndirectDests.push_back(DestBB);
6715 if (parseToken(lltok::rsquare, "expected ']' at end of block list"))
6716 return true;
6718 // If RetType is a non-function pointer type, then this is the short syntax
6719 // for the call, which means that RetType is just the return type. Infer the
6720 // rest of the function argument types from the arguments that are present.
6721 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6722 if (!Ty) {
6723 // Pull out the types of all of the arguments...
6724 std::vector<Type *> ParamTypes;
6725 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6726 ParamTypes.push_back(ArgList[i].V->getType());
6728 if (!FunctionType::isValidReturnType(RetType))
6729 return error(RetTypeLoc, "Invalid result type for LLVM function");
6731 Ty = FunctionType::get(RetType, ParamTypes, false);
6734 CalleeID.FTy = Ty;
6736 // Look up the callee.
6737 Value *Callee;
6738 if (convertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
6739 return true;
6741 // Set up the Attribute for the function.
6742 SmallVector<Value *, 8> Args;
6743 SmallVector<AttributeSet, 8> ArgAttrs;
6745 // Loop through FunctionType's arguments and ensure they are specified
6746 // correctly. Also, gather any parameter attributes.
6747 FunctionType::param_iterator I = Ty->param_begin();
6748 FunctionType::param_iterator E = Ty->param_end();
6749 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6750 Type *ExpectedTy = nullptr;
6751 if (I != E) {
6752 ExpectedTy = *I++;
6753 } else if (!Ty->isVarArg()) {
6754 return error(ArgList[i].Loc, "too many arguments specified");
6757 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6758 return error(ArgList[i].Loc, "argument is not of expected type '" +
6759 getTypeString(ExpectedTy) + "'");
6760 Args.push_back(ArgList[i].V);
6761 ArgAttrs.push_back(ArgList[i].Attrs);
6764 if (I != E)
6765 return error(CallLoc, "not enough parameters specified for call");
6767 if (FnAttrs.hasAlignmentAttr())
6768 return error(CallLoc, "callbr instructions may not have an alignment");
6770 // Finish off the Attribute and check them
6771 AttributeList PAL =
6772 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6773 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6775 CallBrInst *CBI =
6776 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6777 BundleList);
6778 CBI->setCallingConv(CC);
6779 CBI->setAttributes(PAL);
6780 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6781 Inst = CBI;
6782 return false;
6785 //===----------------------------------------------------------------------===//
6786 // Binary Operators.
6787 //===----------------------------------------------------------------------===//
6789 /// parseArithmetic
6790 /// ::= ArithmeticOps TypeAndValue ',' Value
6792 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6793 /// operand is allowed.
6794 bool LLParser::parseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6795 unsigned Opc, bool IsFP) {
6796 LocTy Loc; Value *LHS, *RHS;
6797 if (parseTypeAndValue(LHS, Loc, PFS) ||
6798 parseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6799 parseValue(LHS->getType(), RHS, PFS))
6800 return true;
6802 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6803 : LHS->getType()->isIntOrIntVectorTy();
6805 if (!Valid)
6806 return error(Loc, "invalid operand type for instruction");
6808 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6809 return false;
6812 /// parseLogical
6813 /// ::= ArithmeticOps TypeAndValue ',' Value {
6814 bool LLParser::parseLogical(Instruction *&Inst, PerFunctionState &PFS,
6815 unsigned Opc) {
6816 LocTy Loc; Value *LHS, *RHS;
6817 if (parseTypeAndValue(LHS, Loc, PFS) ||
6818 parseToken(lltok::comma, "expected ',' in logical operation") ||
6819 parseValue(LHS->getType(), RHS, PFS))
6820 return true;
6822 if (!LHS->getType()->isIntOrIntVectorTy())
6823 return error(Loc,
6824 "instruction requires integer or integer vector operands");
6826 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6827 return false;
6830 /// parseCompare
6831 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
6832 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
6833 bool LLParser::parseCompare(Instruction *&Inst, PerFunctionState &PFS,
6834 unsigned Opc) {
6835 // parse the integer/fp comparison predicate.
6836 LocTy Loc;
6837 unsigned Pred;
6838 Value *LHS, *RHS;
6839 if (parseCmpPredicate(Pred, Opc) || parseTypeAndValue(LHS, Loc, PFS) ||
6840 parseToken(lltok::comma, "expected ',' after compare value") ||
6841 parseValue(LHS->getType(), RHS, PFS))
6842 return true;
6844 if (Opc == Instruction::FCmp) {
6845 if (!LHS->getType()->isFPOrFPVectorTy())
6846 return error(Loc, "fcmp requires floating point operands");
6847 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6848 } else {
6849 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
6850 if (!LHS->getType()->isIntOrIntVectorTy() &&
6851 !LHS->getType()->isPtrOrPtrVectorTy())
6852 return error(Loc, "icmp requires integer operands");
6853 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6855 return false;
6858 //===----------------------------------------------------------------------===//
6859 // Other Instructions.
6860 //===----------------------------------------------------------------------===//
6862 /// parseCast
6863 /// ::= CastOpc TypeAndValue 'to' Type
6864 bool LLParser::parseCast(Instruction *&Inst, PerFunctionState &PFS,
6865 unsigned Opc) {
6866 LocTy Loc;
6867 Value *Op;
6868 Type *DestTy = nullptr;
6869 if (parseTypeAndValue(Op, Loc, PFS) ||
6870 parseToken(lltok::kw_to, "expected 'to' after cast value") ||
6871 parseType(DestTy))
6872 return true;
6874 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6875 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
6876 return error(Loc, "invalid cast opcode for cast from '" +
6877 getTypeString(Op->getType()) + "' to '" +
6878 getTypeString(DestTy) + "'");
6880 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6881 return false;
6884 /// parseSelect
6885 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6886 bool LLParser::parseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6887 LocTy Loc;
6888 Value *Op0, *Op1, *Op2;
6889 if (parseTypeAndValue(Op0, Loc, PFS) ||
6890 parseToken(lltok::comma, "expected ',' after select condition") ||
6891 parseTypeAndValue(Op1, PFS) ||
6892 parseToken(lltok::comma, "expected ',' after select value") ||
6893 parseTypeAndValue(Op2, PFS))
6894 return true;
6896 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6897 return error(Loc, Reason);
6899 Inst = SelectInst::Create(Op0, Op1, Op2);
6900 return false;
6903 /// parseVAArg
6904 /// ::= 'va_arg' TypeAndValue ',' Type
6905 bool LLParser::parseVAArg(Instruction *&Inst, PerFunctionState &PFS) {
6906 Value *Op;
6907 Type *EltTy = nullptr;
6908 LocTy TypeLoc;
6909 if (parseTypeAndValue(Op, PFS) ||
6910 parseToken(lltok::comma, "expected ',' after vaarg operand") ||
6911 parseType(EltTy, TypeLoc))
6912 return true;
6914 if (!EltTy->isFirstClassType())
6915 return error(TypeLoc, "va_arg requires operand with first class type");
6917 Inst = new VAArgInst(Op, EltTy);
6918 return false;
6921 /// parseExtractElement
6922 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6923 bool LLParser::parseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6924 LocTy Loc;
6925 Value *Op0, *Op1;
6926 if (parseTypeAndValue(Op0, Loc, PFS) ||
6927 parseToken(lltok::comma, "expected ',' after extract value") ||
6928 parseTypeAndValue(Op1, PFS))
6929 return true;
6931 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6932 return error(Loc, "invalid extractelement operands");
6934 Inst = ExtractElementInst::Create(Op0, Op1);
6935 return false;
6938 /// parseInsertElement
6939 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6940 bool LLParser::parseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6941 LocTy Loc;
6942 Value *Op0, *Op1, *Op2;
6943 if (parseTypeAndValue(Op0, Loc, PFS) ||
6944 parseToken(lltok::comma, "expected ',' after insertelement value") ||
6945 parseTypeAndValue(Op1, PFS) ||
6946 parseToken(lltok::comma, "expected ',' after insertelement value") ||
6947 parseTypeAndValue(Op2, PFS))
6948 return true;
6950 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
6951 return error(Loc, "invalid insertelement operands");
6953 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6954 return false;
6957 /// parseShuffleVector
6958 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6959 bool LLParser::parseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6960 LocTy Loc;
6961 Value *Op0, *Op1, *Op2;
6962 if (parseTypeAndValue(Op0, Loc, PFS) ||
6963 parseToken(lltok::comma, "expected ',' after shuffle mask") ||
6964 parseTypeAndValue(Op1, PFS) ||
6965 parseToken(lltok::comma, "expected ',' after shuffle value") ||
6966 parseTypeAndValue(Op2, PFS))
6967 return true;
6969 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
6970 return error(Loc, "invalid shufflevector operands");
6972 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6973 return false;
6976 /// parsePHI
6977 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6978 int LLParser::parsePHI(Instruction *&Inst, PerFunctionState &PFS) {
6979 Type *Ty = nullptr; LocTy TypeLoc;
6980 Value *Op0, *Op1;
6982 if (parseType(Ty, TypeLoc) ||
6983 parseToken(lltok::lsquare, "expected '[' in phi value list") ||
6984 parseValue(Ty, Op0, PFS) ||
6985 parseToken(lltok::comma, "expected ',' after insertelement value") ||
6986 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
6987 parseToken(lltok::rsquare, "expected ']' in phi value list"))
6988 return true;
6990 bool AteExtraComma = false;
6991 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
6993 while (true) {
6994 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
6996 if (!EatIfPresent(lltok::comma))
6997 break;
6999 if (Lex.getKind() == lltok::MetadataVar) {
7000 AteExtraComma = true;
7001 break;
7004 if (parseToken(lltok::lsquare, "expected '[' in phi value list") ||
7005 parseValue(Ty, Op0, PFS) ||
7006 parseToken(lltok::comma, "expected ',' after insertelement value") ||
7007 parseValue(Type::getLabelTy(Context), Op1, PFS) ||
7008 parseToken(lltok::rsquare, "expected ']' in phi value list"))
7009 return true;
7012 if (!Ty->isFirstClassType())
7013 return error(TypeLoc, "phi node must have first class type");
7015 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
7016 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
7017 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
7018 Inst = PN;
7019 return AteExtraComma ? InstExtraComma : InstNormal;
7022 /// parseLandingPad
7023 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
7024 /// Clause
7025 /// ::= 'catch' TypeAndValue
7026 /// ::= 'filter'
7027 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
7028 bool LLParser::parseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
7029 Type *Ty = nullptr; LocTy TyLoc;
7031 if (parseType(Ty, TyLoc))
7032 return true;
7034 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
7035 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
7037 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
7038 LandingPadInst::ClauseType CT;
7039 if (EatIfPresent(lltok::kw_catch))
7040 CT = LandingPadInst::Catch;
7041 else if (EatIfPresent(lltok::kw_filter))
7042 CT = LandingPadInst::Filter;
7043 else
7044 return tokError("expected 'catch' or 'filter' clause type");
7046 Value *V;
7047 LocTy VLoc;
7048 if (parseTypeAndValue(V, VLoc, PFS))
7049 return true;
7051 // A 'catch' type expects a non-array constant. A filter clause expects an
7052 // array constant.
7053 if (CT == LandingPadInst::Catch) {
7054 if (isa<ArrayType>(V->getType()))
7055 error(VLoc, "'catch' clause has an invalid type");
7056 } else {
7057 if (!isa<ArrayType>(V->getType()))
7058 error(VLoc, "'filter' clause has an invalid type");
7061 Constant *CV = dyn_cast<Constant>(V);
7062 if (!CV)
7063 return error(VLoc, "clause argument must be a constant");
7064 LP->addClause(CV);
7067 Inst = LP.release();
7068 return false;
7071 /// parseFreeze
7072 /// ::= 'freeze' Type Value
7073 bool LLParser::parseFreeze(Instruction *&Inst, PerFunctionState &PFS) {
7074 LocTy Loc;
7075 Value *Op;
7076 if (parseTypeAndValue(Op, Loc, PFS))
7077 return true;
7079 Inst = new FreezeInst(Op);
7080 return false;
7083 /// parseCall
7084 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
7085 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7086 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
7087 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7088 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
7089 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7090 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
7091 /// OptionalAttrs Type Value ParameterList OptionalAttrs
7092 bool LLParser::parseCall(Instruction *&Inst, PerFunctionState &PFS,
7093 CallInst::TailCallKind TCK) {
7094 AttrBuilder RetAttrs(M->getContext()), FnAttrs(M->getContext());
7095 std::vector<unsigned> FwdRefAttrGrps;
7096 LocTy BuiltinLoc;
7097 unsigned CallAddrSpace;
7098 unsigned CC;
7099 Type *RetType = nullptr;
7100 LocTy RetTypeLoc;
7101 ValID CalleeID;
7102 SmallVector<ParamInfo, 16> ArgList;
7103 SmallVector<OperandBundleDef, 2> BundleList;
7104 LocTy CallLoc = Lex.getLoc();
7106 if (TCK != CallInst::TCK_None &&
7107 parseToken(lltok::kw_call,
7108 "expected 'tail call', 'musttail call', or 'notail call'"))
7109 return true;
7111 FastMathFlags FMF = EatFastMathFlagsIfPresent();
7113 if (parseOptionalCallingConv(CC) || parseOptionalReturnAttrs(RetAttrs) ||
7114 parseOptionalProgramAddrSpace(CallAddrSpace) ||
7115 parseType(RetType, RetTypeLoc, true /*void allowed*/) ||
7116 parseValID(CalleeID, &PFS) ||
7117 parseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
7118 PFS.getFunction().isVarArg()) ||
7119 parseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
7120 parseOptionalOperandBundles(BundleList, PFS))
7121 return true;
7123 // If RetType is a non-function pointer type, then this is the short syntax
7124 // for the call, which means that RetType is just the return type. Infer the
7125 // rest of the function argument types from the arguments that are present.
7126 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
7127 if (!Ty) {
7128 // Pull out the types of all of the arguments...
7129 std::vector<Type*> ParamTypes;
7130 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
7131 ParamTypes.push_back(ArgList[i].V->getType());
7133 if (!FunctionType::isValidReturnType(RetType))
7134 return error(RetTypeLoc, "Invalid result type for LLVM function");
7136 Ty = FunctionType::get(RetType, ParamTypes, false);
7139 CalleeID.FTy = Ty;
7141 // Look up the callee.
7142 Value *Callee;
7143 if (convertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
7144 &PFS))
7145 return true;
7147 // Set up the Attribute for the function.
7148 SmallVector<AttributeSet, 8> Attrs;
7150 SmallVector<Value*, 8> Args;
7152 // Loop through FunctionType's arguments and ensure they are specified
7153 // correctly. Also, gather any parameter attributes.
7154 FunctionType::param_iterator I = Ty->param_begin();
7155 FunctionType::param_iterator E = Ty->param_end();
7156 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
7157 Type *ExpectedTy = nullptr;
7158 if (I != E) {
7159 ExpectedTy = *I++;
7160 } else if (!Ty->isVarArg()) {
7161 return error(ArgList[i].Loc, "too many arguments specified");
7164 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
7165 return error(ArgList[i].Loc, "argument is not of expected type '" +
7166 getTypeString(ExpectedTy) + "'");
7167 Args.push_back(ArgList[i].V);
7168 Attrs.push_back(ArgList[i].Attrs);
7171 if (I != E)
7172 return error(CallLoc, "not enough parameters specified for call");
7174 if (FnAttrs.hasAlignmentAttr())
7175 return error(CallLoc, "call instructions may not have an alignment");
7177 // Finish off the Attribute and check them
7178 AttributeList PAL =
7179 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
7180 AttributeSet::get(Context, RetAttrs), Attrs);
7182 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
7183 CI->setTailCallKind(TCK);
7184 CI->setCallingConv(CC);
7185 if (FMF.any()) {
7186 if (!isa<FPMathOperator>(CI)) {
7187 CI->deleteValue();
7188 return error(CallLoc, "fast-math-flags specified for call without "
7189 "floating-point scalar or vector return type");
7191 CI->setFastMathFlags(FMF);
7193 CI->setAttributes(PAL);
7194 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
7195 Inst = CI;
7196 return false;
7199 //===----------------------------------------------------------------------===//
7200 // Memory Instructions.
7201 //===----------------------------------------------------------------------===//
7203 /// parseAlloc
7204 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
7205 /// (',' 'align' i32)? (',', 'addrspace(n))?
7206 int LLParser::parseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
7207 Value *Size = nullptr;
7208 LocTy SizeLoc, TyLoc, ASLoc;
7209 MaybeAlign Alignment;
7210 unsigned AddrSpace = 0;
7211 Type *Ty = nullptr;
7213 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
7214 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
7216 if (parseType(Ty, TyLoc))
7217 return true;
7219 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
7220 return error(TyLoc, "invalid type for alloca");
7222 bool AteExtraComma = false;
7223 if (EatIfPresent(lltok::comma)) {
7224 if (Lex.getKind() == lltok::kw_align) {
7225 if (parseOptionalAlignment(Alignment))
7226 return true;
7227 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7228 return true;
7229 } else if (Lex.getKind() == lltok::kw_addrspace) {
7230 ASLoc = Lex.getLoc();
7231 if (parseOptionalAddrSpace(AddrSpace))
7232 return true;
7233 } else if (Lex.getKind() == lltok::MetadataVar) {
7234 AteExtraComma = true;
7235 } else {
7236 if (parseTypeAndValue(Size, SizeLoc, PFS))
7237 return true;
7238 if (EatIfPresent(lltok::comma)) {
7239 if (Lex.getKind() == lltok::kw_align) {
7240 if (parseOptionalAlignment(Alignment))
7241 return true;
7242 if (parseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
7243 return true;
7244 } else if (Lex.getKind() == lltok::kw_addrspace) {
7245 ASLoc = Lex.getLoc();
7246 if (parseOptionalAddrSpace(AddrSpace))
7247 return true;
7248 } else if (Lex.getKind() == lltok::MetadataVar) {
7249 AteExtraComma = true;
7255 if (Size && !Size->getType()->isIntegerTy())
7256 return error(SizeLoc, "element count must have integer type");
7258 SmallPtrSet<Type *, 4> Visited;
7259 if (!Alignment && !Ty->isSized(&Visited))
7260 return error(TyLoc, "Cannot allocate unsized type");
7261 if (!Alignment)
7262 Alignment = M->getDataLayout().getPrefTypeAlign(Ty);
7263 AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, *Alignment);
7264 AI->setUsedWithInAlloca(IsInAlloca);
7265 AI->setSwiftError(IsSwiftError);
7266 Inst = AI;
7267 return AteExtraComma ? InstExtraComma : InstNormal;
7270 /// parseLoad
7271 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
7272 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
7273 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7274 int LLParser::parseLoad(Instruction *&Inst, PerFunctionState &PFS) {
7275 Value *Val; LocTy Loc;
7276 MaybeAlign Alignment;
7277 bool AteExtraComma = false;
7278 bool isAtomic = false;
7279 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7280 SyncScope::ID SSID = SyncScope::System;
7282 if (Lex.getKind() == lltok::kw_atomic) {
7283 isAtomic = true;
7284 Lex.Lex();
7287 bool isVolatile = false;
7288 if (Lex.getKind() == lltok::kw_volatile) {
7289 isVolatile = true;
7290 Lex.Lex();
7293 Type *Ty;
7294 LocTy ExplicitTypeLoc = Lex.getLoc();
7295 if (parseType(Ty) ||
7296 parseToken(lltok::comma, "expected comma after load's type") ||
7297 parseTypeAndValue(Val, Loc, PFS) ||
7298 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7299 parseOptionalCommaAlign(Alignment, AteExtraComma))
7300 return true;
7302 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
7303 return error(Loc, "load operand must be a pointer to a first class type");
7304 if (isAtomic && !Alignment)
7305 return error(Loc, "atomic load must have explicit non-zero alignment");
7306 if (Ordering == AtomicOrdering::Release ||
7307 Ordering == AtomicOrdering::AcquireRelease)
7308 return error(Loc, "atomic load cannot use Release ordering");
7310 if (!cast<PointerType>(Val->getType())->isOpaqueOrPointeeTypeMatches(Ty)) {
7311 return error(
7312 ExplicitTypeLoc,
7313 typeComparisonErrorMessage(
7314 "explicit pointee type doesn't match operand's pointee type", Ty,
7315 Val->getType()->getNonOpaquePointerElementType()));
7317 SmallPtrSet<Type *, 4> Visited;
7318 if (!Alignment && !Ty->isSized(&Visited))
7319 return error(ExplicitTypeLoc, "loading unsized types is not allowed");
7320 if (!Alignment)
7321 Alignment = M->getDataLayout().getABITypeAlign(Ty);
7322 Inst = new LoadInst(Ty, Val, "", isVolatile, *Alignment, Ordering, SSID);
7323 return AteExtraComma ? InstExtraComma : InstNormal;
7326 /// parseStore
7328 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
7329 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
7330 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
7331 int LLParser::parseStore(Instruction *&Inst, PerFunctionState &PFS) {
7332 Value *Val, *Ptr; LocTy Loc, PtrLoc;
7333 MaybeAlign Alignment;
7334 bool AteExtraComma = false;
7335 bool isAtomic = false;
7336 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7337 SyncScope::ID SSID = SyncScope::System;
7339 if (Lex.getKind() == lltok::kw_atomic) {
7340 isAtomic = true;
7341 Lex.Lex();
7344 bool isVolatile = false;
7345 if (Lex.getKind() == lltok::kw_volatile) {
7346 isVolatile = true;
7347 Lex.Lex();
7350 if (parseTypeAndValue(Val, Loc, PFS) ||
7351 parseToken(lltok::comma, "expected ',' after store operand") ||
7352 parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7353 parseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7354 parseOptionalCommaAlign(Alignment, AteExtraComma))
7355 return true;
7357 if (!Ptr->getType()->isPointerTy())
7358 return error(PtrLoc, "store operand must be a pointer");
7359 if (!Val->getType()->isFirstClassType())
7360 return error(Loc, "store operand must be a first class value");
7361 if (!cast<PointerType>(Ptr->getType())
7362 ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7363 return error(Loc, "stored value and pointer type do not match");
7364 if (isAtomic && !Alignment)
7365 return error(Loc, "atomic store must have explicit non-zero alignment");
7366 if (Ordering == AtomicOrdering::Acquire ||
7367 Ordering == AtomicOrdering::AcquireRelease)
7368 return error(Loc, "atomic store cannot use Acquire ordering");
7369 SmallPtrSet<Type *, 4> Visited;
7370 if (!Alignment && !Val->getType()->isSized(&Visited))
7371 return error(Loc, "storing unsized types is not allowed");
7372 if (!Alignment)
7373 Alignment = M->getDataLayout().getABITypeAlign(Val->getType());
7375 Inst = new StoreInst(Val, Ptr, isVolatile, *Alignment, Ordering, SSID);
7376 return AteExtraComma ? InstExtraComma : InstNormal;
7379 /// parseCmpXchg
7380 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7381 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering ','
7382 /// 'Align'?
7383 int LLParser::parseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
7384 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7385 bool AteExtraComma = false;
7386 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7387 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
7388 SyncScope::ID SSID = SyncScope::System;
7389 bool isVolatile = false;
7390 bool isWeak = false;
7391 MaybeAlign Alignment;
7393 if (EatIfPresent(lltok::kw_weak))
7394 isWeak = true;
7396 if (EatIfPresent(lltok::kw_volatile))
7397 isVolatile = true;
7399 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7400 parseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7401 parseTypeAndValue(Cmp, CmpLoc, PFS) ||
7402 parseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7403 parseTypeAndValue(New, NewLoc, PFS) ||
7404 parseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7405 parseOrdering(FailureOrdering) ||
7406 parseOptionalCommaAlign(Alignment, AteExtraComma))
7407 return true;
7409 if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
7410 return tokError("invalid cmpxchg success ordering");
7411 if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
7412 return tokError("invalid cmpxchg failure ordering");
7413 if (!Ptr->getType()->isPointerTy())
7414 return error(PtrLoc, "cmpxchg operand must be a pointer");
7415 if (!cast<PointerType>(Ptr->getType())
7416 ->isOpaqueOrPointeeTypeMatches(Cmp->getType()))
7417 return error(CmpLoc, "compare value and pointer type do not match");
7418 if (!cast<PointerType>(Ptr->getType())
7419 ->isOpaqueOrPointeeTypeMatches(New->getType()))
7420 return error(NewLoc, "new value and pointer type do not match");
7421 if (Cmp->getType() != New->getType())
7422 return error(NewLoc, "compare value and new value type do not match");
7423 if (!New->getType()->isFirstClassType())
7424 return error(NewLoc, "cmpxchg operand must be a first class value");
7426 const Align DefaultAlignment(
7427 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7428 Cmp->getType()));
7430 AtomicCmpXchgInst *CXI =
7431 new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment.value_or(DefaultAlignment),
7432 SuccessOrdering, FailureOrdering, SSID);
7433 CXI->setVolatile(isVolatile);
7434 CXI->setWeak(isWeak);
7436 Inst = CXI;
7437 return AteExtraComma ? InstExtraComma : InstNormal;
7440 /// parseAtomicRMW
7441 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7442 /// 'singlethread'? AtomicOrdering
7443 int LLParser::parseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7444 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7445 bool AteExtraComma = false;
7446 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7447 SyncScope::ID SSID = SyncScope::System;
7448 bool isVolatile = false;
7449 bool IsFP = false;
7450 AtomicRMWInst::BinOp Operation;
7451 MaybeAlign Alignment;
7453 if (EatIfPresent(lltok::kw_volatile))
7454 isVolatile = true;
7456 switch (Lex.getKind()) {
7457 default:
7458 return tokError("expected binary operation in atomicrmw");
7459 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7460 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7461 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7462 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7463 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7464 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7465 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7466 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7467 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7468 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7469 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7470 case lltok::kw_fadd:
7471 Operation = AtomicRMWInst::FAdd;
7472 IsFP = true;
7473 break;
7474 case lltok::kw_fsub:
7475 Operation = AtomicRMWInst::FSub;
7476 IsFP = true;
7477 break;
7478 case lltok::kw_fmax:
7479 Operation = AtomicRMWInst::FMax;
7480 IsFP = true;
7481 break;
7482 case lltok::kw_fmin:
7483 Operation = AtomicRMWInst::FMin;
7484 IsFP = true;
7485 break;
7487 Lex.Lex(); // Eat the operation.
7489 if (parseTypeAndValue(Ptr, PtrLoc, PFS) ||
7490 parseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7491 parseTypeAndValue(Val, ValLoc, PFS) ||
7492 parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering) ||
7493 parseOptionalCommaAlign(Alignment, AteExtraComma))
7494 return true;
7496 if (Ordering == AtomicOrdering::Unordered)
7497 return tokError("atomicrmw cannot be unordered");
7498 if (!Ptr->getType()->isPointerTy())
7499 return error(PtrLoc, "atomicrmw operand must be a pointer");
7500 if (!cast<PointerType>(Ptr->getType())
7501 ->isOpaqueOrPointeeTypeMatches(Val->getType()))
7502 return error(ValLoc, "atomicrmw value and pointer type do not match");
7504 if (Operation == AtomicRMWInst::Xchg) {
7505 if (!Val->getType()->isIntegerTy() &&
7506 !Val->getType()->isFloatingPointTy() &&
7507 !Val->getType()->isPointerTy()) {
7508 return error(
7509 ValLoc,
7510 "atomicrmw " + AtomicRMWInst::getOperationName(Operation) +
7511 " operand must be an integer, floating point, or pointer type");
7513 } else if (IsFP) {
7514 if (!Val->getType()->isFloatingPointTy()) {
7515 return error(ValLoc, "atomicrmw " +
7516 AtomicRMWInst::getOperationName(Operation) +
7517 " operand must be a floating point type");
7519 } else {
7520 if (!Val->getType()->isIntegerTy()) {
7521 return error(ValLoc, "atomicrmw " +
7522 AtomicRMWInst::getOperationName(Operation) +
7523 " operand must be an integer");
7527 unsigned Size =
7528 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSizeInBits(
7529 Val->getType());
7530 if (Size < 8 || (Size & (Size - 1)))
7531 return error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7532 " integer");
7533 const Align DefaultAlignment(
7534 PFS.getFunction().getParent()->getDataLayout().getTypeStoreSize(
7535 Val->getType()));
7536 AtomicRMWInst *RMWI =
7537 new AtomicRMWInst(Operation, Ptr, Val,
7538 Alignment.value_or(DefaultAlignment), Ordering, SSID);
7539 RMWI->setVolatile(isVolatile);
7540 Inst = RMWI;
7541 return AteExtraComma ? InstExtraComma : InstNormal;
7544 /// parseFence
7545 /// ::= 'fence' 'singlethread'? AtomicOrdering
7546 int LLParser::parseFence(Instruction *&Inst, PerFunctionState &PFS) {
7547 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7548 SyncScope::ID SSID = SyncScope::System;
7549 if (parseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7550 return true;
7552 if (Ordering == AtomicOrdering::Unordered)
7553 return tokError("fence cannot be unordered");
7554 if (Ordering == AtomicOrdering::Monotonic)
7555 return tokError("fence cannot be monotonic");
7557 Inst = new FenceInst(Context, Ordering, SSID);
7558 return InstNormal;
7561 /// parseGetElementPtr
7562 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7563 int LLParser::parseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7564 Value *Ptr = nullptr;
7565 Value *Val = nullptr;
7566 LocTy Loc, EltLoc;
7568 bool InBounds = EatIfPresent(lltok::kw_inbounds);
7570 Type *Ty = nullptr;
7571 LocTy ExplicitTypeLoc = Lex.getLoc();
7572 if (parseType(Ty) ||
7573 parseToken(lltok::comma, "expected comma after getelementptr's type") ||
7574 parseTypeAndValue(Ptr, Loc, PFS))
7575 return true;
7577 Type *BaseType = Ptr->getType();
7578 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7579 if (!BasePointerType)
7580 return error(Loc, "base of getelementptr must be a pointer");
7582 if (!BasePointerType->isOpaqueOrPointeeTypeMatches(Ty)) {
7583 return error(
7584 ExplicitTypeLoc,
7585 typeComparisonErrorMessage(
7586 "explicit pointee type doesn't match operand's pointee type", Ty,
7587 BasePointerType->getNonOpaquePointerElementType()));
7590 SmallVector<Value*, 16> Indices;
7591 bool AteExtraComma = false;
7592 // GEP returns a vector of pointers if at least one of parameters is a vector.
7593 // All vector parameters should have the same vector width.
7594 ElementCount GEPWidth = BaseType->isVectorTy()
7595 ? cast<VectorType>(BaseType)->getElementCount()
7596 : ElementCount::getFixed(0);
7598 while (EatIfPresent(lltok::comma)) {
7599 if (Lex.getKind() == lltok::MetadataVar) {
7600 AteExtraComma = true;
7601 break;
7603 if (parseTypeAndValue(Val, EltLoc, PFS))
7604 return true;
7605 if (!Val->getType()->isIntOrIntVectorTy())
7606 return error(EltLoc, "getelementptr index must be an integer");
7608 if (auto *ValVTy = dyn_cast<VectorType>(Val->getType())) {
7609 ElementCount ValNumEl = ValVTy->getElementCount();
7610 if (GEPWidth != ElementCount::getFixed(0) && GEPWidth != ValNumEl)
7611 return error(
7612 EltLoc,
7613 "getelementptr vector index has a wrong number of elements");
7614 GEPWidth = ValNumEl;
7616 Indices.push_back(Val);
7619 SmallPtrSet<Type*, 4> Visited;
7620 if (!Indices.empty() && !Ty->isSized(&Visited))
7621 return error(Loc, "base element of getelementptr must be sized");
7623 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7624 return error(Loc, "invalid getelementptr indices");
7625 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7626 if (InBounds)
7627 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7628 return AteExtraComma ? InstExtraComma : InstNormal;
7631 /// parseExtractValue
7632 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
7633 int LLParser::parseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7634 Value *Val; LocTy Loc;
7635 SmallVector<unsigned, 4> Indices;
7636 bool AteExtraComma;
7637 if (parseTypeAndValue(Val, Loc, PFS) ||
7638 parseIndexList(Indices, AteExtraComma))
7639 return true;
7641 if (!Val->getType()->isAggregateType())
7642 return error(Loc, "extractvalue operand must be aggregate type");
7644 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7645 return error(Loc, "invalid indices for extractvalue");
7646 Inst = ExtractValueInst::Create(Val, Indices);
7647 return AteExtraComma ? InstExtraComma : InstNormal;
7650 /// parseInsertValue
7651 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7652 int LLParser::parseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7653 Value *Val0, *Val1; LocTy Loc0, Loc1;
7654 SmallVector<unsigned, 4> Indices;
7655 bool AteExtraComma;
7656 if (parseTypeAndValue(Val0, Loc0, PFS) ||
7657 parseToken(lltok::comma, "expected comma after insertvalue operand") ||
7658 parseTypeAndValue(Val1, Loc1, PFS) ||
7659 parseIndexList(Indices, AteExtraComma))
7660 return true;
7662 if (!Val0->getType()->isAggregateType())
7663 return error(Loc0, "insertvalue operand must be aggregate type");
7665 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7666 if (!IndexedType)
7667 return error(Loc0, "invalid indices for insertvalue");
7668 if (IndexedType != Val1->getType())
7669 return error(Loc1, "insertvalue operand and field disagree in type: '" +
7670 getTypeString(Val1->getType()) + "' instead of '" +
7671 getTypeString(IndexedType) + "'");
7672 Inst = InsertValueInst::Create(Val0, Val1, Indices);
7673 return AteExtraComma ? InstExtraComma : InstNormal;
7676 //===----------------------------------------------------------------------===//
7677 // Embedded metadata.
7678 //===----------------------------------------------------------------------===//
7680 /// parseMDNodeVector
7681 /// ::= { Element (',' Element)* }
7682 /// Element
7683 /// ::= 'null' | TypeAndValue
7684 bool LLParser::parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7685 if (parseToken(lltok::lbrace, "expected '{' here"))
7686 return true;
7688 // Check for an empty list.
7689 if (EatIfPresent(lltok::rbrace))
7690 return false;
7692 do {
7693 // Null is a special case since it is typeless.
7694 if (EatIfPresent(lltok::kw_null)) {
7695 Elts.push_back(nullptr);
7696 continue;
7699 Metadata *MD;
7700 if (parseMetadata(MD, nullptr))
7701 return true;
7702 Elts.push_back(MD);
7703 } while (EatIfPresent(lltok::comma));
7705 return parseToken(lltok::rbrace, "expected end of metadata node");
7708 //===----------------------------------------------------------------------===//
7709 // Use-list order directives.
7710 //===----------------------------------------------------------------------===//
7711 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7712 SMLoc Loc) {
7713 if (V->use_empty())
7714 return error(Loc, "value has no uses");
7716 unsigned NumUses = 0;
7717 SmallDenseMap<const Use *, unsigned, 16> Order;
7718 for (const Use &U : V->uses()) {
7719 if (++NumUses > Indexes.size())
7720 break;
7721 Order[&U] = Indexes[NumUses - 1];
7723 if (NumUses < 2)
7724 return error(Loc, "value only has one use");
7725 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7726 return error(Loc,
7727 "wrong number of indexes, expected " + Twine(V->getNumUses()));
7729 V->sortUseList([&](const Use &L, const Use &R) {
7730 return Order.lookup(&L) < Order.lookup(&R);
7732 return false;
7735 /// parseUseListOrderIndexes
7736 /// ::= '{' uint32 (',' uint32)+ '}'
7737 bool LLParser::parseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7738 SMLoc Loc = Lex.getLoc();
7739 if (parseToken(lltok::lbrace, "expected '{' here"))
7740 return true;
7741 if (Lex.getKind() == lltok::rbrace)
7742 return Lex.Error("expected non-empty list of uselistorder indexes");
7744 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7745 // indexes should be distinct numbers in the range [0, size-1], and should
7746 // not be in order.
7747 unsigned Offset = 0;
7748 unsigned Max = 0;
7749 bool IsOrdered = true;
7750 assert(Indexes.empty() && "Expected empty order vector");
7751 do {
7752 unsigned Index;
7753 if (parseUInt32(Index))
7754 return true;
7756 // Update consistency checks.
7757 Offset += Index - Indexes.size();
7758 Max = std::max(Max, Index);
7759 IsOrdered &= Index == Indexes.size();
7761 Indexes.push_back(Index);
7762 } while (EatIfPresent(lltok::comma));
7764 if (parseToken(lltok::rbrace, "expected '}' here"))
7765 return true;
7767 if (Indexes.size() < 2)
7768 return error(Loc, "expected >= 2 uselistorder indexes");
7769 if (Offset != 0 || Max >= Indexes.size())
7770 return error(Loc,
7771 "expected distinct uselistorder indexes in range [0, size)");
7772 if (IsOrdered)
7773 return error(Loc, "expected uselistorder indexes to change the order");
7775 return false;
7778 /// parseUseListOrder
7779 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7780 bool LLParser::parseUseListOrder(PerFunctionState *PFS) {
7781 SMLoc Loc = Lex.getLoc();
7782 if (parseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7783 return true;
7785 Value *V;
7786 SmallVector<unsigned, 16> Indexes;
7787 if (parseTypeAndValue(V, PFS) ||
7788 parseToken(lltok::comma, "expected comma in uselistorder directive") ||
7789 parseUseListOrderIndexes(Indexes))
7790 return true;
7792 return sortUseListOrder(V, Indexes, Loc);
7795 /// parseUseListOrderBB
7796 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7797 bool LLParser::parseUseListOrderBB() {
7798 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7799 SMLoc Loc = Lex.getLoc();
7800 Lex.Lex();
7802 ValID Fn, Label;
7803 SmallVector<unsigned, 16> Indexes;
7804 if (parseValID(Fn, /*PFS=*/nullptr) ||
7805 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7806 parseValID(Label, /*PFS=*/nullptr) ||
7807 parseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7808 parseUseListOrderIndexes(Indexes))
7809 return true;
7811 // Check the function.
7812 GlobalValue *GV;
7813 if (Fn.Kind == ValID::t_GlobalName)
7814 GV = M->getNamedValue(Fn.StrVal);
7815 else if (Fn.Kind == ValID::t_GlobalID)
7816 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7817 else
7818 return error(Fn.Loc, "expected function name in uselistorder_bb");
7819 if (!GV)
7820 return error(Fn.Loc,
7821 "invalid function forward reference in uselistorder_bb");
7822 auto *F = dyn_cast<Function>(GV);
7823 if (!F)
7824 return error(Fn.Loc, "expected function name in uselistorder_bb");
7825 if (F->isDeclaration())
7826 return error(Fn.Loc, "invalid declaration in uselistorder_bb");
7828 // Check the basic block.
7829 if (Label.Kind == ValID::t_LocalID)
7830 return error(Label.Loc, "invalid numeric label in uselistorder_bb");
7831 if (Label.Kind != ValID::t_LocalName)
7832 return error(Label.Loc, "expected basic block name in uselistorder_bb");
7833 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7834 if (!V)
7835 return error(Label.Loc, "invalid basic block in uselistorder_bb");
7836 if (!isa<BasicBlock>(V))
7837 return error(Label.Loc, "expected basic block in uselistorder_bb");
7839 return sortUseListOrder(V, Indexes, Loc);
7842 /// ModuleEntry
7843 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7844 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7845 bool LLParser::parseModuleEntry(unsigned ID) {
7846 assert(Lex.getKind() == lltok::kw_module);
7847 Lex.Lex();
7849 std::string Path;
7850 if (parseToken(lltok::colon, "expected ':' here") ||
7851 parseToken(lltok::lparen, "expected '(' here") ||
7852 parseToken(lltok::kw_path, "expected 'path' here") ||
7853 parseToken(lltok::colon, "expected ':' here") ||
7854 parseStringConstant(Path) ||
7855 parseToken(lltok::comma, "expected ',' here") ||
7856 parseToken(lltok::kw_hash, "expected 'hash' here") ||
7857 parseToken(lltok::colon, "expected ':' here") ||
7858 parseToken(lltok::lparen, "expected '(' here"))
7859 return true;
7861 ModuleHash Hash;
7862 if (parseUInt32(Hash[0]) || parseToken(lltok::comma, "expected ',' here") ||
7863 parseUInt32(Hash[1]) || parseToken(lltok::comma, "expected ',' here") ||
7864 parseUInt32(Hash[2]) || parseToken(lltok::comma, "expected ',' here") ||
7865 parseUInt32(Hash[3]) || parseToken(lltok::comma, "expected ',' here") ||
7866 parseUInt32(Hash[4]))
7867 return true;
7869 if (parseToken(lltok::rparen, "expected ')' here") ||
7870 parseToken(lltok::rparen, "expected ')' here"))
7871 return true;
7873 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7874 ModuleIdMap[ID] = ModuleEntry->first();
7876 return false;
7879 /// TypeIdEntry
7880 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7881 bool LLParser::parseTypeIdEntry(unsigned ID) {
7882 assert(Lex.getKind() == lltok::kw_typeid);
7883 Lex.Lex();
7885 std::string Name;
7886 if (parseToken(lltok::colon, "expected ':' here") ||
7887 parseToken(lltok::lparen, "expected '(' here") ||
7888 parseToken(lltok::kw_name, "expected 'name' here") ||
7889 parseToken(lltok::colon, "expected ':' here") ||
7890 parseStringConstant(Name))
7891 return true;
7893 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7894 if (parseToken(lltok::comma, "expected ',' here") ||
7895 parseTypeIdSummary(TIS) || parseToken(lltok::rparen, "expected ')' here"))
7896 return true;
7898 // Check if this ID was forward referenced, and if so, update the
7899 // corresponding GUIDs.
7900 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7901 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7902 for (auto TIDRef : FwdRefTIDs->second) {
7903 assert(!*TIDRef.first &&
7904 "Forward referenced type id GUID expected to be 0");
7905 *TIDRef.first = GlobalValue::getGUID(Name);
7907 ForwardRefTypeIds.erase(FwdRefTIDs);
7910 return false;
7913 /// TypeIdSummary
7914 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7915 bool LLParser::parseTypeIdSummary(TypeIdSummary &TIS) {
7916 if (parseToken(lltok::kw_summary, "expected 'summary' here") ||
7917 parseToken(lltok::colon, "expected ':' here") ||
7918 parseToken(lltok::lparen, "expected '(' here") ||
7919 parseTypeTestResolution(TIS.TTRes))
7920 return true;
7922 if (EatIfPresent(lltok::comma)) {
7923 // Expect optional wpdResolutions field
7924 if (parseOptionalWpdResolutions(TIS.WPDRes))
7925 return true;
7928 if (parseToken(lltok::rparen, "expected ')' here"))
7929 return true;
7931 return false;
7934 static ValueInfo EmptyVI =
7935 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7937 /// TypeIdCompatibleVtableEntry
7938 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
7939 /// TypeIdCompatibleVtableInfo
7940 /// ')'
7941 bool LLParser::parseTypeIdCompatibleVtableEntry(unsigned ID) {
7942 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
7943 Lex.Lex();
7945 std::string Name;
7946 if (parseToken(lltok::colon, "expected ':' here") ||
7947 parseToken(lltok::lparen, "expected '(' here") ||
7948 parseToken(lltok::kw_name, "expected 'name' here") ||
7949 parseToken(lltok::colon, "expected ':' here") ||
7950 parseStringConstant(Name))
7951 return true;
7953 TypeIdCompatibleVtableInfo &TI =
7954 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
7955 if (parseToken(lltok::comma, "expected ',' here") ||
7956 parseToken(lltok::kw_summary, "expected 'summary' here") ||
7957 parseToken(lltok::colon, "expected ':' here") ||
7958 parseToken(lltok::lparen, "expected '(' here"))
7959 return true;
7961 IdToIndexMapType IdToIndexMap;
7962 // parse each call edge
7963 do {
7964 uint64_t Offset;
7965 if (parseToken(lltok::lparen, "expected '(' here") ||
7966 parseToken(lltok::kw_offset, "expected 'offset' here") ||
7967 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
7968 parseToken(lltok::comma, "expected ',' here"))
7969 return true;
7971 LocTy Loc = Lex.getLoc();
7972 unsigned GVId;
7973 ValueInfo VI;
7974 if (parseGVReference(VI, GVId))
7975 return true;
7977 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
7978 // forward reference. We will save the location of the ValueInfo needing an
7979 // update, but can only do so once the std::vector is finalized.
7980 if (VI == EmptyVI)
7981 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
7982 TI.push_back({Offset, VI});
7984 if (parseToken(lltok::rparen, "expected ')' in call"))
7985 return true;
7986 } while (EatIfPresent(lltok::comma));
7988 // Now that the TI vector is finalized, it is safe to save the locations
7989 // of any forward GV references that need updating later.
7990 for (auto I : IdToIndexMap) {
7991 auto &Infos = ForwardRefValueInfos[I.first];
7992 for (auto P : I.second) {
7993 assert(TI[P.first].VTableVI == EmptyVI &&
7994 "Forward referenced ValueInfo expected to be empty");
7995 Infos.emplace_back(&TI[P.first].VTableVI, P.second);
7999 if (parseToken(lltok::rparen, "expected ')' here") ||
8000 parseToken(lltok::rparen, "expected ')' here"))
8001 return true;
8003 // Check if this ID was forward referenced, and if so, update the
8004 // corresponding GUIDs.
8005 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
8006 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
8007 for (auto TIDRef : FwdRefTIDs->second) {
8008 assert(!*TIDRef.first &&
8009 "Forward referenced type id GUID expected to be 0");
8010 *TIDRef.first = GlobalValue::getGUID(Name);
8012 ForwardRefTypeIds.erase(FwdRefTIDs);
8015 return false;
8018 /// TypeTestResolution
8019 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
8020 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
8021 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
8022 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
8023 /// [',' 'inlinesBits' ':' UInt64]? ')'
8024 bool LLParser::parseTypeTestResolution(TypeTestResolution &TTRes) {
8025 if (parseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
8026 parseToken(lltok::colon, "expected ':' here") ||
8027 parseToken(lltok::lparen, "expected '(' here") ||
8028 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8029 parseToken(lltok::colon, "expected ':' here"))
8030 return true;
8032 switch (Lex.getKind()) {
8033 case lltok::kw_unknown:
8034 TTRes.TheKind = TypeTestResolution::Unknown;
8035 break;
8036 case lltok::kw_unsat:
8037 TTRes.TheKind = TypeTestResolution::Unsat;
8038 break;
8039 case lltok::kw_byteArray:
8040 TTRes.TheKind = TypeTestResolution::ByteArray;
8041 break;
8042 case lltok::kw_inline:
8043 TTRes.TheKind = TypeTestResolution::Inline;
8044 break;
8045 case lltok::kw_single:
8046 TTRes.TheKind = TypeTestResolution::Single;
8047 break;
8048 case lltok::kw_allOnes:
8049 TTRes.TheKind = TypeTestResolution::AllOnes;
8050 break;
8051 default:
8052 return error(Lex.getLoc(), "unexpected TypeTestResolution kind");
8054 Lex.Lex();
8056 if (parseToken(lltok::comma, "expected ',' here") ||
8057 parseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
8058 parseToken(lltok::colon, "expected ':' here") ||
8059 parseUInt32(TTRes.SizeM1BitWidth))
8060 return true;
8062 // parse optional fields
8063 while (EatIfPresent(lltok::comma)) {
8064 switch (Lex.getKind()) {
8065 case lltok::kw_alignLog2:
8066 Lex.Lex();
8067 if (parseToken(lltok::colon, "expected ':'") ||
8068 parseUInt64(TTRes.AlignLog2))
8069 return true;
8070 break;
8071 case lltok::kw_sizeM1:
8072 Lex.Lex();
8073 if (parseToken(lltok::colon, "expected ':'") || parseUInt64(TTRes.SizeM1))
8074 return true;
8075 break;
8076 case lltok::kw_bitMask: {
8077 unsigned Val;
8078 Lex.Lex();
8079 if (parseToken(lltok::colon, "expected ':'") || parseUInt32(Val))
8080 return true;
8081 assert(Val <= 0xff);
8082 TTRes.BitMask = (uint8_t)Val;
8083 break;
8085 case lltok::kw_inlineBits:
8086 Lex.Lex();
8087 if (parseToken(lltok::colon, "expected ':'") ||
8088 parseUInt64(TTRes.InlineBits))
8089 return true;
8090 break;
8091 default:
8092 return error(Lex.getLoc(), "expected optional TypeTestResolution field");
8096 if (parseToken(lltok::rparen, "expected ')' here"))
8097 return true;
8099 return false;
8102 /// OptionalWpdResolutions
8103 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
8104 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
8105 bool LLParser::parseOptionalWpdResolutions(
8106 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
8107 if (parseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
8108 parseToken(lltok::colon, "expected ':' here") ||
8109 parseToken(lltok::lparen, "expected '(' here"))
8110 return true;
8112 do {
8113 uint64_t Offset;
8114 WholeProgramDevirtResolution WPDRes;
8115 if (parseToken(lltok::lparen, "expected '(' here") ||
8116 parseToken(lltok::kw_offset, "expected 'offset' here") ||
8117 parseToken(lltok::colon, "expected ':' here") || parseUInt64(Offset) ||
8118 parseToken(lltok::comma, "expected ',' here") || parseWpdRes(WPDRes) ||
8119 parseToken(lltok::rparen, "expected ')' here"))
8120 return true;
8121 WPDResMap[Offset] = WPDRes;
8122 } while (EatIfPresent(lltok::comma));
8124 if (parseToken(lltok::rparen, "expected ')' here"))
8125 return true;
8127 return false;
8130 /// WpdRes
8131 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
8132 /// [',' OptionalResByArg]? ')'
8133 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
8134 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
8135 /// [',' OptionalResByArg]? ')'
8136 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
8137 /// [',' OptionalResByArg]? ')'
8138 bool LLParser::parseWpdRes(WholeProgramDevirtResolution &WPDRes) {
8139 if (parseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
8140 parseToken(lltok::colon, "expected ':' here") ||
8141 parseToken(lltok::lparen, "expected '(' here") ||
8142 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8143 parseToken(lltok::colon, "expected ':' here"))
8144 return true;
8146 switch (Lex.getKind()) {
8147 case lltok::kw_indir:
8148 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
8149 break;
8150 case lltok::kw_singleImpl:
8151 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
8152 break;
8153 case lltok::kw_branchFunnel:
8154 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
8155 break;
8156 default:
8157 return error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
8159 Lex.Lex();
8161 // parse optional fields
8162 while (EatIfPresent(lltok::comma)) {
8163 switch (Lex.getKind()) {
8164 case lltok::kw_singleImplName:
8165 Lex.Lex();
8166 if (parseToken(lltok::colon, "expected ':' here") ||
8167 parseStringConstant(WPDRes.SingleImplName))
8168 return true;
8169 break;
8170 case lltok::kw_resByArg:
8171 if (parseOptionalResByArg(WPDRes.ResByArg))
8172 return true;
8173 break;
8174 default:
8175 return error(Lex.getLoc(),
8176 "expected optional WholeProgramDevirtResolution field");
8180 if (parseToken(lltok::rparen, "expected ')' here"))
8181 return true;
8183 return false;
8186 /// OptionalResByArg
8187 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
8188 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
8189 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
8190 /// 'virtualConstProp' )
8191 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
8192 /// [',' 'bit' ':' UInt32]? ')'
8193 bool LLParser::parseOptionalResByArg(
8194 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
8195 &ResByArg) {
8196 if (parseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
8197 parseToken(lltok::colon, "expected ':' here") ||
8198 parseToken(lltok::lparen, "expected '(' here"))
8199 return true;
8201 do {
8202 std::vector<uint64_t> Args;
8203 if (parseArgs(Args) || parseToken(lltok::comma, "expected ',' here") ||
8204 parseToken(lltok::kw_byArg, "expected 'byArg here") ||
8205 parseToken(lltok::colon, "expected ':' here") ||
8206 parseToken(lltok::lparen, "expected '(' here") ||
8207 parseToken(lltok::kw_kind, "expected 'kind' here") ||
8208 parseToken(lltok::colon, "expected ':' here"))
8209 return true;
8211 WholeProgramDevirtResolution::ByArg ByArg;
8212 switch (Lex.getKind()) {
8213 case lltok::kw_indir:
8214 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
8215 break;
8216 case lltok::kw_uniformRetVal:
8217 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
8218 break;
8219 case lltok::kw_uniqueRetVal:
8220 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
8221 break;
8222 case lltok::kw_virtualConstProp:
8223 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
8224 break;
8225 default:
8226 return error(Lex.getLoc(),
8227 "unexpected WholeProgramDevirtResolution::ByArg kind");
8229 Lex.Lex();
8231 // parse optional fields
8232 while (EatIfPresent(lltok::comma)) {
8233 switch (Lex.getKind()) {
8234 case lltok::kw_info:
8235 Lex.Lex();
8236 if (parseToken(lltok::colon, "expected ':' here") ||
8237 parseUInt64(ByArg.Info))
8238 return true;
8239 break;
8240 case lltok::kw_byte:
8241 Lex.Lex();
8242 if (parseToken(lltok::colon, "expected ':' here") ||
8243 parseUInt32(ByArg.Byte))
8244 return true;
8245 break;
8246 case lltok::kw_bit:
8247 Lex.Lex();
8248 if (parseToken(lltok::colon, "expected ':' here") ||
8249 parseUInt32(ByArg.Bit))
8250 return true;
8251 break;
8252 default:
8253 return error(Lex.getLoc(),
8254 "expected optional whole program devirt field");
8258 if (parseToken(lltok::rparen, "expected ')' here"))
8259 return true;
8261 ResByArg[Args] = ByArg;
8262 } while (EatIfPresent(lltok::comma));
8264 if (parseToken(lltok::rparen, "expected ')' here"))
8265 return true;
8267 return false;
8270 /// OptionalResByArg
8271 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
8272 bool LLParser::parseArgs(std::vector<uint64_t> &Args) {
8273 if (parseToken(lltok::kw_args, "expected 'args' here") ||
8274 parseToken(lltok::colon, "expected ':' here") ||
8275 parseToken(lltok::lparen, "expected '(' here"))
8276 return true;
8278 do {
8279 uint64_t Val;
8280 if (parseUInt64(Val))
8281 return true;
8282 Args.push_back(Val);
8283 } while (EatIfPresent(lltok::comma));
8285 if (parseToken(lltok::rparen, "expected ')' here"))
8286 return true;
8288 return false;
8291 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
8293 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
8294 bool ReadOnly = Fwd->isReadOnly();
8295 bool WriteOnly = Fwd->isWriteOnly();
8296 assert(!(ReadOnly && WriteOnly));
8297 *Fwd = Resolved;
8298 if (ReadOnly)
8299 Fwd->setReadOnly();
8300 if (WriteOnly)
8301 Fwd->setWriteOnly();
8304 /// Stores the given Name/GUID and associated summary into the Index.
8305 /// Also updates any forward references to the associated entry ID.
8306 void LLParser::addGlobalValueToIndex(
8307 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
8308 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
8309 // First create the ValueInfo utilizing the Name or GUID.
8310 ValueInfo VI;
8311 if (GUID != 0) {
8312 assert(Name.empty());
8313 VI = Index->getOrInsertValueInfo(GUID);
8314 } else {
8315 assert(!Name.empty());
8316 if (M) {
8317 auto *GV = M->getNamedValue(Name);
8318 assert(GV);
8319 VI = Index->getOrInsertValueInfo(GV);
8320 } else {
8321 assert(
8322 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
8323 "Need a source_filename to compute GUID for local");
8324 GUID = GlobalValue::getGUID(
8325 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
8326 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
8330 // Resolve forward references from calls/refs
8331 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
8332 if (FwdRefVIs != ForwardRefValueInfos.end()) {
8333 for (auto VIRef : FwdRefVIs->second) {
8334 assert(VIRef.first->getRef() == FwdVIRef &&
8335 "Forward referenced ValueInfo expected to be empty");
8336 resolveFwdRef(VIRef.first, VI);
8338 ForwardRefValueInfos.erase(FwdRefVIs);
8341 // Resolve forward references from aliases
8342 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
8343 if (FwdRefAliasees != ForwardRefAliasees.end()) {
8344 for (auto AliaseeRef : FwdRefAliasees->second) {
8345 assert(!AliaseeRef.first->hasAliasee() &&
8346 "Forward referencing alias already has aliasee");
8347 assert(Summary && "Aliasee must be a definition");
8348 AliaseeRef.first->setAliasee(VI, Summary.get());
8350 ForwardRefAliasees.erase(FwdRefAliasees);
8353 // Add the summary if one was provided.
8354 if (Summary)
8355 Index->addGlobalValueSummary(VI, std::move(Summary));
8357 // Save the associated ValueInfo for use in later references by ID.
8358 if (ID == NumberedValueInfos.size())
8359 NumberedValueInfos.push_back(VI);
8360 else {
8361 // Handle non-continuous numbers (to make test simplification easier).
8362 if (ID > NumberedValueInfos.size())
8363 NumberedValueInfos.resize(ID + 1);
8364 NumberedValueInfos[ID] = VI;
8368 /// parseSummaryIndexFlags
8369 /// ::= 'flags' ':' UInt64
8370 bool LLParser::parseSummaryIndexFlags() {
8371 assert(Lex.getKind() == lltok::kw_flags);
8372 Lex.Lex();
8374 if (parseToken(lltok::colon, "expected ':' here"))
8375 return true;
8376 uint64_t Flags;
8377 if (parseUInt64(Flags))
8378 return true;
8379 if (Index)
8380 Index->setFlags(Flags);
8381 return false;
8384 /// parseBlockCount
8385 /// ::= 'blockcount' ':' UInt64
8386 bool LLParser::parseBlockCount() {
8387 assert(Lex.getKind() == lltok::kw_blockcount);
8388 Lex.Lex();
8390 if (parseToken(lltok::colon, "expected ':' here"))
8391 return true;
8392 uint64_t BlockCount;
8393 if (parseUInt64(BlockCount))
8394 return true;
8395 if (Index)
8396 Index->setBlockCount(BlockCount);
8397 return false;
8400 /// parseGVEntry
8401 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
8402 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
8403 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
8404 bool LLParser::parseGVEntry(unsigned ID) {
8405 assert(Lex.getKind() == lltok::kw_gv);
8406 Lex.Lex();
8408 if (parseToken(lltok::colon, "expected ':' here") ||
8409 parseToken(lltok::lparen, "expected '(' here"))
8410 return true;
8412 std::string Name;
8413 GlobalValue::GUID GUID = 0;
8414 switch (Lex.getKind()) {
8415 case lltok::kw_name:
8416 Lex.Lex();
8417 if (parseToken(lltok::colon, "expected ':' here") ||
8418 parseStringConstant(Name))
8419 return true;
8420 // Can't create GUID/ValueInfo until we have the linkage.
8421 break;
8422 case lltok::kw_guid:
8423 Lex.Lex();
8424 if (parseToken(lltok::colon, "expected ':' here") || parseUInt64(GUID))
8425 return true;
8426 break;
8427 default:
8428 return error(Lex.getLoc(), "expected name or guid tag");
8431 if (!EatIfPresent(lltok::comma)) {
8432 // No summaries. Wrap up.
8433 if (parseToken(lltok::rparen, "expected ')' here"))
8434 return true;
8435 // This was created for a call to an external or indirect target.
8436 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8437 // created for indirect calls with VP. A Name with no GUID came from
8438 // an external definition. We pass ExternalLinkage since that is only
8439 // used when the GUID must be computed from Name, and in that case
8440 // the symbol must have external linkage.
8441 addGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8442 nullptr);
8443 return false;
8446 // Have a list of summaries
8447 if (parseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8448 parseToken(lltok::colon, "expected ':' here") ||
8449 parseToken(lltok::lparen, "expected '(' here"))
8450 return true;
8451 do {
8452 switch (Lex.getKind()) {
8453 case lltok::kw_function:
8454 if (parseFunctionSummary(Name, GUID, ID))
8455 return true;
8456 break;
8457 case lltok::kw_variable:
8458 if (parseVariableSummary(Name, GUID, ID))
8459 return true;
8460 break;
8461 case lltok::kw_alias:
8462 if (parseAliasSummary(Name, GUID, ID))
8463 return true;
8464 break;
8465 default:
8466 return error(Lex.getLoc(), "expected summary type");
8468 } while (EatIfPresent(lltok::comma));
8470 if (parseToken(lltok::rparen, "expected ')' here") ||
8471 parseToken(lltok::rparen, "expected ')' here"))
8472 return true;
8474 return false;
8477 /// FunctionSummary
8478 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8479 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8480 /// [',' OptionalTypeIdInfo]? [',' OptionalParamAccesses]?
8481 /// [',' OptionalRefs]? ')'
8482 bool LLParser::parseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8483 unsigned ID) {
8484 assert(Lex.getKind() == lltok::kw_function);
8485 Lex.Lex();
8487 StringRef ModulePath;
8488 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8489 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8490 /*NotEligibleToImport=*/false,
8491 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8492 unsigned InstCount;
8493 std::vector<FunctionSummary::EdgeTy> Calls;
8494 FunctionSummary::TypeIdInfo TypeIdInfo;
8495 std::vector<FunctionSummary::ParamAccess> ParamAccesses;
8496 std::vector<ValueInfo> Refs;
8497 // Default is all-zeros (conservative values).
8498 FunctionSummary::FFlags FFlags = {};
8499 if (parseToken(lltok::colon, "expected ':' here") ||
8500 parseToken(lltok::lparen, "expected '(' here") ||
8501 parseModuleReference(ModulePath) ||
8502 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8503 parseToken(lltok::comma, "expected ',' here") ||
8504 parseToken(lltok::kw_insts, "expected 'insts' here") ||
8505 parseToken(lltok::colon, "expected ':' here") || parseUInt32(InstCount))
8506 return true;
8508 // parse optional fields
8509 while (EatIfPresent(lltok::comma)) {
8510 switch (Lex.getKind()) {
8511 case lltok::kw_funcFlags:
8512 if (parseOptionalFFlags(FFlags))
8513 return true;
8514 break;
8515 case lltok::kw_calls:
8516 if (parseOptionalCalls(Calls))
8517 return true;
8518 break;
8519 case lltok::kw_typeIdInfo:
8520 if (parseOptionalTypeIdInfo(TypeIdInfo))
8521 return true;
8522 break;
8523 case lltok::kw_refs:
8524 if (parseOptionalRefs(Refs))
8525 return true;
8526 break;
8527 case lltok::kw_params:
8528 if (parseOptionalParamAccesses(ParamAccesses))
8529 return true;
8530 break;
8531 default:
8532 return error(Lex.getLoc(), "expected optional function summary field");
8536 if (parseToken(lltok::rparen, "expected ')' here"))
8537 return true;
8539 auto FS = std::make_unique<FunctionSummary>(
8540 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8541 std::move(Calls), std::move(TypeIdInfo.TypeTests),
8542 std::move(TypeIdInfo.TypeTestAssumeVCalls),
8543 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8544 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8545 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls),
8546 std::move(ParamAccesses));
8548 FS->setModulePath(ModulePath);
8550 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8551 ID, std::move(FS));
8553 return false;
8556 /// VariableSummary
8557 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8558 /// [',' OptionalRefs]? ')'
8559 bool LLParser::parseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8560 unsigned ID) {
8561 assert(Lex.getKind() == lltok::kw_variable);
8562 Lex.Lex();
8564 StringRef ModulePath;
8565 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8566 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8567 /*NotEligibleToImport=*/false,
8568 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8569 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8570 /* WriteOnly */ false,
8571 /* Constant */ false,
8572 GlobalObject::VCallVisibilityPublic);
8573 std::vector<ValueInfo> Refs;
8574 VTableFuncList VTableFuncs;
8575 if (parseToken(lltok::colon, "expected ':' here") ||
8576 parseToken(lltok::lparen, "expected '(' here") ||
8577 parseModuleReference(ModulePath) ||
8578 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8579 parseToken(lltok::comma, "expected ',' here") ||
8580 parseGVarFlags(GVarFlags))
8581 return true;
8583 // parse optional fields
8584 while (EatIfPresent(lltok::comma)) {
8585 switch (Lex.getKind()) {
8586 case lltok::kw_vTableFuncs:
8587 if (parseOptionalVTableFuncs(VTableFuncs))
8588 return true;
8589 break;
8590 case lltok::kw_refs:
8591 if (parseOptionalRefs(Refs))
8592 return true;
8593 break;
8594 default:
8595 return error(Lex.getLoc(), "expected optional variable summary field");
8599 if (parseToken(lltok::rparen, "expected ')' here"))
8600 return true;
8602 auto GS =
8603 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8605 GS->setModulePath(ModulePath);
8606 GS->setVTableFuncs(std::move(VTableFuncs));
8608 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8609 ID, std::move(GS));
8611 return false;
8614 /// AliasSummary
8615 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8616 /// 'aliasee' ':' GVReference ')'
8617 bool LLParser::parseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8618 unsigned ID) {
8619 assert(Lex.getKind() == lltok::kw_alias);
8620 LocTy Loc = Lex.getLoc();
8621 Lex.Lex();
8623 StringRef ModulePath;
8624 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8625 GlobalValue::ExternalLinkage, GlobalValue::DefaultVisibility,
8626 /*NotEligibleToImport=*/false,
8627 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8628 if (parseToken(lltok::colon, "expected ':' here") ||
8629 parseToken(lltok::lparen, "expected '(' here") ||
8630 parseModuleReference(ModulePath) ||
8631 parseToken(lltok::comma, "expected ',' here") || parseGVFlags(GVFlags) ||
8632 parseToken(lltok::comma, "expected ',' here") ||
8633 parseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8634 parseToken(lltok::colon, "expected ':' here"))
8635 return true;
8637 ValueInfo AliaseeVI;
8638 unsigned GVId;
8639 if (parseGVReference(AliaseeVI, GVId))
8640 return true;
8642 if (parseToken(lltok::rparen, "expected ')' here"))
8643 return true;
8645 auto AS = std::make_unique<AliasSummary>(GVFlags);
8647 AS->setModulePath(ModulePath);
8649 // Record forward reference if the aliasee is not parsed yet.
8650 if (AliaseeVI.getRef() == FwdVIRef) {
8651 ForwardRefAliasees[GVId].emplace_back(AS.get(), Loc);
8652 } else {
8653 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8654 assert(Summary && "Aliasee must be a definition");
8655 AS->setAliasee(AliaseeVI, Summary);
8658 addGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8659 ID, std::move(AS));
8661 return false;
8664 /// Flag
8665 /// ::= [0|1]
8666 bool LLParser::parseFlag(unsigned &Val) {
8667 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8668 return tokError("expected integer");
8669 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8670 Lex.Lex();
8671 return false;
8674 /// OptionalFFlags
8675 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8676 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8677 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
8678 /// [',' 'noInline' ':' Flag]? ')'
8679 /// [',' 'alwaysInline' ':' Flag]? ')'
8680 /// [',' 'noUnwind' ':' Flag]? ')'
8681 /// [',' 'mayThrow' ':' Flag]? ')'
8682 /// [',' 'hasUnknownCall' ':' Flag]? ')'
8683 /// [',' 'mustBeUnreachable' ':' Flag]? ')'
8685 bool LLParser::parseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8686 assert(Lex.getKind() == lltok::kw_funcFlags);
8687 Lex.Lex();
8689 if (parseToken(lltok::colon, "expected ':' in funcFlags") ||
8690 parseToken(lltok::lparen, "expected '(' in funcFlags"))
8691 return true;
8693 do {
8694 unsigned Val = 0;
8695 switch (Lex.getKind()) {
8696 case lltok::kw_readNone:
8697 Lex.Lex();
8698 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8699 return true;
8700 FFlags.ReadNone = Val;
8701 break;
8702 case lltok::kw_readOnly:
8703 Lex.Lex();
8704 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8705 return true;
8706 FFlags.ReadOnly = Val;
8707 break;
8708 case lltok::kw_noRecurse:
8709 Lex.Lex();
8710 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8711 return true;
8712 FFlags.NoRecurse = Val;
8713 break;
8714 case lltok::kw_returnDoesNotAlias:
8715 Lex.Lex();
8716 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8717 return true;
8718 FFlags.ReturnDoesNotAlias = Val;
8719 break;
8720 case lltok::kw_noInline:
8721 Lex.Lex();
8722 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8723 return true;
8724 FFlags.NoInline = Val;
8725 break;
8726 case lltok::kw_alwaysInline:
8727 Lex.Lex();
8728 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8729 return true;
8730 FFlags.AlwaysInline = Val;
8731 break;
8732 case lltok::kw_noUnwind:
8733 Lex.Lex();
8734 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8735 return true;
8736 FFlags.NoUnwind = Val;
8737 break;
8738 case lltok::kw_mayThrow:
8739 Lex.Lex();
8740 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8741 return true;
8742 FFlags.MayThrow = Val;
8743 break;
8744 case lltok::kw_hasUnknownCall:
8745 Lex.Lex();
8746 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8747 return true;
8748 FFlags.HasUnknownCall = Val;
8749 break;
8750 case lltok::kw_mustBeUnreachable:
8751 Lex.Lex();
8752 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Val))
8753 return true;
8754 FFlags.MustBeUnreachable = Val;
8755 break;
8756 default:
8757 return error(Lex.getLoc(), "expected function flag type");
8759 } while (EatIfPresent(lltok::comma));
8761 if (parseToken(lltok::rparen, "expected ')' in funcFlags"))
8762 return true;
8764 return false;
8767 /// OptionalCalls
8768 /// := 'calls' ':' '(' Call [',' Call]* ')'
8769 /// Call ::= '(' 'callee' ':' GVReference
8770 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8771 bool LLParser::parseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8772 assert(Lex.getKind() == lltok::kw_calls);
8773 Lex.Lex();
8775 if (parseToken(lltok::colon, "expected ':' in calls") ||
8776 parseToken(lltok::lparen, "expected '(' in calls"))
8777 return true;
8779 IdToIndexMapType IdToIndexMap;
8780 // parse each call edge
8781 do {
8782 ValueInfo VI;
8783 if (parseToken(lltok::lparen, "expected '(' in call") ||
8784 parseToken(lltok::kw_callee, "expected 'callee' in call") ||
8785 parseToken(lltok::colon, "expected ':'"))
8786 return true;
8788 LocTy Loc = Lex.getLoc();
8789 unsigned GVId;
8790 if (parseGVReference(VI, GVId))
8791 return true;
8793 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8794 unsigned RelBF = 0;
8795 if (EatIfPresent(lltok::comma)) {
8796 // Expect either hotness or relbf
8797 if (EatIfPresent(lltok::kw_hotness)) {
8798 if (parseToken(lltok::colon, "expected ':'") || parseHotness(Hotness))
8799 return true;
8800 } else {
8801 if (parseToken(lltok::kw_relbf, "expected relbf") ||
8802 parseToken(lltok::colon, "expected ':'") || parseUInt32(RelBF))
8803 return true;
8806 // Keep track of the Call array index needing a forward reference.
8807 // We will save the location of the ValueInfo needing an update, but
8808 // can only do so once the std::vector is finalized.
8809 if (VI.getRef() == FwdVIRef)
8810 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8811 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8813 if (parseToken(lltok::rparen, "expected ')' in call"))
8814 return true;
8815 } while (EatIfPresent(lltok::comma));
8817 // Now that the Calls vector is finalized, it is safe to save the locations
8818 // of any forward GV references that need updating later.
8819 for (auto I : IdToIndexMap) {
8820 auto &Infos = ForwardRefValueInfos[I.first];
8821 for (auto P : I.second) {
8822 assert(Calls[P.first].first.getRef() == FwdVIRef &&
8823 "Forward referenced ValueInfo expected to be empty");
8824 Infos.emplace_back(&Calls[P.first].first, P.second);
8828 if (parseToken(lltok::rparen, "expected ')' in calls"))
8829 return true;
8831 return false;
8834 /// Hotness
8835 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
8836 bool LLParser::parseHotness(CalleeInfo::HotnessType &Hotness) {
8837 switch (Lex.getKind()) {
8838 case lltok::kw_unknown:
8839 Hotness = CalleeInfo::HotnessType::Unknown;
8840 break;
8841 case lltok::kw_cold:
8842 Hotness = CalleeInfo::HotnessType::Cold;
8843 break;
8844 case lltok::kw_none:
8845 Hotness = CalleeInfo::HotnessType::None;
8846 break;
8847 case lltok::kw_hot:
8848 Hotness = CalleeInfo::HotnessType::Hot;
8849 break;
8850 case lltok::kw_critical:
8851 Hotness = CalleeInfo::HotnessType::Critical;
8852 break;
8853 default:
8854 return error(Lex.getLoc(), "invalid call edge hotness");
8856 Lex.Lex();
8857 return false;
8860 /// OptionalVTableFuncs
8861 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8862 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8863 bool LLParser::parseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
8864 assert(Lex.getKind() == lltok::kw_vTableFuncs);
8865 Lex.Lex();
8867 if (parseToken(lltok::colon, "expected ':' in vTableFuncs") ||
8868 parseToken(lltok::lparen, "expected '(' in vTableFuncs"))
8869 return true;
8871 IdToIndexMapType IdToIndexMap;
8872 // parse each virtual function pair
8873 do {
8874 ValueInfo VI;
8875 if (parseToken(lltok::lparen, "expected '(' in vTableFunc") ||
8876 parseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
8877 parseToken(lltok::colon, "expected ':'"))
8878 return true;
8880 LocTy Loc = Lex.getLoc();
8881 unsigned GVId;
8882 if (parseGVReference(VI, GVId))
8883 return true;
8885 uint64_t Offset;
8886 if (parseToken(lltok::comma, "expected comma") ||
8887 parseToken(lltok::kw_offset, "expected offset") ||
8888 parseToken(lltok::colon, "expected ':'") || parseUInt64(Offset))
8889 return true;
8891 // Keep track of the VTableFuncs array index needing a forward reference.
8892 // We will save the location of the ValueInfo needing an update, but
8893 // can only do so once the std::vector is finalized.
8894 if (VI == EmptyVI)
8895 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
8896 VTableFuncs.push_back({VI, Offset});
8898 if (parseToken(lltok::rparen, "expected ')' in vTableFunc"))
8899 return true;
8900 } while (EatIfPresent(lltok::comma));
8902 // Now that the VTableFuncs vector is finalized, it is safe to save the
8903 // locations of any forward GV references that need updating later.
8904 for (auto I : IdToIndexMap) {
8905 auto &Infos = ForwardRefValueInfos[I.first];
8906 for (auto P : I.second) {
8907 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
8908 "Forward referenced ValueInfo expected to be empty");
8909 Infos.emplace_back(&VTableFuncs[P.first].FuncVI, P.second);
8913 if (parseToken(lltok::rparen, "expected ')' in vTableFuncs"))
8914 return true;
8916 return false;
8919 /// ParamNo := 'param' ':' UInt64
8920 bool LLParser::parseParamNo(uint64_t &ParamNo) {
8921 if (parseToken(lltok::kw_param, "expected 'param' here") ||
8922 parseToken(lltok::colon, "expected ':' here") || parseUInt64(ParamNo))
8923 return true;
8924 return false;
8927 /// ParamAccessOffset := 'offset' ':' '[' APSINTVAL ',' APSINTVAL ']'
8928 bool LLParser::parseParamAccessOffset(ConstantRange &Range) {
8929 APSInt Lower;
8930 APSInt Upper;
8931 auto ParseAPSInt = [&](APSInt &Val) {
8932 if (Lex.getKind() != lltok::APSInt)
8933 return tokError("expected integer");
8934 Val = Lex.getAPSIntVal();
8935 Val = Val.extOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
8936 Val.setIsSigned(true);
8937 Lex.Lex();
8938 return false;
8940 if (parseToken(lltok::kw_offset, "expected 'offset' here") ||
8941 parseToken(lltok::colon, "expected ':' here") ||
8942 parseToken(lltok::lsquare, "expected '[' here") || ParseAPSInt(Lower) ||
8943 parseToken(lltok::comma, "expected ',' here") || ParseAPSInt(Upper) ||
8944 parseToken(lltok::rsquare, "expected ']' here"))
8945 return true;
8947 ++Upper;
8948 Range =
8949 (Lower == Upper && !Lower.isMaxValue())
8950 ? ConstantRange::getEmpty(FunctionSummary::ParamAccess::RangeWidth)
8951 : ConstantRange(Lower, Upper);
8953 return false;
8956 /// ParamAccessCall
8957 /// := '(' 'callee' ':' GVReference ',' ParamNo ',' ParamAccessOffset ')'
8958 bool LLParser::parseParamAccessCall(FunctionSummary::ParamAccess::Call &Call,
8959 IdLocListType &IdLocList) {
8960 if (parseToken(lltok::lparen, "expected '(' here") ||
8961 parseToken(lltok::kw_callee, "expected 'callee' here") ||
8962 parseToken(lltok::colon, "expected ':' here"))
8963 return true;
8965 unsigned GVId;
8966 ValueInfo VI;
8967 LocTy Loc = Lex.getLoc();
8968 if (parseGVReference(VI, GVId))
8969 return true;
8971 Call.Callee = VI;
8972 IdLocList.emplace_back(GVId, Loc);
8974 if (parseToken(lltok::comma, "expected ',' here") ||
8975 parseParamNo(Call.ParamNo) ||
8976 parseToken(lltok::comma, "expected ',' here") ||
8977 parseParamAccessOffset(Call.Offsets))
8978 return true;
8980 if (parseToken(lltok::rparen, "expected ')' here"))
8981 return true;
8983 return false;
8986 /// ParamAccess
8987 /// := '(' ParamNo ',' ParamAccessOffset [',' OptionalParamAccessCalls]? ')'
8988 /// OptionalParamAccessCalls := '(' Call [',' Call]* ')'
8989 bool LLParser::parseParamAccess(FunctionSummary::ParamAccess &Param,
8990 IdLocListType &IdLocList) {
8991 if (parseToken(lltok::lparen, "expected '(' here") ||
8992 parseParamNo(Param.ParamNo) ||
8993 parseToken(lltok::comma, "expected ',' here") ||
8994 parseParamAccessOffset(Param.Use))
8995 return true;
8997 if (EatIfPresent(lltok::comma)) {
8998 if (parseToken(lltok::kw_calls, "expected 'calls' here") ||
8999 parseToken(lltok::colon, "expected ':' here") ||
9000 parseToken(lltok::lparen, "expected '(' here"))
9001 return true;
9002 do {
9003 FunctionSummary::ParamAccess::Call Call;
9004 if (parseParamAccessCall(Call, IdLocList))
9005 return true;
9006 Param.Calls.push_back(Call);
9007 } while (EatIfPresent(lltok::comma));
9009 if (parseToken(lltok::rparen, "expected ')' here"))
9010 return true;
9013 if (parseToken(lltok::rparen, "expected ')' here"))
9014 return true;
9016 return false;
9019 /// OptionalParamAccesses
9020 /// := 'params' ':' '(' ParamAccess [',' ParamAccess]* ')'
9021 bool LLParser::parseOptionalParamAccesses(
9022 std::vector<FunctionSummary::ParamAccess> &Params) {
9023 assert(Lex.getKind() == lltok::kw_params);
9024 Lex.Lex();
9026 if (parseToken(lltok::colon, "expected ':' here") ||
9027 parseToken(lltok::lparen, "expected '(' here"))
9028 return true;
9030 IdLocListType VContexts;
9031 size_t CallsNum = 0;
9032 do {
9033 FunctionSummary::ParamAccess ParamAccess;
9034 if (parseParamAccess(ParamAccess, VContexts))
9035 return true;
9036 CallsNum += ParamAccess.Calls.size();
9037 assert(VContexts.size() == CallsNum);
9038 (void)CallsNum;
9039 Params.emplace_back(std::move(ParamAccess));
9040 } while (EatIfPresent(lltok::comma));
9042 if (parseToken(lltok::rparen, "expected ')' here"))
9043 return true;
9045 // Now that the Params is finalized, it is safe to save the locations
9046 // of any forward GV references that need updating later.
9047 IdLocListType::const_iterator ItContext = VContexts.begin();
9048 for (auto &PA : Params) {
9049 for (auto &C : PA.Calls) {
9050 if (C.Callee.getRef() == FwdVIRef)
9051 ForwardRefValueInfos[ItContext->first].emplace_back(&C.Callee,
9052 ItContext->second);
9053 ++ItContext;
9056 assert(ItContext == VContexts.end());
9058 return false;
9061 /// OptionalRefs
9062 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
9063 bool LLParser::parseOptionalRefs(std::vector<ValueInfo> &Refs) {
9064 assert(Lex.getKind() == lltok::kw_refs);
9065 Lex.Lex();
9067 if (parseToken(lltok::colon, "expected ':' in refs") ||
9068 parseToken(lltok::lparen, "expected '(' in refs"))
9069 return true;
9071 struct ValueContext {
9072 ValueInfo VI;
9073 unsigned GVId;
9074 LocTy Loc;
9076 std::vector<ValueContext> VContexts;
9077 // parse each ref edge
9078 do {
9079 ValueContext VC;
9080 VC.Loc = Lex.getLoc();
9081 if (parseGVReference(VC.VI, VC.GVId))
9082 return true;
9083 VContexts.push_back(VC);
9084 } while (EatIfPresent(lltok::comma));
9086 // Sort value contexts so that ones with writeonly
9087 // and readonly ValueInfo are at the end of VContexts vector.
9088 // See FunctionSummary::specialRefCounts()
9089 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
9090 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
9093 IdToIndexMapType IdToIndexMap;
9094 for (auto &VC : VContexts) {
9095 // Keep track of the Refs array index needing a forward reference.
9096 // We will save the location of the ValueInfo needing an update, but
9097 // can only do so once the std::vector is finalized.
9098 if (VC.VI.getRef() == FwdVIRef)
9099 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
9100 Refs.push_back(VC.VI);
9103 // Now that the Refs vector is finalized, it is safe to save the locations
9104 // of any forward GV references that need updating later.
9105 for (auto I : IdToIndexMap) {
9106 auto &Infos = ForwardRefValueInfos[I.first];
9107 for (auto P : I.second) {
9108 assert(Refs[P.first].getRef() == FwdVIRef &&
9109 "Forward referenced ValueInfo expected to be empty");
9110 Infos.emplace_back(&Refs[P.first], P.second);
9114 if (parseToken(lltok::rparen, "expected ')' in refs"))
9115 return true;
9117 return false;
9120 /// OptionalTypeIdInfo
9121 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
9122 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
9123 /// [',' TypeCheckedLoadConstVCalls]? ')'
9124 bool LLParser::parseOptionalTypeIdInfo(
9125 FunctionSummary::TypeIdInfo &TypeIdInfo) {
9126 assert(Lex.getKind() == lltok::kw_typeIdInfo);
9127 Lex.Lex();
9129 if (parseToken(lltok::colon, "expected ':' here") ||
9130 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9131 return true;
9133 do {
9134 switch (Lex.getKind()) {
9135 case lltok::kw_typeTests:
9136 if (parseTypeTests(TypeIdInfo.TypeTests))
9137 return true;
9138 break;
9139 case lltok::kw_typeTestAssumeVCalls:
9140 if (parseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
9141 TypeIdInfo.TypeTestAssumeVCalls))
9142 return true;
9143 break;
9144 case lltok::kw_typeCheckedLoadVCalls:
9145 if (parseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
9146 TypeIdInfo.TypeCheckedLoadVCalls))
9147 return true;
9148 break;
9149 case lltok::kw_typeTestAssumeConstVCalls:
9150 if (parseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
9151 TypeIdInfo.TypeTestAssumeConstVCalls))
9152 return true;
9153 break;
9154 case lltok::kw_typeCheckedLoadConstVCalls:
9155 if (parseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
9156 TypeIdInfo.TypeCheckedLoadConstVCalls))
9157 return true;
9158 break;
9159 default:
9160 return error(Lex.getLoc(), "invalid typeIdInfo list type");
9162 } while (EatIfPresent(lltok::comma));
9164 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9165 return true;
9167 return false;
9170 /// TypeTests
9171 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
9172 /// [',' (SummaryID | UInt64)]* ')'
9173 bool LLParser::parseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
9174 assert(Lex.getKind() == lltok::kw_typeTests);
9175 Lex.Lex();
9177 if (parseToken(lltok::colon, "expected ':' here") ||
9178 parseToken(lltok::lparen, "expected '(' in typeIdInfo"))
9179 return true;
9181 IdToIndexMapType IdToIndexMap;
9182 do {
9183 GlobalValue::GUID GUID = 0;
9184 if (Lex.getKind() == lltok::SummaryID) {
9185 unsigned ID = Lex.getUIntVal();
9186 LocTy Loc = Lex.getLoc();
9187 // Keep track of the TypeTests array index needing a forward reference.
9188 // We will save the location of the GUID needing an update, but
9189 // can only do so once the std::vector is finalized.
9190 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
9191 Lex.Lex();
9192 } else if (parseUInt64(GUID))
9193 return true;
9194 TypeTests.push_back(GUID);
9195 } while (EatIfPresent(lltok::comma));
9197 // Now that the TypeTests vector is finalized, it is safe to save the
9198 // locations of any forward GV references that need updating later.
9199 for (auto I : IdToIndexMap) {
9200 auto &Ids = ForwardRefTypeIds[I.first];
9201 for (auto P : I.second) {
9202 assert(TypeTests[P.first] == 0 &&
9203 "Forward referenced type id GUID expected to be 0");
9204 Ids.emplace_back(&TypeTests[P.first], P.second);
9208 if (parseToken(lltok::rparen, "expected ')' in typeIdInfo"))
9209 return true;
9211 return false;
9214 /// VFuncIdList
9215 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
9216 bool LLParser::parseVFuncIdList(
9217 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
9218 assert(Lex.getKind() == Kind);
9219 Lex.Lex();
9221 if (parseToken(lltok::colon, "expected ':' here") ||
9222 parseToken(lltok::lparen, "expected '(' here"))
9223 return true;
9225 IdToIndexMapType IdToIndexMap;
9226 do {
9227 FunctionSummary::VFuncId VFuncId;
9228 if (parseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
9229 return true;
9230 VFuncIdList.push_back(VFuncId);
9231 } while (EatIfPresent(lltok::comma));
9233 if (parseToken(lltok::rparen, "expected ')' here"))
9234 return true;
9236 // Now that the VFuncIdList vector is finalized, it is safe to save the
9237 // locations of any forward GV references that need updating later.
9238 for (auto I : IdToIndexMap) {
9239 auto &Ids = ForwardRefTypeIds[I.first];
9240 for (auto P : I.second) {
9241 assert(VFuncIdList[P.first].GUID == 0 &&
9242 "Forward referenced type id GUID expected to be 0");
9243 Ids.emplace_back(&VFuncIdList[P.first].GUID, P.second);
9247 return false;
9250 /// ConstVCallList
9251 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
9252 bool LLParser::parseConstVCallList(
9253 lltok::Kind Kind,
9254 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
9255 assert(Lex.getKind() == Kind);
9256 Lex.Lex();
9258 if (parseToken(lltok::colon, "expected ':' here") ||
9259 parseToken(lltok::lparen, "expected '(' here"))
9260 return true;
9262 IdToIndexMapType IdToIndexMap;
9263 do {
9264 FunctionSummary::ConstVCall ConstVCall;
9265 if (parseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
9266 return true;
9267 ConstVCallList.push_back(ConstVCall);
9268 } while (EatIfPresent(lltok::comma));
9270 if (parseToken(lltok::rparen, "expected ')' here"))
9271 return true;
9273 // Now that the ConstVCallList vector is finalized, it is safe to save the
9274 // locations of any forward GV references that need updating later.
9275 for (auto I : IdToIndexMap) {
9276 auto &Ids = ForwardRefTypeIds[I.first];
9277 for (auto P : I.second) {
9278 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
9279 "Forward referenced type id GUID expected to be 0");
9280 Ids.emplace_back(&ConstVCallList[P.first].VFunc.GUID, P.second);
9284 return false;
9287 /// ConstVCall
9288 /// ::= '(' VFuncId ',' Args ')'
9289 bool LLParser::parseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
9290 IdToIndexMapType &IdToIndexMap, unsigned Index) {
9291 if (parseToken(lltok::lparen, "expected '(' here") ||
9292 parseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
9293 return true;
9295 if (EatIfPresent(lltok::comma))
9296 if (parseArgs(ConstVCall.Args))
9297 return true;
9299 if (parseToken(lltok::rparen, "expected ')' here"))
9300 return true;
9302 return false;
9305 /// VFuncId
9306 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
9307 /// 'offset' ':' UInt64 ')'
9308 bool LLParser::parseVFuncId(FunctionSummary::VFuncId &VFuncId,
9309 IdToIndexMapType &IdToIndexMap, unsigned Index) {
9310 assert(Lex.getKind() == lltok::kw_vFuncId);
9311 Lex.Lex();
9313 if (parseToken(lltok::colon, "expected ':' here") ||
9314 parseToken(lltok::lparen, "expected '(' here"))
9315 return true;
9317 if (Lex.getKind() == lltok::SummaryID) {
9318 VFuncId.GUID = 0;
9319 unsigned ID = Lex.getUIntVal();
9320 LocTy Loc = Lex.getLoc();
9321 // Keep track of the array index needing a forward reference.
9322 // We will save the location of the GUID needing an update, but
9323 // can only do so once the caller's std::vector is finalized.
9324 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
9325 Lex.Lex();
9326 } else if (parseToken(lltok::kw_guid, "expected 'guid' here") ||
9327 parseToken(lltok::colon, "expected ':' here") ||
9328 parseUInt64(VFuncId.GUID))
9329 return true;
9331 if (parseToken(lltok::comma, "expected ',' here") ||
9332 parseToken(lltok::kw_offset, "expected 'offset' here") ||
9333 parseToken(lltok::colon, "expected ':' here") ||
9334 parseUInt64(VFuncId.Offset) ||
9335 parseToken(lltok::rparen, "expected ')' here"))
9336 return true;
9338 return false;
9341 /// GVFlags
9342 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
9343 /// 'visibility' ':' Flag 'notEligibleToImport' ':' Flag ','
9344 /// 'live' ':' Flag ',' 'dsoLocal' ':' Flag ','
9345 /// 'canAutoHide' ':' Flag ',' ')'
9346 bool LLParser::parseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
9347 assert(Lex.getKind() == lltok::kw_flags);
9348 Lex.Lex();
9350 if (parseToken(lltok::colon, "expected ':' here") ||
9351 parseToken(lltok::lparen, "expected '(' here"))
9352 return true;
9354 do {
9355 unsigned Flag = 0;
9356 switch (Lex.getKind()) {
9357 case lltok::kw_linkage:
9358 Lex.Lex();
9359 if (parseToken(lltok::colon, "expected ':'"))
9360 return true;
9361 bool HasLinkage;
9362 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
9363 assert(HasLinkage && "Linkage not optional in summary entry");
9364 Lex.Lex();
9365 break;
9366 case lltok::kw_visibility:
9367 Lex.Lex();
9368 if (parseToken(lltok::colon, "expected ':'"))
9369 return true;
9370 parseOptionalVisibility(Flag);
9371 GVFlags.Visibility = Flag;
9372 break;
9373 case lltok::kw_notEligibleToImport:
9374 Lex.Lex();
9375 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9376 return true;
9377 GVFlags.NotEligibleToImport = Flag;
9378 break;
9379 case lltok::kw_live:
9380 Lex.Lex();
9381 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9382 return true;
9383 GVFlags.Live = Flag;
9384 break;
9385 case lltok::kw_dsoLocal:
9386 Lex.Lex();
9387 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9388 return true;
9389 GVFlags.DSOLocal = Flag;
9390 break;
9391 case lltok::kw_canAutoHide:
9392 Lex.Lex();
9393 if (parseToken(lltok::colon, "expected ':'") || parseFlag(Flag))
9394 return true;
9395 GVFlags.CanAutoHide = Flag;
9396 break;
9397 default:
9398 return error(Lex.getLoc(), "expected gv flag type");
9400 } while (EatIfPresent(lltok::comma));
9402 if (parseToken(lltok::rparen, "expected ')' here"))
9403 return true;
9405 return false;
9408 /// GVarFlags
9409 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
9410 /// ',' 'writeonly' ':' Flag
9411 /// ',' 'constant' ':' Flag ')'
9412 bool LLParser::parseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
9413 assert(Lex.getKind() == lltok::kw_varFlags);
9414 Lex.Lex();
9416 if (parseToken(lltok::colon, "expected ':' here") ||
9417 parseToken(lltok::lparen, "expected '(' here"))
9418 return true;
9420 auto ParseRest = [this](unsigned int &Val) {
9421 Lex.Lex();
9422 if (parseToken(lltok::colon, "expected ':'"))
9423 return true;
9424 return parseFlag(Val);
9427 do {
9428 unsigned Flag = 0;
9429 switch (Lex.getKind()) {
9430 case lltok::kw_readonly:
9431 if (ParseRest(Flag))
9432 return true;
9433 GVarFlags.MaybeReadOnly = Flag;
9434 break;
9435 case lltok::kw_writeonly:
9436 if (ParseRest(Flag))
9437 return true;
9438 GVarFlags.MaybeWriteOnly = Flag;
9439 break;
9440 case lltok::kw_constant:
9441 if (ParseRest(Flag))
9442 return true;
9443 GVarFlags.Constant = Flag;
9444 break;
9445 case lltok::kw_vcall_visibility:
9446 if (ParseRest(Flag))
9447 return true;
9448 GVarFlags.VCallVisibility = Flag;
9449 break;
9450 default:
9451 return error(Lex.getLoc(), "expected gvar flag type");
9453 } while (EatIfPresent(lltok::comma));
9454 return parseToken(lltok::rparen, "expected ')' here");
9457 /// ModuleReference
9458 /// ::= 'module' ':' UInt
9459 bool LLParser::parseModuleReference(StringRef &ModulePath) {
9460 // parse module id.
9461 if (parseToken(lltok::kw_module, "expected 'module' here") ||
9462 parseToken(lltok::colon, "expected ':' here") ||
9463 parseToken(lltok::SummaryID, "expected module ID"))
9464 return true;
9466 unsigned ModuleID = Lex.getUIntVal();
9467 auto I = ModuleIdMap.find(ModuleID);
9468 // We should have already parsed all module IDs
9469 assert(I != ModuleIdMap.end());
9470 ModulePath = I->second;
9471 return false;
9474 /// GVReference
9475 /// ::= SummaryID
9476 bool LLParser::parseGVReference(ValueInfo &VI, unsigned &GVId) {
9477 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
9478 if (!ReadOnly)
9479 WriteOnly = EatIfPresent(lltok::kw_writeonly);
9480 if (parseToken(lltok::SummaryID, "expected GV ID"))
9481 return true;
9483 GVId = Lex.getUIntVal();
9484 // Check if we already have a VI for this GV
9485 if (GVId < NumberedValueInfos.size()) {
9486 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
9487 VI = NumberedValueInfos[GVId];
9488 } else
9489 // We will create a forward reference to the stored location.
9490 VI = ValueInfo(false, FwdVIRef);
9492 if (ReadOnly)
9493 VI.setReadOnly();
9494 if (WriteOnly)
9495 VI.setWriteOnly();
9496 return false;