[Alignment][NFC] Convert StoreInst to MaybeAlign
[llvm-complete.git] / lib / AsmParser / LLParser.cpp
blob594537307d00e926ff7bd86f04ceb54167331e97
1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the parser class for .ll files.
11 //===----------------------------------------------------------------------===//
13 #include "LLParser.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/AsmParser/SlotMapping.h"
20 #include "llvm/BinaryFormat/Dwarf.h"
21 #include "llvm/IR/Argument.h"
22 #include "llvm/IR/AutoUpgrade.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/CallingConv.h"
25 #include "llvm/IR/Comdat.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DebugInfoMetadata.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalIFunc.h"
31 #include "llvm/IR/GlobalObject.h"
32 #include "llvm/IR/InlineAsm.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/IR/Value.h"
42 #include "llvm/IR/ValueSymbolTable.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/SaveAndRestore.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <algorithm>
49 #include <cassert>
50 #include <cstring>
51 #include <iterator>
52 #include <vector>
54 using namespace llvm;
56 static std::string getTypeString(Type *T) {
57 std::string Result;
58 raw_string_ostream Tmp(Result);
59 Tmp << *T;
60 return Tmp.str();
63 /// Run: module ::= toplevelentity*
64 bool LLParser::Run() {
65 // Prime the lexer.
66 Lex.Lex();
68 if (Context.shouldDiscardValueNames())
69 return Error(
70 Lex.getLoc(),
71 "Can't read textual IR with a Context that discards named Values");
73 return ParseTopLevelEntities() || ValidateEndOfModule() ||
74 ValidateEndOfIndex();
77 bool LLParser::parseStandaloneConstantValue(Constant *&C,
78 const SlotMapping *Slots) {
79 restoreParsingState(Slots);
80 Lex.Lex();
82 Type *Ty = nullptr;
83 if (ParseType(Ty) || parseConstantValue(Ty, C))
84 return true;
85 if (Lex.getKind() != lltok::Eof)
86 return Error(Lex.getLoc(), "expected end of string");
87 return false;
90 bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
91 const SlotMapping *Slots) {
92 restoreParsingState(Slots);
93 Lex.Lex();
95 Read = 0;
96 SMLoc Start = Lex.getLoc();
97 Ty = nullptr;
98 if (ParseType(Ty))
99 return true;
100 SMLoc End = Lex.getLoc();
101 Read = End.getPointer() - Start.getPointer();
103 return false;
106 void LLParser::restoreParsingState(const SlotMapping *Slots) {
107 if (!Slots)
108 return;
109 NumberedVals = Slots->GlobalValues;
110 NumberedMetadata = Slots->MetadataNodes;
111 for (const auto &I : Slots->NamedTypes)
112 NamedTypes.insert(
113 std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
114 for (const auto &I : Slots->Types)
115 NumberedTypes.insert(
116 std::make_pair(I.first, std::make_pair(I.second, LocTy())));
119 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
120 /// module.
121 bool LLParser::ValidateEndOfModule() {
122 if (!M)
123 return false;
124 // Handle any function attribute group forward references.
125 for (const auto &RAG : ForwardRefAttrGroups) {
126 Value *V = RAG.first;
127 const std::vector<unsigned> &Attrs = RAG.second;
128 AttrBuilder B;
130 for (const auto &Attr : Attrs)
131 B.merge(NumberedAttrBuilders[Attr]);
133 if (Function *Fn = dyn_cast<Function>(V)) {
134 AttributeList AS = Fn->getAttributes();
135 AttrBuilder FnAttrs(AS.getFnAttributes());
136 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
138 FnAttrs.merge(B);
140 // If the alignment was parsed as an attribute, move to the alignment
141 // field.
142 if (FnAttrs.hasAlignmentAttr()) {
143 Fn->setAlignment(FnAttrs.getAlignment());
144 FnAttrs.removeAttribute(Attribute::Alignment);
147 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
148 AttributeSet::get(Context, FnAttrs));
149 Fn->setAttributes(AS);
150 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
151 AttributeList AS = CI->getAttributes();
152 AttrBuilder FnAttrs(AS.getFnAttributes());
153 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
154 FnAttrs.merge(B);
155 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
156 AttributeSet::get(Context, FnAttrs));
157 CI->setAttributes(AS);
158 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
159 AttributeList AS = II->getAttributes();
160 AttrBuilder FnAttrs(AS.getFnAttributes());
161 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
162 FnAttrs.merge(B);
163 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
164 AttributeSet::get(Context, FnAttrs));
165 II->setAttributes(AS);
166 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(V)) {
167 AttributeList AS = CBI->getAttributes();
168 AttrBuilder FnAttrs(AS.getFnAttributes());
169 AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
170 FnAttrs.merge(B);
171 AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
172 AttributeSet::get(Context, FnAttrs));
173 CBI->setAttributes(AS);
174 } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
175 AttrBuilder Attrs(GV->getAttributes());
176 Attrs.merge(B);
177 GV->setAttributes(AttributeSet::get(Context,Attrs));
178 } else {
179 llvm_unreachable("invalid object with forward attribute group reference");
183 // If there are entries in ForwardRefBlockAddresses at this point, the
184 // function was never defined.
185 if (!ForwardRefBlockAddresses.empty())
186 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
187 "expected function name in blockaddress");
189 for (const auto &NT : NumberedTypes)
190 if (NT.second.second.isValid())
191 return Error(NT.second.second,
192 "use of undefined type '%" + Twine(NT.first) + "'");
194 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
195 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
196 if (I->second.second.isValid())
197 return Error(I->second.second,
198 "use of undefined type named '" + I->getKey() + "'");
200 if (!ForwardRefComdats.empty())
201 return Error(ForwardRefComdats.begin()->second,
202 "use of undefined comdat '$" +
203 ForwardRefComdats.begin()->first + "'");
205 if (!ForwardRefVals.empty())
206 return Error(ForwardRefVals.begin()->second.second,
207 "use of undefined value '@" + ForwardRefVals.begin()->first +
208 "'");
210 if (!ForwardRefValIDs.empty())
211 return Error(ForwardRefValIDs.begin()->second.second,
212 "use of undefined value '@" +
213 Twine(ForwardRefValIDs.begin()->first) + "'");
215 if (!ForwardRefMDNodes.empty())
216 return Error(ForwardRefMDNodes.begin()->second.second,
217 "use of undefined metadata '!" +
218 Twine(ForwardRefMDNodes.begin()->first) + "'");
220 // Resolve metadata cycles.
221 for (auto &N : NumberedMetadata) {
222 if (N.second && !N.second->isResolved())
223 N.second->resolveCycles();
226 for (auto *Inst : InstsWithTBAATag) {
227 MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
228 assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
229 auto *UpgradedMD = UpgradeTBAANode(*MD);
230 if (MD != UpgradedMD)
231 Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
234 // Look for intrinsic functions and CallInst that need to be upgraded
235 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
236 UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
238 // Some types could be renamed during loading if several modules are
239 // loaded in the same LLVMContext (LTO scenario). In this case we should
240 // remangle intrinsics names as well.
241 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
242 Function *F = &*FI++;
243 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
244 F->replaceAllUsesWith(Remangled.getValue());
245 F->eraseFromParent();
249 if (UpgradeDebugInfo)
250 llvm::UpgradeDebugInfo(*M);
252 UpgradeModuleFlags(*M);
253 UpgradeSectionAttributes(*M);
255 if (!Slots)
256 return false;
257 // Initialize the slot mapping.
258 // Because by this point we've parsed and validated everything, we can "steal"
259 // the mapping from LLParser as it doesn't need it anymore.
260 Slots->GlobalValues = std::move(NumberedVals);
261 Slots->MetadataNodes = std::move(NumberedMetadata);
262 for (const auto &I : NamedTypes)
263 Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
264 for (const auto &I : NumberedTypes)
265 Slots->Types.insert(std::make_pair(I.first, I.second.first));
267 return false;
270 /// Do final validity and sanity checks at the end of the index.
271 bool LLParser::ValidateEndOfIndex() {
272 if (!Index)
273 return false;
275 if (!ForwardRefValueInfos.empty())
276 return Error(ForwardRefValueInfos.begin()->second.front().second,
277 "use of undefined summary '^" +
278 Twine(ForwardRefValueInfos.begin()->first) + "'");
280 if (!ForwardRefAliasees.empty())
281 return Error(ForwardRefAliasees.begin()->second.front().second,
282 "use of undefined summary '^" +
283 Twine(ForwardRefAliasees.begin()->first) + "'");
285 if (!ForwardRefTypeIds.empty())
286 return Error(ForwardRefTypeIds.begin()->second.front().second,
287 "use of undefined type id summary '^" +
288 Twine(ForwardRefTypeIds.begin()->first) + "'");
290 return false;
293 //===----------------------------------------------------------------------===//
294 // Top-Level Entities
295 //===----------------------------------------------------------------------===//
297 bool LLParser::ParseTopLevelEntities() {
298 // If there is no Module, then parse just the summary index entries.
299 if (!M) {
300 while (true) {
301 switch (Lex.getKind()) {
302 case lltok::Eof:
303 return false;
304 case lltok::SummaryID:
305 if (ParseSummaryEntry())
306 return true;
307 break;
308 case lltok::kw_source_filename:
309 if (ParseSourceFileName())
310 return true;
311 break;
312 default:
313 // Skip everything else
314 Lex.Lex();
318 while (true) {
319 switch (Lex.getKind()) {
320 default: return TokError("expected top-level entity");
321 case lltok::Eof: return false;
322 case lltok::kw_declare: if (ParseDeclare()) return true; break;
323 case lltok::kw_define: if (ParseDefine()) return true; break;
324 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
325 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
326 case lltok::kw_source_filename:
327 if (ParseSourceFileName())
328 return true;
329 break;
330 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
331 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
332 case lltok::LocalVar: if (ParseNamedType()) return true; break;
333 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
334 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
335 case lltok::ComdatVar: if (parseComdat()) return true; break;
336 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
337 case lltok::SummaryID:
338 if (ParseSummaryEntry())
339 return true;
340 break;
341 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
342 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
343 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
344 case lltok::kw_uselistorder_bb:
345 if (ParseUseListOrderBB())
346 return true;
347 break;
352 /// toplevelentity
353 /// ::= 'module' 'asm' STRINGCONSTANT
354 bool LLParser::ParseModuleAsm() {
355 assert(Lex.getKind() == lltok::kw_module);
356 Lex.Lex();
358 std::string AsmStr;
359 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
360 ParseStringConstant(AsmStr)) return true;
362 M->appendModuleInlineAsm(AsmStr);
363 return false;
366 /// toplevelentity
367 /// ::= 'target' 'triple' '=' STRINGCONSTANT
368 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
369 bool LLParser::ParseTargetDefinition() {
370 assert(Lex.getKind() == lltok::kw_target);
371 std::string Str;
372 switch (Lex.Lex()) {
373 default: return TokError("unknown target property");
374 case lltok::kw_triple:
375 Lex.Lex();
376 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
377 ParseStringConstant(Str))
378 return true;
379 M->setTargetTriple(Str);
380 return false;
381 case lltok::kw_datalayout:
382 Lex.Lex();
383 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
384 ParseStringConstant(Str))
385 return true;
386 if (DataLayoutStr.empty())
387 M->setDataLayout(Str);
388 return false;
392 /// toplevelentity
393 /// ::= 'source_filename' '=' STRINGCONSTANT
394 bool LLParser::ParseSourceFileName() {
395 assert(Lex.getKind() == lltok::kw_source_filename);
396 Lex.Lex();
397 if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
398 ParseStringConstant(SourceFileName))
399 return true;
400 if (M)
401 M->setSourceFileName(SourceFileName);
402 return false;
405 /// toplevelentity
406 /// ::= 'deplibs' '=' '[' ']'
407 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
408 /// FIXME: Remove in 4.0. Currently parse, but ignore.
409 bool LLParser::ParseDepLibs() {
410 assert(Lex.getKind() == lltok::kw_deplibs);
411 Lex.Lex();
412 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
413 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
414 return true;
416 if (EatIfPresent(lltok::rsquare))
417 return false;
419 do {
420 std::string Str;
421 if (ParseStringConstant(Str)) return true;
422 } while (EatIfPresent(lltok::comma));
424 return ParseToken(lltok::rsquare, "expected ']' at end of list");
427 /// ParseUnnamedType:
428 /// ::= LocalVarID '=' 'type' type
429 bool LLParser::ParseUnnamedType() {
430 LocTy TypeLoc = Lex.getLoc();
431 unsigned TypeID = Lex.getUIntVal();
432 Lex.Lex(); // eat LocalVarID;
434 if (ParseToken(lltok::equal, "expected '=' after name") ||
435 ParseToken(lltok::kw_type, "expected 'type' after '='"))
436 return true;
438 Type *Result = nullptr;
439 if (ParseStructDefinition(TypeLoc, "",
440 NumberedTypes[TypeID], Result)) return true;
442 if (!isa<StructType>(Result)) {
443 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
444 if (Entry.first)
445 return Error(TypeLoc, "non-struct types may not be recursive");
446 Entry.first = Result;
447 Entry.second = SMLoc();
450 return false;
453 /// toplevelentity
454 /// ::= LocalVar '=' 'type' type
455 bool LLParser::ParseNamedType() {
456 std::string Name = Lex.getStrVal();
457 LocTy NameLoc = Lex.getLoc();
458 Lex.Lex(); // eat LocalVar.
460 if (ParseToken(lltok::equal, "expected '=' after name") ||
461 ParseToken(lltok::kw_type, "expected 'type' after name"))
462 return true;
464 Type *Result = nullptr;
465 if (ParseStructDefinition(NameLoc, Name,
466 NamedTypes[Name], Result)) return true;
468 if (!isa<StructType>(Result)) {
469 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
470 if (Entry.first)
471 return Error(NameLoc, "non-struct types may not be recursive");
472 Entry.first = Result;
473 Entry.second = SMLoc();
476 return false;
479 /// toplevelentity
480 /// ::= 'declare' FunctionHeader
481 bool LLParser::ParseDeclare() {
482 assert(Lex.getKind() == lltok::kw_declare);
483 Lex.Lex();
485 std::vector<std::pair<unsigned, MDNode *>> MDs;
486 while (Lex.getKind() == lltok::MetadataVar) {
487 unsigned MDK;
488 MDNode *N;
489 if (ParseMetadataAttachment(MDK, N))
490 return true;
491 MDs.push_back({MDK, N});
494 Function *F;
495 if (ParseFunctionHeader(F, false))
496 return true;
497 for (auto &MD : MDs)
498 F->addMetadata(MD.first, *MD.second);
499 return false;
502 /// toplevelentity
503 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
504 bool LLParser::ParseDefine() {
505 assert(Lex.getKind() == lltok::kw_define);
506 Lex.Lex();
508 Function *F;
509 return ParseFunctionHeader(F, true) ||
510 ParseOptionalFunctionMetadata(*F) ||
511 ParseFunctionBody(*F);
514 /// ParseGlobalType
515 /// ::= 'constant'
516 /// ::= 'global'
517 bool LLParser::ParseGlobalType(bool &IsConstant) {
518 if (Lex.getKind() == lltok::kw_constant)
519 IsConstant = true;
520 else if (Lex.getKind() == lltok::kw_global)
521 IsConstant = false;
522 else {
523 IsConstant = false;
524 return TokError("expected 'global' or 'constant'");
526 Lex.Lex();
527 return false;
530 bool LLParser::ParseOptionalUnnamedAddr(
531 GlobalVariable::UnnamedAddr &UnnamedAddr) {
532 if (EatIfPresent(lltok::kw_unnamed_addr))
533 UnnamedAddr = GlobalValue::UnnamedAddr::Global;
534 else if (EatIfPresent(lltok::kw_local_unnamed_addr))
535 UnnamedAddr = GlobalValue::UnnamedAddr::Local;
536 else
537 UnnamedAddr = GlobalValue::UnnamedAddr::None;
538 return false;
541 /// ParseUnnamedGlobal:
542 /// OptionalVisibility (ALIAS | IFUNC) ...
543 /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
544 /// OptionalDLLStorageClass
545 /// ... -> global variable
546 /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
547 /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
548 /// OptionalDLLStorageClass
549 /// ... -> global variable
550 bool LLParser::ParseUnnamedGlobal() {
551 unsigned VarID = NumberedVals.size();
552 std::string Name;
553 LocTy NameLoc = Lex.getLoc();
555 // Handle the GlobalID form.
556 if (Lex.getKind() == lltok::GlobalID) {
557 if (Lex.getUIntVal() != VarID)
558 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
559 Twine(VarID) + "'");
560 Lex.Lex(); // eat GlobalID;
562 if (ParseToken(lltok::equal, "expected '=' after name"))
563 return true;
566 bool HasLinkage;
567 unsigned Linkage, Visibility, DLLStorageClass;
568 bool DSOLocal;
569 GlobalVariable::ThreadLocalMode TLM;
570 GlobalVariable::UnnamedAddr UnnamedAddr;
571 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
572 DSOLocal) ||
573 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
574 return true;
576 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
577 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
578 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
580 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
581 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
584 /// ParseNamedGlobal:
585 /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
586 /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
587 /// OptionalVisibility OptionalDLLStorageClass
588 /// ... -> global variable
589 bool LLParser::ParseNamedGlobal() {
590 assert(Lex.getKind() == lltok::GlobalVar);
591 LocTy NameLoc = Lex.getLoc();
592 std::string Name = Lex.getStrVal();
593 Lex.Lex();
595 bool HasLinkage;
596 unsigned Linkage, Visibility, DLLStorageClass;
597 bool DSOLocal;
598 GlobalVariable::ThreadLocalMode TLM;
599 GlobalVariable::UnnamedAddr UnnamedAddr;
600 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
601 ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
602 DSOLocal) ||
603 ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
604 return true;
606 if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
607 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
608 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
610 return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
611 DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
614 bool LLParser::parseComdat() {
615 assert(Lex.getKind() == lltok::ComdatVar);
616 std::string Name = Lex.getStrVal();
617 LocTy NameLoc = Lex.getLoc();
618 Lex.Lex();
620 if (ParseToken(lltok::equal, "expected '=' here"))
621 return true;
623 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
624 return TokError("expected comdat type");
626 Comdat::SelectionKind SK;
627 switch (Lex.getKind()) {
628 default:
629 return TokError("unknown selection kind");
630 case lltok::kw_any:
631 SK = Comdat::Any;
632 break;
633 case lltok::kw_exactmatch:
634 SK = Comdat::ExactMatch;
635 break;
636 case lltok::kw_largest:
637 SK = Comdat::Largest;
638 break;
639 case lltok::kw_noduplicates:
640 SK = Comdat::NoDuplicates;
641 break;
642 case lltok::kw_samesize:
643 SK = Comdat::SameSize;
644 break;
646 Lex.Lex();
648 // See if the comdat was forward referenced, if so, use the comdat.
649 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
650 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
651 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
652 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
654 Comdat *C;
655 if (I != ComdatSymTab.end())
656 C = &I->second;
657 else
658 C = M->getOrInsertComdat(Name);
659 C->setSelectionKind(SK);
661 return false;
664 // MDString:
665 // ::= '!' STRINGCONSTANT
666 bool LLParser::ParseMDString(MDString *&Result) {
667 std::string Str;
668 if (ParseStringConstant(Str)) return true;
669 Result = MDString::get(Context, Str);
670 return false;
673 // MDNode:
674 // ::= '!' MDNodeNumber
675 bool LLParser::ParseMDNodeID(MDNode *&Result) {
676 // !{ ..., !42, ... }
677 LocTy IDLoc = Lex.getLoc();
678 unsigned MID = 0;
679 if (ParseUInt32(MID))
680 return true;
682 // If not a forward reference, just return it now.
683 if (NumberedMetadata.count(MID)) {
684 Result = NumberedMetadata[MID];
685 return false;
688 // Otherwise, create MDNode forward reference.
689 auto &FwdRef = ForwardRefMDNodes[MID];
690 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
692 Result = FwdRef.first.get();
693 NumberedMetadata[MID].reset(Result);
694 return false;
697 /// ParseNamedMetadata:
698 /// !foo = !{ !1, !2 }
699 bool LLParser::ParseNamedMetadata() {
700 assert(Lex.getKind() == lltok::MetadataVar);
701 std::string Name = Lex.getStrVal();
702 Lex.Lex();
704 if (ParseToken(lltok::equal, "expected '=' here") ||
705 ParseToken(lltok::exclaim, "Expected '!' here") ||
706 ParseToken(lltok::lbrace, "Expected '{' here"))
707 return true;
709 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
710 if (Lex.getKind() != lltok::rbrace)
711 do {
712 MDNode *N = nullptr;
713 // Parse DIExpressions inline as a special case. They are still MDNodes,
714 // so they can still appear in named metadata. Remove this logic if they
715 // become plain Metadata.
716 if (Lex.getKind() == lltok::MetadataVar &&
717 Lex.getStrVal() == "DIExpression") {
718 if (ParseDIExpression(N, /*IsDistinct=*/false))
719 return true;
720 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
721 ParseMDNodeID(N)) {
722 return true;
724 NMD->addOperand(N);
725 } while (EatIfPresent(lltok::comma));
727 return ParseToken(lltok::rbrace, "expected end of metadata node");
730 /// ParseStandaloneMetadata:
731 /// !42 = !{...}
732 bool LLParser::ParseStandaloneMetadata() {
733 assert(Lex.getKind() == lltok::exclaim);
734 Lex.Lex();
735 unsigned MetadataID = 0;
737 MDNode *Init;
738 if (ParseUInt32(MetadataID) ||
739 ParseToken(lltok::equal, "expected '=' here"))
740 return true;
742 // Detect common error, from old metadata syntax.
743 if (Lex.getKind() == lltok::Type)
744 return TokError("unexpected type in metadata definition");
746 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
747 if (Lex.getKind() == lltok::MetadataVar) {
748 if (ParseSpecializedMDNode(Init, IsDistinct))
749 return true;
750 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
751 ParseMDTuple(Init, IsDistinct))
752 return true;
754 // See if this was forward referenced, if so, handle it.
755 auto FI = ForwardRefMDNodes.find(MetadataID);
756 if (FI != ForwardRefMDNodes.end()) {
757 FI->second.first->replaceAllUsesWith(Init);
758 ForwardRefMDNodes.erase(FI);
760 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
761 } else {
762 if (NumberedMetadata.count(MetadataID))
763 return TokError("Metadata id is already used");
764 NumberedMetadata[MetadataID].reset(Init);
767 return false;
770 // Skips a single module summary entry.
771 bool LLParser::SkipModuleSummaryEntry() {
772 // Each module summary entry consists of a tag for the entry
773 // type, followed by a colon, then the fields surrounded by nested sets of
774 // parentheses. The "tag:" looks like a Label. Once parsing support is
775 // in place we will look for the tokens corresponding to the expected tags.
776 if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
777 Lex.getKind() != lltok::kw_typeid)
778 return TokError(
779 "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
780 Lex.Lex();
781 if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
782 ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
783 return true;
784 // Now walk through the parenthesized entry, until the number of open
785 // parentheses goes back down to 0 (the first '(' was parsed above).
786 unsigned NumOpenParen = 1;
787 do {
788 switch (Lex.getKind()) {
789 case lltok::lparen:
790 NumOpenParen++;
791 break;
792 case lltok::rparen:
793 NumOpenParen--;
794 break;
795 case lltok::Eof:
796 return TokError("found end of file while parsing summary entry");
797 default:
798 // Skip everything in between parentheses.
799 break;
801 Lex.Lex();
802 } while (NumOpenParen > 0);
803 return false;
806 /// SummaryEntry
807 /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
808 bool LLParser::ParseSummaryEntry() {
809 assert(Lex.getKind() == lltok::SummaryID);
810 unsigned SummaryID = Lex.getUIntVal();
812 // For summary entries, colons should be treated as distinct tokens,
813 // not an indication of the end of a label token.
814 Lex.setIgnoreColonInIdentifiers(true);
816 Lex.Lex();
817 if (ParseToken(lltok::equal, "expected '=' here"))
818 return true;
820 // If we don't have an index object, skip the summary entry.
821 if (!Index)
822 return SkipModuleSummaryEntry();
824 bool result = false;
825 switch (Lex.getKind()) {
826 case lltok::kw_gv:
827 result = ParseGVEntry(SummaryID);
828 break;
829 case lltok::kw_module:
830 result = ParseModuleEntry(SummaryID);
831 break;
832 case lltok::kw_typeid:
833 result = ParseTypeIdEntry(SummaryID);
834 break;
835 case lltok::kw_typeidCompatibleVTable:
836 result = ParseTypeIdCompatibleVtableEntry(SummaryID);
837 break;
838 default:
839 result = Error(Lex.getLoc(), "unexpected summary kind");
840 break;
842 Lex.setIgnoreColonInIdentifiers(false);
843 return result;
846 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
847 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
848 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
851 // If there was an explicit dso_local, update GV. In the absence of an explicit
852 // dso_local we keep the default value.
853 static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
854 if (DSOLocal)
855 GV.setDSOLocal(true);
858 /// parseIndirectSymbol:
859 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
860 /// OptionalVisibility OptionalDLLStorageClass
861 /// OptionalThreadLocal OptionalUnnamedAddr
862 /// 'alias|ifunc' IndirectSymbol IndirectSymbolAttr*
864 /// IndirectSymbol
865 /// ::= TypeAndValue
867 /// IndirectSymbolAttr
868 /// ::= ',' 'partition' StringConstant
870 /// Everything through OptionalUnnamedAddr has already been parsed.
872 bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
873 unsigned L, unsigned Visibility,
874 unsigned DLLStorageClass, bool DSOLocal,
875 GlobalVariable::ThreadLocalMode TLM,
876 GlobalVariable::UnnamedAddr UnnamedAddr) {
877 bool IsAlias;
878 if (Lex.getKind() == lltok::kw_alias)
879 IsAlias = true;
880 else if (Lex.getKind() == lltok::kw_ifunc)
881 IsAlias = false;
882 else
883 llvm_unreachable("Not an alias or ifunc!");
884 Lex.Lex();
886 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
888 if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
889 return Error(NameLoc, "invalid linkage type for alias");
891 if (!isValidVisibilityForLinkage(Visibility, L))
892 return Error(NameLoc,
893 "symbol with local linkage must have default visibility");
895 Type *Ty;
896 LocTy ExplicitTypeLoc = Lex.getLoc();
897 if (ParseType(Ty) ||
898 ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
899 return true;
901 Constant *Aliasee;
902 LocTy AliaseeLoc = Lex.getLoc();
903 if (Lex.getKind() != lltok::kw_bitcast &&
904 Lex.getKind() != lltok::kw_getelementptr &&
905 Lex.getKind() != lltok::kw_addrspacecast &&
906 Lex.getKind() != lltok::kw_inttoptr) {
907 if (ParseGlobalTypeAndValue(Aliasee))
908 return true;
909 } else {
910 // The bitcast dest type is not present, it is implied by the dest type.
911 ValID ID;
912 if (ParseValID(ID))
913 return true;
914 if (ID.Kind != ValID::t_Constant)
915 return Error(AliaseeLoc, "invalid aliasee");
916 Aliasee = ID.ConstantVal;
919 Type *AliaseeType = Aliasee->getType();
920 auto *PTy = dyn_cast<PointerType>(AliaseeType);
921 if (!PTy)
922 return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
923 unsigned AddrSpace = PTy->getAddressSpace();
925 if (IsAlias && Ty != PTy->getElementType())
926 return Error(
927 ExplicitTypeLoc,
928 "explicit pointee type doesn't match operand's pointee type");
930 if (!IsAlias && !PTy->getElementType()->isFunctionTy())
931 return Error(
932 ExplicitTypeLoc,
933 "explicit pointee type should be a function type");
935 GlobalValue *GVal = nullptr;
937 // See if the alias was forward referenced, if so, prepare to replace the
938 // forward reference.
939 if (!Name.empty()) {
940 GVal = M->getNamedValue(Name);
941 if (GVal) {
942 if (!ForwardRefVals.erase(Name))
943 return Error(NameLoc, "redefinition of global '@" + Name + "'");
945 } else {
946 auto I = ForwardRefValIDs.find(NumberedVals.size());
947 if (I != ForwardRefValIDs.end()) {
948 GVal = I->second.first;
949 ForwardRefValIDs.erase(I);
953 // Okay, create the alias but do not insert it into the module yet.
954 std::unique_ptr<GlobalIndirectSymbol> GA;
955 if (IsAlias)
956 GA.reset(GlobalAlias::create(Ty, AddrSpace,
957 (GlobalValue::LinkageTypes)Linkage, Name,
958 Aliasee, /*Parent*/ nullptr));
959 else
960 GA.reset(GlobalIFunc::create(Ty, AddrSpace,
961 (GlobalValue::LinkageTypes)Linkage, Name,
962 Aliasee, /*Parent*/ nullptr));
963 GA->setThreadLocalMode(TLM);
964 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
965 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
966 GA->setUnnamedAddr(UnnamedAddr);
967 maybeSetDSOLocal(DSOLocal, *GA);
969 // At this point we've parsed everything except for the IndirectSymbolAttrs.
970 // Now parse them if there are any.
971 while (Lex.getKind() == lltok::comma) {
972 Lex.Lex();
974 if (Lex.getKind() == lltok::kw_partition) {
975 Lex.Lex();
976 GA->setPartition(Lex.getStrVal());
977 if (ParseToken(lltok::StringConstant, "expected partition string"))
978 return true;
979 } else {
980 return TokError("unknown alias or ifunc property!");
984 if (Name.empty())
985 NumberedVals.push_back(GA.get());
987 if (GVal) {
988 // Verify that types agree.
989 if (GVal->getType() != GA->getType())
990 return Error(
991 ExplicitTypeLoc,
992 "forward reference and definition of alias have different types");
994 // If they agree, just RAUW the old value with the alias and remove the
995 // forward ref info.
996 GVal->replaceAllUsesWith(GA.get());
997 GVal->eraseFromParent();
1000 // Insert into the module, we know its name won't collide now.
1001 if (IsAlias)
1002 M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
1003 else
1004 M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
1005 assert(GA->getName() == Name && "Should not be a name conflict!");
1007 // The module owns this now
1008 GA.release();
1010 return false;
1013 /// ParseGlobal
1014 /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
1015 /// OptionalVisibility OptionalDLLStorageClass
1016 /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
1017 /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
1018 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
1019 /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
1020 /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
1021 /// Const OptionalAttrs
1023 /// Everything up to and including OptionalUnnamedAddr has been parsed
1024 /// already.
1026 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
1027 unsigned Linkage, bool HasLinkage,
1028 unsigned Visibility, unsigned DLLStorageClass,
1029 bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
1030 GlobalVariable::UnnamedAddr UnnamedAddr) {
1031 if (!isValidVisibilityForLinkage(Visibility, Linkage))
1032 return Error(NameLoc,
1033 "symbol with local linkage must have default visibility");
1035 unsigned AddrSpace;
1036 bool IsConstant, IsExternallyInitialized;
1037 LocTy IsExternallyInitializedLoc;
1038 LocTy TyLoc;
1040 Type *Ty = nullptr;
1041 if (ParseOptionalAddrSpace(AddrSpace) ||
1042 ParseOptionalToken(lltok::kw_externally_initialized,
1043 IsExternallyInitialized,
1044 &IsExternallyInitializedLoc) ||
1045 ParseGlobalType(IsConstant) ||
1046 ParseType(Ty, TyLoc))
1047 return true;
1049 // If the linkage is specified and is external, then no initializer is
1050 // present.
1051 Constant *Init = nullptr;
1052 if (!HasLinkage ||
1053 !GlobalValue::isValidDeclarationLinkage(
1054 (GlobalValue::LinkageTypes)Linkage)) {
1055 if (ParseGlobalValue(Ty, Init))
1056 return true;
1059 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
1060 return Error(TyLoc, "invalid type for global variable");
1062 GlobalValue *GVal = nullptr;
1064 // See if the global was forward referenced, if so, use the global.
1065 if (!Name.empty()) {
1066 GVal = M->getNamedValue(Name);
1067 if (GVal) {
1068 if (!ForwardRefVals.erase(Name))
1069 return Error(NameLoc, "redefinition of global '@" + Name + "'");
1071 } else {
1072 auto I = ForwardRefValIDs.find(NumberedVals.size());
1073 if (I != ForwardRefValIDs.end()) {
1074 GVal = I->second.first;
1075 ForwardRefValIDs.erase(I);
1079 GlobalVariable *GV;
1080 if (!GVal) {
1081 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
1082 Name, nullptr, GlobalVariable::NotThreadLocal,
1083 AddrSpace);
1084 } else {
1085 if (GVal->getValueType() != Ty)
1086 return Error(TyLoc,
1087 "forward reference and definition of global have different types");
1089 GV = cast<GlobalVariable>(GVal);
1091 // Move the forward-reference to the correct spot in the module.
1092 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
1095 if (Name.empty())
1096 NumberedVals.push_back(GV);
1098 // Set the parsed properties on the global.
1099 if (Init)
1100 GV->setInitializer(Init);
1101 GV->setConstant(IsConstant);
1102 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
1103 maybeSetDSOLocal(DSOLocal, *GV);
1104 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
1105 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
1106 GV->setExternallyInitialized(IsExternallyInitialized);
1107 GV->setThreadLocalMode(TLM);
1108 GV->setUnnamedAddr(UnnamedAddr);
1110 // Parse attributes on the global.
1111 while (Lex.getKind() == lltok::comma) {
1112 Lex.Lex();
1114 if (Lex.getKind() == lltok::kw_section) {
1115 Lex.Lex();
1116 GV->setSection(Lex.getStrVal());
1117 if (ParseToken(lltok::StringConstant, "expected global section string"))
1118 return true;
1119 } else if (Lex.getKind() == lltok::kw_partition) {
1120 Lex.Lex();
1121 GV->setPartition(Lex.getStrVal());
1122 if (ParseToken(lltok::StringConstant, "expected partition string"))
1123 return true;
1124 } else if (Lex.getKind() == lltok::kw_align) {
1125 MaybeAlign Alignment;
1126 if (ParseOptionalAlignment(Alignment)) return true;
1127 GV->setAlignment(Alignment);
1128 } else if (Lex.getKind() == lltok::MetadataVar) {
1129 if (ParseGlobalObjectMetadataAttachment(*GV))
1130 return true;
1131 } else {
1132 Comdat *C;
1133 if (parseOptionalComdat(Name, C))
1134 return true;
1135 if (C)
1136 GV->setComdat(C);
1137 else
1138 return TokError("unknown global variable property!");
1142 AttrBuilder Attrs;
1143 LocTy BuiltinLoc;
1144 std::vector<unsigned> FwdRefAttrGrps;
1145 if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
1146 return true;
1147 if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
1148 GV->setAttributes(AttributeSet::get(Context, Attrs));
1149 ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
1152 return false;
1155 /// ParseUnnamedAttrGrp
1156 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
1157 bool LLParser::ParseUnnamedAttrGrp() {
1158 assert(Lex.getKind() == lltok::kw_attributes);
1159 LocTy AttrGrpLoc = Lex.getLoc();
1160 Lex.Lex();
1162 if (Lex.getKind() != lltok::AttrGrpID)
1163 return TokError("expected attribute group id");
1165 unsigned VarID = Lex.getUIntVal();
1166 std::vector<unsigned> unused;
1167 LocTy BuiltinLoc;
1168 Lex.Lex();
1170 if (ParseToken(lltok::equal, "expected '=' here") ||
1171 ParseToken(lltok::lbrace, "expected '{' here") ||
1172 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
1173 BuiltinLoc) ||
1174 ParseToken(lltok::rbrace, "expected end of attribute group"))
1175 return true;
1177 if (!NumberedAttrBuilders[VarID].hasAttributes())
1178 return Error(AttrGrpLoc, "attribute group has no attributes");
1180 return false;
1183 /// ParseFnAttributeValuePairs
1184 /// ::= <attr> | <attr> '=' <value>
1185 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
1186 std::vector<unsigned> &FwdRefAttrGrps,
1187 bool inAttrGrp, LocTy &BuiltinLoc) {
1188 bool HaveError = false;
1190 B.clear();
1192 while (true) {
1193 lltok::Kind Token = Lex.getKind();
1194 if (Token == lltok::kw_builtin)
1195 BuiltinLoc = Lex.getLoc();
1196 switch (Token) {
1197 default:
1198 if (!inAttrGrp) return HaveError;
1199 return Error(Lex.getLoc(), "unterminated attribute group");
1200 case lltok::rbrace:
1201 // Finished.
1202 return false;
1204 case lltok::AttrGrpID: {
1205 // Allow a function to reference an attribute group:
1207 // define void @foo() #1 { ... }
1208 if (inAttrGrp)
1209 HaveError |=
1210 Error(Lex.getLoc(),
1211 "cannot have an attribute group reference in an attribute group");
1213 unsigned AttrGrpNum = Lex.getUIntVal();
1214 if (inAttrGrp) break;
1216 // Save the reference to the attribute group. We'll fill it in later.
1217 FwdRefAttrGrps.push_back(AttrGrpNum);
1218 break;
1220 // Target-dependent attributes:
1221 case lltok::StringConstant: {
1222 if (ParseStringAttribute(B))
1223 return true;
1224 continue;
1227 // Target-independent attributes:
1228 case lltok::kw_align: {
1229 // As a hack, we allow function alignment to be initially parsed as an
1230 // attribute on a function declaration/definition or added to an attribute
1231 // group and later moved to the alignment field.
1232 MaybeAlign Alignment;
1233 if (inAttrGrp) {
1234 Lex.Lex();
1235 uint32_t Value = 0;
1236 if (ParseToken(lltok::equal, "expected '=' here") || ParseUInt32(Value))
1237 return true;
1238 Alignment = Align(Value);
1239 } else {
1240 if (ParseOptionalAlignment(Alignment))
1241 return true;
1243 B.addAlignmentAttr(Alignment);
1244 continue;
1246 case lltok::kw_alignstack: {
1247 unsigned Alignment;
1248 if (inAttrGrp) {
1249 Lex.Lex();
1250 if (ParseToken(lltok::equal, "expected '=' here") ||
1251 ParseUInt32(Alignment))
1252 return true;
1253 } else {
1254 if (ParseOptionalStackAlignment(Alignment))
1255 return true;
1257 B.addStackAlignmentAttr(Alignment);
1258 continue;
1260 case lltok::kw_allocsize: {
1261 unsigned ElemSizeArg;
1262 Optional<unsigned> NumElemsArg;
1263 // inAttrGrp doesn't matter; we only support allocsize(a[, b])
1264 if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
1265 return true;
1266 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1267 continue;
1269 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1270 case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
1271 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1272 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1273 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
1274 case lltok::kw_inaccessiblememonly:
1275 B.addAttribute(Attribute::InaccessibleMemOnly); break;
1276 case lltok::kw_inaccessiblemem_or_argmemonly:
1277 B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
1278 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1279 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1280 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1281 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1282 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1283 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1284 case lltok::kw_nofree: B.addAttribute(Attribute::NoFree); break;
1285 case lltok::kw_noimplicitfloat:
1286 B.addAttribute(Attribute::NoImplicitFloat); break;
1287 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1288 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1289 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1290 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1291 case lltok::kw_nosync: B.addAttribute(Attribute::NoSync); break;
1292 case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
1293 case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
1294 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1295 case lltok::kw_optforfuzzing:
1296 B.addAttribute(Attribute::OptForFuzzing); break;
1297 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1298 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1299 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1300 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1301 case lltok::kw_returns_twice:
1302 B.addAttribute(Attribute::ReturnsTwice); break;
1303 case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
1304 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1305 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1306 case lltok::kw_sspstrong:
1307 B.addAttribute(Attribute::StackProtectStrong); break;
1308 case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
1309 case lltok::kw_shadowcallstack:
1310 B.addAttribute(Attribute::ShadowCallStack); break;
1311 case lltok::kw_sanitize_address:
1312 B.addAttribute(Attribute::SanitizeAddress); break;
1313 case lltok::kw_sanitize_hwaddress:
1314 B.addAttribute(Attribute::SanitizeHWAddress); break;
1315 case lltok::kw_sanitize_memtag:
1316 B.addAttribute(Attribute::SanitizeMemTag); break;
1317 case lltok::kw_sanitize_thread:
1318 B.addAttribute(Attribute::SanitizeThread); break;
1319 case lltok::kw_sanitize_memory:
1320 B.addAttribute(Attribute::SanitizeMemory); break;
1321 case lltok::kw_speculative_load_hardening:
1322 B.addAttribute(Attribute::SpeculativeLoadHardening);
1323 break;
1324 case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
1325 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1326 case lltok::kw_willreturn: B.addAttribute(Attribute::WillReturn); break;
1327 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1329 // Error handling.
1330 case lltok::kw_inreg:
1331 case lltok::kw_signext:
1332 case lltok::kw_zeroext:
1333 HaveError |=
1334 Error(Lex.getLoc(),
1335 "invalid use of attribute on a function");
1336 break;
1337 case lltok::kw_byval:
1338 case lltok::kw_dereferenceable:
1339 case lltok::kw_dereferenceable_or_null:
1340 case lltok::kw_inalloca:
1341 case lltok::kw_nest:
1342 case lltok::kw_noalias:
1343 case lltok::kw_nocapture:
1344 case lltok::kw_nonnull:
1345 case lltok::kw_returned:
1346 case lltok::kw_sret:
1347 case lltok::kw_swifterror:
1348 case lltok::kw_swiftself:
1349 case lltok::kw_immarg:
1350 HaveError |=
1351 Error(Lex.getLoc(),
1352 "invalid use of parameter-only attribute on a function");
1353 break;
1356 Lex.Lex();
1360 //===----------------------------------------------------------------------===//
1361 // GlobalValue Reference/Resolution Routines.
1362 //===----------------------------------------------------------------------===//
1364 static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
1365 const std::string &Name) {
1366 if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1367 return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
1368 PTy->getAddressSpace(), Name, M);
1369 else
1370 return new GlobalVariable(*M, PTy->getElementType(), false,
1371 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1372 nullptr, GlobalVariable::NotThreadLocal,
1373 PTy->getAddressSpace());
1376 Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
1377 Value *Val, bool IsCall) {
1378 if (Val->getType() == Ty)
1379 return Val;
1380 // For calls we also accept variables in the program address space.
1381 Type *SuggestedTy = Ty;
1382 if (IsCall && isa<PointerType>(Ty)) {
1383 Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
1384 M->getDataLayout().getProgramAddressSpace());
1385 SuggestedTy = TyInProgAS;
1386 if (Val->getType() == TyInProgAS)
1387 return Val;
1389 if (Ty->isLabelTy())
1390 Error(Loc, "'" + Name + "' is not a basic block");
1391 else
1392 Error(Loc, "'" + Name + "' defined with type '" +
1393 getTypeString(Val->getType()) + "' but expected '" +
1394 getTypeString(SuggestedTy) + "'");
1395 return nullptr;
1398 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1399 /// forward reference record if needed. This can return null if the value
1400 /// exists but does not have the right type.
1401 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1402 LocTy Loc, bool IsCall) {
1403 PointerType *PTy = dyn_cast<PointerType>(Ty);
1404 if (!PTy) {
1405 Error(Loc, "global variable reference must have pointer type");
1406 return nullptr;
1409 // Look this name up in the normal function symbol table.
1410 GlobalValue *Val =
1411 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1413 // If this is a forward reference for the value, see if we already created a
1414 // forward ref record.
1415 if (!Val) {
1416 auto I = ForwardRefVals.find(Name);
1417 if (I != ForwardRefVals.end())
1418 Val = I->second.first;
1421 // If we have the value in the symbol table or fwd-ref table, return it.
1422 if (Val)
1423 return cast_or_null<GlobalValue>(
1424 checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
1426 // Otherwise, create a new forward reference for this value and remember it.
1427 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
1428 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1429 return FwdVal;
1432 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
1433 bool IsCall) {
1434 PointerType *PTy = dyn_cast<PointerType>(Ty);
1435 if (!PTy) {
1436 Error(Loc, "global variable reference must have pointer type");
1437 return nullptr;
1440 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1442 // If this is a forward reference for the value, see if we already created a
1443 // forward ref record.
1444 if (!Val) {
1445 auto I = ForwardRefValIDs.find(ID);
1446 if (I != ForwardRefValIDs.end())
1447 Val = I->second.first;
1450 // If we have the value in the symbol table or fwd-ref table, return it.
1451 if (Val)
1452 return cast_or_null<GlobalValue>(
1453 checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
1455 // Otherwise, create a new forward reference for this value and remember it.
1456 GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
1457 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1458 return FwdVal;
1461 //===----------------------------------------------------------------------===//
1462 // Comdat Reference/Resolution Routines.
1463 //===----------------------------------------------------------------------===//
1465 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1466 // Look this name up in the comdat symbol table.
1467 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1468 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1469 if (I != ComdatSymTab.end())
1470 return &I->second;
1472 // Otherwise, create a new forward reference for this value and remember it.
1473 Comdat *C = M->getOrInsertComdat(Name);
1474 ForwardRefComdats[Name] = Loc;
1475 return C;
1478 //===----------------------------------------------------------------------===//
1479 // Helper Routines.
1480 //===----------------------------------------------------------------------===//
1482 /// ParseToken - If the current token has the specified kind, eat it and return
1483 /// success. Otherwise, emit the specified error and return failure.
1484 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1485 if (Lex.getKind() != T)
1486 return TokError(ErrMsg);
1487 Lex.Lex();
1488 return false;
1491 /// ParseStringConstant
1492 /// ::= StringConstant
1493 bool LLParser::ParseStringConstant(std::string &Result) {
1494 if (Lex.getKind() != lltok::StringConstant)
1495 return TokError("expected string constant");
1496 Result = Lex.getStrVal();
1497 Lex.Lex();
1498 return false;
1501 /// ParseUInt32
1502 /// ::= uint32
1503 bool LLParser::ParseUInt32(uint32_t &Val) {
1504 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1505 return TokError("expected integer");
1506 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1507 if (Val64 != unsigned(Val64))
1508 return TokError("expected 32-bit integer (too large)");
1509 Val = Val64;
1510 Lex.Lex();
1511 return false;
1514 /// ParseUInt64
1515 /// ::= uint64
1516 bool LLParser::ParseUInt64(uint64_t &Val) {
1517 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1518 return TokError("expected integer");
1519 Val = Lex.getAPSIntVal().getLimitedValue();
1520 Lex.Lex();
1521 return false;
1524 /// ParseTLSModel
1525 /// := 'localdynamic'
1526 /// := 'initialexec'
1527 /// := 'localexec'
1528 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1529 switch (Lex.getKind()) {
1530 default:
1531 return TokError("expected localdynamic, initialexec or localexec");
1532 case lltok::kw_localdynamic:
1533 TLM = GlobalVariable::LocalDynamicTLSModel;
1534 break;
1535 case lltok::kw_initialexec:
1536 TLM = GlobalVariable::InitialExecTLSModel;
1537 break;
1538 case lltok::kw_localexec:
1539 TLM = GlobalVariable::LocalExecTLSModel;
1540 break;
1543 Lex.Lex();
1544 return false;
1547 /// ParseOptionalThreadLocal
1548 /// := /*empty*/
1549 /// := 'thread_local'
1550 /// := 'thread_local' '(' tlsmodel ')'
1551 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1552 TLM = GlobalVariable::NotThreadLocal;
1553 if (!EatIfPresent(lltok::kw_thread_local))
1554 return false;
1556 TLM = GlobalVariable::GeneralDynamicTLSModel;
1557 if (Lex.getKind() == lltok::lparen) {
1558 Lex.Lex();
1559 return ParseTLSModel(TLM) ||
1560 ParseToken(lltok::rparen, "expected ')' after thread local model");
1562 return false;
1565 /// ParseOptionalAddrSpace
1566 /// := /*empty*/
1567 /// := 'addrspace' '(' uint32 ')'
1568 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
1569 AddrSpace = DefaultAS;
1570 if (!EatIfPresent(lltok::kw_addrspace))
1571 return false;
1572 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1573 ParseUInt32(AddrSpace) ||
1574 ParseToken(lltok::rparen, "expected ')' in address space");
1577 /// ParseStringAttribute
1578 /// := StringConstant
1579 /// := StringConstant '=' StringConstant
1580 bool LLParser::ParseStringAttribute(AttrBuilder &B) {
1581 std::string Attr = Lex.getStrVal();
1582 Lex.Lex();
1583 std::string Val;
1584 if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
1585 return true;
1586 B.addAttribute(Attr, Val);
1587 return false;
1590 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1591 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1592 bool HaveError = false;
1594 B.clear();
1596 while (true) {
1597 lltok::Kind Token = Lex.getKind();
1598 switch (Token) {
1599 default: // End of attributes.
1600 return HaveError;
1601 case lltok::StringConstant: {
1602 if (ParseStringAttribute(B))
1603 return true;
1604 continue;
1606 case lltok::kw_align: {
1607 MaybeAlign Alignment;
1608 if (ParseOptionalAlignment(Alignment))
1609 return true;
1610 B.addAlignmentAttr(Alignment);
1611 continue;
1613 case lltok::kw_byval: {
1614 Type *Ty;
1615 if (ParseByValWithOptionalType(Ty))
1616 return true;
1617 B.addByValAttr(Ty);
1618 continue;
1620 case lltok::kw_dereferenceable: {
1621 uint64_t Bytes;
1622 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1623 return true;
1624 B.addDereferenceableAttr(Bytes);
1625 continue;
1627 case lltok::kw_dereferenceable_or_null: {
1628 uint64_t Bytes;
1629 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1630 return true;
1631 B.addDereferenceableOrNullAttr(Bytes);
1632 continue;
1634 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1635 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1636 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1637 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1638 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1639 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1640 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1641 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1642 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1643 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1644 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1645 case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
1646 case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
1647 case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
1648 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1649 case lltok::kw_immarg: B.addAttribute(Attribute::ImmArg); break;
1651 case lltok::kw_alignstack:
1652 case lltok::kw_alwaysinline:
1653 case lltok::kw_argmemonly:
1654 case lltok::kw_builtin:
1655 case lltok::kw_inlinehint:
1656 case lltok::kw_jumptable:
1657 case lltok::kw_minsize:
1658 case lltok::kw_naked:
1659 case lltok::kw_nobuiltin:
1660 case lltok::kw_noduplicate:
1661 case lltok::kw_noimplicitfloat:
1662 case lltok::kw_noinline:
1663 case lltok::kw_nonlazybind:
1664 case lltok::kw_noredzone:
1665 case lltok::kw_noreturn:
1666 case lltok::kw_nocf_check:
1667 case lltok::kw_nounwind:
1668 case lltok::kw_optforfuzzing:
1669 case lltok::kw_optnone:
1670 case lltok::kw_optsize:
1671 case lltok::kw_returns_twice:
1672 case lltok::kw_sanitize_address:
1673 case lltok::kw_sanitize_hwaddress:
1674 case lltok::kw_sanitize_memtag:
1675 case lltok::kw_sanitize_memory:
1676 case lltok::kw_sanitize_thread:
1677 case lltok::kw_speculative_load_hardening:
1678 case lltok::kw_ssp:
1679 case lltok::kw_sspreq:
1680 case lltok::kw_sspstrong:
1681 case lltok::kw_safestack:
1682 case lltok::kw_shadowcallstack:
1683 case lltok::kw_strictfp:
1684 case lltok::kw_uwtable:
1685 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1686 break;
1689 Lex.Lex();
1693 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1694 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1695 bool HaveError = false;
1697 B.clear();
1699 while (true) {
1700 lltok::Kind Token = Lex.getKind();
1701 switch (Token) {
1702 default: // End of attributes.
1703 return HaveError;
1704 case lltok::StringConstant: {
1705 if (ParseStringAttribute(B))
1706 return true;
1707 continue;
1709 case lltok::kw_dereferenceable: {
1710 uint64_t Bytes;
1711 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1712 return true;
1713 B.addDereferenceableAttr(Bytes);
1714 continue;
1716 case lltok::kw_dereferenceable_or_null: {
1717 uint64_t Bytes;
1718 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1719 return true;
1720 B.addDereferenceableOrNullAttr(Bytes);
1721 continue;
1723 case lltok::kw_align: {
1724 MaybeAlign Alignment;
1725 if (ParseOptionalAlignment(Alignment))
1726 return true;
1727 B.addAlignmentAttr(Alignment);
1728 continue;
1730 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1731 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1732 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1733 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1734 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1736 // Error handling.
1737 case lltok::kw_byval:
1738 case lltok::kw_inalloca:
1739 case lltok::kw_nest:
1740 case lltok::kw_nocapture:
1741 case lltok::kw_returned:
1742 case lltok::kw_sret:
1743 case lltok::kw_swifterror:
1744 case lltok::kw_swiftself:
1745 case lltok::kw_immarg:
1746 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1747 break;
1749 case lltok::kw_alignstack:
1750 case lltok::kw_alwaysinline:
1751 case lltok::kw_argmemonly:
1752 case lltok::kw_builtin:
1753 case lltok::kw_cold:
1754 case lltok::kw_inlinehint:
1755 case lltok::kw_jumptable:
1756 case lltok::kw_minsize:
1757 case lltok::kw_naked:
1758 case lltok::kw_nobuiltin:
1759 case lltok::kw_noduplicate:
1760 case lltok::kw_noimplicitfloat:
1761 case lltok::kw_noinline:
1762 case lltok::kw_nonlazybind:
1763 case lltok::kw_noredzone:
1764 case lltok::kw_noreturn:
1765 case lltok::kw_nocf_check:
1766 case lltok::kw_nounwind:
1767 case lltok::kw_optforfuzzing:
1768 case lltok::kw_optnone:
1769 case lltok::kw_optsize:
1770 case lltok::kw_returns_twice:
1771 case lltok::kw_sanitize_address:
1772 case lltok::kw_sanitize_hwaddress:
1773 case lltok::kw_sanitize_memtag:
1774 case lltok::kw_sanitize_memory:
1775 case lltok::kw_sanitize_thread:
1776 case lltok::kw_speculative_load_hardening:
1777 case lltok::kw_ssp:
1778 case lltok::kw_sspreq:
1779 case lltok::kw_sspstrong:
1780 case lltok::kw_safestack:
1781 case lltok::kw_shadowcallstack:
1782 case lltok::kw_strictfp:
1783 case lltok::kw_uwtable:
1784 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1785 break;
1787 case lltok::kw_readnone:
1788 case lltok::kw_readonly:
1789 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1792 Lex.Lex();
1796 static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
1797 HasLinkage = true;
1798 switch (Kind) {
1799 default:
1800 HasLinkage = false;
1801 return GlobalValue::ExternalLinkage;
1802 case lltok::kw_private:
1803 return GlobalValue::PrivateLinkage;
1804 case lltok::kw_internal:
1805 return GlobalValue::InternalLinkage;
1806 case lltok::kw_weak:
1807 return GlobalValue::WeakAnyLinkage;
1808 case lltok::kw_weak_odr:
1809 return GlobalValue::WeakODRLinkage;
1810 case lltok::kw_linkonce:
1811 return GlobalValue::LinkOnceAnyLinkage;
1812 case lltok::kw_linkonce_odr:
1813 return GlobalValue::LinkOnceODRLinkage;
1814 case lltok::kw_available_externally:
1815 return GlobalValue::AvailableExternallyLinkage;
1816 case lltok::kw_appending:
1817 return GlobalValue::AppendingLinkage;
1818 case lltok::kw_common:
1819 return GlobalValue::CommonLinkage;
1820 case lltok::kw_extern_weak:
1821 return GlobalValue::ExternalWeakLinkage;
1822 case lltok::kw_external:
1823 return GlobalValue::ExternalLinkage;
1827 /// ParseOptionalLinkage
1828 /// ::= /*empty*/
1829 /// ::= 'private'
1830 /// ::= 'internal'
1831 /// ::= 'weak'
1832 /// ::= 'weak_odr'
1833 /// ::= 'linkonce'
1834 /// ::= 'linkonce_odr'
1835 /// ::= 'available_externally'
1836 /// ::= 'appending'
1837 /// ::= 'common'
1838 /// ::= 'extern_weak'
1839 /// ::= 'external'
1840 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
1841 unsigned &Visibility,
1842 unsigned &DLLStorageClass,
1843 bool &DSOLocal) {
1844 Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
1845 if (HasLinkage)
1846 Lex.Lex();
1847 ParseOptionalDSOLocal(DSOLocal);
1848 ParseOptionalVisibility(Visibility);
1849 ParseOptionalDLLStorageClass(DLLStorageClass);
1851 if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
1852 return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
1855 return false;
1858 void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
1859 switch (Lex.getKind()) {
1860 default:
1861 DSOLocal = false;
1862 break;
1863 case lltok::kw_dso_local:
1864 DSOLocal = true;
1865 Lex.Lex();
1866 break;
1867 case lltok::kw_dso_preemptable:
1868 DSOLocal = false;
1869 Lex.Lex();
1870 break;
1874 /// ParseOptionalVisibility
1875 /// ::= /*empty*/
1876 /// ::= 'default'
1877 /// ::= 'hidden'
1878 /// ::= 'protected'
1880 void LLParser::ParseOptionalVisibility(unsigned &Res) {
1881 switch (Lex.getKind()) {
1882 default:
1883 Res = GlobalValue::DefaultVisibility;
1884 return;
1885 case lltok::kw_default:
1886 Res = GlobalValue::DefaultVisibility;
1887 break;
1888 case lltok::kw_hidden:
1889 Res = GlobalValue::HiddenVisibility;
1890 break;
1891 case lltok::kw_protected:
1892 Res = GlobalValue::ProtectedVisibility;
1893 break;
1895 Lex.Lex();
1898 /// ParseOptionalDLLStorageClass
1899 /// ::= /*empty*/
1900 /// ::= 'dllimport'
1901 /// ::= 'dllexport'
1903 void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1904 switch (Lex.getKind()) {
1905 default:
1906 Res = GlobalValue::DefaultStorageClass;
1907 return;
1908 case lltok::kw_dllimport:
1909 Res = GlobalValue::DLLImportStorageClass;
1910 break;
1911 case lltok::kw_dllexport:
1912 Res = GlobalValue::DLLExportStorageClass;
1913 break;
1915 Lex.Lex();
1918 /// ParseOptionalCallingConv
1919 /// ::= /*empty*/
1920 /// ::= 'ccc'
1921 /// ::= 'fastcc'
1922 /// ::= 'intel_ocl_bicc'
1923 /// ::= 'coldcc'
1924 /// ::= 'x86_stdcallcc'
1925 /// ::= 'x86_fastcallcc'
1926 /// ::= 'x86_thiscallcc'
1927 /// ::= 'x86_vectorcallcc'
1928 /// ::= 'arm_apcscc'
1929 /// ::= 'arm_aapcscc'
1930 /// ::= 'arm_aapcs_vfpcc'
1931 /// ::= 'aarch64_vector_pcs'
1932 /// ::= 'msp430_intrcc'
1933 /// ::= 'avr_intrcc'
1934 /// ::= 'avr_signalcc'
1935 /// ::= 'ptx_kernel'
1936 /// ::= 'ptx_device'
1937 /// ::= 'spir_func'
1938 /// ::= 'spir_kernel'
1939 /// ::= 'x86_64_sysvcc'
1940 /// ::= 'win64cc'
1941 /// ::= 'webkit_jscc'
1942 /// ::= 'anyregcc'
1943 /// ::= 'preserve_mostcc'
1944 /// ::= 'preserve_allcc'
1945 /// ::= 'ghccc'
1946 /// ::= 'swiftcc'
1947 /// ::= 'x86_intrcc'
1948 /// ::= 'hhvmcc'
1949 /// ::= 'hhvm_ccc'
1950 /// ::= 'cxx_fast_tlscc'
1951 /// ::= 'amdgpu_vs'
1952 /// ::= 'amdgpu_ls'
1953 /// ::= 'amdgpu_hs'
1954 /// ::= 'amdgpu_es'
1955 /// ::= 'amdgpu_gs'
1956 /// ::= 'amdgpu_ps'
1957 /// ::= 'amdgpu_cs'
1958 /// ::= 'amdgpu_kernel'
1959 /// ::= 'tailcc'
1960 /// ::= 'cc' UINT
1962 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1963 switch (Lex.getKind()) {
1964 default: CC = CallingConv::C; return false;
1965 case lltok::kw_ccc: CC = CallingConv::C; break;
1966 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1967 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1968 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1969 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1970 case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
1971 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1972 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1973 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1974 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1975 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1976 case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
1977 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1978 case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
1979 case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
1980 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1981 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1982 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1983 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1984 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1985 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1986 case lltok::kw_win64cc: CC = CallingConv::Win64; break;
1987 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1988 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1989 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1990 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1991 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1992 case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
1993 case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
1994 case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
1995 case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
1996 case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
1997 case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
1998 case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
1999 case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
2000 case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
2001 case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
2002 case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
2003 case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
2004 case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
2005 case lltok::kw_tailcc: CC = CallingConv::Tail; break;
2006 case lltok::kw_cc: {
2007 Lex.Lex();
2008 return ParseUInt32(CC);
2012 Lex.Lex();
2013 return false;
2016 /// ParseMetadataAttachment
2017 /// ::= !dbg !42
2018 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
2019 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
2021 std::string Name = Lex.getStrVal();
2022 Kind = M->getMDKindID(Name);
2023 Lex.Lex();
2025 return ParseMDNode(MD);
2028 /// ParseInstructionMetadata
2029 /// ::= !dbg !42 (',' !dbg !57)*
2030 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
2031 do {
2032 if (Lex.getKind() != lltok::MetadataVar)
2033 return TokError("expected metadata after comma");
2035 unsigned MDK;
2036 MDNode *N;
2037 if (ParseMetadataAttachment(MDK, N))
2038 return true;
2040 Inst.setMetadata(MDK, N);
2041 if (MDK == LLVMContext::MD_tbaa)
2042 InstsWithTBAATag.push_back(&Inst);
2044 // If this is the end of the list, we're done.
2045 } while (EatIfPresent(lltok::comma));
2046 return false;
2049 /// ParseGlobalObjectMetadataAttachment
2050 /// ::= !dbg !57
2051 bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
2052 unsigned MDK;
2053 MDNode *N;
2054 if (ParseMetadataAttachment(MDK, N))
2055 return true;
2057 GO.addMetadata(MDK, *N);
2058 return false;
2061 /// ParseOptionalFunctionMetadata
2062 /// ::= (!dbg !57)*
2063 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
2064 while (Lex.getKind() == lltok::MetadataVar)
2065 if (ParseGlobalObjectMetadataAttachment(F))
2066 return true;
2067 return false;
2070 /// ParseOptionalAlignment
2071 /// ::= /* empty */
2072 /// ::= 'align' 4
2073 bool LLParser::ParseOptionalAlignment(MaybeAlign &Alignment) {
2074 Alignment = None;
2075 if (!EatIfPresent(lltok::kw_align))
2076 return false;
2077 LocTy AlignLoc = Lex.getLoc();
2078 uint32_t Value = 0;
2079 if (ParseUInt32(Value))
2080 return true;
2081 if (!isPowerOf2_32(Value))
2082 return Error(AlignLoc, "alignment is not a power of two");
2083 if (Value > Value::MaximumAlignment)
2084 return Error(AlignLoc, "huge alignments are not supported yet");
2085 Alignment = Align(Value);
2086 return false;
2089 /// ParseOptionalDerefAttrBytes
2090 /// ::= /* empty */
2091 /// ::= AttrKind '(' 4 ')'
2093 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
2094 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
2095 uint64_t &Bytes) {
2096 assert((AttrKind == lltok::kw_dereferenceable ||
2097 AttrKind == lltok::kw_dereferenceable_or_null) &&
2098 "contract!");
2100 Bytes = 0;
2101 if (!EatIfPresent(AttrKind))
2102 return false;
2103 LocTy ParenLoc = Lex.getLoc();
2104 if (!EatIfPresent(lltok::lparen))
2105 return Error(ParenLoc, "expected '('");
2106 LocTy DerefLoc = Lex.getLoc();
2107 if (ParseUInt64(Bytes)) return true;
2108 ParenLoc = Lex.getLoc();
2109 if (!EatIfPresent(lltok::rparen))
2110 return Error(ParenLoc, "expected ')'");
2111 if (!Bytes)
2112 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
2113 return false;
2116 /// ParseOptionalCommaAlign
2117 /// ::=
2118 /// ::= ',' align 4
2120 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2121 /// end.
2122 bool LLParser::ParseOptionalCommaAlign(MaybeAlign &Alignment,
2123 bool &AteExtraComma) {
2124 AteExtraComma = false;
2125 while (EatIfPresent(lltok::comma)) {
2126 // Metadata at the end is an early exit.
2127 if (Lex.getKind() == lltok::MetadataVar) {
2128 AteExtraComma = true;
2129 return false;
2132 if (Lex.getKind() != lltok::kw_align)
2133 return Error(Lex.getLoc(), "expected metadata or 'align'");
2135 if (ParseOptionalAlignment(Alignment)) return true;
2138 return false;
2141 /// ParseOptionalCommaAddrSpace
2142 /// ::=
2143 /// ::= ',' addrspace(1)
2145 /// This returns with AteExtraComma set to true if it ate an excess comma at the
2146 /// end.
2147 bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
2148 LocTy &Loc,
2149 bool &AteExtraComma) {
2150 AteExtraComma = false;
2151 while (EatIfPresent(lltok::comma)) {
2152 // Metadata at the end is an early exit.
2153 if (Lex.getKind() == lltok::MetadataVar) {
2154 AteExtraComma = true;
2155 return false;
2158 Loc = Lex.getLoc();
2159 if (Lex.getKind() != lltok::kw_addrspace)
2160 return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
2162 if (ParseOptionalAddrSpace(AddrSpace))
2163 return true;
2166 return false;
2169 bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
2170 Optional<unsigned> &HowManyArg) {
2171 Lex.Lex();
2173 auto StartParen = Lex.getLoc();
2174 if (!EatIfPresent(lltok::lparen))
2175 return Error(StartParen, "expected '('");
2177 if (ParseUInt32(BaseSizeArg))
2178 return true;
2180 if (EatIfPresent(lltok::comma)) {
2181 auto HowManyAt = Lex.getLoc();
2182 unsigned HowMany;
2183 if (ParseUInt32(HowMany))
2184 return true;
2185 if (HowMany == BaseSizeArg)
2186 return Error(HowManyAt,
2187 "'allocsize' indices can't refer to the same parameter");
2188 HowManyArg = HowMany;
2189 } else
2190 HowManyArg = None;
2192 auto EndParen = Lex.getLoc();
2193 if (!EatIfPresent(lltok::rparen))
2194 return Error(EndParen, "expected ')'");
2195 return false;
2198 /// ParseScopeAndOrdering
2199 /// if isAtomic: ::= SyncScope? AtomicOrdering
2200 /// else: ::=
2202 /// This sets Scope and Ordering to the parsed values.
2203 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
2204 AtomicOrdering &Ordering) {
2205 if (!isAtomic)
2206 return false;
2208 return ParseScope(SSID) || ParseOrdering(Ordering);
2211 /// ParseScope
2212 /// ::= syncscope("singlethread" | "<target scope>")?
2214 /// This sets synchronization scope ID to the ID of the parsed value.
2215 bool LLParser::ParseScope(SyncScope::ID &SSID) {
2216 SSID = SyncScope::System;
2217 if (EatIfPresent(lltok::kw_syncscope)) {
2218 auto StartParenAt = Lex.getLoc();
2219 if (!EatIfPresent(lltok::lparen))
2220 return Error(StartParenAt, "Expected '(' in syncscope");
2222 std::string SSN;
2223 auto SSNAt = Lex.getLoc();
2224 if (ParseStringConstant(SSN))
2225 return Error(SSNAt, "Expected synchronization scope name");
2227 auto EndParenAt = Lex.getLoc();
2228 if (!EatIfPresent(lltok::rparen))
2229 return Error(EndParenAt, "Expected ')' in syncscope");
2231 SSID = Context.getOrInsertSyncScopeID(SSN);
2234 return false;
2237 /// ParseOrdering
2238 /// ::= AtomicOrdering
2240 /// This sets Ordering to the parsed value.
2241 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
2242 switch (Lex.getKind()) {
2243 default: return TokError("Expected ordering on atomic instruction");
2244 case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
2245 case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
2246 // Not specified yet:
2247 // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
2248 case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
2249 case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
2250 case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
2251 case lltok::kw_seq_cst:
2252 Ordering = AtomicOrdering::SequentiallyConsistent;
2253 break;
2255 Lex.Lex();
2256 return false;
2259 /// ParseOptionalStackAlignment
2260 /// ::= /* empty */
2261 /// ::= 'alignstack' '(' 4 ')'
2262 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
2263 Alignment = 0;
2264 if (!EatIfPresent(lltok::kw_alignstack))
2265 return false;
2266 LocTy ParenLoc = Lex.getLoc();
2267 if (!EatIfPresent(lltok::lparen))
2268 return Error(ParenLoc, "expected '('");
2269 LocTy AlignLoc = Lex.getLoc();
2270 if (ParseUInt32(Alignment)) return true;
2271 ParenLoc = Lex.getLoc();
2272 if (!EatIfPresent(lltok::rparen))
2273 return Error(ParenLoc, "expected ')'");
2274 if (!isPowerOf2_32(Alignment))
2275 return Error(AlignLoc, "stack alignment is not a power of two");
2276 return false;
2279 /// ParseIndexList - This parses the index list for an insert/extractvalue
2280 /// instruction. This sets AteExtraComma in the case where we eat an extra
2281 /// comma at the end of the line and find that it is followed by metadata.
2282 /// Clients that don't allow metadata can call the version of this function that
2283 /// only takes one argument.
2285 /// ParseIndexList
2286 /// ::= (',' uint32)+
2288 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
2289 bool &AteExtraComma) {
2290 AteExtraComma = false;
2292 if (Lex.getKind() != lltok::comma)
2293 return TokError("expected ',' as start of index list");
2295 while (EatIfPresent(lltok::comma)) {
2296 if (Lex.getKind() == lltok::MetadataVar) {
2297 if (Indices.empty()) return TokError("expected index");
2298 AteExtraComma = true;
2299 return false;
2301 unsigned Idx = 0;
2302 if (ParseUInt32(Idx)) return true;
2303 Indices.push_back(Idx);
2306 return false;
2309 //===----------------------------------------------------------------------===//
2310 // Type Parsing.
2311 //===----------------------------------------------------------------------===//
2313 /// ParseType - Parse a type.
2314 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
2315 SMLoc TypeLoc = Lex.getLoc();
2316 switch (Lex.getKind()) {
2317 default:
2318 return TokError(Msg);
2319 case lltok::Type:
2320 // Type ::= 'float' | 'void' (etc)
2321 Result = Lex.getTyVal();
2322 Lex.Lex();
2323 break;
2324 case lltok::lbrace:
2325 // Type ::= StructType
2326 if (ParseAnonStructType(Result, false))
2327 return true;
2328 break;
2329 case lltok::lsquare:
2330 // Type ::= '[' ... ']'
2331 Lex.Lex(); // eat the lsquare.
2332 if (ParseArrayVectorType(Result, false))
2333 return true;
2334 break;
2335 case lltok::less: // Either vector or packed struct.
2336 // Type ::= '<' ... '>'
2337 Lex.Lex();
2338 if (Lex.getKind() == lltok::lbrace) {
2339 if (ParseAnonStructType(Result, true) ||
2340 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
2341 return true;
2342 } else if (ParseArrayVectorType(Result, true))
2343 return true;
2344 break;
2345 case lltok::LocalVar: {
2346 // Type ::= %foo
2347 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
2349 // If the type hasn't been defined yet, create a forward definition and
2350 // remember where that forward def'n was seen (in case it never is defined).
2351 if (!Entry.first) {
2352 Entry.first = StructType::create(Context, Lex.getStrVal());
2353 Entry.second = Lex.getLoc();
2355 Result = Entry.first;
2356 Lex.Lex();
2357 break;
2360 case lltok::LocalVarID: {
2361 // Type ::= %4
2362 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
2364 // If the type hasn't been defined yet, create a forward definition and
2365 // remember where that forward def'n was seen (in case it never is defined).
2366 if (!Entry.first) {
2367 Entry.first = StructType::create(Context);
2368 Entry.second = Lex.getLoc();
2370 Result = Entry.first;
2371 Lex.Lex();
2372 break;
2376 // Parse the type suffixes.
2377 while (true) {
2378 switch (Lex.getKind()) {
2379 // End of type.
2380 default:
2381 if (!AllowVoid && Result->isVoidTy())
2382 return Error(TypeLoc, "void type only allowed for function results");
2383 return false;
2385 // Type ::= Type '*'
2386 case lltok::star:
2387 if (Result->isLabelTy())
2388 return TokError("basic block pointers are invalid");
2389 if (Result->isVoidTy())
2390 return TokError("pointers to void are invalid - use i8* instead");
2391 if (!PointerType::isValidElementType(Result))
2392 return TokError("pointer to this type is invalid");
2393 Result = PointerType::getUnqual(Result);
2394 Lex.Lex();
2395 break;
2397 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
2398 case lltok::kw_addrspace: {
2399 if (Result->isLabelTy())
2400 return TokError("basic block pointers are invalid");
2401 if (Result->isVoidTy())
2402 return TokError("pointers to void are invalid; use i8* instead");
2403 if (!PointerType::isValidElementType(Result))
2404 return TokError("pointer to this type is invalid");
2405 unsigned AddrSpace;
2406 if (ParseOptionalAddrSpace(AddrSpace) ||
2407 ParseToken(lltok::star, "expected '*' in address space"))
2408 return true;
2410 Result = PointerType::get(Result, AddrSpace);
2411 break;
2414 /// Types '(' ArgTypeListI ')' OptFuncAttrs
2415 case lltok::lparen:
2416 if (ParseFunctionType(Result))
2417 return true;
2418 break;
2423 /// ParseParameterList
2424 /// ::= '(' ')'
2425 /// ::= '(' Arg (',' Arg)* ')'
2426 /// Arg
2427 /// ::= Type OptionalAttributes Value OptionalAttributes
2428 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
2429 PerFunctionState &PFS, bool IsMustTailCall,
2430 bool InVarArgsFunc) {
2431 if (ParseToken(lltok::lparen, "expected '(' in call"))
2432 return true;
2434 while (Lex.getKind() != lltok::rparen) {
2435 // If this isn't the first argument, we need a comma.
2436 if (!ArgList.empty() &&
2437 ParseToken(lltok::comma, "expected ',' in argument list"))
2438 return true;
2440 // Parse an ellipsis if this is a musttail call in a variadic function.
2441 if (Lex.getKind() == lltok::dotdotdot) {
2442 const char *Msg = "unexpected ellipsis in argument list for ";
2443 if (!IsMustTailCall)
2444 return TokError(Twine(Msg) + "non-musttail call");
2445 if (!InVarArgsFunc)
2446 return TokError(Twine(Msg) + "musttail call in non-varargs function");
2447 Lex.Lex(); // Lex the '...', it is purely for readability.
2448 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2451 // Parse the argument.
2452 LocTy ArgLoc;
2453 Type *ArgTy = nullptr;
2454 AttrBuilder ArgAttrs;
2455 Value *V;
2456 if (ParseType(ArgTy, ArgLoc))
2457 return true;
2459 if (ArgTy->isMetadataTy()) {
2460 if (ParseMetadataAsValue(V, PFS))
2461 return true;
2462 } else {
2463 // Otherwise, handle normal operands.
2464 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
2465 return true;
2467 ArgList.push_back(ParamInfo(
2468 ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
2471 if (IsMustTailCall && InVarArgsFunc)
2472 return TokError("expected '...' at end of argument list for musttail call "
2473 "in varargs function");
2475 Lex.Lex(); // Lex the ')'.
2476 return false;
2479 /// ParseByValWithOptionalType
2480 /// ::= byval
2481 /// ::= byval(<ty>)
2482 bool LLParser::ParseByValWithOptionalType(Type *&Result) {
2483 Result = nullptr;
2484 if (!EatIfPresent(lltok::kw_byval))
2485 return true;
2486 if (!EatIfPresent(lltok::lparen))
2487 return false;
2488 if (ParseType(Result))
2489 return true;
2490 if (!EatIfPresent(lltok::rparen))
2491 return Error(Lex.getLoc(), "expected ')'");
2492 return false;
2495 /// ParseOptionalOperandBundles
2496 /// ::= /*empty*/
2497 /// ::= '[' OperandBundle [, OperandBundle ]* ']'
2499 /// OperandBundle
2500 /// ::= bundle-tag '(' ')'
2501 /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
2503 /// bundle-tag ::= String Constant
2504 bool LLParser::ParseOptionalOperandBundles(
2505 SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
2506 LocTy BeginLoc = Lex.getLoc();
2507 if (!EatIfPresent(lltok::lsquare))
2508 return false;
2510 while (Lex.getKind() != lltok::rsquare) {
2511 // If this isn't the first operand bundle, we need a comma.
2512 if (!BundleList.empty() &&
2513 ParseToken(lltok::comma, "expected ',' in input list"))
2514 return true;
2516 std::string Tag;
2517 if (ParseStringConstant(Tag))
2518 return true;
2520 if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
2521 return true;
2523 std::vector<Value *> Inputs;
2524 while (Lex.getKind() != lltok::rparen) {
2525 // If this isn't the first input, we need a comma.
2526 if (!Inputs.empty() &&
2527 ParseToken(lltok::comma, "expected ',' in input list"))
2528 return true;
2530 Type *Ty = nullptr;
2531 Value *Input = nullptr;
2532 if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
2533 return true;
2534 Inputs.push_back(Input);
2537 BundleList.emplace_back(std::move(Tag), std::move(Inputs));
2539 Lex.Lex(); // Lex the ')'.
2542 if (BundleList.empty())
2543 return Error(BeginLoc, "operand bundle set must not be empty");
2545 Lex.Lex(); // Lex the ']'.
2546 return false;
2549 /// ParseArgumentList - Parse the argument list for a function type or function
2550 /// prototype.
2551 /// ::= '(' ArgTypeListI ')'
2552 /// ArgTypeListI
2553 /// ::= /*empty*/
2554 /// ::= '...'
2555 /// ::= ArgTypeList ',' '...'
2556 /// ::= ArgType (',' ArgType)*
2558 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
2559 bool &isVarArg){
2560 unsigned CurValID = 0;
2561 isVarArg = false;
2562 assert(Lex.getKind() == lltok::lparen);
2563 Lex.Lex(); // eat the (.
2565 if (Lex.getKind() == lltok::rparen) {
2566 // empty
2567 } else if (Lex.getKind() == lltok::dotdotdot) {
2568 isVarArg = true;
2569 Lex.Lex();
2570 } else {
2571 LocTy TypeLoc = Lex.getLoc();
2572 Type *ArgTy = nullptr;
2573 AttrBuilder Attrs;
2574 std::string Name;
2576 if (ParseType(ArgTy) ||
2577 ParseOptionalParamAttrs(Attrs)) return true;
2579 if (ArgTy->isVoidTy())
2580 return Error(TypeLoc, "argument can not have void type");
2582 if (Lex.getKind() == lltok::LocalVar) {
2583 Name = Lex.getStrVal();
2584 Lex.Lex();
2585 } else if (Lex.getKind() == lltok::LocalVarID) {
2586 if (Lex.getUIntVal() != CurValID)
2587 return Error(TypeLoc, "argument expected to be numbered '%" +
2588 Twine(CurValID) + "'");
2589 ++CurValID;
2590 Lex.Lex();
2593 if (!FunctionType::isValidArgumentType(ArgTy))
2594 return Error(TypeLoc, "invalid type for function argument");
2596 ArgList.emplace_back(TypeLoc, ArgTy,
2597 AttributeSet::get(ArgTy->getContext(), Attrs),
2598 std::move(Name));
2600 while (EatIfPresent(lltok::comma)) {
2601 // Handle ... at end of arg list.
2602 if (EatIfPresent(lltok::dotdotdot)) {
2603 isVarArg = true;
2604 break;
2607 // Otherwise must be an argument type.
2608 TypeLoc = Lex.getLoc();
2609 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
2611 if (ArgTy->isVoidTy())
2612 return Error(TypeLoc, "argument can not have void type");
2614 if (Lex.getKind() == lltok::LocalVar) {
2615 Name = Lex.getStrVal();
2616 Lex.Lex();
2617 } else {
2618 if (Lex.getKind() == lltok::LocalVarID) {
2619 if (Lex.getUIntVal() != CurValID)
2620 return Error(TypeLoc, "argument expected to be numbered '%" +
2621 Twine(CurValID) + "'");
2622 Lex.Lex();
2624 ++CurValID;
2625 Name = "";
2628 if (!ArgTy->isFirstClassType())
2629 return Error(TypeLoc, "invalid type for function argument");
2631 ArgList.emplace_back(TypeLoc, ArgTy,
2632 AttributeSet::get(ArgTy->getContext(), Attrs),
2633 std::move(Name));
2637 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
2640 /// ParseFunctionType
2641 /// ::= Type ArgumentList OptionalAttrs
2642 bool LLParser::ParseFunctionType(Type *&Result) {
2643 assert(Lex.getKind() == lltok::lparen);
2645 if (!FunctionType::isValidReturnType(Result))
2646 return TokError("invalid function return type");
2648 SmallVector<ArgInfo, 8> ArgList;
2649 bool isVarArg;
2650 if (ParseArgumentList(ArgList, isVarArg))
2651 return true;
2653 // Reject names on the arguments lists.
2654 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
2655 if (!ArgList[i].Name.empty())
2656 return Error(ArgList[i].Loc, "argument name invalid in function type");
2657 if (ArgList[i].Attrs.hasAttributes())
2658 return Error(ArgList[i].Loc,
2659 "argument attributes invalid in function type");
2662 SmallVector<Type*, 16> ArgListTy;
2663 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2664 ArgListTy.push_back(ArgList[i].Ty);
2666 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2667 return false;
2670 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2671 /// other structs.
2672 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2673 SmallVector<Type*, 8> Elts;
2674 if (ParseStructBody(Elts)) return true;
2676 Result = StructType::get(Context, Elts, Packed);
2677 return false;
2680 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2681 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2682 std::pair<Type*, LocTy> &Entry,
2683 Type *&ResultTy) {
2684 // If the type was already defined, diagnose the redefinition.
2685 if (Entry.first && !Entry.second.isValid())
2686 return Error(TypeLoc, "redefinition of type");
2688 // If we have opaque, just return without filling in the definition for the
2689 // struct. This counts as a definition as far as the .ll file goes.
2690 if (EatIfPresent(lltok::kw_opaque)) {
2691 // This type is being defined, so clear the location to indicate this.
2692 Entry.second = SMLoc();
2694 // If this type number has never been uttered, create it.
2695 if (!Entry.first)
2696 Entry.first = StructType::create(Context, Name);
2697 ResultTy = Entry.first;
2698 return false;
2701 // If the type starts with '<', then it is either a packed struct or a vector.
2702 bool isPacked = EatIfPresent(lltok::less);
2704 // If we don't have a struct, then we have a random type alias, which we
2705 // accept for compatibility with old files. These types are not allowed to be
2706 // forward referenced and not allowed to be recursive.
2707 if (Lex.getKind() != lltok::lbrace) {
2708 if (Entry.first)
2709 return Error(TypeLoc, "forward references to non-struct type");
2711 ResultTy = nullptr;
2712 if (isPacked)
2713 return ParseArrayVectorType(ResultTy, true);
2714 return ParseType(ResultTy);
2717 // This type is being defined, so clear the location to indicate this.
2718 Entry.second = SMLoc();
2720 // If this type number has never been uttered, create it.
2721 if (!Entry.first)
2722 Entry.first = StructType::create(Context, Name);
2724 StructType *STy = cast<StructType>(Entry.first);
2726 SmallVector<Type*, 8> Body;
2727 if (ParseStructBody(Body) ||
2728 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2729 return true;
2731 STy->setBody(Body, isPacked);
2732 ResultTy = STy;
2733 return false;
2736 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2737 /// StructType
2738 /// ::= '{' '}'
2739 /// ::= '{' Type (',' Type)* '}'
2740 /// ::= '<' '{' '}' '>'
2741 /// ::= '<' '{' Type (',' Type)* '}' '>'
2742 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2743 assert(Lex.getKind() == lltok::lbrace);
2744 Lex.Lex(); // Consume the '{'
2746 // Handle the empty struct.
2747 if (EatIfPresent(lltok::rbrace))
2748 return false;
2750 LocTy EltTyLoc = Lex.getLoc();
2751 Type *Ty = nullptr;
2752 if (ParseType(Ty)) return true;
2753 Body.push_back(Ty);
2755 if (!StructType::isValidElementType(Ty))
2756 return Error(EltTyLoc, "invalid element type for struct");
2758 while (EatIfPresent(lltok::comma)) {
2759 EltTyLoc = Lex.getLoc();
2760 if (ParseType(Ty)) return true;
2762 if (!StructType::isValidElementType(Ty))
2763 return Error(EltTyLoc, "invalid element type for struct");
2765 Body.push_back(Ty);
2768 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2771 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2772 /// token has already been consumed.
2773 /// Type
2774 /// ::= '[' APSINTVAL 'x' Types ']'
2775 /// ::= '<' APSINTVAL 'x' Types '>'
2776 /// ::= '<' 'vscale' 'x' APSINTVAL 'x' Types '>'
2777 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2778 bool Scalable = false;
2780 if (isVector && Lex.getKind() == lltok::kw_vscale) {
2781 Lex.Lex(); // consume the 'vscale'
2782 if (ParseToken(lltok::kw_x, "expected 'x' after vscale"))
2783 return true;
2785 Scalable = true;
2788 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2789 Lex.getAPSIntVal().getBitWidth() > 64)
2790 return TokError("expected number in address space");
2792 LocTy SizeLoc = Lex.getLoc();
2793 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2794 Lex.Lex();
2796 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2797 return true;
2799 LocTy TypeLoc = Lex.getLoc();
2800 Type *EltTy = nullptr;
2801 if (ParseType(EltTy)) return true;
2803 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2804 "expected end of sequential type"))
2805 return true;
2807 if (isVector) {
2808 if (Size == 0)
2809 return Error(SizeLoc, "zero element vector is illegal");
2810 if ((unsigned)Size != Size)
2811 return Error(SizeLoc, "size too large for vector");
2812 if (!VectorType::isValidElementType(EltTy))
2813 return Error(TypeLoc, "invalid vector element type");
2814 Result = VectorType::get(EltTy, unsigned(Size), Scalable);
2815 } else {
2816 if (!ArrayType::isValidElementType(EltTy))
2817 return Error(TypeLoc, "invalid array element type");
2818 Result = ArrayType::get(EltTy, Size);
2820 return false;
2823 //===----------------------------------------------------------------------===//
2824 // Function Semantic Analysis.
2825 //===----------------------------------------------------------------------===//
2827 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2828 int functionNumber)
2829 : P(p), F(f), FunctionNumber(functionNumber) {
2831 // Insert unnamed arguments into the NumberedVals list.
2832 for (Argument &A : F.args())
2833 if (!A.hasName())
2834 NumberedVals.push_back(&A);
2837 LLParser::PerFunctionState::~PerFunctionState() {
2838 // If there were any forward referenced non-basicblock values, delete them.
2840 for (const auto &P : ForwardRefVals) {
2841 if (isa<BasicBlock>(P.second.first))
2842 continue;
2843 P.second.first->replaceAllUsesWith(
2844 UndefValue::get(P.second.first->getType()));
2845 P.second.first->deleteValue();
2848 for (const auto &P : ForwardRefValIDs) {
2849 if (isa<BasicBlock>(P.second.first))
2850 continue;
2851 P.second.first->replaceAllUsesWith(
2852 UndefValue::get(P.second.first->getType()));
2853 P.second.first->deleteValue();
2857 bool LLParser::PerFunctionState::FinishFunction() {
2858 if (!ForwardRefVals.empty())
2859 return P.Error(ForwardRefVals.begin()->second.second,
2860 "use of undefined value '%" + ForwardRefVals.begin()->first +
2861 "'");
2862 if (!ForwardRefValIDs.empty())
2863 return P.Error(ForwardRefValIDs.begin()->second.second,
2864 "use of undefined value '%" +
2865 Twine(ForwardRefValIDs.begin()->first) + "'");
2866 return false;
2869 /// GetVal - Get a value with the specified name or ID, creating a
2870 /// forward reference record if needed. This can return null if the value
2871 /// exists but does not have the right type.
2872 Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
2873 LocTy Loc, bool IsCall) {
2874 // Look this name up in the normal function symbol table.
2875 Value *Val = F.getValueSymbolTable()->lookup(Name);
2877 // If this is a forward reference for the value, see if we already created a
2878 // forward ref record.
2879 if (!Val) {
2880 auto I = ForwardRefVals.find(Name);
2881 if (I != ForwardRefVals.end())
2882 Val = I->second.first;
2885 // If we have the value in the symbol table or fwd-ref table, return it.
2886 if (Val)
2887 return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
2889 // Don't make placeholders with invalid type.
2890 if (!Ty->isFirstClassType()) {
2891 P.Error(Loc, "invalid use of a non-first-class type");
2892 return nullptr;
2895 // Otherwise, create a new forward reference for this value and remember it.
2896 Value *FwdVal;
2897 if (Ty->isLabelTy()) {
2898 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2899 } else {
2900 FwdVal = new Argument(Ty, Name);
2903 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2904 return FwdVal;
2907 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
2908 bool IsCall) {
2909 // Look this name up in the normal function symbol table.
2910 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2912 // If this is a forward reference for the value, see if we already created a
2913 // forward ref record.
2914 if (!Val) {
2915 auto I = ForwardRefValIDs.find(ID);
2916 if (I != ForwardRefValIDs.end())
2917 Val = I->second.first;
2920 // If we have the value in the symbol table or fwd-ref table, return it.
2921 if (Val)
2922 return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
2924 if (!Ty->isFirstClassType()) {
2925 P.Error(Loc, "invalid use of a non-first-class type");
2926 return nullptr;
2929 // Otherwise, create a new forward reference for this value and remember it.
2930 Value *FwdVal;
2931 if (Ty->isLabelTy()) {
2932 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2933 } else {
2934 FwdVal = new Argument(Ty);
2937 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2938 return FwdVal;
2941 /// SetInstName - After an instruction is parsed and inserted into its
2942 /// basic block, this installs its name.
2943 bool LLParser::PerFunctionState::SetInstName(int NameID,
2944 const std::string &NameStr,
2945 LocTy NameLoc, Instruction *Inst) {
2946 // If this instruction has void type, it cannot have a name or ID specified.
2947 if (Inst->getType()->isVoidTy()) {
2948 if (NameID != -1 || !NameStr.empty())
2949 return P.Error(NameLoc, "instructions returning void cannot have a name");
2950 return false;
2953 // If this was a numbered instruction, verify that the instruction is the
2954 // expected value and resolve any forward references.
2955 if (NameStr.empty()) {
2956 // If neither a name nor an ID was specified, just use the next ID.
2957 if (NameID == -1)
2958 NameID = NumberedVals.size();
2960 if (unsigned(NameID) != NumberedVals.size())
2961 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2962 Twine(NumberedVals.size()) + "'");
2964 auto FI = ForwardRefValIDs.find(NameID);
2965 if (FI != ForwardRefValIDs.end()) {
2966 Value *Sentinel = FI->second.first;
2967 if (Sentinel->getType() != Inst->getType())
2968 return P.Error(NameLoc, "instruction forward referenced with type '" +
2969 getTypeString(FI->second.first->getType()) + "'");
2971 Sentinel->replaceAllUsesWith(Inst);
2972 Sentinel->deleteValue();
2973 ForwardRefValIDs.erase(FI);
2976 NumberedVals.push_back(Inst);
2977 return false;
2980 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2981 auto FI = ForwardRefVals.find(NameStr);
2982 if (FI != ForwardRefVals.end()) {
2983 Value *Sentinel = FI->second.first;
2984 if (Sentinel->getType() != Inst->getType())
2985 return P.Error(NameLoc, "instruction forward referenced with type '" +
2986 getTypeString(FI->second.first->getType()) + "'");
2988 Sentinel->replaceAllUsesWith(Inst);
2989 Sentinel->deleteValue();
2990 ForwardRefVals.erase(FI);
2993 // Set the name on the instruction.
2994 Inst->setName(NameStr);
2996 if (Inst->getName() != NameStr)
2997 return P.Error(NameLoc, "multiple definition of local value named '" +
2998 NameStr + "'");
2999 return false;
3002 /// GetBB - Get a basic block with the specified name or ID, creating a
3003 /// forward reference record if needed.
3004 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
3005 LocTy Loc) {
3006 return dyn_cast_or_null<BasicBlock>(
3007 GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
3010 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
3011 return dyn_cast_or_null<BasicBlock>(
3012 GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
3015 /// DefineBB - Define the specified basic block, which is either named or
3016 /// unnamed. If there is an error, this returns null otherwise it returns
3017 /// the block being defined.
3018 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
3019 int NameID, LocTy Loc) {
3020 BasicBlock *BB;
3021 if (Name.empty()) {
3022 if (NameID != -1 && unsigned(NameID) != NumberedVals.size()) {
3023 P.Error(Loc, "label expected to be numbered '" +
3024 Twine(NumberedVals.size()) + "'");
3025 return nullptr;
3027 BB = GetBB(NumberedVals.size(), Loc);
3028 if (!BB) {
3029 P.Error(Loc, "unable to create block numbered '" +
3030 Twine(NumberedVals.size()) + "'");
3031 return nullptr;
3033 } else {
3034 BB = GetBB(Name, Loc);
3035 if (!BB) {
3036 P.Error(Loc, "unable to create block named '" + Name + "'");
3037 return nullptr;
3041 // Move the block to the end of the function. Forward ref'd blocks are
3042 // inserted wherever they happen to be referenced.
3043 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
3045 // Remove the block from forward ref sets.
3046 if (Name.empty()) {
3047 ForwardRefValIDs.erase(NumberedVals.size());
3048 NumberedVals.push_back(BB);
3049 } else {
3050 // BB forward references are already in the function symbol table.
3051 ForwardRefVals.erase(Name);
3054 return BB;
3057 //===----------------------------------------------------------------------===//
3058 // Constants.
3059 //===----------------------------------------------------------------------===//
3061 /// ParseValID - Parse an abstract value that doesn't necessarily have a
3062 /// type implied. For example, if we parse "4" we don't know what integer type
3063 /// it has. The value will later be combined with its type and checked for
3064 /// sanity. PFS is used to convert function-local operands of metadata (since
3065 /// metadata operands are not just parsed here but also converted to values).
3066 /// PFS can be null when we are not parsing metadata values inside a function.
3067 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
3068 ID.Loc = Lex.getLoc();
3069 switch (Lex.getKind()) {
3070 default: return TokError("expected value token");
3071 case lltok::GlobalID: // @42
3072 ID.UIntVal = Lex.getUIntVal();
3073 ID.Kind = ValID::t_GlobalID;
3074 break;
3075 case lltok::GlobalVar: // @foo
3076 ID.StrVal = Lex.getStrVal();
3077 ID.Kind = ValID::t_GlobalName;
3078 break;
3079 case lltok::LocalVarID: // %42
3080 ID.UIntVal = Lex.getUIntVal();
3081 ID.Kind = ValID::t_LocalID;
3082 break;
3083 case lltok::LocalVar: // %foo
3084 ID.StrVal = Lex.getStrVal();
3085 ID.Kind = ValID::t_LocalName;
3086 break;
3087 case lltok::APSInt:
3088 ID.APSIntVal = Lex.getAPSIntVal();
3089 ID.Kind = ValID::t_APSInt;
3090 break;
3091 case lltok::APFloat:
3092 ID.APFloatVal = Lex.getAPFloatVal();
3093 ID.Kind = ValID::t_APFloat;
3094 break;
3095 case lltok::kw_true:
3096 ID.ConstantVal = ConstantInt::getTrue(Context);
3097 ID.Kind = ValID::t_Constant;
3098 break;
3099 case lltok::kw_false:
3100 ID.ConstantVal = ConstantInt::getFalse(Context);
3101 ID.Kind = ValID::t_Constant;
3102 break;
3103 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
3104 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
3105 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
3106 case lltok::kw_none: ID.Kind = ValID::t_None; break;
3108 case lltok::lbrace: {
3109 // ValID ::= '{' ConstVector '}'
3110 Lex.Lex();
3111 SmallVector<Constant*, 16> Elts;
3112 if (ParseGlobalValueVector(Elts) ||
3113 ParseToken(lltok::rbrace, "expected end of struct constant"))
3114 return true;
3116 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3117 ID.UIntVal = Elts.size();
3118 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3119 Elts.size() * sizeof(Elts[0]));
3120 ID.Kind = ValID::t_ConstantStruct;
3121 return false;
3123 case lltok::less: {
3124 // ValID ::= '<' ConstVector '>' --> Vector.
3125 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
3126 Lex.Lex();
3127 bool isPackedStruct = EatIfPresent(lltok::lbrace);
3129 SmallVector<Constant*, 16> Elts;
3130 LocTy FirstEltLoc = Lex.getLoc();
3131 if (ParseGlobalValueVector(Elts) ||
3132 (isPackedStruct &&
3133 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
3134 ParseToken(lltok::greater, "expected end of constant"))
3135 return true;
3137 if (isPackedStruct) {
3138 ID.ConstantStructElts = std::make_unique<Constant *[]>(Elts.size());
3139 memcpy(ID.ConstantStructElts.get(), Elts.data(),
3140 Elts.size() * sizeof(Elts[0]));
3141 ID.UIntVal = Elts.size();
3142 ID.Kind = ValID::t_PackedConstantStruct;
3143 return false;
3146 if (Elts.empty())
3147 return Error(ID.Loc, "constant vector must not be empty");
3149 if (!Elts[0]->getType()->isIntegerTy() &&
3150 !Elts[0]->getType()->isFloatingPointTy() &&
3151 !Elts[0]->getType()->isPointerTy())
3152 return Error(FirstEltLoc,
3153 "vector elements must have integer, pointer or floating point type");
3155 // Verify that all the vector elements have the same type.
3156 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
3157 if (Elts[i]->getType() != Elts[0]->getType())
3158 return Error(FirstEltLoc,
3159 "vector element #" + Twine(i) +
3160 " is not of type '" + getTypeString(Elts[0]->getType()));
3162 ID.ConstantVal = ConstantVector::get(Elts);
3163 ID.Kind = ValID::t_Constant;
3164 return false;
3166 case lltok::lsquare: { // Array Constant
3167 Lex.Lex();
3168 SmallVector<Constant*, 16> Elts;
3169 LocTy FirstEltLoc = Lex.getLoc();
3170 if (ParseGlobalValueVector(Elts) ||
3171 ParseToken(lltok::rsquare, "expected end of array constant"))
3172 return true;
3174 // Handle empty element.
3175 if (Elts.empty()) {
3176 // Use undef instead of an array because it's inconvenient to determine
3177 // the element type at this point, there being no elements to examine.
3178 ID.Kind = ValID::t_EmptyArray;
3179 return false;
3182 if (!Elts[0]->getType()->isFirstClassType())
3183 return Error(FirstEltLoc, "invalid array element type: " +
3184 getTypeString(Elts[0]->getType()));
3186 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
3188 // Verify all elements are correct type!
3189 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
3190 if (Elts[i]->getType() != Elts[0]->getType())
3191 return Error(FirstEltLoc,
3192 "array element #" + Twine(i) +
3193 " is not of type '" + getTypeString(Elts[0]->getType()));
3196 ID.ConstantVal = ConstantArray::get(ATy, Elts);
3197 ID.Kind = ValID::t_Constant;
3198 return false;
3200 case lltok::kw_c: // c "foo"
3201 Lex.Lex();
3202 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
3203 false);
3204 if (ParseToken(lltok::StringConstant, "expected string")) return true;
3205 ID.Kind = ValID::t_Constant;
3206 return false;
3208 case lltok::kw_asm: {
3209 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
3210 // STRINGCONSTANT
3211 bool HasSideEffect, AlignStack, AsmDialect;
3212 Lex.Lex();
3213 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
3214 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
3215 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
3216 ParseStringConstant(ID.StrVal) ||
3217 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
3218 ParseToken(lltok::StringConstant, "expected constraint string"))
3219 return true;
3220 ID.StrVal2 = Lex.getStrVal();
3221 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
3222 (unsigned(AsmDialect)<<2);
3223 ID.Kind = ValID::t_InlineAsm;
3224 return false;
3227 case lltok::kw_blockaddress: {
3228 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
3229 Lex.Lex();
3231 ValID Fn, Label;
3233 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
3234 ParseValID(Fn) ||
3235 ParseToken(lltok::comma, "expected comma in block address expression")||
3236 ParseValID(Label) ||
3237 ParseToken(lltok::rparen, "expected ')' in block address expression"))
3238 return true;
3240 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
3241 return Error(Fn.Loc, "expected function name in blockaddress");
3242 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
3243 return Error(Label.Loc, "expected basic block name in blockaddress");
3245 // Try to find the function (but skip it if it's forward-referenced).
3246 GlobalValue *GV = nullptr;
3247 if (Fn.Kind == ValID::t_GlobalID) {
3248 if (Fn.UIntVal < NumberedVals.size())
3249 GV = NumberedVals[Fn.UIntVal];
3250 } else if (!ForwardRefVals.count(Fn.StrVal)) {
3251 GV = M->getNamedValue(Fn.StrVal);
3253 Function *F = nullptr;
3254 if (GV) {
3255 // Confirm that it's actually a function with a definition.
3256 if (!isa<Function>(GV))
3257 return Error(Fn.Loc, "expected function name in blockaddress");
3258 F = cast<Function>(GV);
3259 if (F->isDeclaration())
3260 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
3263 if (!F) {
3264 // Make a global variable as a placeholder for this reference.
3265 GlobalValue *&FwdRef =
3266 ForwardRefBlockAddresses.insert(std::make_pair(
3267 std::move(Fn),
3268 std::map<ValID, GlobalValue *>()))
3269 .first->second.insert(std::make_pair(std::move(Label), nullptr))
3270 .first->second;
3271 if (!FwdRef)
3272 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
3273 GlobalValue::InternalLinkage, nullptr, "");
3274 ID.ConstantVal = FwdRef;
3275 ID.Kind = ValID::t_Constant;
3276 return false;
3279 // We found the function; now find the basic block. Don't use PFS, since we
3280 // might be inside a constant expression.
3281 BasicBlock *BB;
3282 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
3283 if (Label.Kind == ValID::t_LocalID)
3284 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
3285 else
3286 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
3287 if (!BB)
3288 return Error(Label.Loc, "referenced value is not a basic block");
3289 } else {
3290 if (Label.Kind == ValID::t_LocalID)
3291 return Error(Label.Loc, "cannot take address of numeric label after "
3292 "the function is defined");
3293 BB = dyn_cast_or_null<BasicBlock>(
3294 F->getValueSymbolTable()->lookup(Label.StrVal));
3295 if (!BB)
3296 return Error(Label.Loc, "referenced value is not a basic block");
3299 ID.ConstantVal = BlockAddress::get(F, BB);
3300 ID.Kind = ValID::t_Constant;
3301 return false;
3304 case lltok::kw_trunc:
3305 case lltok::kw_zext:
3306 case lltok::kw_sext:
3307 case lltok::kw_fptrunc:
3308 case lltok::kw_fpext:
3309 case lltok::kw_bitcast:
3310 case lltok::kw_addrspacecast:
3311 case lltok::kw_uitofp:
3312 case lltok::kw_sitofp:
3313 case lltok::kw_fptoui:
3314 case lltok::kw_fptosi:
3315 case lltok::kw_inttoptr:
3316 case lltok::kw_ptrtoint: {
3317 unsigned Opc = Lex.getUIntVal();
3318 Type *DestTy = nullptr;
3319 Constant *SrcVal;
3320 Lex.Lex();
3321 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
3322 ParseGlobalTypeAndValue(SrcVal) ||
3323 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
3324 ParseType(DestTy) ||
3325 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
3326 return true;
3327 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
3328 return Error(ID.Loc, "invalid cast opcode for cast from '" +
3329 getTypeString(SrcVal->getType()) + "' to '" +
3330 getTypeString(DestTy) + "'");
3331 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
3332 SrcVal, DestTy);
3333 ID.Kind = ValID::t_Constant;
3334 return false;
3336 case lltok::kw_extractvalue: {
3337 Lex.Lex();
3338 Constant *Val;
3339 SmallVector<unsigned, 4> Indices;
3340 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
3341 ParseGlobalTypeAndValue(Val) ||
3342 ParseIndexList(Indices) ||
3343 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
3344 return true;
3346 if (!Val->getType()->isAggregateType())
3347 return Error(ID.Loc, "extractvalue operand must be aggregate type");
3348 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
3349 return Error(ID.Loc, "invalid indices for extractvalue");
3350 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
3351 ID.Kind = ValID::t_Constant;
3352 return false;
3354 case lltok::kw_insertvalue: {
3355 Lex.Lex();
3356 Constant *Val0, *Val1;
3357 SmallVector<unsigned, 4> Indices;
3358 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
3359 ParseGlobalTypeAndValue(Val0) ||
3360 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
3361 ParseGlobalTypeAndValue(Val1) ||
3362 ParseIndexList(Indices) ||
3363 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
3364 return true;
3365 if (!Val0->getType()->isAggregateType())
3366 return Error(ID.Loc, "insertvalue operand must be aggregate type");
3367 Type *IndexedType =
3368 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
3369 if (!IndexedType)
3370 return Error(ID.Loc, "invalid indices for insertvalue");
3371 if (IndexedType != Val1->getType())
3372 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
3373 getTypeString(Val1->getType()) +
3374 "' instead of '" + getTypeString(IndexedType) +
3375 "'");
3376 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
3377 ID.Kind = ValID::t_Constant;
3378 return false;
3380 case lltok::kw_icmp:
3381 case lltok::kw_fcmp: {
3382 unsigned PredVal, Opc = Lex.getUIntVal();
3383 Constant *Val0, *Val1;
3384 Lex.Lex();
3385 if (ParseCmpPredicate(PredVal, Opc) ||
3386 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
3387 ParseGlobalTypeAndValue(Val0) ||
3388 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
3389 ParseGlobalTypeAndValue(Val1) ||
3390 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
3391 return true;
3393 if (Val0->getType() != Val1->getType())
3394 return Error(ID.Loc, "compare operands must have the same type");
3396 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
3398 if (Opc == Instruction::FCmp) {
3399 if (!Val0->getType()->isFPOrFPVectorTy())
3400 return Error(ID.Loc, "fcmp requires floating point operands");
3401 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
3402 } else {
3403 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
3404 if (!Val0->getType()->isIntOrIntVectorTy() &&
3405 !Val0->getType()->isPtrOrPtrVectorTy())
3406 return Error(ID.Loc, "icmp requires pointer or integer operands");
3407 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
3409 ID.Kind = ValID::t_Constant;
3410 return false;
3413 // Unary Operators.
3414 case lltok::kw_fneg: {
3415 unsigned Opc = Lex.getUIntVal();
3416 Constant *Val;
3417 Lex.Lex();
3418 if (ParseToken(lltok::lparen, "expected '(' in unary constantexpr") ||
3419 ParseGlobalTypeAndValue(Val) ||
3420 ParseToken(lltok::rparen, "expected ')' in unary constantexpr"))
3421 return true;
3423 // Check that the type is valid for the operator.
3424 switch (Opc) {
3425 case Instruction::FNeg:
3426 if (!Val->getType()->isFPOrFPVectorTy())
3427 return Error(ID.Loc, "constexpr requires fp operands");
3428 break;
3429 default: llvm_unreachable("Unknown unary operator!");
3431 unsigned Flags = 0;
3432 Constant *C = ConstantExpr::get(Opc, Val, Flags);
3433 ID.ConstantVal = C;
3434 ID.Kind = ValID::t_Constant;
3435 return false;
3437 // Binary Operators.
3438 case lltok::kw_add:
3439 case lltok::kw_fadd:
3440 case lltok::kw_sub:
3441 case lltok::kw_fsub:
3442 case lltok::kw_mul:
3443 case lltok::kw_fmul:
3444 case lltok::kw_udiv:
3445 case lltok::kw_sdiv:
3446 case lltok::kw_fdiv:
3447 case lltok::kw_urem:
3448 case lltok::kw_srem:
3449 case lltok::kw_frem:
3450 case lltok::kw_shl:
3451 case lltok::kw_lshr:
3452 case lltok::kw_ashr: {
3453 bool NUW = false;
3454 bool NSW = false;
3455 bool Exact = false;
3456 unsigned Opc = Lex.getUIntVal();
3457 Constant *Val0, *Val1;
3458 Lex.Lex();
3459 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
3460 Opc == Instruction::Mul || Opc == Instruction::Shl) {
3461 if (EatIfPresent(lltok::kw_nuw))
3462 NUW = true;
3463 if (EatIfPresent(lltok::kw_nsw)) {
3464 NSW = true;
3465 if (EatIfPresent(lltok::kw_nuw))
3466 NUW = true;
3468 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
3469 Opc == Instruction::LShr || Opc == Instruction::AShr) {
3470 if (EatIfPresent(lltok::kw_exact))
3471 Exact = true;
3473 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
3474 ParseGlobalTypeAndValue(Val0) ||
3475 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
3476 ParseGlobalTypeAndValue(Val1) ||
3477 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
3478 return true;
3479 if (Val0->getType() != Val1->getType())
3480 return Error(ID.Loc, "operands of constexpr must have same type");
3481 // Check that the type is valid for the operator.
3482 switch (Opc) {
3483 case Instruction::Add:
3484 case Instruction::Sub:
3485 case Instruction::Mul:
3486 case Instruction::UDiv:
3487 case Instruction::SDiv:
3488 case Instruction::URem:
3489 case Instruction::SRem:
3490 case Instruction::Shl:
3491 case Instruction::AShr:
3492 case Instruction::LShr:
3493 if (!Val0->getType()->isIntOrIntVectorTy())
3494 return Error(ID.Loc, "constexpr requires integer operands");
3495 break;
3496 case Instruction::FAdd:
3497 case Instruction::FSub:
3498 case Instruction::FMul:
3499 case Instruction::FDiv:
3500 case Instruction::FRem:
3501 if (!Val0->getType()->isFPOrFPVectorTy())
3502 return Error(ID.Loc, "constexpr requires fp operands");
3503 break;
3504 default: llvm_unreachable("Unknown binary operator!");
3506 unsigned Flags = 0;
3507 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3508 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
3509 if (Exact) Flags |= PossiblyExactOperator::IsExact;
3510 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
3511 ID.ConstantVal = C;
3512 ID.Kind = ValID::t_Constant;
3513 return false;
3516 // Logical Operations
3517 case lltok::kw_and:
3518 case lltok::kw_or:
3519 case lltok::kw_xor: {
3520 unsigned Opc = Lex.getUIntVal();
3521 Constant *Val0, *Val1;
3522 Lex.Lex();
3523 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
3524 ParseGlobalTypeAndValue(Val0) ||
3525 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
3526 ParseGlobalTypeAndValue(Val1) ||
3527 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
3528 return true;
3529 if (Val0->getType() != Val1->getType())
3530 return Error(ID.Loc, "operands of constexpr must have same type");
3531 if (!Val0->getType()->isIntOrIntVectorTy())
3532 return Error(ID.Loc,
3533 "constexpr requires integer or integer vector operands");
3534 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
3535 ID.Kind = ValID::t_Constant;
3536 return false;
3539 case lltok::kw_getelementptr:
3540 case lltok::kw_shufflevector:
3541 case lltok::kw_insertelement:
3542 case lltok::kw_extractelement:
3543 case lltok::kw_select: {
3544 unsigned Opc = Lex.getUIntVal();
3545 SmallVector<Constant*, 16> Elts;
3546 bool InBounds = false;
3547 Type *Ty;
3548 Lex.Lex();
3550 if (Opc == Instruction::GetElementPtr)
3551 InBounds = EatIfPresent(lltok::kw_inbounds);
3553 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
3554 return true;
3556 LocTy ExplicitTypeLoc = Lex.getLoc();
3557 if (Opc == Instruction::GetElementPtr) {
3558 if (ParseType(Ty) ||
3559 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
3560 return true;
3563 Optional<unsigned> InRangeOp;
3564 if (ParseGlobalValueVector(
3565 Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
3566 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
3567 return true;
3569 if (Opc == Instruction::GetElementPtr) {
3570 if (Elts.size() == 0 ||
3571 !Elts[0]->getType()->isPtrOrPtrVectorTy())
3572 return Error(ID.Loc, "base of getelementptr must be a pointer");
3574 Type *BaseType = Elts[0]->getType();
3575 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
3576 if (Ty != BasePointerType->getElementType())
3577 return Error(
3578 ExplicitTypeLoc,
3579 "explicit pointee type doesn't match operand's pointee type");
3581 unsigned GEPWidth =
3582 BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
3584 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
3585 for (Constant *Val : Indices) {
3586 Type *ValTy = Val->getType();
3587 if (!ValTy->isIntOrIntVectorTy())
3588 return Error(ID.Loc, "getelementptr index must be an integer");
3589 if (ValTy->isVectorTy()) {
3590 unsigned ValNumEl = ValTy->getVectorNumElements();
3591 if (GEPWidth && (ValNumEl != GEPWidth))
3592 return Error(
3593 ID.Loc,
3594 "getelementptr vector index has a wrong number of elements");
3595 // GEPWidth may have been unknown because the base is a scalar,
3596 // but it is known now.
3597 GEPWidth = ValNumEl;
3601 SmallPtrSet<Type*, 4> Visited;
3602 if (!Indices.empty() && !Ty->isSized(&Visited))
3603 return Error(ID.Loc, "base element of getelementptr must be sized");
3605 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
3606 return Error(ID.Loc, "invalid getelementptr indices");
3608 if (InRangeOp) {
3609 if (*InRangeOp == 0)
3610 return Error(ID.Loc,
3611 "inrange keyword may not appear on pointer operand");
3612 --*InRangeOp;
3615 ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
3616 InBounds, InRangeOp);
3617 } else if (Opc == Instruction::Select) {
3618 if (Elts.size() != 3)
3619 return Error(ID.Loc, "expected three operands to select");
3620 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
3621 Elts[2]))
3622 return Error(ID.Loc, Reason);
3623 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
3624 } else if (Opc == Instruction::ShuffleVector) {
3625 if (Elts.size() != 3)
3626 return Error(ID.Loc, "expected three operands to shufflevector");
3627 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3628 return Error(ID.Loc, "invalid operands to shufflevector");
3629 ID.ConstantVal =
3630 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
3631 } else if (Opc == Instruction::ExtractElement) {
3632 if (Elts.size() != 2)
3633 return Error(ID.Loc, "expected two operands to extractelement");
3634 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
3635 return Error(ID.Loc, "invalid extractelement operands");
3636 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
3637 } else {
3638 assert(Opc == Instruction::InsertElement && "Unknown opcode");
3639 if (Elts.size() != 3)
3640 return Error(ID.Loc, "expected three operands to insertelement");
3641 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
3642 return Error(ID.Loc, "invalid insertelement operands");
3643 ID.ConstantVal =
3644 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
3647 ID.Kind = ValID::t_Constant;
3648 return false;
3652 Lex.Lex();
3653 return false;
3656 /// ParseGlobalValue - Parse a global value with the specified type.
3657 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
3658 C = nullptr;
3659 ValID ID;
3660 Value *V = nullptr;
3661 bool Parsed = ParseValID(ID) ||
3662 ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
3663 if (V && !(C = dyn_cast<Constant>(V)))
3664 return Error(ID.Loc, "global values must be constants");
3665 return Parsed;
3668 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
3669 Type *Ty = nullptr;
3670 return ParseType(Ty) ||
3671 ParseGlobalValue(Ty, V);
3674 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
3675 C = nullptr;
3677 LocTy KwLoc = Lex.getLoc();
3678 if (!EatIfPresent(lltok::kw_comdat))
3679 return false;
3681 if (EatIfPresent(lltok::lparen)) {
3682 if (Lex.getKind() != lltok::ComdatVar)
3683 return TokError("expected comdat variable");
3684 C = getComdat(Lex.getStrVal(), Lex.getLoc());
3685 Lex.Lex();
3686 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
3687 return true;
3688 } else {
3689 if (GlobalName.empty())
3690 return TokError("comdat cannot be unnamed");
3691 C = getComdat(GlobalName, KwLoc);
3694 return false;
3697 /// ParseGlobalValueVector
3698 /// ::= /*empty*/
3699 /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
3700 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
3701 Optional<unsigned> *InRangeOp) {
3702 // Empty list.
3703 if (Lex.getKind() == lltok::rbrace ||
3704 Lex.getKind() == lltok::rsquare ||
3705 Lex.getKind() == lltok::greater ||
3706 Lex.getKind() == lltok::rparen)
3707 return false;
3709 do {
3710 if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
3711 *InRangeOp = Elts.size();
3713 Constant *C;
3714 if (ParseGlobalTypeAndValue(C)) return true;
3715 Elts.push_back(C);
3716 } while (EatIfPresent(lltok::comma));
3718 return false;
3721 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
3722 SmallVector<Metadata *, 16> Elts;
3723 if (ParseMDNodeVector(Elts))
3724 return true;
3726 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
3727 return false;
3730 /// MDNode:
3731 /// ::= !{ ... }
3732 /// ::= !7
3733 /// ::= !DILocation(...)
3734 bool LLParser::ParseMDNode(MDNode *&N) {
3735 if (Lex.getKind() == lltok::MetadataVar)
3736 return ParseSpecializedMDNode(N);
3738 return ParseToken(lltok::exclaim, "expected '!' here") ||
3739 ParseMDNodeTail(N);
3742 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3743 // !{ ... }
3744 if (Lex.getKind() == lltok::lbrace)
3745 return ParseMDTuple(N);
3747 // !42
3748 return ParseMDNodeID(N);
3751 namespace {
3753 /// Structure to represent an optional metadata field.
3754 template <class FieldTy> struct MDFieldImpl {
3755 typedef MDFieldImpl ImplTy;
3756 FieldTy Val;
3757 bool Seen;
3759 void assign(FieldTy Val) {
3760 Seen = true;
3761 this->Val = std::move(Val);
3764 explicit MDFieldImpl(FieldTy Default)
3765 : Val(std::move(Default)), Seen(false) {}
3768 /// Structure to represent an optional metadata field that
3769 /// can be of either type (A or B) and encapsulates the
3770 /// MD<typeofA>Field and MD<typeofB>Field structs, so not
3771 /// to reimplement the specifics for representing each Field.
3772 template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
3773 typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
3774 FieldTypeA A;
3775 FieldTypeB B;
3776 bool Seen;
3778 enum {
3779 IsInvalid = 0,
3780 IsTypeA = 1,
3781 IsTypeB = 2
3782 } WhatIs;
3784 void assign(FieldTypeA A) {
3785 Seen = true;
3786 this->A = std::move(A);
3787 WhatIs = IsTypeA;
3790 void assign(FieldTypeB B) {
3791 Seen = true;
3792 this->B = std::move(B);
3793 WhatIs = IsTypeB;
3796 explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
3797 : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
3798 WhatIs(IsInvalid) {}
3801 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3802 uint64_t Max;
3804 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3805 : ImplTy(Default), Max(Max) {}
3808 struct LineField : public MDUnsignedField {
3809 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3812 struct ColumnField : public MDUnsignedField {
3813 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3816 struct DwarfTagField : public MDUnsignedField {
3817 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3818 DwarfTagField(dwarf::Tag DefaultTag)
3819 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3822 struct DwarfMacinfoTypeField : public MDUnsignedField {
3823 DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
3824 DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
3825 : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
3828 struct DwarfAttEncodingField : public MDUnsignedField {
3829 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3832 struct DwarfVirtualityField : public MDUnsignedField {
3833 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3836 struct DwarfLangField : public MDUnsignedField {
3837 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3840 struct DwarfCCField : public MDUnsignedField {
3841 DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
3844 struct EmissionKindField : public MDUnsignedField {
3845 EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
3848 struct NameTableKindField : public MDUnsignedField {
3849 NameTableKindField()
3850 : MDUnsignedField(
3851 0, (unsigned)
3852 DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
3855 struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
3856 DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
3859 struct DISPFlagField : public MDFieldImpl<DISubprogram::DISPFlags> {
3860 DISPFlagField() : MDFieldImpl(DISubprogram::SPFlagZero) {}
3863 struct MDSignedField : public MDFieldImpl<int64_t> {
3864 int64_t Min;
3865 int64_t Max;
3867 MDSignedField(int64_t Default = 0)
3868 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3869 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3870 : ImplTy(Default), Min(Min), Max(Max) {}
3873 struct MDBoolField : public MDFieldImpl<bool> {
3874 MDBoolField(bool Default = false) : ImplTy(Default) {}
3877 struct MDField : public MDFieldImpl<Metadata *> {
3878 bool AllowNull;
3880 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3883 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3884 MDConstant() : ImplTy(nullptr) {}
3887 struct MDStringField : public MDFieldImpl<MDString *> {
3888 bool AllowEmpty;
3889 MDStringField(bool AllowEmpty = true)
3890 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3893 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3894 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3897 struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
3898 ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
3901 struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
3902 MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
3903 : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
3905 MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
3906 bool AllowNull = true)
3907 : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
3909 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3910 bool isMDField() const { return WhatIs == IsTypeB; }
3911 int64_t getMDSignedValue() const {
3912 assert(isMDSignedField() && "Wrong field type");
3913 return A.Val;
3915 Metadata *getMDFieldValue() const {
3916 assert(isMDField() && "Wrong field type");
3917 return B.Val;
3921 struct MDSignedOrUnsignedField
3922 : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
3923 MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
3925 bool isMDSignedField() const { return WhatIs == IsTypeA; }
3926 bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
3927 int64_t getMDSignedValue() const {
3928 assert(isMDSignedField() && "Wrong field type");
3929 return A.Val;
3931 uint64_t getMDUnsignedValue() const {
3932 assert(isMDUnsignedField() && "Wrong field type");
3933 return B.Val;
3937 } // end anonymous namespace
3939 namespace llvm {
3941 template <>
3942 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3943 MDUnsignedField &Result) {
3944 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3945 return TokError("expected unsigned integer");
3947 auto &U = Lex.getAPSIntVal();
3948 if (U.ugt(Result.Max))
3949 return TokError("value for '" + Name + "' too large, limit is " +
3950 Twine(Result.Max));
3951 Result.assign(U.getZExtValue());
3952 assert(Result.Val <= Result.Max && "Expected value in range");
3953 Lex.Lex();
3954 return false;
3957 template <>
3958 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3959 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3961 template <>
3962 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3963 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3966 template <>
3967 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3968 if (Lex.getKind() == lltok::APSInt)
3969 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3971 if (Lex.getKind() != lltok::DwarfTag)
3972 return TokError("expected DWARF tag");
3974 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3975 if (Tag == dwarf::DW_TAG_invalid)
3976 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3977 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3979 Result.assign(Tag);
3980 Lex.Lex();
3981 return false;
3984 template <>
3985 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3986 DwarfMacinfoTypeField &Result) {
3987 if (Lex.getKind() == lltok::APSInt)
3988 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3990 if (Lex.getKind() != lltok::DwarfMacinfo)
3991 return TokError("expected DWARF macinfo type");
3993 unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
3994 if (Macinfo == dwarf::DW_MACINFO_invalid)
3995 return TokError(
3996 "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
3997 assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
3999 Result.assign(Macinfo);
4000 Lex.Lex();
4001 return false;
4004 template <>
4005 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4006 DwarfVirtualityField &Result) {
4007 if (Lex.getKind() == lltok::APSInt)
4008 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4010 if (Lex.getKind() != lltok::DwarfVirtuality)
4011 return TokError("expected DWARF virtuality code");
4013 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
4014 if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
4015 return TokError("invalid DWARF virtuality code" + Twine(" '") +
4016 Lex.getStrVal() + "'");
4017 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
4018 Result.assign(Virtuality);
4019 Lex.Lex();
4020 return false;
4023 template <>
4024 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
4025 if (Lex.getKind() == lltok::APSInt)
4026 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4028 if (Lex.getKind() != lltok::DwarfLang)
4029 return TokError("expected DWARF language");
4031 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
4032 if (!Lang)
4033 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
4034 "'");
4035 assert(Lang <= Result.Max && "Expected valid DWARF language");
4036 Result.assign(Lang);
4037 Lex.Lex();
4038 return false;
4041 template <>
4042 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
4043 if (Lex.getKind() == lltok::APSInt)
4044 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4046 if (Lex.getKind() != lltok::DwarfCC)
4047 return TokError("expected DWARF calling convention");
4049 unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
4050 if (!CC)
4051 return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
4052 "'");
4053 assert(CC <= Result.Max && "Expected valid DWARF calling convention");
4054 Result.assign(CC);
4055 Lex.Lex();
4056 return false;
4059 template <>
4060 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
4061 if (Lex.getKind() == lltok::APSInt)
4062 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4064 if (Lex.getKind() != lltok::EmissionKind)
4065 return TokError("expected emission kind");
4067 auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
4068 if (!Kind)
4069 return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
4070 "'");
4071 assert(*Kind <= Result.Max && "Expected valid emission kind");
4072 Result.assign(*Kind);
4073 Lex.Lex();
4074 return false;
4077 template <>
4078 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4079 NameTableKindField &Result) {
4080 if (Lex.getKind() == lltok::APSInt)
4081 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4083 if (Lex.getKind() != lltok::NameTableKind)
4084 return TokError("expected nameTable kind");
4086 auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
4087 if (!Kind)
4088 return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
4089 "'");
4090 assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
4091 Result.assign((unsigned)*Kind);
4092 Lex.Lex();
4093 return false;
4096 template <>
4097 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4098 DwarfAttEncodingField &Result) {
4099 if (Lex.getKind() == lltok::APSInt)
4100 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
4102 if (Lex.getKind() != lltok::DwarfAttEncoding)
4103 return TokError("expected DWARF type attribute encoding");
4105 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
4106 if (!Encoding)
4107 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
4108 Lex.getStrVal() + "'");
4109 assert(Encoding <= Result.Max && "Expected valid DWARF language");
4110 Result.assign(Encoding);
4111 Lex.Lex();
4112 return false;
4115 /// DIFlagField
4116 /// ::= uint32
4117 /// ::= DIFlagVector
4118 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
4119 template <>
4120 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
4122 // Parser for a single flag.
4123 auto parseFlag = [&](DINode::DIFlags &Val) {
4124 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4125 uint32_t TempVal = static_cast<uint32_t>(Val);
4126 bool Res = ParseUInt32(TempVal);
4127 Val = static_cast<DINode::DIFlags>(TempVal);
4128 return Res;
4131 if (Lex.getKind() != lltok::DIFlag)
4132 return TokError("expected debug info flag");
4134 Val = DINode::getFlag(Lex.getStrVal());
4135 if (!Val)
4136 return TokError(Twine("invalid debug info flag flag '") +
4137 Lex.getStrVal() + "'");
4138 Lex.Lex();
4139 return false;
4142 // Parse the flags and combine them together.
4143 DINode::DIFlags Combined = DINode::FlagZero;
4144 do {
4145 DINode::DIFlags Val;
4146 if (parseFlag(Val))
4147 return true;
4148 Combined |= Val;
4149 } while (EatIfPresent(lltok::bar));
4151 Result.assign(Combined);
4152 return false;
4155 /// DISPFlagField
4156 /// ::= uint32
4157 /// ::= DISPFlagVector
4158 /// ::= DISPFlagVector '|' DISPFlag* '|' uint32
4159 template <>
4160 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DISPFlagField &Result) {
4162 // Parser for a single flag.
4163 auto parseFlag = [&](DISubprogram::DISPFlags &Val) {
4164 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
4165 uint32_t TempVal = static_cast<uint32_t>(Val);
4166 bool Res = ParseUInt32(TempVal);
4167 Val = static_cast<DISubprogram::DISPFlags>(TempVal);
4168 return Res;
4171 if (Lex.getKind() != lltok::DISPFlag)
4172 return TokError("expected debug info flag");
4174 Val = DISubprogram::getFlag(Lex.getStrVal());
4175 if (!Val)
4176 return TokError(Twine("invalid subprogram debug info flag '") +
4177 Lex.getStrVal() + "'");
4178 Lex.Lex();
4179 return false;
4182 // Parse the flags and combine them together.
4183 DISubprogram::DISPFlags Combined = DISubprogram::SPFlagZero;
4184 do {
4185 DISubprogram::DISPFlags Val;
4186 if (parseFlag(Val))
4187 return true;
4188 Combined |= Val;
4189 } while (EatIfPresent(lltok::bar));
4191 Result.assign(Combined);
4192 return false;
4195 template <>
4196 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4197 MDSignedField &Result) {
4198 if (Lex.getKind() != lltok::APSInt)
4199 return TokError("expected signed integer");
4201 auto &S = Lex.getAPSIntVal();
4202 if (S < Result.Min)
4203 return TokError("value for '" + Name + "' too small, limit is " +
4204 Twine(Result.Min));
4205 if (S > Result.Max)
4206 return TokError("value for '" + Name + "' too large, limit is " +
4207 Twine(Result.Max));
4208 Result.assign(S.getExtValue());
4209 assert(Result.Val >= Result.Min && "Expected value in range");
4210 assert(Result.Val <= Result.Max && "Expected value in range");
4211 Lex.Lex();
4212 return false;
4215 template <>
4216 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
4217 switch (Lex.getKind()) {
4218 default:
4219 return TokError("expected 'true' or 'false'");
4220 case lltok::kw_true:
4221 Result.assign(true);
4222 break;
4223 case lltok::kw_false:
4224 Result.assign(false);
4225 break;
4227 Lex.Lex();
4228 return false;
4231 template <>
4232 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
4233 if (Lex.getKind() == lltok::kw_null) {
4234 if (!Result.AllowNull)
4235 return TokError("'" + Name + "' cannot be null");
4236 Lex.Lex();
4237 Result.assign(nullptr);
4238 return false;
4241 Metadata *MD;
4242 if (ParseMetadata(MD, nullptr))
4243 return true;
4245 Result.assign(MD);
4246 return false;
4249 template <>
4250 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4251 MDSignedOrMDField &Result) {
4252 // Try to parse a signed int.
4253 if (Lex.getKind() == lltok::APSInt) {
4254 MDSignedField Res = Result.A;
4255 if (!ParseMDField(Loc, Name, Res)) {
4256 Result.assign(Res);
4257 return false;
4259 return true;
4262 // Otherwise, try to parse as an MDField.
4263 MDField Res = Result.B;
4264 if (!ParseMDField(Loc, Name, Res)) {
4265 Result.assign(Res);
4266 return false;
4269 return true;
4272 template <>
4273 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4274 MDSignedOrUnsignedField &Result) {
4275 if (Lex.getKind() != lltok::APSInt)
4276 return false;
4278 if (Lex.getAPSIntVal().isSigned()) {
4279 MDSignedField Res = Result.A;
4280 if (ParseMDField(Loc, Name, Res))
4281 return true;
4282 Result.assign(Res);
4283 return false;
4286 MDUnsignedField Res = Result.B;
4287 if (ParseMDField(Loc, Name, Res))
4288 return true;
4289 Result.assign(Res);
4290 return false;
4293 template <>
4294 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
4295 LocTy ValueLoc = Lex.getLoc();
4296 std::string S;
4297 if (ParseStringConstant(S))
4298 return true;
4300 if (!Result.AllowEmpty && S.empty())
4301 return Error(ValueLoc, "'" + Name + "' cannot be empty");
4303 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
4304 return false;
4307 template <>
4308 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
4309 SmallVector<Metadata *, 4> MDs;
4310 if (ParseMDNodeVector(MDs))
4311 return true;
4313 Result.assign(std::move(MDs));
4314 return false;
4317 template <>
4318 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
4319 ChecksumKindField &Result) {
4320 Optional<DIFile::ChecksumKind> CSKind =
4321 DIFile::getChecksumKind(Lex.getStrVal());
4323 if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
4324 return TokError(
4325 "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
4327 Result.assign(*CSKind);
4328 Lex.Lex();
4329 return false;
4332 } // end namespace llvm
4334 template <class ParserTy>
4335 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
4336 do {
4337 if (Lex.getKind() != lltok::LabelStr)
4338 return TokError("expected field label here");
4340 if (parseField())
4341 return true;
4342 } while (EatIfPresent(lltok::comma));
4344 return false;
4347 template <class ParserTy>
4348 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
4349 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4350 Lex.Lex();
4352 if (ParseToken(lltok::lparen, "expected '(' here"))
4353 return true;
4354 if (Lex.getKind() != lltok::rparen)
4355 if (ParseMDFieldsImplBody(parseField))
4356 return true;
4358 ClosingLoc = Lex.getLoc();
4359 return ParseToken(lltok::rparen, "expected ')' here");
4362 template <class FieldTy>
4363 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
4364 if (Result.Seen)
4365 return TokError("field '" + Name + "' cannot be specified more than once");
4367 LocTy Loc = Lex.getLoc();
4368 Lex.Lex();
4369 return ParseMDField(Loc, Name, Result);
4372 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
4373 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4375 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
4376 if (Lex.getStrVal() == #CLASS) \
4377 return Parse##CLASS(N, IsDistinct);
4378 #include "llvm/IR/Metadata.def"
4380 return TokError("expected metadata type");
4383 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
4384 #define NOP_FIELD(NAME, TYPE, INIT)
4385 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
4386 if (!NAME.Seen) \
4387 return Error(ClosingLoc, "missing required field '" #NAME "'");
4388 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
4389 if (Lex.getStrVal() == #NAME) \
4390 return ParseMDField(#NAME, NAME);
4391 #define PARSE_MD_FIELDS() \
4392 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
4393 do { \
4394 LocTy ClosingLoc; \
4395 if (ParseMDFieldsImpl([&]() -> bool { \
4396 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
4397 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
4398 }, ClosingLoc)) \
4399 return true; \
4400 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
4401 } while (false)
4402 #define GET_OR_DISTINCT(CLASS, ARGS) \
4403 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
4405 /// ParseDILocationFields:
4406 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
4407 /// isImplicitCode: true)
4408 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
4409 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4410 OPTIONAL(line, LineField, ); \
4411 OPTIONAL(column, ColumnField, ); \
4412 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4413 OPTIONAL(inlinedAt, MDField, ); \
4414 OPTIONAL(isImplicitCode, MDBoolField, (false));
4415 PARSE_MD_FIELDS();
4416 #undef VISIT_MD_FIELDS
4418 Result =
4419 GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
4420 inlinedAt.Val, isImplicitCode.Val));
4421 return false;
4424 /// ParseGenericDINode:
4425 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
4426 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
4427 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4428 REQUIRED(tag, DwarfTagField, ); \
4429 OPTIONAL(header, MDStringField, ); \
4430 OPTIONAL(operands, MDFieldList, );
4431 PARSE_MD_FIELDS();
4432 #undef VISIT_MD_FIELDS
4434 Result = GET_OR_DISTINCT(GenericDINode,
4435 (Context, tag.Val, header.Val, operands.Val));
4436 return false;
4439 /// ParseDISubrange:
4440 /// ::= !DISubrange(count: 30, lowerBound: 2)
4441 /// ::= !DISubrange(count: !node, lowerBound: 2)
4442 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
4443 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4444 REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
4445 OPTIONAL(lowerBound, MDSignedField, );
4446 PARSE_MD_FIELDS();
4447 #undef VISIT_MD_FIELDS
4449 if (count.isMDSignedField())
4450 Result = GET_OR_DISTINCT(
4451 DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
4452 else if (count.isMDField())
4453 Result = GET_OR_DISTINCT(
4454 DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
4455 else
4456 return true;
4458 return false;
4461 /// ParseDIEnumerator:
4462 /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
4463 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
4464 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4465 REQUIRED(name, MDStringField, ); \
4466 REQUIRED(value, MDSignedOrUnsignedField, ); \
4467 OPTIONAL(isUnsigned, MDBoolField, (false));
4468 PARSE_MD_FIELDS();
4469 #undef VISIT_MD_FIELDS
4471 if (isUnsigned.Val && value.isMDSignedField())
4472 return TokError("unsigned enumerator with negative value");
4474 int64_t Value = value.isMDSignedField()
4475 ? value.getMDSignedValue()
4476 : static_cast<int64_t>(value.getMDUnsignedValue());
4477 Result =
4478 GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
4480 return false;
4483 /// ParseDIBasicType:
4484 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
4485 /// encoding: DW_ATE_encoding, flags: 0)
4486 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
4487 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4488 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
4489 OPTIONAL(name, MDStringField, ); \
4490 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4491 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4492 OPTIONAL(encoding, DwarfAttEncodingField, ); \
4493 OPTIONAL(flags, DIFlagField, );
4494 PARSE_MD_FIELDS();
4495 #undef VISIT_MD_FIELDS
4497 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
4498 align.Val, encoding.Val, flags.Val));
4499 return false;
4502 /// ParseDIDerivedType:
4503 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
4504 /// line: 7, scope: !1, baseType: !2, size: 32,
4505 /// align: 32, offset: 0, flags: 0, extraData: !3,
4506 /// dwarfAddressSpace: 3)
4507 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
4508 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4509 REQUIRED(tag, DwarfTagField, ); \
4510 OPTIONAL(name, MDStringField, ); \
4511 OPTIONAL(file, MDField, ); \
4512 OPTIONAL(line, LineField, ); \
4513 OPTIONAL(scope, MDField, ); \
4514 REQUIRED(baseType, MDField, ); \
4515 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4516 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4517 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4518 OPTIONAL(flags, DIFlagField, ); \
4519 OPTIONAL(extraData, MDField, ); \
4520 OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
4521 PARSE_MD_FIELDS();
4522 #undef VISIT_MD_FIELDS
4524 Optional<unsigned> DWARFAddressSpace;
4525 if (dwarfAddressSpace.Val != UINT32_MAX)
4526 DWARFAddressSpace = dwarfAddressSpace.Val;
4528 Result = GET_OR_DISTINCT(DIDerivedType,
4529 (Context, tag.Val, name.Val, file.Val, line.Val,
4530 scope.Val, baseType.Val, size.Val, align.Val,
4531 offset.Val, DWARFAddressSpace, flags.Val,
4532 extraData.Val));
4533 return false;
4536 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
4537 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4538 REQUIRED(tag, DwarfTagField, ); \
4539 OPTIONAL(name, MDStringField, ); \
4540 OPTIONAL(file, MDField, ); \
4541 OPTIONAL(line, LineField, ); \
4542 OPTIONAL(scope, MDField, ); \
4543 OPTIONAL(baseType, MDField, ); \
4544 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
4545 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
4546 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
4547 OPTIONAL(flags, DIFlagField, ); \
4548 OPTIONAL(elements, MDField, ); \
4549 OPTIONAL(runtimeLang, DwarfLangField, ); \
4550 OPTIONAL(vtableHolder, MDField, ); \
4551 OPTIONAL(templateParams, MDField, ); \
4552 OPTIONAL(identifier, MDStringField, ); \
4553 OPTIONAL(discriminator, MDField, );
4554 PARSE_MD_FIELDS();
4555 #undef VISIT_MD_FIELDS
4557 // If this has an identifier try to build an ODR type.
4558 if (identifier.Val)
4559 if (auto *CT = DICompositeType::buildODRType(
4560 Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
4561 scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
4562 elements.Val, runtimeLang.Val, vtableHolder.Val,
4563 templateParams.Val, discriminator.Val)) {
4564 Result = CT;
4565 return false;
4568 // Create a new node, and save it in the context if it belongs in the type
4569 // map.
4570 Result = GET_OR_DISTINCT(
4571 DICompositeType,
4572 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
4573 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
4574 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
4575 discriminator.Val));
4576 return false;
4579 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
4580 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4581 OPTIONAL(flags, DIFlagField, ); \
4582 OPTIONAL(cc, DwarfCCField, ); \
4583 REQUIRED(types, MDField, );
4584 PARSE_MD_FIELDS();
4585 #undef VISIT_MD_FIELDS
4587 Result = GET_OR_DISTINCT(DISubroutineType,
4588 (Context, flags.Val, cc.Val, types.Val));
4589 return false;
4592 /// ParseDIFileType:
4593 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
4594 /// checksumkind: CSK_MD5,
4595 /// checksum: "000102030405060708090a0b0c0d0e0f",
4596 /// source: "source file contents")
4597 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
4598 // The default constructed value for checksumkind is required, but will never
4599 // be used, as the parser checks if the field was actually Seen before using
4600 // the Val.
4601 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4602 REQUIRED(filename, MDStringField, ); \
4603 REQUIRED(directory, MDStringField, ); \
4604 OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
4605 OPTIONAL(checksum, MDStringField, ); \
4606 OPTIONAL(source, MDStringField, );
4607 PARSE_MD_FIELDS();
4608 #undef VISIT_MD_FIELDS
4610 Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
4611 if (checksumkind.Seen && checksum.Seen)
4612 OptChecksum.emplace(checksumkind.Val, checksum.Val);
4613 else if (checksumkind.Seen || checksum.Seen)
4614 return Lex.Error("'checksumkind' and 'checksum' must be provided together");
4616 Optional<MDString *> OptSource;
4617 if (source.Seen)
4618 OptSource = source.Val;
4619 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
4620 OptChecksum, OptSource));
4621 return false;
4624 /// ParseDICompileUnit:
4625 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
4626 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
4627 /// splitDebugFilename: "abc.debug",
4628 /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
4629 /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
4630 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
4631 if (!IsDistinct)
4632 return Lex.Error("missing 'distinct', required for !DICompileUnit");
4634 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4635 REQUIRED(language, DwarfLangField, ); \
4636 REQUIRED(file, MDField, (/* AllowNull */ false)); \
4637 OPTIONAL(producer, MDStringField, ); \
4638 OPTIONAL(isOptimized, MDBoolField, ); \
4639 OPTIONAL(flags, MDStringField, ); \
4640 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
4641 OPTIONAL(splitDebugFilename, MDStringField, ); \
4642 OPTIONAL(emissionKind, EmissionKindField, ); \
4643 OPTIONAL(enums, MDField, ); \
4644 OPTIONAL(retainedTypes, MDField, ); \
4645 OPTIONAL(globals, MDField, ); \
4646 OPTIONAL(imports, MDField, ); \
4647 OPTIONAL(macros, MDField, ); \
4648 OPTIONAL(dwoId, MDUnsignedField, ); \
4649 OPTIONAL(splitDebugInlining, MDBoolField, = true); \
4650 OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
4651 OPTIONAL(nameTableKind, NameTableKindField, ); \
4652 OPTIONAL(debugBaseAddress, MDBoolField, = false);
4653 PARSE_MD_FIELDS();
4654 #undef VISIT_MD_FIELDS
4656 Result = DICompileUnit::getDistinct(
4657 Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
4658 runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
4659 retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
4660 splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val,
4661 debugBaseAddress.Val);
4662 return false;
4665 /// ParseDISubprogram:
4666 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
4667 /// file: !1, line: 7, type: !2, isLocal: false,
4668 /// isDefinition: true, scopeLine: 8, containingType: !3,
4669 /// virtuality: DW_VIRTUALTIY_pure_virtual,
4670 /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
4671 /// spFlags: 10, isOptimized: false, templateParams: !4,
4672 /// declaration: !5, retainedNodes: !6, thrownTypes: !7)
4673 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
4674 auto Loc = Lex.getLoc();
4675 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4676 OPTIONAL(scope, MDField, ); \
4677 OPTIONAL(name, MDStringField, ); \
4678 OPTIONAL(linkageName, MDStringField, ); \
4679 OPTIONAL(file, MDField, ); \
4680 OPTIONAL(line, LineField, ); \
4681 OPTIONAL(type, MDField, ); \
4682 OPTIONAL(isLocal, MDBoolField, ); \
4683 OPTIONAL(isDefinition, MDBoolField, (true)); \
4684 OPTIONAL(scopeLine, LineField, ); \
4685 OPTIONAL(containingType, MDField, ); \
4686 OPTIONAL(virtuality, DwarfVirtualityField, ); \
4687 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
4688 OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
4689 OPTIONAL(flags, DIFlagField, ); \
4690 OPTIONAL(spFlags, DISPFlagField, ); \
4691 OPTIONAL(isOptimized, MDBoolField, ); \
4692 OPTIONAL(unit, MDField, ); \
4693 OPTIONAL(templateParams, MDField, ); \
4694 OPTIONAL(declaration, MDField, ); \
4695 OPTIONAL(retainedNodes, MDField, ); \
4696 OPTIONAL(thrownTypes, MDField, );
4697 PARSE_MD_FIELDS();
4698 #undef VISIT_MD_FIELDS
4700 // An explicit spFlags field takes precedence over individual fields in
4701 // older IR versions.
4702 DISubprogram::DISPFlags SPFlags =
4703 spFlags.Seen ? spFlags.Val
4704 : DISubprogram::toSPFlags(isLocal.Val, isDefinition.Val,
4705 isOptimized.Val, virtuality.Val);
4706 if ((SPFlags & DISubprogram::SPFlagDefinition) && !IsDistinct)
4707 return Lex.Error(
4708 Loc,
4709 "missing 'distinct', required for !DISubprogram that is a Definition");
4710 Result = GET_OR_DISTINCT(
4711 DISubprogram,
4712 (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
4713 type.Val, scopeLine.Val, containingType.Val, virtualIndex.Val,
4714 thisAdjustment.Val, flags.Val, SPFlags, unit.Val, templateParams.Val,
4715 declaration.Val, retainedNodes.Val, thrownTypes.Val));
4716 return false;
4719 /// ParseDILexicalBlock:
4720 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
4721 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
4722 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4723 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4724 OPTIONAL(file, MDField, ); \
4725 OPTIONAL(line, LineField, ); \
4726 OPTIONAL(column, ColumnField, );
4727 PARSE_MD_FIELDS();
4728 #undef VISIT_MD_FIELDS
4730 Result = GET_OR_DISTINCT(
4731 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
4732 return false;
4735 /// ParseDILexicalBlockFile:
4736 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
4737 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
4738 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4739 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4740 OPTIONAL(file, MDField, ); \
4741 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
4742 PARSE_MD_FIELDS();
4743 #undef VISIT_MD_FIELDS
4745 Result = GET_OR_DISTINCT(DILexicalBlockFile,
4746 (Context, scope.Val, file.Val, discriminator.Val));
4747 return false;
4750 /// ParseDICommonBlock:
4751 /// ::= !DICommonBlock(scope: !0, file: !2, name: "COMMON name", line: 9)
4752 bool LLParser::ParseDICommonBlock(MDNode *&Result, bool IsDistinct) {
4753 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4754 REQUIRED(scope, MDField, ); \
4755 OPTIONAL(declaration, MDField, ); \
4756 OPTIONAL(name, MDStringField, ); \
4757 OPTIONAL(file, MDField, ); \
4758 OPTIONAL(line, LineField, );
4759 PARSE_MD_FIELDS();
4760 #undef VISIT_MD_FIELDS
4762 Result = GET_OR_DISTINCT(DICommonBlock,
4763 (Context, scope.Val, declaration.Val, name.Val,
4764 file.Val, line.Val));
4765 return false;
4768 /// ParseDINamespace:
4769 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
4770 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
4771 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4772 REQUIRED(scope, MDField, ); \
4773 OPTIONAL(name, MDStringField, ); \
4774 OPTIONAL(exportSymbols, MDBoolField, );
4775 PARSE_MD_FIELDS();
4776 #undef VISIT_MD_FIELDS
4778 Result = GET_OR_DISTINCT(DINamespace,
4779 (Context, scope.Val, name.Val, exportSymbols.Val));
4780 return false;
4783 /// ParseDIMacro:
4784 /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
4785 bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
4786 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4787 REQUIRED(type, DwarfMacinfoTypeField, ); \
4788 OPTIONAL(line, LineField, ); \
4789 REQUIRED(name, MDStringField, ); \
4790 OPTIONAL(value, MDStringField, );
4791 PARSE_MD_FIELDS();
4792 #undef VISIT_MD_FIELDS
4794 Result = GET_OR_DISTINCT(DIMacro,
4795 (Context, type.Val, line.Val, name.Val, value.Val));
4796 return false;
4799 /// ParseDIMacroFile:
4800 /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
4801 bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
4802 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4803 OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
4804 OPTIONAL(line, LineField, ); \
4805 REQUIRED(file, MDField, ); \
4806 OPTIONAL(nodes, MDField, );
4807 PARSE_MD_FIELDS();
4808 #undef VISIT_MD_FIELDS
4810 Result = GET_OR_DISTINCT(DIMacroFile,
4811 (Context, type.Val, line.Val, file.Val, nodes.Val));
4812 return false;
4815 /// ParseDIModule:
4816 /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
4817 /// includePath: "/usr/include", isysroot: "/")
4818 bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
4819 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4820 REQUIRED(scope, MDField, ); \
4821 REQUIRED(name, MDStringField, ); \
4822 OPTIONAL(configMacros, MDStringField, ); \
4823 OPTIONAL(includePath, MDStringField, ); \
4824 OPTIONAL(isysroot, MDStringField, );
4825 PARSE_MD_FIELDS();
4826 #undef VISIT_MD_FIELDS
4828 Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
4829 configMacros.Val, includePath.Val, isysroot.Val));
4830 return false;
4833 /// ParseDITemplateTypeParameter:
4834 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
4835 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
4836 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4837 OPTIONAL(name, MDStringField, ); \
4838 REQUIRED(type, MDField, );
4839 PARSE_MD_FIELDS();
4840 #undef VISIT_MD_FIELDS
4842 Result =
4843 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
4844 return false;
4847 /// ParseDITemplateValueParameter:
4848 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
4849 /// name: "V", type: !1, value: i32 7)
4850 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
4851 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4852 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
4853 OPTIONAL(name, MDStringField, ); \
4854 OPTIONAL(type, MDField, ); \
4855 REQUIRED(value, MDField, );
4856 PARSE_MD_FIELDS();
4857 #undef VISIT_MD_FIELDS
4859 Result = GET_OR_DISTINCT(DITemplateValueParameter,
4860 (Context, tag.Val, name.Val, type.Val, value.Val));
4861 return false;
4864 /// ParseDIGlobalVariable:
4865 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
4866 /// file: !1, line: 7, type: !2, isLocal: false,
4867 /// isDefinition: true, templateParams: !3,
4868 /// declaration: !4, align: 8)
4869 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
4870 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4871 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
4872 OPTIONAL(scope, MDField, ); \
4873 OPTIONAL(linkageName, MDStringField, ); \
4874 OPTIONAL(file, MDField, ); \
4875 OPTIONAL(line, LineField, ); \
4876 OPTIONAL(type, MDField, ); \
4877 OPTIONAL(isLocal, MDBoolField, ); \
4878 OPTIONAL(isDefinition, MDBoolField, (true)); \
4879 OPTIONAL(templateParams, MDField, ); \
4880 OPTIONAL(declaration, MDField, ); \
4881 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4882 PARSE_MD_FIELDS();
4883 #undef VISIT_MD_FIELDS
4885 Result =
4886 GET_OR_DISTINCT(DIGlobalVariable,
4887 (Context, scope.Val, name.Val, linkageName.Val, file.Val,
4888 line.Val, type.Val, isLocal.Val, isDefinition.Val,
4889 declaration.Val, templateParams.Val, align.Val));
4890 return false;
4893 /// ParseDILocalVariable:
4894 /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
4895 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4896 /// align: 8)
4897 /// ::= !DILocalVariable(scope: !0, name: "foo",
4898 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
4899 /// align: 8)
4900 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
4901 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4902 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4903 OPTIONAL(name, MDStringField, ); \
4904 OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
4905 OPTIONAL(file, MDField, ); \
4906 OPTIONAL(line, LineField, ); \
4907 OPTIONAL(type, MDField, ); \
4908 OPTIONAL(flags, DIFlagField, ); \
4909 OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
4910 PARSE_MD_FIELDS();
4911 #undef VISIT_MD_FIELDS
4913 Result = GET_OR_DISTINCT(DILocalVariable,
4914 (Context, scope.Val, name.Val, file.Val, line.Val,
4915 type.Val, arg.Val, flags.Val, align.Val));
4916 return false;
4919 /// ParseDILabel:
4920 /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
4921 bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
4922 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4923 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
4924 REQUIRED(name, MDStringField, ); \
4925 REQUIRED(file, MDField, ); \
4926 REQUIRED(line, LineField, );
4927 PARSE_MD_FIELDS();
4928 #undef VISIT_MD_FIELDS
4930 Result = GET_OR_DISTINCT(DILabel,
4931 (Context, scope.Val, name.Val, file.Val, line.Val));
4932 return false;
4935 /// ParseDIExpression:
4936 /// ::= !DIExpression(0, 7, -1)
4937 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
4938 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
4939 Lex.Lex();
4941 if (ParseToken(lltok::lparen, "expected '(' here"))
4942 return true;
4944 SmallVector<uint64_t, 8> Elements;
4945 if (Lex.getKind() != lltok::rparen)
4946 do {
4947 if (Lex.getKind() == lltok::DwarfOp) {
4948 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
4949 Lex.Lex();
4950 Elements.push_back(Op);
4951 continue;
4953 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
4956 if (Lex.getKind() == lltok::DwarfAttEncoding) {
4957 if (unsigned Op = dwarf::getAttributeEncoding(Lex.getStrVal())) {
4958 Lex.Lex();
4959 Elements.push_back(Op);
4960 continue;
4962 return TokError(Twine("invalid DWARF attribute encoding '") + Lex.getStrVal() + "'");
4965 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
4966 return TokError("expected unsigned integer");
4968 auto &U = Lex.getAPSIntVal();
4969 if (U.ugt(UINT64_MAX))
4970 return TokError("element too large, limit is " + Twine(UINT64_MAX));
4971 Elements.push_back(U.getZExtValue());
4972 Lex.Lex();
4973 } while (EatIfPresent(lltok::comma));
4975 if (ParseToken(lltok::rparen, "expected ')' here"))
4976 return true;
4978 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
4979 return false;
4982 /// ParseDIGlobalVariableExpression:
4983 /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
4984 bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
4985 bool IsDistinct) {
4986 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
4987 REQUIRED(var, MDField, ); \
4988 REQUIRED(expr, MDField, );
4989 PARSE_MD_FIELDS();
4990 #undef VISIT_MD_FIELDS
4992 Result =
4993 GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
4994 return false;
4997 /// ParseDIObjCProperty:
4998 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
4999 /// getter: "getFoo", attributes: 7, type: !2)
5000 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
5001 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5002 OPTIONAL(name, MDStringField, ); \
5003 OPTIONAL(file, MDField, ); \
5004 OPTIONAL(line, LineField, ); \
5005 OPTIONAL(setter, MDStringField, ); \
5006 OPTIONAL(getter, MDStringField, ); \
5007 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
5008 OPTIONAL(type, MDField, );
5009 PARSE_MD_FIELDS();
5010 #undef VISIT_MD_FIELDS
5012 Result = GET_OR_DISTINCT(DIObjCProperty,
5013 (Context, name.Val, file.Val, line.Val, setter.Val,
5014 getter.Val, attributes.Val, type.Val));
5015 return false;
5018 /// ParseDIImportedEntity:
5019 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
5020 /// line: 7, name: "foo")
5021 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
5022 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
5023 REQUIRED(tag, DwarfTagField, ); \
5024 REQUIRED(scope, MDField, ); \
5025 OPTIONAL(entity, MDField, ); \
5026 OPTIONAL(file, MDField, ); \
5027 OPTIONAL(line, LineField, ); \
5028 OPTIONAL(name, MDStringField, );
5029 PARSE_MD_FIELDS();
5030 #undef VISIT_MD_FIELDS
5032 Result = GET_OR_DISTINCT(
5033 DIImportedEntity,
5034 (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
5035 return false;
5038 #undef PARSE_MD_FIELD
5039 #undef NOP_FIELD
5040 #undef REQUIRE_FIELD
5041 #undef DECLARE_FIELD
5043 /// ParseMetadataAsValue
5044 /// ::= metadata i32 %local
5045 /// ::= metadata i32 @global
5046 /// ::= metadata i32 7
5047 /// ::= metadata !0
5048 /// ::= metadata !{...}
5049 /// ::= metadata !"string"
5050 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
5051 // Note: the type 'metadata' has already been parsed.
5052 Metadata *MD;
5053 if (ParseMetadata(MD, &PFS))
5054 return true;
5056 V = MetadataAsValue::get(Context, MD);
5057 return false;
5060 /// ParseValueAsMetadata
5061 /// ::= i32 %local
5062 /// ::= i32 @global
5063 /// ::= i32 7
5064 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
5065 PerFunctionState *PFS) {
5066 Type *Ty;
5067 LocTy Loc;
5068 if (ParseType(Ty, TypeMsg, Loc))
5069 return true;
5070 if (Ty->isMetadataTy())
5071 return Error(Loc, "invalid metadata-value-metadata roundtrip");
5073 Value *V;
5074 if (ParseValue(Ty, V, PFS))
5075 return true;
5077 MD = ValueAsMetadata::get(V);
5078 return false;
5081 /// ParseMetadata
5082 /// ::= i32 %local
5083 /// ::= i32 @global
5084 /// ::= i32 7
5085 /// ::= !42
5086 /// ::= !{...}
5087 /// ::= !"string"
5088 /// ::= !DILocation(...)
5089 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
5090 if (Lex.getKind() == lltok::MetadataVar) {
5091 MDNode *N;
5092 if (ParseSpecializedMDNode(N))
5093 return true;
5094 MD = N;
5095 return false;
5098 // ValueAsMetadata:
5099 // <type> <value>
5100 if (Lex.getKind() != lltok::exclaim)
5101 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
5103 // '!'.
5104 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
5105 Lex.Lex();
5107 // MDString:
5108 // ::= '!' STRINGCONSTANT
5109 if (Lex.getKind() == lltok::StringConstant) {
5110 MDString *S;
5111 if (ParseMDString(S))
5112 return true;
5113 MD = S;
5114 return false;
5117 // MDNode:
5118 // !{ ... }
5119 // !7
5120 MDNode *N;
5121 if (ParseMDNodeTail(N))
5122 return true;
5123 MD = N;
5124 return false;
5127 //===----------------------------------------------------------------------===//
5128 // Function Parsing.
5129 //===----------------------------------------------------------------------===//
5131 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
5132 PerFunctionState *PFS, bool IsCall) {
5133 if (Ty->isFunctionTy())
5134 return Error(ID.Loc, "functions are not values, refer to them as pointers");
5136 switch (ID.Kind) {
5137 case ValID::t_LocalID:
5138 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5139 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5140 return V == nullptr;
5141 case ValID::t_LocalName:
5142 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
5143 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
5144 return V == nullptr;
5145 case ValID::t_InlineAsm: {
5146 if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
5147 return Error(ID.Loc, "invalid type for inline asm constraint string");
5148 V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
5149 (ID.UIntVal >> 1) & 1,
5150 (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
5151 return false;
5153 case ValID::t_GlobalName:
5154 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
5155 return V == nullptr;
5156 case ValID::t_GlobalID:
5157 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
5158 return V == nullptr;
5159 case ValID::t_APSInt:
5160 if (!Ty->isIntegerTy())
5161 return Error(ID.Loc, "integer constant must have integer type");
5162 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
5163 V = ConstantInt::get(Context, ID.APSIntVal);
5164 return false;
5165 case ValID::t_APFloat:
5166 if (!Ty->isFloatingPointTy() ||
5167 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
5168 return Error(ID.Loc, "floating point constant invalid for type");
5170 // The lexer has no type info, so builds all half, float, and double FP
5171 // constants as double. Fix this here. Long double does not need this.
5172 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
5173 bool Ignored;
5174 if (Ty->isHalfTy())
5175 ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
5176 &Ignored);
5177 else if (Ty->isFloatTy())
5178 ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
5179 &Ignored);
5181 V = ConstantFP::get(Context, ID.APFloatVal);
5183 if (V->getType() != Ty)
5184 return Error(ID.Loc, "floating point constant does not have type '" +
5185 getTypeString(Ty) + "'");
5187 return false;
5188 case ValID::t_Null:
5189 if (!Ty->isPointerTy())
5190 return Error(ID.Loc, "null must be a pointer type");
5191 V = ConstantPointerNull::get(cast<PointerType>(Ty));
5192 return false;
5193 case ValID::t_Undef:
5194 // FIXME: LabelTy should not be a first-class type.
5195 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5196 return Error(ID.Loc, "invalid type for undef constant");
5197 V = UndefValue::get(Ty);
5198 return false;
5199 case ValID::t_EmptyArray:
5200 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
5201 return Error(ID.Loc, "invalid empty array initializer");
5202 V = UndefValue::get(Ty);
5203 return false;
5204 case ValID::t_Zero:
5205 // FIXME: LabelTy should not be a first-class type.
5206 if (!Ty->isFirstClassType() || Ty->isLabelTy())
5207 return Error(ID.Loc, "invalid type for null constant");
5208 V = Constant::getNullValue(Ty);
5209 return false;
5210 case ValID::t_None:
5211 if (!Ty->isTokenTy())
5212 return Error(ID.Loc, "invalid type for none constant");
5213 V = Constant::getNullValue(Ty);
5214 return false;
5215 case ValID::t_Constant:
5216 if (ID.ConstantVal->getType() != Ty)
5217 return Error(ID.Loc, "constant expression type mismatch");
5219 V = ID.ConstantVal;
5220 return false;
5221 case ValID::t_ConstantStruct:
5222 case ValID::t_PackedConstantStruct:
5223 if (StructType *ST = dyn_cast<StructType>(Ty)) {
5224 if (ST->getNumElements() != ID.UIntVal)
5225 return Error(ID.Loc,
5226 "initializer with struct type has wrong # elements");
5227 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
5228 return Error(ID.Loc, "packed'ness of initializer and type don't match");
5230 // Verify that the elements are compatible with the structtype.
5231 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
5232 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
5233 return Error(ID.Loc, "element " + Twine(i) +
5234 " of struct initializer doesn't match struct element type");
5236 V = ConstantStruct::get(
5237 ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
5238 } else
5239 return Error(ID.Loc, "constant expression type mismatch");
5240 return false;
5242 llvm_unreachable("Invalid ValID");
5245 bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
5246 C = nullptr;
5247 ValID ID;
5248 auto Loc = Lex.getLoc();
5249 if (ParseValID(ID, /*PFS=*/nullptr))
5250 return true;
5251 switch (ID.Kind) {
5252 case ValID::t_APSInt:
5253 case ValID::t_APFloat:
5254 case ValID::t_Undef:
5255 case ValID::t_Constant:
5256 case ValID::t_ConstantStruct:
5257 case ValID::t_PackedConstantStruct: {
5258 Value *V;
5259 if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
5260 return true;
5261 assert(isa<Constant>(V) && "Expected a constant value");
5262 C = cast<Constant>(V);
5263 return false;
5265 case ValID::t_Null:
5266 C = Constant::getNullValue(Ty);
5267 return false;
5268 default:
5269 return Error(Loc, "expected a constant value");
5273 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
5274 V = nullptr;
5275 ValID ID;
5276 return ParseValID(ID, PFS) ||
5277 ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
5280 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
5281 Type *Ty = nullptr;
5282 return ParseType(Ty) ||
5283 ParseValue(Ty, V, PFS);
5286 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
5287 PerFunctionState &PFS) {
5288 Value *V;
5289 Loc = Lex.getLoc();
5290 if (ParseTypeAndValue(V, PFS)) return true;
5291 if (!isa<BasicBlock>(V))
5292 return Error(Loc, "expected a basic block");
5293 BB = cast<BasicBlock>(V);
5294 return false;
5297 /// FunctionHeader
5298 /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
5299 /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
5300 /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
5301 /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
5302 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
5303 // Parse the linkage.
5304 LocTy LinkageLoc = Lex.getLoc();
5305 unsigned Linkage;
5306 unsigned Visibility;
5307 unsigned DLLStorageClass;
5308 bool DSOLocal;
5309 AttrBuilder RetAttrs;
5310 unsigned CC;
5311 bool HasLinkage;
5312 Type *RetType = nullptr;
5313 LocTy RetTypeLoc = Lex.getLoc();
5314 if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
5315 DSOLocal) ||
5316 ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
5317 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
5318 return true;
5320 // Verify that the linkage is ok.
5321 switch ((GlobalValue::LinkageTypes)Linkage) {
5322 case GlobalValue::ExternalLinkage:
5323 break; // always ok.
5324 case GlobalValue::ExternalWeakLinkage:
5325 if (isDefine)
5326 return Error(LinkageLoc, "invalid linkage for function definition");
5327 break;
5328 case GlobalValue::PrivateLinkage:
5329 case GlobalValue::InternalLinkage:
5330 case GlobalValue::AvailableExternallyLinkage:
5331 case GlobalValue::LinkOnceAnyLinkage:
5332 case GlobalValue::LinkOnceODRLinkage:
5333 case GlobalValue::WeakAnyLinkage:
5334 case GlobalValue::WeakODRLinkage:
5335 if (!isDefine)
5336 return Error(LinkageLoc, "invalid linkage for function declaration");
5337 break;
5338 case GlobalValue::AppendingLinkage:
5339 case GlobalValue::CommonLinkage:
5340 return Error(LinkageLoc, "invalid function linkage type");
5343 if (!isValidVisibilityForLinkage(Visibility, Linkage))
5344 return Error(LinkageLoc,
5345 "symbol with local linkage must have default visibility");
5347 if (!FunctionType::isValidReturnType(RetType))
5348 return Error(RetTypeLoc, "invalid function return type");
5350 LocTy NameLoc = Lex.getLoc();
5352 std::string FunctionName;
5353 if (Lex.getKind() == lltok::GlobalVar) {
5354 FunctionName = Lex.getStrVal();
5355 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
5356 unsigned NameID = Lex.getUIntVal();
5358 if (NameID != NumberedVals.size())
5359 return TokError("function expected to be numbered '%" +
5360 Twine(NumberedVals.size()) + "'");
5361 } else {
5362 return TokError("expected function name");
5365 Lex.Lex();
5367 if (Lex.getKind() != lltok::lparen)
5368 return TokError("expected '(' in function argument list");
5370 SmallVector<ArgInfo, 8> ArgList;
5371 bool isVarArg;
5372 AttrBuilder FuncAttrs;
5373 std::vector<unsigned> FwdRefAttrGrps;
5374 LocTy BuiltinLoc;
5375 std::string Section;
5376 std::string Partition;
5377 MaybeAlign Alignment;
5378 std::string GC;
5379 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
5380 unsigned AddrSpace = 0;
5381 Constant *Prefix = nullptr;
5382 Constant *Prologue = nullptr;
5383 Constant *PersonalityFn = nullptr;
5384 Comdat *C;
5386 if (ParseArgumentList(ArgList, isVarArg) ||
5387 ParseOptionalUnnamedAddr(UnnamedAddr) ||
5388 ParseOptionalProgramAddrSpace(AddrSpace) ||
5389 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
5390 BuiltinLoc) ||
5391 (EatIfPresent(lltok::kw_section) &&
5392 ParseStringConstant(Section)) ||
5393 (EatIfPresent(lltok::kw_partition) &&
5394 ParseStringConstant(Partition)) ||
5395 parseOptionalComdat(FunctionName, C) ||
5396 ParseOptionalAlignment(Alignment) ||
5397 (EatIfPresent(lltok::kw_gc) &&
5398 ParseStringConstant(GC)) ||
5399 (EatIfPresent(lltok::kw_prefix) &&
5400 ParseGlobalTypeAndValue(Prefix)) ||
5401 (EatIfPresent(lltok::kw_prologue) &&
5402 ParseGlobalTypeAndValue(Prologue)) ||
5403 (EatIfPresent(lltok::kw_personality) &&
5404 ParseGlobalTypeAndValue(PersonalityFn)))
5405 return true;
5407 if (FuncAttrs.contains(Attribute::Builtin))
5408 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
5410 // If the alignment was parsed as an attribute, move to the alignment field.
5411 if (FuncAttrs.hasAlignmentAttr()) {
5412 Alignment = FuncAttrs.getAlignment();
5413 FuncAttrs.removeAttribute(Attribute::Alignment);
5416 // Okay, if we got here, the function is syntactically valid. Convert types
5417 // and do semantic checks.
5418 std::vector<Type*> ParamTypeList;
5419 SmallVector<AttributeSet, 8> Attrs;
5421 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5422 ParamTypeList.push_back(ArgList[i].Ty);
5423 Attrs.push_back(ArgList[i].Attrs);
5426 AttributeList PAL =
5427 AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
5428 AttributeSet::get(Context, RetAttrs), Attrs);
5430 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
5431 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
5433 FunctionType *FT =
5434 FunctionType::get(RetType, ParamTypeList, isVarArg);
5435 PointerType *PFT = PointerType::get(FT, AddrSpace);
5437 Fn = nullptr;
5438 if (!FunctionName.empty()) {
5439 // If this was a definition of a forward reference, remove the definition
5440 // from the forward reference table and fill in the forward ref.
5441 auto FRVI = ForwardRefVals.find(FunctionName);
5442 if (FRVI != ForwardRefVals.end()) {
5443 Fn = M->getFunction(FunctionName);
5444 if (!Fn)
5445 return Error(FRVI->second.second, "invalid forward reference to "
5446 "function as global value!");
5447 if (Fn->getType() != PFT)
5448 return Error(FRVI->second.second, "invalid forward reference to "
5449 "function '" + FunctionName + "' with wrong type: "
5450 "expected '" + getTypeString(PFT) + "' but was '" +
5451 getTypeString(Fn->getType()) + "'");
5452 ForwardRefVals.erase(FRVI);
5453 } else if ((Fn = M->getFunction(FunctionName))) {
5454 // Reject redefinitions.
5455 return Error(NameLoc, "invalid redefinition of function '" +
5456 FunctionName + "'");
5457 } else if (M->getNamedValue(FunctionName)) {
5458 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
5461 } else {
5462 // If this is a definition of a forward referenced function, make sure the
5463 // types agree.
5464 auto I = ForwardRefValIDs.find(NumberedVals.size());
5465 if (I != ForwardRefValIDs.end()) {
5466 Fn = cast<Function>(I->second.first);
5467 if (Fn->getType() != PFT)
5468 return Error(NameLoc, "type of definition and forward reference of '@" +
5469 Twine(NumberedVals.size()) + "' disagree: "
5470 "expected '" + getTypeString(PFT) + "' but was '" +
5471 getTypeString(Fn->getType()) + "'");
5472 ForwardRefValIDs.erase(I);
5476 if (!Fn)
5477 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
5478 FunctionName, M);
5479 else // Move the forward-reference to the correct spot in the module.
5480 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
5482 assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
5484 if (FunctionName.empty())
5485 NumberedVals.push_back(Fn);
5487 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
5488 maybeSetDSOLocal(DSOLocal, *Fn);
5489 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
5490 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
5491 Fn->setCallingConv(CC);
5492 Fn->setAttributes(PAL);
5493 Fn->setUnnamedAddr(UnnamedAddr);
5494 Fn->setAlignment(MaybeAlign(Alignment));
5495 Fn->setSection(Section);
5496 Fn->setPartition(Partition);
5497 Fn->setComdat(C);
5498 Fn->setPersonalityFn(PersonalityFn);
5499 if (!GC.empty()) Fn->setGC(GC);
5500 Fn->setPrefixData(Prefix);
5501 Fn->setPrologueData(Prologue);
5502 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
5504 // Add all of the arguments we parsed to the function.
5505 Function::arg_iterator ArgIt = Fn->arg_begin();
5506 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
5507 // If the argument has a name, insert it into the argument symbol table.
5508 if (ArgList[i].Name.empty()) continue;
5510 // Set the name, if it conflicted, it will be auto-renamed.
5511 ArgIt->setName(ArgList[i].Name);
5513 if (ArgIt->getName() != ArgList[i].Name)
5514 return Error(ArgList[i].Loc, "redefinition of argument '%" +
5515 ArgList[i].Name + "'");
5518 if (isDefine)
5519 return false;
5521 // Check the declaration has no block address forward references.
5522 ValID ID;
5523 if (FunctionName.empty()) {
5524 ID.Kind = ValID::t_GlobalID;
5525 ID.UIntVal = NumberedVals.size() - 1;
5526 } else {
5527 ID.Kind = ValID::t_GlobalName;
5528 ID.StrVal = FunctionName;
5530 auto Blocks = ForwardRefBlockAddresses.find(ID);
5531 if (Blocks != ForwardRefBlockAddresses.end())
5532 return Error(Blocks->first.Loc,
5533 "cannot take blockaddress inside a declaration");
5534 return false;
5537 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
5538 ValID ID;
5539 if (FunctionNumber == -1) {
5540 ID.Kind = ValID::t_GlobalName;
5541 ID.StrVal = F.getName();
5542 } else {
5543 ID.Kind = ValID::t_GlobalID;
5544 ID.UIntVal = FunctionNumber;
5547 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
5548 if (Blocks == P.ForwardRefBlockAddresses.end())
5549 return false;
5551 for (const auto &I : Blocks->second) {
5552 const ValID &BBID = I.first;
5553 GlobalValue *GV = I.second;
5555 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
5556 "Expected local id or name");
5557 BasicBlock *BB;
5558 if (BBID.Kind == ValID::t_LocalName)
5559 BB = GetBB(BBID.StrVal, BBID.Loc);
5560 else
5561 BB = GetBB(BBID.UIntVal, BBID.Loc);
5562 if (!BB)
5563 return P.Error(BBID.Loc, "referenced value is not a basic block");
5565 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
5566 GV->eraseFromParent();
5569 P.ForwardRefBlockAddresses.erase(Blocks);
5570 return false;
5573 /// ParseFunctionBody
5574 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
5575 bool LLParser::ParseFunctionBody(Function &Fn) {
5576 if (Lex.getKind() != lltok::lbrace)
5577 return TokError("expected '{' in function body");
5578 Lex.Lex(); // eat the {.
5580 int FunctionNumber = -1;
5581 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
5583 PerFunctionState PFS(*this, Fn, FunctionNumber);
5585 // Resolve block addresses and allow basic blocks to be forward-declared
5586 // within this function.
5587 if (PFS.resolveForwardRefBlockAddresses())
5588 return true;
5589 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
5591 // We need at least one basic block.
5592 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
5593 return TokError("function body requires at least one basic block");
5595 while (Lex.getKind() != lltok::rbrace &&
5596 Lex.getKind() != lltok::kw_uselistorder)
5597 if (ParseBasicBlock(PFS)) return true;
5599 while (Lex.getKind() != lltok::rbrace)
5600 if (ParseUseListOrder(&PFS))
5601 return true;
5603 // Eat the }.
5604 Lex.Lex();
5606 // Verify function is ok.
5607 return PFS.FinishFunction();
5610 /// ParseBasicBlock
5611 /// ::= (LabelStr|LabelID)? Instruction*
5612 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
5613 // If this basic block starts out with a name, remember it.
5614 std::string Name;
5615 int NameID = -1;
5616 LocTy NameLoc = Lex.getLoc();
5617 if (Lex.getKind() == lltok::LabelStr) {
5618 Name = Lex.getStrVal();
5619 Lex.Lex();
5620 } else if (Lex.getKind() == lltok::LabelID) {
5621 NameID = Lex.getUIntVal();
5622 Lex.Lex();
5625 BasicBlock *BB = PFS.DefineBB(Name, NameID, NameLoc);
5626 if (!BB)
5627 return true;
5629 std::string NameStr;
5631 // Parse the instructions in this block until we get a terminator.
5632 Instruction *Inst;
5633 do {
5634 // This instruction may have three possibilities for a name: a) none
5635 // specified, b) name specified "%foo =", c) number specified: "%4 =".
5636 LocTy NameLoc = Lex.getLoc();
5637 int NameID = -1;
5638 NameStr = "";
5640 if (Lex.getKind() == lltok::LocalVarID) {
5641 NameID = Lex.getUIntVal();
5642 Lex.Lex();
5643 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
5644 return true;
5645 } else if (Lex.getKind() == lltok::LocalVar) {
5646 NameStr = Lex.getStrVal();
5647 Lex.Lex();
5648 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
5649 return true;
5652 switch (ParseInstruction(Inst, BB, PFS)) {
5653 default: llvm_unreachable("Unknown ParseInstruction result!");
5654 case InstError: return true;
5655 case InstNormal:
5656 BB->getInstList().push_back(Inst);
5658 // With a normal result, we check to see if the instruction is followed by
5659 // a comma and metadata.
5660 if (EatIfPresent(lltok::comma))
5661 if (ParseInstructionMetadata(*Inst))
5662 return true;
5663 break;
5664 case InstExtraComma:
5665 BB->getInstList().push_back(Inst);
5667 // If the instruction parser ate an extra comma at the end of it, it
5668 // *must* be followed by metadata.
5669 if (ParseInstructionMetadata(*Inst))
5670 return true;
5671 break;
5674 // Set the name on the instruction.
5675 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
5676 } while (!Inst->isTerminator());
5678 return false;
5681 //===----------------------------------------------------------------------===//
5682 // Instruction Parsing.
5683 //===----------------------------------------------------------------------===//
5685 /// ParseInstruction - Parse one of the many different instructions.
5687 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
5688 PerFunctionState &PFS) {
5689 lltok::Kind Token = Lex.getKind();
5690 if (Token == lltok::Eof)
5691 return TokError("found end of file when expecting more instructions");
5692 LocTy Loc = Lex.getLoc();
5693 unsigned KeywordVal = Lex.getUIntVal();
5694 Lex.Lex(); // Eat the keyword.
5696 switch (Token) {
5697 default: return Error(Loc, "expected instruction opcode");
5698 // Terminator Instructions.
5699 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
5700 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
5701 case lltok::kw_br: return ParseBr(Inst, PFS);
5702 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
5703 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
5704 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
5705 case lltok::kw_resume: return ParseResume(Inst, PFS);
5706 case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
5707 case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
5708 case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
5709 case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
5710 case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
5711 case lltok::kw_callbr: return ParseCallBr(Inst, PFS);
5712 // Unary Operators.
5713 case lltok::kw_fneg: {
5714 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5715 int Res = ParseUnaryOp(Inst, PFS, KeywordVal, /*IsFP*/true);
5716 if (Res != 0)
5717 return Res;
5718 if (FMF.any())
5719 Inst->setFastMathFlags(FMF);
5720 return false;
5722 // Binary Operators.
5723 case lltok::kw_add:
5724 case lltok::kw_sub:
5725 case lltok::kw_mul:
5726 case lltok::kw_shl: {
5727 bool NUW = EatIfPresent(lltok::kw_nuw);
5728 bool NSW = EatIfPresent(lltok::kw_nsw);
5729 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
5731 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true;
5733 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
5734 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
5735 return false;
5737 case lltok::kw_fadd:
5738 case lltok::kw_fsub:
5739 case lltok::kw_fmul:
5740 case lltok::kw_fdiv:
5741 case lltok::kw_frem: {
5742 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5743 int Res = ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/true);
5744 if (Res != 0)
5745 return Res;
5746 if (FMF.any())
5747 Inst->setFastMathFlags(FMF);
5748 return 0;
5751 case lltok::kw_sdiv:
5752 case lltok::kw_udiv:
5753 case lltok::kw_lshr:
5754 case lltok::kw_ashr: {
5755 bool Exact = EatIfPresent(lltok::kw_exact);
5757 if (ParseArithmetic(Inst, PFS, KeywordVal, /*IsFP*/false)) return true;
5758 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
5759 return false;
5762 case lltok::kw_urem:
5763 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal,
5764 /*IsFP*/false);
5765 case lltok::kw_and:
5766 case lltok::kw_or:
5767 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
5768 case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
5769 case lltok::kw_fcmp: {
5770 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5771 int Res = ParseCompare(Inst, PFS, KeywordVal);
5772 if (Res != 0)
5773 return Res;
5774 if (FMF.any())
5775 Inst->setFastMathFlags(FMF);
5776 return 0;
5779 // Casts.
5780 case lltok::kw_trunc:
5781 case lltok::kw_zext:
5782 case lltok::kw_sext:
5783 case lltok::kw_fptrunc:
5784 case lltok::kw_fpext:
5785 case lltok::kw_bitcast:
5786 case lltok::kw_addrspacecast:
5787 case lltok::kw_uitofp:
5788 case lltok::kw_sitofp:
5789 case lltok::kw_fptoui:
5790 case lltok::kw_fptosi:
5791 case lltok::kw_inttoptr:
5792 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
5793 // Other.
5794 case lltok::kw_select: {
5795 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5796 int Res = ParseSelect(Inst, PFS);
5797 if (Res != 0)
5798 return Res;
5799 if (FMF.any()) {
5800 if (!Inst->getType()->isFPOrFPVectorTy())
5801 return Error(Loc, "fast-math-flags specified for select without "
5802 "floating-point scalar or vector return type");
5803 Inst->setFastMathFlags(FMF);
5805 return 0;
5807 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
5808 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
5809 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
5810 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
5811 case lltok::kw_phi: {
5812 FastMathFlags FMF = EatFastMathFlagsIfPresent();
5813 int Res = ParsePHI(Inst, PFS);
5814 if (Res != 0)
5815 return Res;
5816 if (FMF.any()) {
5817 if (!Inst->getType()->isFPOrFPVectorTy())
5818 return Error(Loc, "fast-math-flags specified for phi without "
5819 "floating-point scalar or vector return type");
5820 Inst->setFastMathFlags(FMF);
5822 return 0;
5824 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
5825 // Call.
5826 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
5827 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
5828 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
5829 case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
5830 // Memory.
5831 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
5832 case lltok::kw_load: return ParseLoad(Inst, PFS);
5833 case lltok::kw_store: return ParseStore(Inst, PFS);
5834 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
5835 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
5836 case lltok::kw_fence: return ParseFence(Inst, PFS);
5837 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
5838 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
5839 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
5843 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
5844 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
5845 if (Opc == Instruction::FCmp) {
5846 switch (Lex.getKind()) {
5847 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
5848 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
5849 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
5850 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
5851 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
5852 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
5853 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
5854 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
5855 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
5856 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
5857 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
5858 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
5859 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
5860 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
5861 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
5862 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
5863 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
5865 } else {
5866 switch (Lex.getKind()) {
5867 default: return TokError("expected icmp predicate (e.g. 'eq')");
5868 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
5869 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
5870 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
5871 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
5872 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
5873 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
5874 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
5875 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
5876 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
5877 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
5880 Lex.Lex();
5881 return false;
5884 //===----------------------------------------------------------------------===//
5885 // Terminator Instructions.
5886 //===----------------------------------------------------------------------===//
5888 /// ParseRet - Parse a return instruction.
5889 /// ::= 'ret' void (',' !dbg, !1)*
5890 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
5891 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
5892 PerFunctionState &PFS) {
5893 SMLoc TypeLoc = Lex.getLoc();
5894 Type *Ty = nullptr;
5895 if (ParseType(Ty, true /*void allowed*/)) return true;
5897 Type *ResType = PFS.getFunction().getReturnType();
5899 if (Ty->isVoidTy()) {
5900 if (!ResType->isVoidTy())
5901 return Error(TypeLoc, "value doesn't match function result type '" +
5902 getTypeString(ResType) + "'");
5904 Inst = ReturnInst::Create(Context);
5905 return false;
5908 Value *RV;
5909 if (ParseValue(Ty, RV, PFS)) return true;
5911 if (ResType != RV->getType())
5912 return Error(TypeLoc, "value doesn't match function result type '" +
5913 getTypeString(ResType) + "'");
5915 Inst = ReturnInst::Create(Context, RV);
5916 return false;
5919 /// ParseBr
5920 /// ::= 'br' TypeAndValue
5921 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5922 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
5923 LocTy Loc, Loc2;
5924 Value *Op0;
5925 BasicBlock *Op1, *Op2;
5926 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
5928 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
5929 Inst = BranchInst::Create(BB);
5930 return false;
5933 if (Op0->getType() != Type::getInt1Ty(Context))
5934 return Error(Loc, "branch condition must have 'i1' type");
5936 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
5937 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
5938 ParseToken(lltok::comma, "expected ',' after true destination") ||
5939 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
5940 return true;
5942 Inst = BranchInst::Create(Op1, Op2, Op0);
5943 return false;
5946 /// ParseSwitch
5947 /// Instruction
5948 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
5949 /// JumpTable
5950 /// ::= (TypeAndValue ',' TypeAndValue)*
5951 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
5952 LocTy CondLoc, BBLoc;
5953 Value *Cond;
5954 BasicBlock *DefaultBB;
5955 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
5956 ParseToken(lltok::comma, "expected ',' after switch condition") ||
5957 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
5958 ParseToken(lltok::lsquare, "expected '[' with switch table"))
5959 return true;
5961 if (!Cond->getType()->isIntegerTy())
5962 return Error(CondLoc, "switch condition must have integer type");
5964 // Parse the jump table pairs.
5965 SmallPtrSet<Value*, 32> SeenCases;
5966 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
5967 while (Lex.getKind() != lltok::rsquare) {
5968 Value *Constant;
5969 BasicBlock *DestBB;
5971 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
5972 ParseToken(lltok::comma, "expected ',' after case value") ||
5973 ParseTypeAndBasicBlock(DestBB, PFS))
5974 return true;
5976 if (!SeenCases.insert(Constant).second)
5977 return Error(CondLoc, "duplicate case value in switch");
5978 if (!isa<ConstantInt>(Constant))
5979 return Error(CondLoc, "case value is not a constant integer");
5981 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
5984 Lex.Lex(); // Eat the ']'.
5986 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
5987 for (unsigned i = 0, e = Table.size(); i != e; ++i)
5988 SI->addCase(Table[i].first, Table[i].second);
5989 Inst = SI;
5990 return false;
5993 /// ParseIndirectBr
5994 /// Instruction
5995 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
5996 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
5997 LocTy AddrLoc;
5998 Value *Address;
5999 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
6000 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
6001 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
6002 return true;
6004 if (!Address->getType()->isPointerTy())
6005 return Error(AddrLoc, "indirectbr address must have pointer type");
6007 // Parse the destination list.
6008 SmallVector<BasicBlock*, 16> DestList;
6010 if (Lex.getKind() != lltok::rsquare) {
6011 BasicBlock *DestBB;
6012 if (ParseTypeAndBasicBlock(DestBB, PFS))
6013 return true;
6014 DestList.push_back(DestBB);
6016 while (EatIfPresent(lltok::comma)) {
6017 if (ParseTypeAndBasicBlock(DestBB, PFS))
6018 return true;
6019 DestList.push_back(DestBB);
6023 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
6024 return true;
6026 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
6027 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
6028 IBI->addDestination(DestList[i]);
6029 Inst = IBI;
6030 return false;
6033 /// ParseInvoke
6034 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
6035 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
6036 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
6037 LocTy CallLoc = Lex.getLoc();
6038 AttrBuilder RetAttrs, FnAttrs;
6039 std::vector<unsigned> FwdRefAttrGrps;
6040 LocTy NoBuiltinLoc;
6041 unsigned CC;
6042 unsigned InvokeAddrSpace;
6043 Type *RetType = nullptr;
6044 LocTy RetTypeLoc;
6045 ValID CalleeID;
6046 SmallVector<ParamInfo, 16> ArgList;
6047 SmallVector<OperandBundleDef, 2> BundleList;
6049 BasicBlock *NormalBB, *UnwindBB;
6050 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6051 ParseOptionalProgramAddrSpace(InvokeAddrSpace) ||
6052 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6053 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
6054 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6055 NoBuiltinLoc) ||
6056 ParseOptionalOperandBundles(BundleList, PFS) ||
6057 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
6058 ParseTypeAndBasicBlock(NormalBB, PFS) ||
6059 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
6060 ParseTypeAndBasicBlock(UnwindBB, PFS))
6061 return true;
6063 // If RetType is a non-function pointer type, then this is the short syntax
6064 // for the call, which means that RetType is just the return type. Infer the
6065 // rest of the function argument types from the arguments that are present.
6066 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6067 if (!Ty) {
6068 // Pull out the types of all of the arguments...
6069 std::vector<Type*> ParamTypes;
6070 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6071 ParamTypes.push_back(ArgList[i].V->getType());
6073 if (!FunctionType::isValidReturnType(RetType))
6074 return Error(RetTypeLoc, "Invalid result type for LLVM function");
6076 Ty = FunctionType::get(RetType, ParamTypes, false);
6079 CalleeID.FTy = Ty;
6081 // Look up the callee.
6082 Value *Callee;
6083 if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
6084 Callee, &PFS, /*IsCall=*/true))
6085 return true;
6087 // Set up the Attribute for the function.
6088 SmallVector<Value *, 8> Args;
6089 SmallVector<AttributeSet, 8> ArgAttrs;
6091 // Loop through FunctionType's arguments and ensure they are specified
6092 // correctly. Also, gather any parameter attributes.
6093 FunctionType::param_iterator I = Ty->param_begin();
6094 FunctionType::param_iterator E = Ty->param_end();
6095 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6096 Type *ExpectedTy = nullptr;
6097 if (I != E) {
6098 ExpectedTy = *I++;
6099 } else if (!Ty->isVarArg()) {
6100 return Error(ArgList[i].Loc, "too many arguments specified");
6103 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6104 return Error(ArgList[i].Loc, "argument is not of expected type '" +
6105 getTypeString(ExpectedTy) + "'");
6106 Args.push_back(ArgList[i].V);
6107 ArgAttrs.push_back(ArgList[i].Attrs);
6110 if (I != E)
6111 return Error(CallLoc, "not enough parameters specified for call");
6113 if (FnAttrs.hasAlignmentAttr())
6114 return Error(CallLoc, "invoke instructions may not have an alignment");
6116 // Finish off the Attribute and check them
6117 AttributeList PAL =
6118 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6119 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6121 InvokeInst *II =
6122 InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
6123 II->setCallingConv(CC);
6124 II->setAttributes(PAL);
6125 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
6126 Inst = II;
6127 return false;
6130 /// ParseResume
6131 /// ::= 'resume' TypeAndValue
6132 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
6133 Value *Exn; LocTy ExnLoc;
6134 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
6135 return true;
6137 ResumeInst *RI = ResumeInst::Create(Exn);
6138 Inst = RI;
6139 return false;
6142 bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
6143 PerFunctionState &PFS) {
6144 if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
6145 return true;
6147 while (Lex.getKind() != lltok::rsquare) {
6148 // If this isn't the first argument, we need a comma.
6149 if (!Args.empty() &&
6150 ParseToken(lltok::comma, "expected ',' in argument list"))
6151 return true;
6153 // Parse the argument.
6154 LocTy ArgLoc;
6155 Type *ArgTy = nullptr;
6156 if (ParseType(ArgTy, ArgLoc))
6157 return true;
6159 Value *V;
6160 if (ArgTy->isMetadataTy()) {
6161 if (ParseMetadataAsValue(V, PFS))
6162 return true;
6163 } else {
6164 if (ParseValue(ArgTy, V, PFS))
6165 return true;
6167 Args.push_back(V);
6170 Lex.Lex(); // Lex the ']'.
6171 return false;
6174 /// ParseCleanupRet
6175 /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
6176 bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
6177 Value *CleanupPad = nullptr;
6179 if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
6180 return true;
6182 if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
6183 return true;
6185 if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
6186 return true;
6188 BasicBlock *UnwindBB = nullptr;
6189 if (Lex.getKind() == lltok::kw_to) {
6190 Lex.Lex();
6191 if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
6192 return true;
6193 } else {
6194 if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
6195 return true;
6199 Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
6200 return false;
6203 /// ParseCatchRet
6204 /// ::= 'catchret' from Parent Value 'to' TypeAndValue
6205 bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
6206 Value *CatchPad = nullptr;
6208 if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
6209 return true;
6211 if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
6212 return true;
6214 BasicBlock *BB;
6215 if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
6216 ParseTypeAndBasicBlock(BB, PFS))
6217 return true;
6219 Inst = CatchReturnInst::Create(CatchPad, BB);
6220 return false;
6223 /// ParseCatchSwitch
6224 /// ::= 'catchswitch' within Parent
6225 bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
6226 Value *ParentPad;
6228 if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
6229 return true;
6231 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6232 Lex.getKind() != lltok::LocalVarID)
6233 return TokError("expected scope value for catchswitch");
6235 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6236 return true;
6238 if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
6239 return true;
6241 SmallVector<BasicBlock *, 32> Table;
6242 do {
6243 BasicBlock *DestBB;
6244 if (ParseTypeAndBasicBlock(DestBB, PFS))
6245 return true;
6246 Table.push_back(DestBB);
6247 } while (EatIfPresent(lltok::comma));
6249 if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
6250 return true;
6252 if (ParseToken(lltok::kw_unwind,
6253 "expected 'unwind' after catchswitch scope"))
6254 return true;
6256 BasicBlock *UnwindBB = nullptr;
6257 if (EatIfPresent(lltok::kw_to)) {
6258 if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
6259 return true;
6260 } else {
6261 if (ParseTypeAndBasicBlock(UnwindBB, PFS))
6262 return true;
6265 auto *CatchSwitch =
6266 CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
6267 for (BasicBlock *DestBB : Table)
6268 CatchSwitch->addHandler(DestBB);
6269 Inst = CatchSwitch;
6270 return false;
6273 /// ParseCatchPad
6274 /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
6275 bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
6276 Value *CatchSwitch = nullptr;
6278 if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
6279 return true;
6281 if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
6282 return TokError("expected scope value for catchpad");
6284 if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
6285 return true;
6287 SmallVector<Value *, 8> Args;
6288 if (ParseExceptionArgs(Args, PFS))
6289 return true;
6291 Inst = CatchPadInst::Create(CatchSwitch, Args);
6292 return false;
6295 /// ParseCleanupPad
6296 /// ::= 'cleanuppad' within Parent ParamList
6297 bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
6298 Value *ParentPad = nullptr;
6300 if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
6301 return true;
6303 if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
6304 Lex.getKind() != lltok::LocalVarID)
6305 return TokError("expected scope value for cleanuppad");
6307 if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
6308 return true;
6310 SmallVector<Value *, 8> Args;
6311 if (ParseExceptionArgs(Args, PFS))
6312 return true;
6314 Inst = CleanupPadInst::Create(ParentPad, Args);
6315 return false;
6318 //===----------------------------------------------------------------------===//
6319 // Unary Operators.
6320 //===----------------------------------------------------------------------===//
6322 /// ParseUnaryOp
6323 /// ::= UnaryOp TypeAndValue ',' Value
6325 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6326 /// operand is allowed.
6327 bool LLParser::ParseUnaryOp(Instruction *&Inst, PerFunctionState &PFS,
6328 unsigned Opc, bool IsFP) {
6329 LocTy Loc; Value *LHS;
6330 if (ParseTypeAndValue(LHS, Loc, PFS))
6331 return true;
6333 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6334 : LHS->getType()->isIntOrIntVectorTy();
6336 if (!Valid)
6337 return Error(Loc, "invalid operand type for instruction");
6339 Inst = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
6340 return false;
6343 /// ParseCallBr
6344 /// ::= 'callbr' OptionalCallingConv OptionalAttrs Type Value ParamList
6345 /// OptionalAttrs OptionalOperandBundles 'to' TypeAndValue
6346 /// '[' LabelList ']'
6347 bool LLParser::ParseCallBr(Instruction *&Inst, PerFunctionState &PFS) {
6348 LocTy CallLoc = Lex.getLoc();
6349 AttrBuilder RetAttrs, FnAttrs;
6350 std::vector<unsigned> FwdRefAttrGrps;
6351 LocTy NoBuiltinLoc;
6352 unsigned CC;
6353 Type *RetType = nullptr;
6354 LocTy RetTypeLoc;
6355 ValID CalleeID;
6356 SmallVector<ParamInfo, 16> ArgList;
6357 SmallVector<OperandBundleDef, 2> BundleList;
6359 BasicBlock *DefaultDest;
6360 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6361 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6362 ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
6363 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
6364 NoBuiltinLoc) ||
6365 ParseOptionalOperandBundles(BundleList, PFS) ||
6366 ParseToken(lltok::kw_to, "expected 'to' in callbr") ||
6367 ParseTypeAndBasicBlock(DefaultDest, PFS) ||
6368 ParseToken(lltok::lsquare, "expected '[' in callbr"))
6369 return true;
6371 // Parse the destination list.
6372 SmallVector<BasicBlock *, 16> IndirectDests;
6374 if (Lex.getKind() != lltok::rsquare) {
6375 BasicBlock *DestBB;
6376 if (ParseTypeAndBasicBlock(DestBB, PFS))
6377 return true;
6378 IndirectDests.push_back(DestBB);
6380 while (EatIfPresent(lltok::comma)) {
6381 if (ParseTypeAndBasicBlock(DestBB, PFS))
6382 return true;
6383 IndirectDests.push_back(DestBB);
6387 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
6388 return true;
6390 // If RetType is a non-function pointer type, then this is the short syntax
6391 // for the call, which means that RetType is just the return type. Infer the
6392 // rest of the function argument types from the arguments that are present.
6393 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6394 if (!Ty) {
6395 // Pull out the types of all of the arguments...
6396 std::vector<Type *> ParamTypes;
6397 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6398 ParamTypes.push_back(ArgList[i].V->getType());
6400 if (!FunctionType::isValidReturnType(RetType))
6401 return Error(RetTypeLoc, "Invalid result type for LLVM function");
6403 Ty = FunctionType::get(RetType, ParamTypes, false);
6406 CalleeID.FTy = Ty;
6408 // Look up the callee.
6409 Value *Callee;
6410 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS,
6411 /*IsCall=*/true))
6412 return true;
6414 if (isa<InlineAsm>(Callee) && !Ty->getReturnType()->isVoidTy())
6415 return Error(RetTypeLoc, "asm-goto outputs not supported");
6417 // Set up the Attribute for the function.
6418 SmallVector<Value *, 8> Args;
6419 SmallVector<AttributeSet, 8> ArgAttrs;
6421 // Loop through FunctionType's arguments and ensure they are specified
6422 // correctly. Also, gather any parameter attributes.
6423 FunctionType::param_iterator I = Ty->param_begin();
6424 FunctionType::param_iterator E = Ty->param_end();
6425 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6426 Type *ExpectedTy = nullptr;
6427 if (I != E) {
6428 ExpectedTy = *I++;
6429 } else if (!Ty->isVarArg()) {
6430 return Error(ArgList[i].Loc, "too many arguments specified");
6433 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6434 return Error(ArgList[i].Loc, "argument is not of expected type '" +
6435 getTypeString(ExpectedTy) + "'");
6436 Args.push_back(ArgList[i].V);
6437 ArgAttrs.push_back(ArgList[i].Attrs);
6440 if (I != E)
6441 return Error(CallLoc, "not enough parameters specified for call");
6443 if (FnAttrs.hasAlignmentAttr())
6444 return Error(CallLoc, "callbr instructions may not have an alignment");
6446 // Finish off the Attribute and check them
6447 AttributeList PAL =
6448 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6449 AttributeSet::get(Context, RetAttrs), ArgAttrs);
6451 CallBrInst *CBI =
6452 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
6453 BundleList);
6454 CBI->setCallingConv(CC);
6455 CBI->setAttributes(PAL);
6456 ForwardRefAttrGroups[CBI] = FwdRefAttrGrps;
6457 Inst = CBI;
6458 return false;
6461 //===----------------------------------------------------------------------===//
6462 // Binary Operators.
6463 //===----------------------------------------------------------------------===//
6465 /// ParseArithmetic
6466 /// ::= ArithmeticOps TypeAndValue ',' Value
6468 /// If IsFP is false, then any integer operand is allowed, if it is true, any fp
6469 /// operand is allowed.
6470 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
6471 unsigned Opc, bool IsFP) {
6472 LocTy Loc; Value *LHS, *RHS;
6473 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6474 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
6475 ParseValue(LHS->getType(), RHS, PFS))
6476 return true;
6478 bool Valid = IsFP ? LHS->getType()->isFPOrFPVectorTy()
6479 : LHS->getType()->isIntOrIntVectorTy();
6481 if (!Valid)
6482 return Error(Loc, "invalid operand type for instruction");
6484 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6485 return false;
6488 /// ParseLogical
6489 /// ::= ArithmeticOps TypeAndValue ',' Value {
6490 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
6491 unsigned Opc) {
6492 LocTy Loc; Value *LHS, *RHS;
6493 if (ParseTypeAndValue(LHS, Loc, PFS) ||
6494 ParseToken(lltok::comma, "expected ',' in logical operation") ||
6495 ParseValue(LHS->getType(), RHS, PFS))
6496 return true;
6498 if (!LHS->getType()->isIntOrIntVectorTy())
6499 return Error(Loc,"instruction requires integer or integer vector operands");
6501 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
6502 return false;
6505 /// ParseCompare
6506 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
6507 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
6508 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
6509 unsigned Opc) {
6510 // Parse the integer/fp comparison predicate.
6511 LocTy Loc;
6512 unsigned Pred;
6513 Value *LHS, *RHS;
6514 if (ParseCmpPredicate(Pred, Opc) ||
6515 ParseTypeAndValue(LHS, Loc, PFS) ||
6516 ParseToken(lltok::comma, "expected ',' after compare value") ||
6517 ParseValue(LHS->getType(), RHS, PFS))
6518 return true;
6520 if (Opc == Instruction::FCmp) {
6521 if (!LHS->getType()->isFPOrFPVectorTy())
6522 return Error(Loc, "fcmp requires floating point operands");
6523 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6524 } else {
6525 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
6526 if (!LHS->getType()->isIntOrIntVectorTy() &&
6527 !LHS->getType()->isPtrOrPtrVectorTy())
6528 return Error(Loc, "icmp requires integer operands");
6529 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
6531 return false;
6534 //===----------------------------------------------------------------------===//
6535 // Other Instructions.
6536 //===----------------------------------------------------------------------===//
6539 /// ParseCast
6540 /// ::= CastOpc TypeAndValue 'to' Type
6541 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
6542 unsigned Opc) {
6543 LocTy Loc;
6544 Value *Op;
6545 Type *DestTy = nullptr;
6546 if (ParseTypeAndValue(Op, Loc, PFS) ||
6547 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
6548 ParseType(DestTy))
6549 return true;
6551 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
6552 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
6553 return Error(Loc, "invalid cast opcode for cast from '" +
6554 getTypeString(Op->getType()) + "' to '" +
6555 getTypeString(DestTy) + "'");
6557 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
6558 return false;
6561 /// ParseSelect
6562 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6563 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
6564 LocTy Loc;
6565 Value *Op0, *Op1, *Op2;
6566 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6567 ParseToken(lltok::comma, "expected ',' after select condition") ||
6568 ParseTypeAndValue(Op1, PFS) ||
6569 ParseToken(lltok::comma, "expected ',' after select value") ||
6570 ParseTypeAndValue(Op2, PFS))
6571 return true;
6573 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
6574 return Error(Loc, Reason);
6576 Inst = SelectInst::Create(Op0, Op1, Op2);
6577 return false;
6580 /// ParseVA_Arg
6581 /// ::= 'va_arg' TypeAndValue ',' Type
6582 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
6583 Value *Op;
6584 Type *EltTy = nullptr;
6585 LocTy TypeLoc;
6586 if (ParseTypeAndValue(Op, PFS) ||
6587 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
6588 ParseType(EltTy, TypeLoc))
6589 return true;
6591 if (!EltTy->isFirstClassType())
6592 return Error(TypeLoc, "va_arg requires operand with first class type");
6594 Inst = new VAArgInst(Op, EltTy);
6595 return false;
6598 /// ParseExtractElement
6599 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
6600 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
6601 LocTy Loc;
6602 Value *Op0, *Op1;
6603 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6604 ParseToken(lltok::comma, "expected ',' after extract value") ||
6605 ParseTypeAndValue(Op1, PFS))
6606 return true;
6608 if (!ExtractElementInst::isValidOperands(Op0, Op1))
6609 return Error(Loc, "invalid extractelement operands");
6611 Inst = ExtractElementInst::Create(Op0, Op1);
6612 return false;
6615 /// ParseInsertElement
6616 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6617 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
6618 LocTy Loc;
6619 Value *Op0, *Op1, *Op2;
6620 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6621 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6622 ParseTypeAndValue(Op1, PFS) ||
6623 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6624 ParseTypeAndValue(Op2, PFS))
6625 return true;
6627 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
6628 return Error(Loc, "invalid insertelement operands");
6630 Inst = InsertElementInst::Create(Op0, Op1, Op2);
6631 return false;
6634 /// ParseShuffleVector
6635 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
6636 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
6637 LocTy Loc;
6638 Value *Op0, *Op1, *Op2;
6639 if (ParseTypeAndValue(Op0, Loc, PFS) ||
6640 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
6641 ParseTypeAndValue(Op1, PFS) ||
6642 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
6643 ParseTypeAndValue(Op2, PFS))
6644 return true;
6646 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
6647 return Error(Loc, "invalid shufflevector operands");
6649 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
6650 return false;
6653 /// ParsePHI
6654 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
6655 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
6656 Type *Ty = nullptr; LocTy TypeLoc;
6657 Value *Op0, *Op1;
6659 if (ParseType(Ty, TypeLoc) ||
6660 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6661 ParseValue(Ty, Op0, PFS) ||
6662 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6663 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
6664 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6665 return true;
6667 bool AteExtraComma = false;
6668 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
6670 while (true) {
6671 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
6673 if (!EatIfPresent(lltok::comma))
6674 break;
6676 if (Lex.getKind() == lltok::MetadataVar) {
6677 AteExtraComma = true;
6678 break;
6681 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
6682 ParseValue(Ty, Op0, PFS) ||
6683 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
6684 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
6685 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
6686 return true;
6689 if (!Ty->isFirstClassType())
6690 return Error(TypeLoc, "phi node must have first class type");
6692 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
6693 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
6694 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
6695 Inst = PN;
6696 return AteExtraComma ? InstExtraComma : InstNormal;
6699 /// ParseLandingPad
6700 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
6701 /// Clause
6702 /// ::= 'catch' TypeAndValue
6703 /// ::= 'filter'
6704 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
6705 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
6706 Type *Ty = nullptr; LocTy TyLoc;
6708 if (ParseType(Ty, TyLoc))
6709 return true;
6711 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
6712 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
6714 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
6715 LandingPadInst::ClauseType CT;
6716 if (EatIfPresent(lltok::kw_catch))
6717 CT = LandingPadInst::Catch;
6718 else if (EatIfPresent(lltok::kw_filter))
6719 CT = LandingPadInst::Filter;
6720 else
6721 return TokError("expected 'catch' or 'filter' clause type");
6723 Value *V;
6724 LocTy VLoc;
6725 if (ParseTypeAndValue(V, VLoc, PFS))
6726 return true;
6728 // A 'catch' type expects a non-array constant. A filter clause expects an
6729 // array constant.
6730 if (CT == LandingPadInst::Catch) {
6731 if (isa<ArrayType>(V->getType()))
6732 Error(VLoc, "'catch' clause has an invalid type");
6733 } else {
6734 if (!isa<ArrayType>(V->getType()))
6735 Error(VLoc, "'filter' clause has an invalid type");
6738 Constant *CV = dyn_cast<Constant>(V);
6739 if (!CV)
6740 return Error(VLoc, "clause argument must be a constant");
6741 LP->addClause(CV);
6744 Inst = LP.release();
6745 return false;
6748 /// ParseCall
6749 /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
6750 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6751 /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
6752 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6753 /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
6754 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6755 /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
6756 /// OptionalAttrs Type Value ParameterList OptionalAttrs
6757 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
6758 CallInst::TailCallKind TCK) {
6759 AttrBuilder RetAttrs, FnAttrs;
6760 std::vector<unsigned> FwdRefAttrGrps;
6761 LocTy BuiltinLoc;
6762 unsigned CallAddrSpace;
6763 unsigned CC;
6764 Type *RetType = nullptr;
6765 LocTy RetTypeLoc;
6766 ValID CalleeID;
6767 SmallVector<ParamInfo, 16> ArgList;
6768 SmallVector<OperandBundleDef, 2> BundleList;
6769 LocTy CallLoc = Lex.getLoc();
6771 if (TCK != CallInst::TCK_None &&
6772 ParseToken(lltok::kw_call,
6773 "expected 'tail call', 'musttail call', or 'notail call'"))
6774 return true;
6776 FastMathFlags FMF = EatFastMathFlagsIfPresent();
6778 if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
6779 ParseOptionalProgramAddrSpace(CallAddrSpace) ||
6780 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
6781 ParseValID(CalleeID) ||
6782 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
6783 PFS.getFunction().isVarArg()) ||
6784 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
6785 ParseOptionalOperandBundles(BundleList, PFS))
6786 return true;
6788 if (FMF.any() && !RetType->isFPOrFPVectorTy())
6789 return Error(CallLoc, "fast-math-flags specified for call without "
6790 "floating-point scalar or vector return type");
6792 // If RetType is a non-function pointer type, then this is the short syntax
6793 // for the call, which means that RetType is just the return type. Infer the
6794 // rest of the function argument types from the arguments that are present.
6795 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
6796 if (!Ty) {
6797 // Pull out the types of all of the arguments...
6798 std::vector<Type*> ParamTypes;
6799 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
6800 ParamTypes.push_back(ArgList[i].V->getType());
6802 if (!FunctionType::isValidReturnType(RetType))
6803 return Error(RetTypeLoc, "Invalid result type for LLVM function");
6805 Ty = FunctionType::get(RetType, ParamTypes, false);
6808 CalleeID.FTy = Ty;
6810 // Look up the callee.
6811 Value *Callee;
6812 if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
6813 &PFS, /*IsCall=*/true))
6814 return true;
6816 // Set up the Attribute for the function.
6817 SmallVector<AttributeSet, 8> Attrs;
6819 SmallVector<Value*, 8> Args;
6821 // Loop through FunctionType's arguments and ensure they are specified
6822 // correctly. Also, gather any parameter attributes.
6823 FunctionType::param_iterator I = Ty->param_begin();
6824 FunctionType::param_iterator E = Ty->param_end();
6825 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
6826 Type *ExpectedTy = nullptr;
6827 if (I != E) {
6828 ExpectedTy = *I++;
6829 } else if (!Ty->isVarArg()) {
6830 return Error(ArgList[i].Loc, "too many arguments specified");
6833 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
6834 return Error(ArgList[i].Loc, "argument is not of expected type '" +
6835 getTypeString(ExpectedTy) + "'");
6836 Args.push_back(ArgList[i].V);
6837 Attrs.push_back(ArgList[i].Attrs);
6840 if (I != E)
6841 return Error(CallLoc, "not enough parameters specified for call");
6843 if (FnAttrs.hasAlignmentAttr())
6844 return Error(CallLoc, "call instructions may not have an alignment");
6846 // Finish off the Attribute and check them
6847 AttributeList PAL =
6848 AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
6849 AttributeSet::get(Context, RetAttrs), Attrs);
6851 CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
6852 CI->setTailCallKind(TCK);
6853 CI->setCallingConv(CC);
6854 if (FMF.any())
6855 CI->setFastMathFlags(FMF);
6856 CI->setAttributes(PAL);
6857 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
6858 Inst = CI;
6859 return false;
6862 //===----------------------------------------------------------------------===//
6863 // Memory Instructions.
6864 //===----------------------------------------------------------------------===//
6866 /// ParseAlloc
6867 /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
6868 /// (',' 'align' i32)? (',', 'addrspace(n))?
6869 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
6870 Value *Size = nullptr;
6871 LocTy SizeLoc, TyLoc, ASLoc;
6872 MaybeAlign Alignment;
6873 unsigned AddrSpace = 0;
6874 Type *Ty = nullptr;
6876 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
6877 bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
6879 if (ParseType(Ty, TyLoc)) return true;
6881 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
6882 return Error(TyLoc, "invalid type for alloca");
6884 bool AteExtraComma = false;
6885 if (EatIfPresent(lltok::comma)) {
6886 if (Lex.getKind() == lltok::kw_align) {
6887 if (ParseOptionalAlignment(Alignment))
6888 return true;
6889 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6890 return true;
6891 } else if (Lex.getKind() == lltok::kw_addrspace) {
6892 ASLoc = Lex.getLoc();
6893 if (ParseOptionalAddrSpace(AddrSpace))
6894 return true;
6895 } else if (Lex.getKind() == lltok::MetadataVar) {
6896 AteExtraComma = true;
6897 } else {
6898 if (ParseTypeAndValue(Size, SizeLoc, PFS))
6899 return true;
6900 if (EatIfPresent(lltok::comma)) {
6901 if (Lex.getKind() == lltok::kw_align) {
6902 if (ParseOptionalAlignment(Alignment))
6903 return true;
6904 if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
6905 return true;
6906 } else if (Lex.getKind() == lltok::kw_addrspace) {
6907 ASLoc = Lex.getLoc();
6908 if (ParseOptionalAddrSpace(AddrSpace))
6909 return true;
6910 } else if (Lex.getKind() == lltok::MetadataVar) {
6911 AteExtraComma = true;
6917 if (Size && !Size->getType()->isIntegerTy())
6918 return Error(SizeLoc, "element count must have integer type");
6920 AllocaInst *AI =
6921 new AllocaInst(Ty, AddrSpace, Size, Alignment ? Alignment->value() : 0);
6922 AI->setUsedWithInAlloca(IsInAlloca);
6923 AI->setSwiftError(IsSwiftError);
6924 Inst = AI;
6925 return AteExtraComma ? InstExtraComma : InstNormal;
6928 /// ParseLoad
6929 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
6930 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
6931 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6932 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
6933 Value *Val; LocTy Loc;
6934 MaybeAlign Alignment;
6935 bool AteExtraComma = false;
6936 bool isAtomic = false;
6937 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6938 SyncScope::ID SSID = SyncScope::System;
6940 if (Lex.getKind() == lltok::kw_atomic) {
6941 isAtomic = true;
6942 Lex.Lex();
6945 bool isVolatile = false;
6946 if (Lex.getKind() == lltok::kw_volatile) {
6947 isVolatile = true;
6948 Lex.Lex();
6951 Type *Ty;
6952 LocTy ExplicitTypeLoc = Lex.getLoc();
6953 if (ParseType(Ty) ||
6954 ParseToken(lltok::comma, "expected comma after load's type") ||
6955 ParseTypeAndValue(Val, Loc, PFS) ||
6956 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
6957 ParseOptionalCommaAlign(Alignment, AteExtraComma))
6958 return true;
6960 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
6961 return Error(Loc, "load operand must be a pointer to a first class type");
6962 if (isAtomic && !Alignment)
6963 return Error(Loc, "atomic load must have explicit non-zero alignment");
6964 if (Ordering == AtomicOrdering::Release ||
6965 Ordering == AtomicOrdering::AcquireRelease)
6966 return Error(Loc, "atomic load cannot use Release ordering");
6968 if (Ty != cast<PointerType>(Val->getType())->getElementType())
6969 return Error(ExplicitTypeLoc,
6970 "explicit pointee type doesn't match operand's pointee type");
6972 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
6973 return AteExtraComma ? InstExtraComma : InstNormal;
6976 /// ParseStore
6978 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
6979 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
6980 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
6981 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
6982 Value *Val, *Ptr; LocTy Loc, PtrLoc;
6983 MaybeAlign Alignment;
6984 bool AteExtraComma = false;
6985 bool isAtomic = false;
6986 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
6987 SyncScope::ID SSID = SyncScope::System;
6989 if (Lex.getKind() == lltok::kw_atomic) {
6990 isAtomic = true;
6991 Lex.Lex();
6994 bool isVolatile = false;
6995 if (Lex.getKind() == lltok::kw_volatile) {
6996 isVolatile = true;
6997 Lex.Lex();
7000 if (ParseTypeAndValue(Val, Loc, PFS) ||
7001 ParseToken(lltok::comma, "expected ',' after store operand") ||
7002 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
7003 ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
7004 ParseOptionalCommaAlign(Alignment, AteExtraComma))
7005 return true;
7007 if (!Ptr->getType()->isPointerTy())
7008 return Error(PtrLoc, "store operand must be a pointer");
7009 if (!Val->getType()->isFirstClassType())
7010 return Error(Loc, "store operand must be a first class value");
7011 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
7012 return Error(Loc, "stored value and pointer type do not match");
7013 if (isAtomic && !Alignment)
7014 return Error(Loc, "atomic store must have explicit non-zero alignment");
7015 if (Ordering == AtomicOrdering::Acquire ||
7016 Ordering == AtomicOrdering::AcquireRelease)
7017 return Error(Loc, "atomic store cannot use Acquire ordering");
7019 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
7020 return AteExtraComma ? InstExtraComma : InstNormal;
7023 /// ParseCmpXchg
7024 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
7025 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
7026 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
7027 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
7028 bool AteExtraComma = false;
7029 AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
7030 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
7031 SyncScope::ID SSID = SyncScope::System;
7032 bool isVolatile = false;
7033 bool isWeak = false;
7035 if (EatIfPresent(lltok::kw_weak))
7036 isWeak = true;
7038 if (EatIfPresent(lltok::kw_volatile))
7039 isVolatile = true;
7041 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
7042 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
7043 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
7044 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
7045 ParseTypeAndValue(New, NewLoc, PFS) ||
7046 ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
7047 ParseOrdering(FailureOrdering))
7048 return true;
7050 if (SuccessOrdering == AtomicOrdering::Unordered ||
7051 FailureOrdering == AtomicOrdering::Unordered)
7052 return TokError("cmpxchg cannot be unordered");
7053 if (isStrongerThan(FailureOrdering, SuccessOrdering))
7054 return TokError("cmpxchg failure argument shall be no stronger than the "
7055 "success argument");
7056 if (FailureOrdering == AtomicOrdering::Release ||
7057 FailureOrdering == AtomicOrdering::AcquireRelease)
7058 return TokError(
7059 "cmpxchg failure ordering cannot include release semantics");
7060 if (!Ptr->getType()->isPointerTy())
7061 return Error(PtrLoc, "cmpxchg operand must be a pointer");
7062 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
7063 return Error(CmpLoc, "compare value and pointer type do not match");
7064 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
7065 return Error(NewLoc, "new value and pointer type do not match");
7066 if (!New->getType()->isFirstClassType())
7067 return Error(NewLoc, "cmpxchg operand must be a first class value");
7068 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
7069 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
7070 CXI->setVolatile(isVolatile);
7071 CXI->setWeak(isWeak);
7072 Inst = CXI;
7073 return AteExtraComma ? InstExtraComma : InstNormal;
7076 /// ParseAtomicRMW
7077 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
7078 /// 'singlethread'? AtomicOrdering
7079 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
7080 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
7081 bool AteExtraComma = false;
7082 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7083 SyncScope::ID SSID = SyncScope::System;
7084 bool isVolatile = false;
7085 bool IsFP = false;
7086 AtomicRMWInst::BinOp Operation;
7088 if (EatIfPresent(lltok::kw_volatile))
7089 isVolatile = true;
7091 switch (Lex.getKind()) {
7092 default: return TokError("expected binary operation in atomicrmw");
7093 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
7094 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
7095 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
7096 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
7097 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
7098 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
7099 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
7100 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
7101 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
7102 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
7103 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
7104 case lltok::kw_fadd:
7105 Operation = AtomicRMWInst::FAdd;
7106 IsFP = true;
7107 break;
7108 case lltok::kw_fsub:
7109 Operation = AtomicRMWInst::FSub;
7110 IsFP = true;
7111 break;
7113 Lex.Lex(); // Eat the operation.
7115 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
7116 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
7117 ParseTypeAndValue(Val, ValLoc, PFS) ||
7118 ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7119 return true;
7121 if (Ordering == AtomicOrdering::Unordered)
7122 return TokError("atomicrmw cannot be unordered");
7123 if (!Ptr->getType()->isPointerTy())
7124 return Error(PtrLoc, "atomicrmw operand must be a pointer");
7125 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
7126 return Error(ValLoc, "atomicrmw value and pointer type do not match");
7128 if (Operation == AtomicRMWInst::Xchg) {
7129 if (!Val->getType()->isIntegerTy() &&
7130 !Val->getType()->isFloatingPointTy()) {
7131 return Error(ValLoc, "atomicrmw " +
7132 AtomicRMWInst::getOperationName(Operation) +
7133 " operand must be an integer or floating point type");
7135 } else if (IsFP) {
7136 if (!Val->getType()->isFloatingPointTy()) {
7137 return Error(ValLoc, "atomicrmw " +
7138 AtomicRMWInst::getOperationName(Operation) +
7139 " operand must be a floating point type");
7141 } else {
7142 if (!Val->getType()->isIntegerTy()) {
7143 return Error(ValLoc, "atomicrmw " +
7144 AtomicRMWInst::getOperationName(Operation) +
7145 " operand must be an integer");
7149 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
7150 if (Size < 8 || (Size & (Size - 1)))
7151 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
7152 " integer");
7154 AtomicRMWInst *RMWI =
7155 new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
7156 RMWI->setVolatile(isVolatile);
7157 Inst = RMWI;
7158 return AteExtraComma ? InstExtraComma : InstNormal;
7161 /// ParseFence
7162 /// ::= 'fence' 'singlethread'? AtomicOrdering
7163 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
7164 AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
7165 SyncScope::ID SSID = SyncScope::System;
7166 if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
7167 return true;
7169 if (Ordering == AtomicOrdering::Unordered)
7170 return TokError("fence cannot be unordered");
7171 if (Ordering == AtomicOrdering::Monotonic)
7172 return TokError("fence cannot be monotonic");
7174 Inst = new FenceInst(Context, Ordering, SSID);
7175 return InstNormal;
7178 /// ParseGetElementPtr
7179 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
7180 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
7181 Value *Ptr = nullptr;
7182 Value *Val = nullptr;
7183 LocTy Loc, EltLoc;
7185 bool InBounds = EatIfPresent(lltok::kw_inbounds);
7187 Type *Ty = nullptr;
7188 LocTy ExplicitTypeLoc = Lex.getLoc();
7189 if (ParseType(Ty) ||
7190 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
7191 ParseTypeAndValue(Ptr, Loc, PFS))
7192 return true;
7194 Type *BaseType = Ptr->getType();
7195 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
7196 if (!BasePointerType)
7197 return Error(Loc, "base of getelementptr must be a pointer");
7199 if (Ty != BasePointerType->getElementType())
7200 return Error(ExplicitTypeLoc,
7201 "explicit pointee type doesn't match operand's pointee type");
7203 SmallVector<Value*, 16> Indices;
7204 bool AteExtraComma = false;
7205 // GEP returns a vector of pointers if at least one of parameters is a vector.
7206 // All vector parameters should have the same vector width.
7207 unsigned GEPWidth = BaseType->isVectorTy() ?
7208 BaseType->getVectorNumElements() : 0;
7210 while (EatIfPresent(lltok::comma)) {
7211 if (Lex.getKind() == lltok::MetadataVar) {
7212 AteExtraComma = true;
7213 break;
7215 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
7216 if (!Val->getType()->isIntOrIntVectorTy())
7217 return Error(EltLoc, "getelementptr index must be an integer");
7219 if (Val->getType()->isVectorTy()) {
7220 unsigned ValNumEl = Val->getType()->getVectorNumElements();
7221 if (GEPWidth && GEPWidth != ValNumEl)
7222 return Error(EltLoc,
7223 "getelementptr vector index has a wrong number of elements");
7224 GEPWidth = ValNumEl;
7226 Indices.push_back(Val);
7229 SmallPtrSet<Type*, 4> Visited;
7230 if (!Indices.empty() && !Ty->isSized(&Visited))
7231 return Error(Loc, "base element of getelementptr must be sized");
7233 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
7234 return Error(Loc, "invalid getelementptr indices");
7235 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
7236 if (InBounds)
7237 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
7238 return AteExtraComma ? InstExtraComma : InstNormal;
7241 /// ParseExtractValue
7242 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
7243 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
7244 Value *Val; LocTy Loc;
7245 SmallVector<unsigned, 4> Indices;
7246 bool AteExtraComma;
7247 if (ParseTypeAndValue(Val, Loc, PFS) ||
7248 ParseIndexList(Indices, AteExtraComma))
7249 return true;
7251 if (!Val->getType()->isAggregateType())
7252 return Error(Loc, "extractvalue operand must be aggregate type");
7254 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
7255 return Error(Loc, "invalid indices for extractvalue");
7256 Inst = ExtractValueInst::Create(Val, Indices);
7257 return AteExtraComma ? InstExtraComma : InstNormal;
7260 /// ParseInsertValue
7261 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
7262 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
7263 Value *Val0, *Val1; LocTy Loc0, Loc1;
7264 SmallVector<unsigned, 4> Indices;
7265 bool AteExtraComma;
7266 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
7267 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
7268 ParseTypeAndValue(Val1, Loc1, PFS) ||
7269 ParseIndexList(Indices, AteExtraComma))
7270 return true;
7272 if (!Val0->getType()->isAggregateType())
7273 return Error(Loc0, "insertvalue operand must be aggregate type");
7275 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
7276 if (!IndexedType)
7277 return Error(Loc0, "invalid indices for insertvalue");
7278 if (IndexedType != Val1->getType())
7279 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
7280 getTypeString(Val1->getType()) + "' instead of '" +
7281 getTypeString(IndexedType) + "'");
7282 Inst = InsertValueInst::Create(Val0, Val1, Indices);
7283 return AteExtraComma ? InstExtraComma : InstNormal;
7286 //===----------------------------------------------------------------------===//
7287 // Embedded metadata.
7288 //===----------------------------------------------------------------------===//
7290 /// ParseMDNodeVector
7291 /// ::= { Element (',' Element)* }
7292 /// Element
7293 /// ::= 'null' | TypeAndValue
7294 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
7295 if (ParseToken(lltok::lbrace, "expected '{' here"))
7296 return true;
7298 // Check for an empty list.
7299 if (EatIfPresent(lltok::rbrace))
7300 return false;
7302 do {
7303 // Null is a special case since it is typeless.
7304 if (EatIfPresent(lltok::kw_null)) {
7305 Elts.push_back(nullptr);
7306 continue;
7309 Metadata *MD;
7310 if (ParseMetadata(MD, nullptr))
7311 return true;
7312 Elts.push_back(MD);
7313 } while (EatIfPresent(lltok::comma));
7315 return ParseToken(lltok::rbrace, "expected end of metadata node");
7318 //===----------------------------------------------------------------------===//
7319 // Use-list order directives.
7320 //===----------------------------------------------------------------------===//
7321 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
7322 SMLoc Loc) {
7323 if (V->use_empty())
7324 return Error(Loc, "value has no uses");
7326 unsigned NumUses = 0;
7327 SmallDenseMap<const Use *, unsigned, 16> Order;
7328 for (const Use &U : V->uses()) {
7329 if (++NumUses > Indexes.size())
7330 break;
7331 Order[&U] = Indexes[NumUses - 1];
7333 if (NumUses < 2)
7334 return Error(Loc, "value only has one use");
7335 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
7336 return Error(Loc,
7337 "wrong number of indexes, expected " + Twine(V->getNumUses()));
7339 V->sortUseList([&](const Use &L, const Use &R) {
7340 return Order.lookup(&L) < Order.lookup(&R);
7342 return false;
7345 /// ParseUseListOrderIndexes
7346 /// ::= '{' uint32 (',' uint32)+ '}'
7347 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
7348 SMLoc Loc = Lex.getLoc();
7349 if (ParseToken(lltok::lbrace, "expected '{' here"))
7350 return true;
7351 if (Lex.getKind() == lltok::rbrace)
7352 return Lex.Error("expected non-empty list of uselistorder indexes");
7354 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
7355 // indexes should be distinct numbers in the range [0, size-1], and should
7356 // not be in order.
7357 unsigned Offset = 0;
7358 unsigned Max = 0;
7359 bool IsOrdered = true;
7360 assert(Indexes.empty() && "Expected empty order vector");
7361 do {
7362 unsigned Index;
7363 if (ParseUInt32(Index))
7364 return true;
7366 // Update consistency checks.
7367 Offset += Index - Indexes.size();
7368 Max = std::max(Max, Index);
7369 IsOrdered &= Index == Indexes.size();
7371 Indexes.push_back(Index);
7372 } while (EatIfPresent(lltok::comma));
7374 if (ParseToken(lltok::rbrace, "expected '}' here"))
7375 return true;
7377 if (Indexes.size() < 2)
7378 return Error(Loc, "expected >= 2 uselistorder indexes");
7379 if (Offset != 0 || Max >= Indexes.size())
7380 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
7381 if (IsOrdered)
7382 return Error(Loc, "expected uselistorder indexes to change the order");
7384 return false;
7387 /// ParseUseListOrder
7388 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
7389 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
7390 SMLoc Loc = Lex.getLoc();
7391 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
7392 return true;
7394 Value *V;
7395 SmallVector<unsigned, 16> Indexes;
7396 if (ParseTypeAndValue(V, PFS) ||
7397 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
7398 ParseUseListOrderIndexes(Indexes))
7399 return true;
7401 return sortUseListOrder(V, Indexes, Loc);
7404 /// ParseUseListOrderBB
7405 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
7406 bool LLParser::ParseUseListOrderBB() {
7407 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
7408 SMLoc Loc = Lex.getLoc();
7409 Lex.Lex();
7411 ValID Fn, Label;
7412 SmallVector<unsigned, 16> Indexes;
7413 if (ParseValID(Fn) ||
7414 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7415 ParseValID(Label) ||
7416 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
7417 ParseUseListOrderIndexes(Indexes))
7418 return true;
7420 // Check the function.
7421 GlobalValue *GV;
7422 if (Fn.Kind == ValID::t_GlobalName)
7423 GV = M->getNamedValue(Fn.StrVal);
7424 else if (Fn.Kind == ValID::t_GlobalID)
7425 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
7426 else
7427 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7428 if (!GV)
7429 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
7430 auto *F = dyn_cast<Function>(GV);
7431 if (!F)
7432 return Error(Fn.Loc, "expected function name in uselistorder_bb");
7433 if (F->isDeclaration())
7434 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
7436 // Check the basic block.
7437 if (Label.Kind == ValID::t_LocalID)
7438 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
7439 if (Label.Kind != ValID::t_LocalName)
7440 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
7441 Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
7442 if (!V)
7443 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
7444 if (!isa<BasicBlock>(V))
7445 return Error(Label.Loc, "expected basic block in uselistorder_bb");
7447 return sortUseListOrder(V, Indexes, Loc);
7450 /// ModuleEntry
7451 /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
7452 /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
7453 bool LLParser::ParseModuleEntry(unsigned ID) {
7454 assert(Lex.getKind() == lltok::kw_module);
7455 Lex.Lex();
7457 std::string Path;
7458 if (ParseToken(lltok::colon, "expected ':' here") ||
7459 ParseToken(lltok::lparen, "expected '(' here") ||
7460 ParseToken(lltok::kw_path, "expected 'path' here") ||
7461 ParseToken(lltok::colon, "expected ':' here") ||
7462 ParseStringConstant(Path) ||
7463 ParseToken(lltok::comma, "expected ',' here") ||
7464 ParseToken(lltok::kw_hash, "expected 'hash' here") ||
7465 ParseToken(lltok::colon, "expected ':' here") ||
7466 ParseToken(lltok::lparen, "expected '(' here"))
7467 return true;
7469 ModuleHash Hash;
7470 if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
7471 ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
7472 ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
7473 ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
7474 ParseUInt32(Hash[4]))
7475 return true;
7477 if (ParseToken(lltok::rparen, "expected ')' here") ||
7478 ParseToken(lltok::rparen, "expected ')' here"))
7479 return true;
7481 auto ModuleEntry = Index->addModule(Path, ID, Hash);
7482 ModuleIdMap[ID] = ModuleEntry->first();
7484 return false;
7487 /// TypeIdEntry
7488 /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
7489 bool LLParser::ParseTypeIdEntry(unsigned ID) {
7490 assert(Lex.getKind() == lltok::kw_typeid);
7491 Lex.Lex();
7493 std::string Name;
7494 if (ParseToken(lltok::colon, "expected ':' here") ||
7495 ParseToken(lltok::lparen, "expected '(' here") ||
7496 ParseToken(lltok::kw_name, "expected 'name' here") ||
7497 ParseToken(lltok::colon, "expected ':' here") ||
7498 ParseStringConstant(Name))
7499 return true;
7501 TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
7502 if (ParseToken(lltok::comma, "expected ',' here") ||
7503 ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
7504 return true;
7506 // Check if this ID was forward referenced, and if so, update the
7507 // corresponding GUIDs.
7508 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7509 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7510 for (auto TIDRef : FwdRefTIDs->second) {
7511 assert(!*TIDRef.first &&
7512 "Forward referenced type id GUID expected to be 0");
7513 *TIDRef.first = GlobalValue::getGUID(Name);
7515 ForwardRefTypeIds.erase(FwdRefTIDs);
7518 return false;
7521 /// TypeIdSummary
7522 /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
7523 bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
7524 if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7525 ParseToken(lltok::colon, "expected ':' here") ||
7526 ParseToken(lltok::lparen, "expected '(' here") ||
7527 ParseTypeTestResolution(TIS.TTRes))
7528 return true;
7530 if (EatIfPresent(lltok::comma)) {
7531 // Expect optional wpdResolutions field
7532 if (ParseOptionalWpdResolutions(TIS.WPDRes))
7533 return true;
7536 if (ParseToken(lltok::rparen, "expected ')' here"))
7537 return true;
7539 return false;
7542 static ValueInfo EmptyVI =
7543 ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
7545 /// TypeIdCompatibleVtableEntry
7546 /// ::= 'typeidCompatibleVTable' ':' '(' 'name' ':' STRINGCONSTANT ','
7547 /// TypeIdCompatibleVtableInfo
7548 /// ')'
7549 bool LLParser::ParseTypeIdCompatibleVtableEntry(unsigned ID) {
7550 assert(Lex.getKind() == lltok::kw_typeidCompatibleVTable);
7551 Lex.Lex();
7553 std::string Name;
7554 if (ParseToken(lltok::colon, "expected ':' here") ||
7555 ParseToken(lltok::lparen, "expected '(' here") ||
7556 ParseToken(lltok::kw_name, "expected 'name' here") ||
7557 ParseToken(lltok::colon, "expected ':' here") ||
7558 ParseStringConstant(Name))
7559 return true;
7561 TypeIdCompatibleVtableInfo &TI =
7562 Index->getOrInsertTypeIdCompatibleVtableSummary(Name);
7563 if (ParseToken(lltok::comma, "expected ',' here") ||
7564 ParseToken(lltok::kw_summary, "expected 'summary' here") ||
7565 ParseToken(lltok::colon, "expected ':' here") ||
7566 ParseToken(lltok::lparen, "expected '(' here"))
7567 return true;
7569 IdToIndexMapType IdToIndexMap;
7570 // Parse each call edge
7571 do {
7572 uint64_t Offset;
7573 if (ParseToken(lltok::lparen, "expected '(' here") ||
7574 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7575 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7576 ParseToken(lltok::comma, "expected ',' here"))
7577 return true;
7579 LocTy Loc = Lex.getLoc();
7580 unsigned GVId;
7581 ValueInfo VI;
7582 if (ParseGVReference(VI, GVId))
7583 return true;
7585 // Keep track of the TypeIdCompatibleVtableInfo array index needing a
7586 // forward reference. We will save the location of the ValueInfo needing an
7587 // update, but can only do so once the std::vector is finalized.
7588 if (VI == EmptyVI)
7589 IdToIndexMap[GVId].push_back(std::make_pair(TI.size(), Loc));
7590 TI.push_back({Offset, VI});
7592 if (ParseToken(lltok::rparen, "expected ')' in call"))
7593 return true;
7594 } while (EatIfPresent(lltok::comma));
7596 // Now that the TI vector is finalized, it is safe to save the locations
7597 // of any forward GV references that need updating later.
7598 for (auto I : IdToIndexMap) {
7599 for (auto P : I.second) {
7600 assert(TI[P.first].VTableVI == EmptyVI &&
7601 "Forward referenced ValueInfo expected to be empty");
7602 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
7603 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
7604 FwdRef.first->second.push_back(
7605 std::make_pair(&TI[P.first].VTableVI, P.second));
7609 if (ParseToken(lltok::rparen, "expected ')' here") ||
7610 ParseToken(lltok::rparen, "expected ')' here"))
7611 return true;
7613 // Check if this ID was forward referenced, and if so, update the
7614 // corresponding GUIDs.
7615 auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
7616 if (FwdRefTIDs != ForwardRefTypeIds.end()) {
7617 for (auto TIDRef : FwdRefTIDs->second) {
7618 assert(!*TIDRef.first &&
7619 "Forward referenced type id GUID expected to be 0");
7620 *TIDRef.first = GlobalValue::getGUID(Name);
7622 ForwardRefTypeIds.erase(FwdRefTIDs);
7625 return false;
7628 /// TypeTestResolution
7629 /// ::= 'typeTestRes' ':' '(' 'kind' ':'
7630 /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
7631 /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
7632 /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
7633 /// [',' 'inlinesBits' ':' UInt64]? ')'
7634 bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
7635 if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
7636 ParseToken(lltok::colon, "expected ':' here") ||
7637 ParseToken(lltok::lparen, "expected '(' here") ||
7638 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7639 ParseToken(lltok::colon, "expected ':' here"))
7640 return true;
7642 switch (Lex.getKind()) {
7643 case lltok::kw_unsat:
7644 TTRes.TheKind = TypeTestResolution::Unsat;
7645 break;
7646 case lltok::kw_byteArray:
7647 TTRes.TheKind = TypeTestResolution::ByteArray;
7648 break;
7649 case lltok::kw_inline:
7650 TTRes.TheKind = TypeTestResolution::Inline;
7651 break;
7652 case lltok::kw_single:
7653 TTRes.TheKind = TypeTestResolution::Single;
7654 break;
7655 case lltok::kw_allOnes:
7656 TTRes.TheKind = TypeTestResolution::AllOnes;
7657 break;
7658 default:
7659 return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
7661 Lex.Lex();
7663 if (ParseToken(lltok::comma, "expected ',' here") ||
7664 ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
7665 ParseToken(lltok::colon, "expected ':' here") ||
7666 ParseUInt32(TTRes.SizeM1BitWidth))
7667 return true;
7669 // Parse optional fields
7670 while (EatIfPresent(lltok::comma)) {
7671 switch (Lex.getKind()) {
7672 case lltok::kw_alignLog2:
7673 Lex.Lex();
7674 if (ParseToken(lltok::colon, "expected ':'") ||
7675 ParseUInt64(TTRes.AlignLog2))
7676 return true;
7677 break;
7678 case lltok::kw_sizeM1:
7679 Lex.Lex();
7680 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
7681 return true;
7682 break;
7683 case lltok::kw_bitMask: {
7684 unsigned Val;
7685 Lex.Lex();
7686 if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
7687 return true;
7688 assert(Val <= 0xff);
7689 TTRes.BitMask = (uint8_t)Val;
7690 break;
7692 case lltok::kw_inlineBits:
7693 Lex.Lex();
7694 if (ParseToken(lltok::colon, "expected ':'") ||
7695 ParseUInt64(TTRes.InlineBits))
7696 return true;
7697 break;
7698 default:
7699 return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
7703 if (ParseToken(lltok::rparen, "expected ')' here"))
7704 return true;
7706 return false;
7709 /// OptionalWpdResolutions
7710 /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
7711 /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
7712 bool LLParser::ParseOptionalWpdResolutions(
7713 std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
7714 if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
7715 ParseToken(lltok::colon, "expected ':' here") ||
7716 ParseToken(lltok::lparen, "expected '(' here"))
7717 return true;
7719 do {
7720 uint64_t Offset;
7721 WholeProgramDevirtResolution WPDRes;
7722 if (ParseToken(lltok::lparen, "expected '(' here") ||
7723 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
7724 ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
7725 ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
7726 ParseToken(lltok::rparen, "expected ')' here"))
7727 return true;
7728 WPDResMap[Offset] = WPDRes;
7729 } while (EatIfPresent(lltok::comma));
7731 if (ParseToken(lltok::rparen, "expected ')' here"))
7732 return true;
7734 return false;
7737 /// WpdRes
7738 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
7739 /// [',' OptionalResByArg]? ')'
7740 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
7741 /// ',' 'singleImplName' ':' STRINGCONSTANT ','
7742 /// [',' OptionalResByArg]? ')'
7743 /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
7744 /// [',' OptionalResByArg]? ')'
7745 bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
7746 if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
7747 ParseToken(lltok::colon, "expected ':' here") ||
7748 ParseToken(lltok::lparen, "expected '(' here") ||
7749 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7750 ParseToken(lltok::colon, "expected ':' here"))
7751 return true;
7753 switch (Lex.getKind()) {
7754 case lltok::kw_indir:
7755 WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
7756 break;
7757 case lltok::kw_singleImpl:
7758 WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
7759 break;
7760 case lltok::kw_branchFunnel:
7761 WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
7762 break;
7763 default:
7764 return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
7766 Lex.Lex();
7768 // Parse optional fields
7769 while (EatIfPresent(lltok::comma)) {
7770 switch (Lex.getKind()) {
7771 case lltok::kw_singleImplName:
7772 Lex.Lex();
7773 if (ParseToken(lltok::colon, "expected ':' here") ||
7774 ParseStringConstant(WPDRes.SingleImplName))
7775 return true;
7776 break;
7777 case lltok::kw_resByArg:
7778 if (ParseOptionalResByArg(WPDRes.ResByArg))
7779 return true;
7780 break;
7781 default:
7782 return Error(Lex.getLoc(),
7783 "expected optional WholeProgramDevirtResolution field");
7787 if (ParseToken(lltok::rparen, "expected ')' here"))
7788 return true;
7790 return false;
7793 /// OptionalResByArg
7794 /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
7795 /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
7796 /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
7797 /// 'virtualConstProp' )
7798 /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
7799 /// [',' 'bit' ':' UInt32]? ')'
7800 bool LLParser::ParseOptionalResByArg(
7801 std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
7802 &ResByArg) {
7803 if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
7804 ParseToken(lltok::colon, "expected ':' here") ||
7805 ParseToken(lltok::lparen, "expected '(' here"))
7806 return true;
7808 do {
7809 std::vector<uint64_t> Args;
7810 if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
7811 ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
7812 ParseToken(lltok::colon, "expected ':' here") ||
7813 ParseToken(lltok::lparen, "expected '(' here") ||
7814 ParseToken(lltok::kw_kind, "expected 'kind' here") ||
7815 ParseToken(lltok::colon, "expected ':' here"))
7816 return true;
7818 WholeProgramDevirtResolution::ByArg ByArg;
7819 switch (Lex.getKind()) {
7820 case lltok::kw_indir:
7821 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
7822 break;
7823 case lltok::kw_uniformRetVal:
7824 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
7825 break;
7826 case lltok::kw_uniqueRetVal:
7827 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
7828 break;
7829 case lltok::kw_virtualConstProp:
7830 ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
7831 break;
7832 default:
7833 return Error(Lex.getLoc(),
7834 "unexpected WholeProgramDevirtResolution::ByArg kind");
7836 Lex.Lex();
7838 // Parse optional fields
7839 while (EatIfPresent(lltok::comma)) {
7840 switch (Lex.getKind()) {
7841 case lltok::kw_info:
7842 Lex.Lex();
7843 if (ParseToken(lltok::colon, "expected ':' here") ||
7844 ParseUInt64(ByArg.Info))
7845 return true;
7846 break;
7847 case lltok::kw_byte:
7848 Lex.Lex();
7849 if (ParseToken(lltok::colon, "expected ':' here") ||
7850 ParseUInt32(ByArg.Byte))
7851 return true;
7852 break;
7853 case lltok::kw_bit:
7854 Lex.Lex();
7855 if (ParseToken(lltok::colon, "expected ':' here") ||
7856 ParseUInt32(ByArg.Bit))
7857 return true;
7858 break;
7859 default:
7860 return Error(Lex.getLoc(),
7861 "expected optional whole program devirt field");
7865 if (ParseToken(lltok::rparen, "expected ')' here"))
7866 return true;
7868 ResByArg[Args] = ByArg;
7869 } while (EatIfPresent(lltok::comma));
7871 if (ParseToken(lltok::rparen, "expected ')' here"))
7872 return true;
7874 return false;
7877 /// OptionalResByArg
7878 /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
7879 bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
7880 if (ParseToken(lltok::kw_args, "expected 'args' here") ||
7881 ParseToken(lltok::colon, "expected ':' here") ||
7882 ParseToken(lltok::lparen, "expected '(' here"))
7883 return true;
7885 do {
7886 uint64_t Val;
7887 if (ParseUInt64(Val))
7888 return true;
7889 Args.push_back(Val);
7890 } while (EatIfPresent(lltok::comma));
7892 if (ParseToken(lltok::rparen, "expected ')' here"))
7893 return true;
7895 return false;
7898 static const auto FwdVIRef = (GlobalValueSummaryMapTy::value_type *)-8;
7900 static void resolveFwdRef(ValueInfo *Fwd, ValueInfo &Resolved) {
7901 bool ReadOnly = Fwd->isReadOnly();
7902 bool WriteOnly = Fwd->isWriteOnly();
7903 assert(!(ReadOnly && WriteOnly));
7904 *Fwd = Resolved;
7905 if (ReadOnly)
7906 Fwd->setReadOnly();
7907 if (WriteOnly)
7908 Fwd->setWriteOnly();
7911 /// Stores the given Name/GUID and associated summary into the Index.
7912 /// Also updates any forward references to the associated entry ID.
7913 void LLParser::AddGlobalValueToIndex(
7914 std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
7915 unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
7916 // First create the ValueInfo utilizing the Name or GUID.
7917 ValueInfo VI;
7918 if (GUID != 0) {
7919 assert(Name.empty());
7920 VI = Index->getOrInsertValueInfo(GUID);
7921 } else {
7922 assert(!Name.empty());
7923 if (M) {
7924 auto *GV = M->getNamedValue(Name);
7925 assert(GV);
7926 VI = Index->getOrInsertValueInfo(GV);
7927 } else {
7928 assert(
7929 (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
7930 "Need a source_filename to compute GUID for local");
7931 GUID = GlobalValue::getGUID(
7932 GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
7933 VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
7937 // Resolve forward references from calls/refs
7938 auto FwdRefVIs = ForwardRefValueInfos.find(ID);
7939 if (FwdRefVIs != ForwardRefValueInfos.end()) {
7940 for (auto VIRef : FwdRefVIs->second) {
7941 assert(VIRef.first->getRef() == FwdVIRef &&
7942 "Forward referenced ValueInfo expected to be empty");
7943 resolveFwdRef(VIRef.first, VI);
7945 ForwardRefValueInfos.erase(FwdRefVIs);
7948 // Resolve forward references from aliases
7949 auto FwdRefAliasees = ForwardRefAliasees.find(ID);
7950 if (FwdRefAliasees != ForwardRefAliasees.end()) {
7951 for (auto AliaseeRef : FwdRefAliasees->second) {
7952 assert(!AliaseeRef.first->hasAliasee() &&
7953 "Forward referencing alias already has aliasee");
7954 assert(Summary && "Aliasee must be a definition");
7955 AliaseeRef.first->setAliasee(VI, Summary.get());
7957 ForwardRefAliasees.erase(FwdRefAliasees);
7960 // Add the summary if one was provided.
7961 if (Summary)
7962 Index->addGlobalValueSummary(VI, std::move(Summary));
7964 // Save the associated ValueInfo for use in later references by ID.
7965 if (ID == NumberedValueInfos.size())
7966 NumberedValueInfos.push_back(VI);
7967 else {
7968 // Handle non-continuous numbers (to make test simplification easier).
7969 if (ID > NumberedValueInfos.size())
7970 NumberedValueInfos.resize(ID + 1);
7971 NumberedValueInfos[ID] = VI;
7975 /// ParseGVEntry
7976 /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
7977 /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
7978 /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
7979 bool LLParser::ParseGVEntry(unsigned ID) {
7980 assert(Lex.getKind() == lltok::kw_gv);
7981 Lex.Lex();
7983 if (ParseToken(lltok::colon, "expected ':' here") ||
7984 ParseToken(lltok::lparen, "expected '(' here"))
7985 return true;
7987 std::string Name;
7988 GlobalValue::GUID GUID = 0;
7989 switch (Lex.getKind()) {
7990 case lltok::kw_name:
7991 Lex.Lex();
7992 if (ParseToken(lltok::colon, "expected ':' here") ||
7993 ParseStringConstant(Name))
7994 return true;
7995 // Can't create GUID/ValueInfo until we have the linkage.
7996 break;
7997 case lltok::kw_guid:
7998 Lex.Lex();
7999 if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
8000 return true;
8001 break;
8002 default:
8003 return Error(Lex.getLoc(), "expected name or guid tag");
8006 if (!EatIfPresent(lltok::comma)) {
8007 // No summaries. Wrap up.
8008 if (ParseToken(lltok::rparen, "expected ')' here"))
8009 return true;
8010 // This was created for a call to an external or indirect target.
8011 // A GUID with no summary came from a VALUE_GUID record, dummy GUID
8012 // created for indirect calls with VP. A Name with no GUID came from
8013 // an external definition. We pass ExternalLinkage since that is only
8014 // used when the GUID must be computed from Name, and in that case
8015 // the symbol must have external linkage.
8016 AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
8017 nullptr);
8018 return false;
8021 // Have a list of summaries
8022 if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
8023 ParseToken(lltok::colon, "expected ':' here"))
8024 return true;
8026 do {
8027 if (ParseToken(lltok::lparen, "expected '(' here"))
8028 return true;
8029 switch (Lex.getKind()) {
8030 case lltok::kw_function:
8031 if (ParseFunctionSummary(Name, GUID, ID))
8032 return true;
8033 break;
8034 case lltok::kw_variable:
8035 if (ParseVariableSummary(Name, GUID, ID))
8036 return true;
8037 break;
8038 case lltok::kw_alias:
8039 if (ParseAliasSummary(Name, GUID, ID))
8040 return true;
8041 break;
8042 default:
8043 return Error(Lex.getLoc(), "expected summary type");
8045 if (ParseToken(lltok::rparen, "expected ')' here"))
8046 return true;
8047 } while (EatIfPresent(lltok::comma));
8049 if (ParseToken(lltok::rparen, "expected ')' here"))
8050 return true;
8052 return false;
8055 /// FunctionSummary
8056 /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8057 /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
8058 /// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
8059 bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
8060 unsigned ID) {
8061 assert(Lex.getKind() == lltok::kw_function);
8062 Lex.Lex();
8064 StringRef ModulePath;
8065 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8066 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
8067 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8068 unsigned InstCount;
8069 std::vector<FunctionSummary::EdgeTy> Calls;
8070 FunctionSummary::TypeIdInfo TypeIdInfo;
8071 std::vector<ValueInfo> Refs;
8072 // Default is all-zeros (conservative values).
8073 FunctionSummary::FFlags FFlags = {};
8074 if (ParseToken(lltok::colon, "expected ':' here") ||
8075 ParseToken(lltok::lparen, "expected '(' here") ||
8076 ParseModuleReference(ModulePath) ||
8077 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
8078 ParseToken(lltok::comma, "expected ',' here") ||
8079 ParseToken(lltok::kw_insts, "expected 'insts' here") ||
8080 ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
8081 return true;
8083 // Parse optional fields
8084 while (EatIfPresent(lltok::comma)) {
8085 switch (Lex.getKind()) {
8086 case lltok::kw_funcFlags:
8087 if (ParseOptionalFFlags(FFlags))
8088 return true;
8089 break;
8090 case lltok::kw_calls:
8091 if (ParseOptionalCalls(Calls))
8092 return true;
8093 break;
8094 case lltok::kw_typeIdInfo:
8095 if (ParseOptionalTypeIdInfo(TypeIdInfo))
8096 return true;
8097 break;
8098 case lltok::kw_refs:
8099 if (ParseOptionalRefs(Refs))
8100 return true;
8101 break;
8102 default:
8103 return Error(Lex.getLoc(), "expected optional function summary field");
8107 if (ParseToken(lltok::rparen, "expected ')' here"))
8108 return true;
8110 auto FS = std::make_unique<FunctionSummary>(
8111 GVFlags, InstCount, FFlags, /*EntryCount=*/0, std::move(Refs),
8112 std::move(Calls), std::move(TypeIdInfo.TypeTests),
8113 std::move(TypeIdInfo.TypeTestAssumeVCalls),
8114 std::move(TypeIdInfo.TypeCheckedLoadVCalls),
8115 std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
8116 std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
8118 FS->setModulePath(ModulePath);
8120 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8121 ID, std::move(FS));
8123 return false;
8126 /// VariableSummary
8127 /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
8128 /// [',' OptionalRefs]? ')'
8129 bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
8130 unsigned ID) {
8131 assert(Lex.getKind() == lltok::kw_variable);
8132 Lex.Lex();
8134 StringRef ModulePath;
8135 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8136 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
8137 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8138 GlobalVarSummary::GVarFlags GVarFlags(/*ReadOnly*/ false,
8139 /* WriteOnly */ false);
8140 std::vector<ValueInfo> Refs;
8141 VTableFuncList VTableFuncs;
8142 if (ParseToken(lltok::colon, "expected ':' here") ||
8143 ParseToken(lltok::lparen, "expected '(' here") ||
8144 ParseModuleReference(ModulePath) ||
8145 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
8146 ParseToken(lltok::comma, "expected ',' here") ||
8147 ParseGVarFlags(GVarFlags))
8148 return true;
8150 // Parse optional fields
8151 while (EatIfPresent(lltok::comma)) {
8152 switch (Lex.getKind()) {
8153 case lltok::kw_vTableFuncs:
8154 if (ParseOptionalVTableFuncs(VTableFuncs))
8155 return true;
8156 break;
8157 case lltok::kw_refs:
8158 if (ParseOptionalRefs(Refs))
8159 return true;
8160 break;
8161 default:
8162 return Error(Lex.getLoc(), "expected optional variable summary field");
8166 if (ParseToken(lltok::rparen, "expected ')' here"))
8167 return true;
8169 auto GS =
8170 std::make_unique<GlobalVarSummary>(GVFlags, GVarFlags, std::move(Refs));
8172 GS->setModulePath(ModulePath);
8173 GS->setVTableFuncs(std::move(VTableFuncs));
8175 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8176 ID, std::move(GS));
8178 return false;
8181 /// AliasSummary
8182 /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
8183 /// 'aliasee' ':' GVReference ')'
8184 bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
8185 unsigned ID) {
8186 assert(Lex.getKind() == lltok::kw_alias);
8187 LocTy Loc = Lex.getLoc();
8188 Lex.Lex();
8190 StringRef ModulePath;
8191 GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
8192 /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
8193 /*Live=*/false, /*IsLocal=*/false, /*CanAutoHide=*/false);
8194 if (ParseToken(lltok::colon, "expected ':' here") ||
8195 ParseToken(lltok::lparen, "expected '(' here") ||
8196 ParseModuleReference(ModulePath) ||
8197 ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
8198 ParseToken(lltok::comma, "expected ',' here") ||
8199 ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
8200 ParseToken(lltok::colon, "expected ':' here"))
8201 return true;
8203 ValueInfo AliaseeVI;
8204 unsigned GVId;
8205 if (ParseGVReference(AliaseeVI, GVId))
8206 return true;
8208 if (ParseToken(lltok::rparen, "expected ')' here"))
8209 return true;
8211 auto AS = std::make_unique<AliasSummary>(GVFlags);
8213 AS->setModulePath(ModulePath);
8215 // Record forward reference if the aliasee is not parsed yet.
8216 if (AliaseeVI.getRef() == FwdVIRef) {
8217 auto FwdRef = ForwardRefAliasees.insert(
8218 std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
8219 FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
8220 } else {
8221 auto Summary = Index->findSummaryInModule(AliaseeVI, ModulePath);
8222 assert(Summary && "Aliasee must be a definition");
8223 AS->setAliasee(AliaseeVI, Summary);
8226 AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
8227 ID, std::move(AS));
8229 return false;
8232 /// Flag
8233 /// ::= [0|1]
8234 bool LLParser::ParseFlag(unsigned &Val) {
8235 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
8236 return TokError("expected integer");
8237 Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
8238 Lex.Lex();
8239 return false;
8242 /// OptionalFFlags
8243 /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
8244 /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
8245 /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
8246 /// [',' 'noInline' ':' Flag]? ')'
8247 bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
8248 assert(Lex.getKind() == lltok::kw_funcFlags);
8249 Lex.Lex();
8251 if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
8252 ParseToken(lltok::lparen, "expected '(' in funcFlags"))
8253 return true;
8255 do {
8256 unsigned Val = 0;
8257 switch (Lex.getKind()) {
8258 case lltok::kw_readNone:
8259 Lex.Lex();
8260 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8261 return true;
8262 FFlags.ReadNone = Val;
8263 break;
8264 case lltok::kw_readOnly:
8265 Lex.Lex();
8266 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8267 return true;
8268 FFlags.ReadOnly = Val;
8269 break;
8270 case lltok::kw_noRecurse:
8271 Lex.Lex();
8272 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8273 return true;
8274 FFlags.NoRecurse = Val;
8275 break;
8276 case lltok::kw_returnDoesNotAlias:
8277 Lex.Lex();
8278 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8279 return true;
8280 FFlags.ReturnDoesNotAlias = Val;
8281 break;
8282 case lltok::kw_noInline:
8283 Lex.Lex();
8284 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
8285 return true;
8286 FFlags.NoInline = Val;
8287 break;
8288 default:
8289 return Error(Lex.getLoc(), "expected function flag type");
8291 } while (EatIfPresent(lltok::comma));
8293 if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
8294 return true;
8296 return false;
8299 /// OptionalCalls
8300 /// := 'calls' ':' '(' Call [',' Call]* ')'
8301 /// Call ::= '(' 'callee' ':' GVReference
8302 /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
8303 bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
8304 assert(Lex.getKind() == lltok::kw_calls);
8305 Lex.Lex();
8307 if (ParseToken(lltok::colon, "expected ':' in calls") |
8308 ParseToken(lltok::lparen, "expected '(' in calls"))
8309 return true;
8311 IdToIndexMapType IdToIndexMap;
8312 // Parse each call edge
8313 do {
8314 ValueInfo VI;
8315 if (ParseToken(lltok::lparen, "expected '(' in call") ||
8316 ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
8317 ParseToken(lltok::colon, "expected ':'"))
8318 return true;
8320 LocTy Loc = Lex.getLoc();
8321 unsigned GVId;
8322 if (ParseGVReference(VI, GVId))
8323 return true;
8325 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
8326 unsigned RelBF = 0;
8327 if (EatIfPresent(lltok::comma)) {
8328 // Expect either hotness or relbf
8329 if (EatIfPresent(lltok::kw_hotness)) {
8330 if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
8331 return true;
8332 } else {
8333 if (ParseToken(lltok::kw_relbf, "expected relbf") ||
8334 ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
8335 return true;
8338 // Keep track of the Call array index needing a forward reference.
8339 // We will save the location of the ValueInfo needing an update, but
8340 // can only do so once the std::vector is finalized.
8341 if (VI.getRef() == FwdVIRef)
8342 IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
8343 Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
8345 if (ParseToken(lltok::rparen, "expected ')' in call"))
8346 return true;
8347 } while (EatIfPresent(lltok::comma));
8349 // Now that the Calls vector is finalized, it is safe to save the locations
8350 // of any forward GV references that need updating later.
8351 for (auto I : IdToIndexMap) {
8352 for (auto P : I.second) {
8353 assert(Calls[P.first].first.getRef() == FwdVIRef &&
8354 "Forward referenced ValueInfo expected to be empty");
8355 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8356 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8357 FwdRef.first->second.push_back(
8358 std::make_pair(&Calls[P.first].first, P.second));
8362 if (ParseToken(lltok::rparen, "expected ')' in calls"))
8363 return true;
8365 return false;
8368 /// Hotness
8369 /// := ('unknown'|'cold'|'none'|'hot'|'critical')
8370 bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
8371 switch (Lex.getKind()) {
8372 case lltok::kw_unknown:
8373 Hotness = CalleeInfo::HotnessType::Unknown;
8374 break;
8375 case lltok::kw_cold:
8376 Hotness = CalleeInfo::HotnessType::Cold;
8377 break;
8378 case lltok::kw_none:
8379 Hotness = CalleeInfo::HotnessType::None;
8380 break;
8381 case lltok::kw_hot:
8382 Hotness = CalleeInfo::HotnessType::Hot;
8383 break;
8384 case lltok::kw_critical:
8385 Hotness = CalleeInfo::HotnessType::Critical;
8386 break;
8387 default:
8388 return Error(Lex.getLoc(), "invalid call edge hotness");
8390 Lex.Lex();
8391 return false;
8394 /// OptionalVTableFuncs
8395 /// := 'vTableFuncs' ':' '(' VTableFunc [',' VTableFunc]* ')'
8396 /// VTableFunc ::= '(' 'virtFunc' ':' GVReference ',' 'offset' ':' UInt64 ')'
8397 bool LLParser::ParseOptionalVTableFuncs(VTableFuncList &VTableFuncs) {
8398 assert(Lex.getKind() == lltok::kw_vTableFuncs);
8399 Lex.Lex();
8401 if (ParseToken(lltok::colon, "expected ':' in vTableFuncs") |
8402 ParseToken(lltok::lparen, "expected '(' in vTableFuncs"))
8403 return true;
8405 IdToIndexMapType IdToIndexMap;
8406 // Parse each virtual function pair
8407 do {
8408 ValueInfo VI;
8409 if (ParseToken(lltok::lparen, "expected '(' in vTableFunc") ||
8410 ParseToken(lltok::kw_virtFunc, "expected 'callee' in vTableFunc") ||
8411 ParseToken(lltok::colon, "expected ':'"))
8412 return true;
8414 LocTy Loc = Lex.getLoc();
8415 unsigned GVId;
8416 if (ParseGVReference(VI, GVId))
8417 return true;
8419 uint64_t Offset;
8420 if (ParseToken(lltok::comma, "expected comma") ||
8421 ParseToken(lltok::kw_offset, "expected offset") ||
8422 ParseToken(lltok::colon, "expected ':'") || ParseUInt64(Offset))
8423 return true;
8425 // Keep track of the VTableFuncs array index needing a forward reference.
8426 // We will save the location of the ValueInfo needing an update, but
8427 // can only do so once the std::vector is finalized.
8428 if (VI == EmptyVI)
8429 IdToIndexMap[GVId].push_back(std::make_pair(VTableFuncs.size(), Loc));
8430 VTableFuncs.push_back({VI, Offset});
8432 if (ParseToken(lltok::rparen, "expected ')' in vTableFunc"))
8433 return true;
8434 } while (EatIfPresent(lltok::comma));
8436 // Now that the VTableFuncs vector is finalized, it is safe to save the
8437 // locations of any forward GV references that need updating later.
8438 for (auto I : IdToIndexMap) {
8439 for (auto P : I.second) {
8440 assert(VTableFuncs[P.first].FuncVI == EmptyVI &&
8441 "Forward referenced ValueInfo expected to be empty");
8442 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8443 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8444 FwdRef.first->second.push_back(
8445 std::make_pair(&VTableFuncs[P.first].FuncVI, P.second));
8449 if (ParseToken(lltok::rparen, "expected ')' in vTableFuncs"))
8450 return true;
8452 return false;
8455 /// OptionalRefs
8456 /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
8457 bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
8458 assert(Lex.getKind() == lltok::kw_refs);
8459 Lex.Lex();
8461 if (ParseToken(lltok::colon, "expected ':' in refs") |
8462 ParseToken(lltok::lparen, "expected '(' in refs"))
8463 return true;
8465 struct ValueContext {
8466 ValueInfo VI;
8467 unsigned GVId;
8468 LocTy Loc;
8470 std::vector<ValueContext> VContexts;
8471 // Parse each ref edge
8472 do {
8473 ValueContext VC;
8474 VC.Loc = Lex.getLoc();
8475 if (ParseGVReference(VC.VI, VC.GVId))
8476 return true;
8477 VContexts.push_back(VC);
8478 } while (EatIfPresent(lltok::comma));
8480 // Sort value contexts so that ones with writeonly
8481 // and readonly ValueInfo are at the end of VContexts vector.
8482 // See FunctionSummary::specialRefCounts()
8483 llvm::sort(VContexts, [](const ValueContext &VC1, const ValueContext &VC2) {
8484 return VC1.VI.getAccessSpecifier() < VC2.VI.getAccessSpecifier();
8487 IdToIndexMapType IdToIndexMap;
8488 for (auto &VC : VContexts) {
8489 // Keep track of the Refs array index needing a forward reference.
8490 // We will save the location of the ValueInfo needing an update, but
8491 // can only do so once the std::vector is finalized.
8492 if (VC.VI.getRef() == FwdVIRef)
8493 IdToIndexMap[VC.GVId].push_back(std::make_pair(Refs.size(), VC.Loc));
8494 Refs.push_back(VC.VI);
8497 // Now that the Refs vector is finalized, it is safe to save the locations
8498 // of any forward GV references that need updating later.
8499 for (auto I : IdToIndexMap) {
8500 for (auto P : I.second) {
8501 assert(Refs[P.first].getRef() == FwdVIRef &&
8502 "Forward referenced ValueInfo expected to be empty");
8503 auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
8504 I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
8505 FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
8509 if (ParseToken(lltok::rparen, "expected ')' in refs"))
8510 return true;
8512 return false;
8515 /// OptionalTypeIdInfo
8516 /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
8517 /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
8518 /// [',' TypeCheckedLoadConstVCalls]? ')'
8519 bool LLParser::ParseOptionalTypeIdInfo(
8520 FunctionSummary::TypeIdInfo &TypeIdInfo) {
8521 assert(Lex.getKind() == lltok::kw_typeIdInfo);
8522 Lex.Lex();
8524 if (ParseToken(lltok::colon, "expected ':' here") ||
8525 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8526 return true;
8528 do {
8529 switch (Lex.getKind()) {
8530 case lltok::kw_typeTests:
8531 if (ParseTypeTests(TypeIdInfo.TypeTests))
8532 return true;
8533 break;
8534 case lltok::kw_typeTestAssumeVCalls:
8535 if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
8536 TypeIdInfo.TypeTestAssumeVCalls))
8537 return true;
8538 break;
8539 case lltok::kw_typeCheckedLoadVCalls:
8540 if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
8541 TypeIdInfo.TypeCheckedLoadVCalls))
8542 return true;
8543 break;
8544 case lltok::kw_typeTestAssumeConstVCalls:
8545 if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
8546 TypeIdInfo.TypeTestAssumeConstVCalls))
8547 return true;
8548 break;
8549 case lltok::kw_typeCheckedLoadConstVCalls:
8550 if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
8551 TypeIdInfo.TypeCheckedLoadConstVCalls))
8552 return true;
8553 break;
8554 default:
8555 return Error(Lex.getLoc(), "invalid typeIdInfo list type");
8557 } while (EatIfPresent(lltok::comma));
8559 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8560 return true;
8562 return false;
8565 /// TypeTests
8566 /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
8567 /// [',' (SummaryID | UInt64)]* ')'
8568 bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
8569 assert(Lex.getKind() == lltok::kw_typeTests);
8570 Lex.Lex();
8572 if (ParseToken(lltok::colon, "expected ':' here") ||
8573 ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
8574 return true;
8576 IdToIndexMapType IdToIndexMap;
8577 do {
8578 GlobalValue::GUID GUID = 0;
8579 if (Lex.getKind() == lltok::SummaryID) {
8580 unsigned ID = Lex.getUIntVal();
8581 LocTy Loc = Lex.getLoc();
8582 // Keep track of the TypeTests array index needing a forward reference.
8583 // We will save the location of the GUID needing an update, but
8584 // can only do so once the std::vector is finalized.
8585 IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
8586 Lex.Lex();
8587 } else if (ParseUInt64(GUID))
8588 return true;
8589 TypeTests.push_back(GUID);
8590 } while (EatIfPresent(lltok::comma));
8592 // Now that the TypeTests vector is finalized, it is safe to save the
8593 // locations of any forward GV references that need updating later.
8594 for (auto I : IdToIndexMap) {
8595 for (auto P : I.second) {
8596 assert(TypeTests[P.first] == 0 &&
8597 "Forward referenced type id GUID expected to be 0");
8598 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8599 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8600 FwdRef.first->second.push_back(
8601 std::make_pair(&TypeTests[P.first], P.second));
8605 if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
8606 return true;
8608 return false;
8611 /// VFuncIdList
8612 /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
8613 bool LLParser::ParseVFuncIdList(
8614 lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
8615 assert(Lex.getKind() == Kind);
8616 Lex.Lex();
8618 if (ParseToken(lltok::colon, "expected ':' here") ||
8619 ParseToken(lltok::lparen, "expected '(' here"))
8620 return true;
8622 IdToIndexMapType IdToIndexMap;
8623 do {
8624 FunctionSummary::VFuncId VFuncId;
8625 if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
8626 return true;
8627 VFuncIdList.push_back(VFuncId);
8628 } while (EatIfPresent(lltok::comma));
8630 if (ParseToken(lltok::rparen, "expected ')' here"))
8631 return true;
8633 // Now that the VFuncIdList vector is finalized, it is safe to save the
8634 // locations of any forward GV references that need updating later.
8635 for (auto I : IdToIndexMap) {
8636 for (auto P : I.second) {
8637 assert(VFuncIdList[P.first].GUID == 0 &&
8638 "Forward referenced type id GUID expected to be 0");
8639 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8640 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8641 FwdRef.first->second.push_back(
8642 std::make_pair(&VFuncIdList[P.first].GUID, P.second));
8646 return false;
8649 /// ConstVCallList
8650 /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
8651 bool LLParser::ParseConstVCallList(
8652 lltok::Kind Kind,
8653 std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
8654 assert(Lex.getKind() == Kind);
8655 Lex.Lex();
8657 if (ParseToken(lltok::colon, "expected ':' here") ||
8658 ParseToken(lltok::lparen, "expected '(' here"))
8659 return true;
8661 IdToIndexMapType IdToIndexMap;
8662 do {
8663 FunctionSummary::ConstVCall ConstVCall;
8664 if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
8665 return true;
8666 ConstVCallList.push_back(ConstVCall);
8667 } while (EatIfPresent(lltok::comma));
8669 if (ParseToken(lltok::rparen, "expected ')' here"))
8670 return true;
8672 // Now that the ConstVCallList vector is finalized, it is safe to save the
8673 // locations of any forward GV references that need updating later.
8674 for (auto I : IdToIndexMap) {
8675 for (auto P : I.second) {
8676 assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
8677 "Forward referenced type id GUID expected to be 0");
8678 auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
8679 I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
8680 FwdRef.first->second.push_back(
8681 std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
8685 return false;
8688 /// ConstVCall
8689 /// ::= '(' VFuncId ',' Args ')'
8690 bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
8691 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8692 if (ParseToken(lltok::lparen, "expected '(' here") ||
8693 ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
8694 return true;
8696 if (EatIfPresent(lltok::comma))
8697 if (ParseArgs(ConstVCall.Args))
8698 return true;
8700 if (ParseToken(lltok::rparen, "expected ')' here"))
8701 return true;
8703 return false;
8706 /// VFuncId
8707 /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
8708 /// 'offset' ':' UInt64 ')'
8709 bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
8710 IdToIndexMapType &IdToIndexMap, unsigned Index) {
8711 assert(Lex.getKind() == lltok::kw_vFuncId);
8712 Lex.Lex();
8714 if (ParseToken(lltok::colon, "expected ':' here") ||
8715 ParseToken(lltok::lparen, "expected '(' here"))
8716 return true;
8718 if (Lex.getKind() == lltok::SummaryID) {
8719 VFuncId.GUID = 0;
8720 unsigned ID = Lex.getUIntVal();
8721 LocTy Loc = Lex.getLoc();
8722 // Keep track of the array index needing a forward reference.
8723 // We will save the location of the GUID needing an update, but
8724 // can only do so once the caller's std::vector is finalized.
8725 IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
8726 Lex.Lex();
8727 } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
8728 ParseToken(lltok::colon, "expected ':' here") ||
8729 ParseUInt64(VFuncId.GUID))
8730 return true;
8732 if (ParseToken(lltok::comma, "expected ',' here") ||
8733 ParseToken(lltok::kw_offset, "expected 'offset' here") ||
8734 ParseToken(lltok::colon, "expected ':' here") ||
8735 ParseUInt64(VFuncId.Offset) ||
8736 ParseToken(lltok::rparen, "expected ')' here"))
8737 return true;
8739 return false;
8742 /// GVFlags
8743 /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
8744 /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
8745 /// 'dsoLocal' ':' Flag ',' 'canAutoHide' ':' Flag ')'
8746 bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
8747 assert(Lex.getKind() == lltok::kw_flags);
8748 Lex.Lex();
8750 if (ParseToken(lltok::colon, "expected ':' here") ||
8751 ParseToken(lltok::lparen, "expected '(' here"))
8752 return true;
8754 do {
8755 unsigned Flag = 0;
8756 switch (Lex.getKind()) {
8757 case lltok::kw_linkage:
8758 Lex.Lex();
8759 if (ParseToken(lltok::colon, "expected ':'"))
8760 return true;
8761 bool HasLinkage;
8762 GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
8763 assert(HasLinkage && "Linkage not optional in summary entry");
8764 Lex.Lex();
8765 break;
8766 case lltok::kw_notEligibleToImport:
8767 Lex.Lex();
8768 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8769 return true;
8770 GVFlags.NotEligibleToImport = Flag;
8771 break;
8772 case lltok::kw_live:
8773 Lex.Lex();
8774 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8775 return true;
8776 GVFlags.Live = Flag;
8777 break;
8778 case lltok::kw_dsoLocal:
8779 Lex.Lex();
8780 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8781 return true;
8782 GVFlags.DSOLocal = Flag;
8783 break;
8784 case lltok::kw_canAutoHide:
8785 Lex.Lex();
8786 if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Flag))
8787 return true;
8788 GVFlags.CanAutoHide = Flag;
8789 break;
8790 default:
8791 return Error(Lex.getLoc(), "expected gv flag type");
8793 } while (EatIfPresent(lltok::comma));
8795 if (ParseToken(lltok::rparen, "expected ')' here"))
8796 return true;
8798 return false;
8801 /// GVarFlags
8802 /// ::= 'varFlags' ':' '(' 'readonly' ':' Flag
8803 /// ',' 'writeonly' ':' Flag ')'
8804 bool LLParser::ParseGVarFlags(GlobalVarSummary::GVarFlags &GVarFlags) {
8805 assert(Lex.getKind() == lltok::kw_varFlags);
8806 Lex.Lex();
8808 if (ParseToken(lltok::colon, "expected ':' here") ||
8809 ParseToken(lltok::lparen, "expected '(' here"))
8810 return true;
8812 auto ParseRest = [this](unsigned int &Val) {
8813 Lex.Lex();
8814 if (ParseToken(lltok::colon, "expected ':'"))
8815 return true;
8816 return ParseFlag(Val);
8819 do {
8820 unsigned Flag = 0;
8821 switch (Lex.getKind()) {
8822 case lltok::kw_readonly:
8823 if (ParseRest(Flag))
8824 return true;
8825 GVarFlags.MaybeReadOnly = Flag;
8826 break;
8827 case lltok::kw_writeonly:
8828 if (ParseRest(Flag))
8829 return true;
8830 GVarFlags.MaybeWriteOnly = Flag;
8831 break;
8832 default:
8833 return Error(Lex.getLoc(), "expected gvar flag type");
8835 } while (EatIfPresent(lltok::comma));
8836 return ParseToken(lltok::rparen, "expected ')' here");
8839 /// ModuleReference
8840 /// ::= 'module' ':' UInt
8841 bool LLParser::ParseModuleReference(StringRef &ModulePath) {
8842 // Parse module id.
8843 if (ParseToken(lltok::kw_module, "expected 'module' here") ||
8844 ParseToken(lltok::colon, "expected ':' here") ||
8845 ParseToken(lltok::SummaryID, "expected module ID"))
8846 return true;
8848 unsigned ModuleID = Lex.getUIntVal();
8849 auto I = ModuleIdMap.find(ModuleID);
8850 // We should have already parsed all module IDs
8851 assert(I != ModuleIdMap.end());
8852 ModulePath = I->second;
8853 return false;
8856 /// GVReference
8857 /// ::= SummaryID
8858 bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
8859 bool WriteOnly = false, ReadOnly = EatIfPresent(lltok::kw_readonly);
8860 if (!ReadOnly)
8861 WriteOnly = EatIfPresent(lltok::kw_writeonly);
8862 if (ParseToken(lltok::SummaryID, "expected GV ID"))
8863 return true;
8865 GVId = Lex.getUIntVal();
8866 // Check if we already have a VI for this GV
8867 if (GVId < NumberedValueInfos.size()) {
8868 assert(NumberedValueInfos[GVId].getRef() != FwdVIRef);
8869 VI = NumberedValueInfos[GVId];
8870 } else
8871 // We will create a forward reference to the stored location.
8872 VI = ValueInfo(false, FwdVIRef);
8874 if (ReadOnly)
8875 VI.setReadOnly();
8876 if (WriteOnly)
8877 VI.setWriteOnly();
8878 return false;