1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DebugInfoMetadata.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/ValueSymbolTable.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/SaveAndRestore.h"
31 #include "llvm/Support/raw_ostream.h"
34 static std::string getTypeString(Type *T) {
36 raw_string_ostream Tmp(Result);
41 /// Run: module ::= toplevelentity*
42 bool LLParser::Run() {
46 return ParseTopLevelEntities() ||
47 ValidateEndOfModule();
50 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
52 bool LLParser::ValidateEndOfModule() {
53 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
54 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
56 // Handle any function attribute group forward references.
57 for (std::map<Value*, std::vector<unsigned> >::iterator
58 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
61 std::vector<unsigned> &Vec = I->second;
64 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
66 B.merge(NumberedAttrBuilders[*VI]);
68 if (Function *Fn = dyn_cast<Function>(V)) {
69 AttributeSet AS = Fn->getAttributes();
70 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
71 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
72 AS.getFnAttributes());
76 // If the alignment was parsed as an attribute, move to the alignment
78 if (FnAttrs.hasAlignmentAttr()) {
79 Fn->setAlignment(FnAttrs.getAlignment());
80 FnAttrs.removeAttribute(Attribute::Alignment);
83 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
84 AttributeSet::get(Context,
85 AttributeSet::FunctionIndex,
87 Fn->setAttributes(AS);
88 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
89 AttributeSet AS = CI->getAttributes();
90 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
91 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
92 AS.getFnAttributes());
94 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
95 AttributeSet::get(Context,
96 AttributeSet::FunctionIndex,
98 CI->setAttributes(AS);
99 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
100 AttributeSet AS = II->getAttributes();
101 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
102 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
103 AS.getFnAttributes());
105 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
106 AttributeSet::get(Context,
107 AttributeSet::FunctionIndex,
109 II->setAttributes(AS);
111 llvm_unreachable("invalid object with forward attribute group reference");
115 // If there are entries in ForwardRefBlockAddresses at this point, the
116 // function was never defined.
117 if (!ForwardRefBlockAddresses.empty())
118 return Error(ForwardRefBlockAddresses.begin()->first.Loc,
119 "expected function name in blockaddress");
121 for (const auto &NT : NumberedTypes)
122 if (NT.second.second.isValid())
123 return Error(NT.second.second,
124 "use of undefined type '%" + Twine(NT.first) + "'");
126 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
127 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
128 if (I->second.second.isValid())
129 return Error(I->second.second,
130 "use of undefined type named '" + I->getKey() + "'");
132 if (!ForwardRefComdats.empty())
133 return Error(ForwardRefComdats.begin()->second,
134 "use of undefined comdat '$" +
135 ForwardRefComdats.begin()->first + "'");
137 if (!ForwardRefVals.empty())
138 return Error(ForwardRefVals.begin()->second.second,
139 "use of undefined value '@" + ForwardRefVals.begin()->first +
142 if (!ForwardRefValIDs.empty())
143 return Error(ForwardRefValIDs.begin()->second.second,
144 "use of undefined value '@" +
145 Twine(ForwardRefValIDs.begin()->first) + "'");
147 if (!ForwardRefMDNodes.empty())
148 return Error(ForwardRefMDNodes.begin()->second.second,
149 "use of undefined metadata '!" +
150 Twine(ForwardRefMDNodes.begin()->first) + "'");
152 // Resolve metadata cycles.
153 for (auto &N : NumberedMetadata) {
154 if (N.second && !N.second->isResolved())
155 N.second->resolveCycles();
158 // Look for intrinsic functions and CallInst that need to be upgraded
159 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
160 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
162 UpgradeDebugInfo(*M);
167 //===----------------------------------------------------------------------===//
168 // Top-Level Entities
169 //===----------------------------------------------------------------------===//
171 bool LLParser::ParseTopLevelEntities() {
173 switch (Lex.getKind()) {
174 default: return TokError("expected top-level entity");
175 case lltok::Eof: return false;
176 case lltok::kw_declare: if (ParseDeclare()) return true; break;
177 case lltok::kw_define: if (ParseDefine()) return true; break;
178 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
179 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
180 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
181 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
182 case lltok::LocalVar: if (ParseNamedType()) return true; break;
183 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
184 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
185 case lltok::ComdatVar: if (parseComdat()) return true; break;
186 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
187 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
189 // The Global variable production with no name can have many different
190 // optional leading prefixes, the production is:
191 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
192 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
193 // ('constant'|'global') ...
194 case lltok::kw_private: // OptionalLinkage
195 case lltok::kw_internal: // OptionalLinkage
196 case lltok::kw_weak: // OptionalLinkage
197 case lltok::kw_weak_odr: // OptionalLinkage
198 case lltok::kw_linkonce: // OptionalLinkage
199 case lltok::kw_linkonce_odr: // OptionalLinkage
200 case lltok::kw_appending: // OptionalLinkage
201 case lltok::kw_common: // OptionalLinkage
202 case lltok::kw_extern_weak: // OptionalLinkage
203 case lltok::kw_external: // OptionalLinkage
204 case lltok::kw_default: // OptionalVisibility
205 case lltok::kw_hidden: // OptionalVisibility
206 case lltok::kw_protected: // OptionalVisibility
207 case lltok::kw_dllimport: // OptionalDLLStorageClass
208 case lltok::kw_dllexport: // OptionalDLLStorageClass
209 case lltok::kw_thread_local: // OptionalThreadLocal
210 case lltok::kw_addrspace: // OptionalAddrSpace
211 case lltok::kw_constant: // GlobalType
212 case lltok::kw_global: { // GlobalType
213 unsigned Linkage, Visibility, DLLStorageClass;
215 GlobalVariable::ThreadLocalMode TLM;
217 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
218 ParseOptionalVisibility(Visibility) ||
219 ParseOptionalDLLStorageClass(DLLStorageClass) ||
220 ParseOptionalThreadLocal(TLM) ||
221 parseOptionalUnnamedAddr(UnnamedAddr) ||
222 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
223 DLLStorageClass, TLM, UnnamedAddr))
228 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
229 case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
230 case lltok::kw_uselistorder_bb:
231 if (ParseUseListOrderBB()) return true; break;
238 /// ::= 'module' 'asm' STRINGCONSTANT
239 bool LLParser::ParseModuleAsm() {
240 assert(Lex.getKind() == lltok::kw_module);
244 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
245 ParseStringConstant(AsmStr)) return true;
247 M->appendModuleInlineAsm(AsmStr);
252 /// ::= 'target' 'triple' '=' STRINGCONSTANT
253 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
254 bool LLParser::ParseTargetDefinition() {
255 assert(Lex.getKind() == lltok::kw_target);
258 default: return TokError("unknown target property");
259 case lltok::kw_triple:
261 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
262 ParseStringConstant(Str))
264 M->setTargetTriple(Str);
266 case lltok::kw_datalayout:
268 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
269 ParseStringConstant(Str))
271 M->setDataLayout(Str);
277 /// ::= 'deplibs' '=' '[' ']'
278 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
279 /// FIXME: Remove in 4.0. Currently parse, but ignore.
280 bool LLParser::ParseDepLibs() {
281 assert(Lex.getKind() == lltok::kw_deplibs);
283 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
284 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
287 if (EatIfPresent(lltok::rsquare))
292 if (ParseStringConstant(Str)) return true;
293 } while (EatIfPresent(lltok::comma));
295 return ParseToken(lltok::rsquare, "expected ']' at end of list");
298 /// ParseUnnamedType:
299 /// ::= LocalVarID '=' 'type' type
300 bool LLParser::ParseUnnamedType() {
301 LocTy TypeLoc = Lex.getLoc();
302 unsigned TypeID = Lex.getUIntVal();
303 Lex.Lex(); // eat LocalVarID;
305 if (ParseToken(lltok::equal, "expected '=' after name") ||
306 ParseToken(lltok::kw_type, "expected 'type' after '='"))
309 Type *Result = nullptr;
310 if (ParseStructDefinition(TypeLoc, "",
311 NumberedTypes[TypeID], Result)) return true;
313 if (!isa<StructType>(Result)) {
314 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
316 return Error(TypeLoc, "non-struct types may not be recursive");
317 Entry.first = Result;
318 Entry.second = SMLoc();
326 /// ::= LocalVar '=' 'type' type
327 bool LLParser::ParseNamedType() {
328 std::string Name = Lex.getStrVal();
329 LocTy NameLoc = Lex.getLoc();
330 Lex.Lex(); // eat LocalVar.
332 if (ParseToken(lltok::equal, "expected '=' after name") ||
333 ParseToken(lltok::kw_type, "expected 'type' after name"))
336 Type *Result = nullptr;
337 if (ParseStructDefinition(NameLoc, Name,
338 NamedTypes[Name], Result)) return true;
340 if (!isa<StructType>(Result)) {
341 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
343 return Error(NameLoc, "non-struct types may not be recursive");
344 Entry.first = Result;
345 Entry.second = SMLoc();
353 /// ::= 'declare' FunctionHeader
354 bool LLParser::ParseDeclare() {
355 assert(Lex.getKind() == lltok::kw_declare);
359 return ParseFunctionHeader(F, false);
363 /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
364 bool LLParser::ParseDefine() {
365 assert(Lex.getKind() == lltok::kw_define);
369 return ParseFunctionHeader(F, true) ||
370 ParseOptionalFunctionMetadata(*F) ||
371 ParseFunctionBody(*F);
377 bool LLParser::ParseGlobalType(bool &IsConstant) {
378 if (Lex.getKind() == lltok::kw_constant)
380 else if (Lex.getKind() == lltok::kw_global)
384 return TokError("expected 'global' or 'constant'");
390 /// ParseUnnamedGlobal:
391 /// OptionalVisibility ALIAS ...
392 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
393 /// ... -> global variable
394 /// GlobalID '=' OptionalVisibility ALIAS ...
395 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
396 /// ... -> global variable
397 bool LLParser::ParseUnnamedGlobal() {
398 unsigned VarID = NumberedVals.size();
400 LocTy NameLoc = Lex.getLoc();
402 // Handle the GlobalID form.
403 if (Lex.getKind() == lltok::GlobalID) {
404 if (Lex.getUIntVal() != VarID)
405 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
407 Lex.Lex(); // eat GlobalID;
409 if (ParseToken(lltok::equal, "expected '=' after name"))
414 unsigned Linkage, Visibility, DLLStorageClass;
415 GlobalVariable::ThreadLocalMode TLM;
417 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
418 ParseOptionalVisibility(Visibility) ||
419 ParseOptionalDLLStorageClass(DLLStorageClass) ||
420 ParseOptionalThreadLocal(TLM) ||
421 parseOptionalUnnamedAddr(UnnamedAddr))
424 if (Lex.getKind() != lltok::kw_alias)
425 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
426 DLLStorageClass, TLM, UnnamedAddr);
427 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
431 /// ParseNamedGlobal:
432 /// GlobalVar '=' OptionalVisibility ALIAS ...
433 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
434 /// ... -> global variable
435 bool LLParser::ParseNamedGlobal() {
436 assert(Lex.getKind() == lltok::GlobalVar);
437 LocTy NameLoc = Lex.getLoc();
438 std::string Name = Lex.getStrVal();
442 unsigned Linkage, Visibility, DLLStorageClass;
443 GlobalVariable::ThreadLocalMode TLM;
445 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
446 ParseOptionalLinkage(Linkage, HasLinkage) ||
447 ParseOptionalVisibility(Visibility) ||
448 ParseOptionalDLLStorageClass(DLLStorageClass) ||
449 ParseOptionalThreadLocal(TLM) ||
450 parseOptionalUnnamedAddr(UnnamedAddr))
453 if (Lex.getKind() != lltok::kw_alias)
454 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
455 DLLStorageClass, TLM, UnnamedAddr);
457 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
461 bool LLParser::parseComdat() {
462 assert(Lex.getKind() == lltok::ComdatVar);
463 std::string Name = Lex.getStrVal();
464 LocTy NameLoc = Lex.getLoc();
467 if (ParseToken(lltok::equal, "expected '=' here"))
470 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
471 return TokError("expected comdat type");
473 Comdat::SelectionKind SK;
474 switch (Lex.getKind()) {
476 return TokError("unknown selection kind");
480 case lltok::kw_exactmatch:
481 SK = Comdat::ExactMatch;
483 case lltok::kw_largest:
484 SK = Comdat::Largest;
486 case lltok::kw_noduplicates:
487 SK = Comdat::NoDuplicates;
489 case lltok::kw_samesize:
490 SK = Comdat::SameSize;
495 // See if the comdat was forward referenced, if so, use the comdat.
496 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
497 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
498 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
499 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
502 if (I != ComdatSymTab.end())
505 C = M->getOrInsertComdat(Name);
506 C->setSelectionKind(SK);
512 // ::= '!' STRINGCONSTANT
513 bool LLParser::ParseMDString(MDString *&Result) {
515 if (ParseStringConstant(Str)) return true;
516 llvm::UpgradeMDStringConstant(Str);
517 Result = MDString::get(Context, Str);
522 // ::= '!' MDNodeNumber
523 bool LLParser::ParseMDNodeID(MDNode *&Result) {
524 // !{ ..., !42, ... }
526 if (ParseUInt32(MID))
529 // If not a forward reference, just return it now.
530 if (NumberedMetadata.count(MID)) {
531 Result = NumberedMetadata[MID];
535 // Otherwise, create MDNode forward reference.
536 auto &FwdRef = ForwardRefMDNodes[MID];
537 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
539 Result = FwdRef.first.get();
540 NumberedMetadata[MID].reset(Result);
544 /// ParseNamedMetadata:
545 /// !foo = !{ !1, !2 }
546 bool LLParser::ParseNamedMetadata() {
547 assert(Lex.getKind() == lltok::MetadataVar);
548 std::string Name = Lex.getStrVal();
551 if (ParseToken(lltok::equal, "expected '=' here") ||
552 ParseToken(lltok::exclaim, "Expected '!' here") ||
553 ParseToken(lltok::lbrace, "Expected '{' here"))
556 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
557 if (Lex.getKind() != lltok::rbrace)
559 if (ParseToken(lltok::exclaim, "Expected '!' here"))
563 if (ParseMDNodeID(N)) return true;
565 } while (EatIfPresent(lltok::comma));
567 return ParseToken(lltok::rbrace, "expected end of metadata node");
570 /// ParseStandaloneMetadata:
572 bool LLParser::ParseStandaloneMetadata() {
573 assert(Lex.getKind() == lltok::exclaim);
575 unsigned MetadataID = 0;
578 if (ParseUInt32(MetadataID) ||
579 ParseToken(lltok::equal, "expected '=' here"))
582 // Detect common error, from old metadata syntax.
583 if (Lex.getKind() == lltok::Type)
584 return TokError("unexpected type in metadata definition");
586 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
587 if (Lex.getKind() == lltok::MetadataVar) {
588 if (ParseSpecializedMDNode(Init, IsDistinct))
590 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
591 ParseMDTuple(Init, IsDistinct))
594 // See if this was forward referenced, if so, handle it.
595 auto FI = ForwardRefMDNodes.find(MetadataID);
596 if (FI != ForwardRefMDNodes.end()) {
597 FI->second.first->replaceAllUsesWith(Init);
598 ForwardRefMDNodes.erase(FI);
600 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
602 if (NumberedMetadata.count(MetadataID))
603 return TokError("Metadata id is already used");
604 NumberedMetadata[MetadataID].reset(Init);
610 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
611 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
612 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
616 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
617 /// OptionalDLLStorageClass OptionalThreadLocal
618 /// OptionalUnNammedAddr 'alias' Aliasee
623 /// Everything through OptionalUnNammedAddr has already been parsed.
625 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
626 unsigned Visibility, unsigned DLLStorageClass,
627 GlobalVariable::ThreadLocalMode TLM,
629 assert(Lex.getKind() == lltok::kw_alias);
632 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
634 if(!GlobalAlias::isValidLinkage(Linkage))
635 return Error(NameLoc, "invalid linkage type for alias");
637 if (!isValidVisibilityForLinkage(Visibility, L))
638 return Error(NameLoc,
639 "symbol with local linkage must have default visibility");
642 LocTy AliaseeLoc = Lex.getLoc();
643 if (Lex.getKind() != lltok::kw_bitcast &&
644 Lex.getKind() != lltok::kw_getelementptr &&
645 Lex.getKind() != lltok::kw_addrspacecast &&
646 Lex.getKind() != lltok::kw_inttoptr) {
647 if (ParseGlobalTypeAndValue(Aliasee))
650 // The bitcast dest type is not present, it is implied by the dest type.
654 if (ID.Kind != ValID::t_Constant)
655 return Error(AliaseeLoc, "invalid aliasee");
656 Aliasee = ID.ConstantVal;
659 Type *AliaseeType = Aliasee->getType();
660 auto *PTy = dyn_cast<PointerType>(AliaseeType);
662 return Error(AliaseeLoc, "An alias must have pointer type");
664 // Okay, create the alias but do not insert it into the module yet.
665 std::unique_ptr<GlobalAlias> GA(
666 GlobalAlias::create(PTy, (GlobalValue::LinkageTypes)Linkage, Name,
667 Aliasee, /*Parent*/ nullptr));
668 GA->setThreadLocalMode(TLM);
669 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
670 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
671 GA->setUnnamedAddr(UnnamedAddr);
673 // See if this value already exists in the symbol table. If so, it is either
674 // a redefinition or a definition of a forward reference.
675 if (GlobalValue *Val = M->getNamedValue(Name)) {
676 // See if this was a redefinition. If so, there is no entry in
678 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
679 I = ForwardRefVals.find(Name);
680 if (I == ForwardRefVals.end())
681 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
683 // Otherwise, this was a definition of forward ref. Verify that types
685 if (Val->getType() != GA->getType())
686 return Error(NameLoc,
687 "forward reference and definition of alias have different types");
689 // If they agree, just RAUW the old value with the alias and remove the
691 Val->replaceAllUsesWith(GA.get());
692 Val->eraseFromParent();
693 ForwardRefVals.erase(I);
696 // Insert into the module, we know its name won't collide now.
697 M->getAliasList().push_back(GA.get());
698 assert(GA->getName() == Name && "Should not be a name conflict!");
700 // The module owns this now
707 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
708 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
709 /// OptionalExternallyInitialized GlobalType Type Const
710 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
711 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
712 /// OptionalExternallyInitialized GlobalType Type Const
714 /// Everything up to and including OptionalUnNammedAddr has been parsed
717 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
718 unsigned Linkage, bool HasLinkage,
719 unsigned Visibility, unsigned DLLStorageClass,
720 GlobalVariable::ThreadLocalMode TLM,
722 if (!isValidVisibilityForLinkage(Visibility, Linkage))
723 return Error(NameLoc,
724 "symbol with local linkage must have default visibility");
727 bool IsConstant, IsExternallyInitialized;
728 LocTy IsExternallyInitializedLoc;
732 if (ParseOptionalAddrSpace(AddrSpace) ||
733 ParseOptionalToken(lltok::kw_externally_initialized,
734 IsExternallyInitialized,
735 &IsExternallyInitializedLoc) ||
736 ParseGlobalType(IsConstant) ||
737 ParseType(Ty, TyLoc))
740 // If the linkage is specified and is external, then no initializer is
742 Constant *Init = nullptr;
743 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
744 Linkage != GlobalValue::ExternalLinkage)) {
745 if (ParseGlobalValue(Ty, Init))
749 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
750 return Error(TyLoc, "invalid type for global variable");
752 GlobalValue *GVal = nullptr;
754 // See if the global was forward referenced, if so, use the global.
756 GVal = M->getNamedValue(Name);
758 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
759 return Error(NameLoc, "redefinition of global '@" + Name + "'");
762 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
763 I = ForwardRefValIDs.find(NumberedVals.size());
764 if (I != ForwardRefValIDs.end()) {
765 GVal = I->second.first;
766 ForwardRefValIDs.erase(I);
772 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
773 Name, nullptr, GlobalVariable::NotThreadLocal,
776 if (GVal->getValueType() != Ty)
778 "forward reference and definition of global have different types");
780 GV = cast<GlobalVariable>(GVal);
782 // Move the forward-reference to the correct spot in the module.
783 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
787 NumberedVals.push_back(GV);
789 // Set the parsed properties on the global.
791 GV->setInitializer(Init);
792 GV->setConstant(IsConstant);
793 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
794 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
795 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
796 GV->setExternallyInitialized(IsExternallyInitialized);
797 GV->setThreadLocalMode(TLM);
798 GV->setUnnamedAddr(UnnamedAddr);
800 // Parse attributes on the global.
801 while (Lex.getKind() == lltok::comma) {
804 if (Lex.getKind() == lltok::kw_section) {
806 GV->setSection(Lex.getStrVal());
807 if (ParseToken(lltok::StringConstant, "expected global section string"))
809 } else if (Lex.getKind() == lltok::kw_align) {
811 if (ParseOptionalAlignment(Alignment)) return true;
812 GV->setAlignment(Alignment);
815 if (parseOptionalComdat(Name, C))
820 return TokError("unknown global variable property!");
827 /// ParseUnnamedAttrGrp
828 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
829 bool LLParser::ParseUnnamedAttrGrp() {
830 assert(Lex.getKind() == lltok::kw_attributes);
831 LocTy AttrGrpLoc = Lex.getLoc();
834 if (Lex.getKind() != lltok::AttrGrpID)
835 return TokError("expected attribute group id");
837 unsigned VarID = Lex.getUIntVal();
838 std::vector<unsigned> unused;
842 if (ParseToken(lltok::equal, "expected '=' here") ||
843 ParseToken(lltok::lbrace, "expected '{' here") ||
844 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
846 ParseToken(lltok::rbrace, "expected end of attribute group"))
849 if (!NumberedAttrBuilders[VarID].hasAttributes())
850 return Error(AttrGrpLoc, "attribute group has no attributes");
855 /// ParseFnAttributeValuePairs
856 /// ::= <attr> | <attr> '=' <value>
857 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
858 std::vector<unsigned> &FwdRefAttrGrps,
859 bool inAttrGrp, LocTy &BuiltinLoc) {
860 bool HaveError = false;
865 lltok::Kind Token = Lex.getKind();
866 if (Token == lltok::kw_builtin)
867 BuiltinLoc = Lex.getLoc();
870 if (!inAttrGrp) return HaveError;
871 return Error(Lex.getLoc(), "unterminated attribute group");
876 case lltok::AttrGrpID: {
877 // Allow a function to reference an attribute group:
879 // define void @foo() #1 { ... }
883 "cannot have an attribute group reference in an attribute group");
885 unsigned AttrGrpNum = Lex.getUIntVal();
886 if (inAttrGrp) break;
888 // Save the reference to the attribute group. We'll fill it in later.
889 FwdRefAttrGrps.push_back(AttrGrpNum);
892 // Target-dependent attributes:
893 case lltok::StringConstant: {
894 std::string Attr = Lex.getStrVal();
897 if (EatIfPresent(lltok::equal) &&
898 ParseStringConstant(Val))
901 B.addAttribute(Attr, Val);
905 // Target-independent attributes:
906 case lltok::kw_align: {
907 // As a hack, we allow function alignment to be initially parsed as an
908 // attribute on a function declaration/definition or added to an attribute
909 // group and later moved to the alignment field.
913 if (ParseToken(lltok::equal, "expected '=' here") ||
914 ParseUInt32(Alignment))
917 if (ParseOptionalAlignment(Alignment))
920 B.addAlignmentAttr(Alignment);
923 case lltok::kw_alignstack: {
927 if (ParseToken(lltok::equal, "expected '=' here") ||
928 ParseUInt32(Alignment))
931 if (ParseOptionalStackAlignment(Alignment))
934 B.addStackAlignmentAttr(Alignment);
937 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
938 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
939 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
940 case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
941 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
942 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
943 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
944 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
945 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
946 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
947 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
948 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
949 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
950 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
951 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
952 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
953 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
954 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
955 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
956 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
957 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
958 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
959 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
960 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
961 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
962 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
963 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
964 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
967 case lltok::kw_inreg:
968 case lltok::kw_signext:
969 case lltok::kw_zeroext:
972 "invalid use of attribute on a function");
974 case lltok::kw_byval:
975 case lltok::kw_dereferenceable:
976 case lltok::kw_dereferenceable_or_null:
977 case lltok::kw_inalloca:
979 case lltok::kw_noalias:
980 case lltok::kw_nocapture:
981 case lltok::kw_nonnull:
982 case lltok::kw_returned:
986 "invalid use of parameter-only attribute on a function");
994 //===----------------------------------------------------------------------===//
995 // GlobalValue Reference/Resolution Routines.
996 //===----------------------------------------------------------------------===//
998 /// GetGlobalVal - Get a value with the specified name or ID, creating a
999 /// forward reference record if needed. This can return null if the value
1000 /// exists but does not have the right type.
1001 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1003 PointerType *PTy = dyn_cast<PointerType>(Ty);
1005 Error(Loc, "global variable reference must have pointer type");
1009 // Look this name up in the normal function symbol table.
1011 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1013 // If this is a forward reference for the value, see if we already created a
1014 // forward ref record.
1016 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1017 I = ForwardRefVals.find(Name);
1018 if (I != ForwardRefVals.end())
1019 Val = I->second.first;
1022 // If we have the value in the symbol table or fwd-ref table, return it.
1024 if (Val->getType() == Ty) return Val;
1025 Error(Loc, "'@" + Name + "' defined with type '" +
1026 getTypeString(Val->getType()) + "'");
1030 // Otherwise, create a new forward reference for this value and remember it.
1031 GlobalValue *FwdVal;
1032 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1033 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1035 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1036 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1037 nullptr, GlobalVariable::NotThreadLocal,
1038 PTy->getAddressSpace());
1040 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1044 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1045 PointerType *PTy = dyn_cast<PointerType>(Ty);
1047 Error(Loc, "global variable reference must have pointer type");
1051 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1053 // If this is a forward reference for the value, see if we already created a
1054 // forward ref record.
1056 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1057 I = ForwardRefValIDs.find(ID);
1058 if (I != ForwardRefValIDs.end())
1059 Val = I->second.first;
1062 // If we have the value in the symbol table or fwd-ref table, return it.
1064 if (Val->getType() == Ty) return Val;
1065 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1066 getTypeString(Val->getType()) + "'");
1070 // Otherwise, create a new forward reference for this value and remember it.
1071 GlobalValue *FwdVal;
1072 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1073 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1075 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1076 GlobalValue::ExternalWeakLinkage, nullptr, "");
1078 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1083 //===----------------------------------------------------------------------===//
1084 // Comdat Reference/Resolution Routines.
1085 //===----------------------------------------------------------------------===//
1087 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1088 // Look this name up in the comdat symbol table.
1089 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1090 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1091 if (I != ComdatSymTab.end())
1094 // Otherwise, create a new forward reference for this value and remember it.
1095 Comdat *C = M->getOrInsertComdat(Name);
1096 ForwardRefComdats[Name] = Loc;
1101 //===----------------------------------------------------------------------===//
1103 //===----------------------------------------------------------------------===//
1105 /// ParseToken - If the current token has the specified kind, eat it and return
1106 /// success. Otherwise, emit the specified error and return failure.
1107 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1108 if (Lex.getKind() != T)
1109 return TokError(ErrMsg);
1114 /// ParseStringConstant
1115 /// ::= StringConstant
1116 bool LLParser::ParseStringConstant(std::string &Result) {
1117 if (Lex.getKind() != lltok::StringConstant)
1118 return TokError("expected string constant");
1119 Result = Lex.getStrVal();
1126 bool LLParser::ParseUInt32(unsigned &Val) {
1127 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1128 return TokError("expected integer");
1129 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1130 if (Val64 != unsigned(Val64))
1131 return TokError("expected 32-bit integer (too large)");
1139 bool LLParser::ParseUInt64(uint64_t &Val) {
1140 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1141 return TokError("expected integer");
1142 Val = Lex.getAPSIntVal().getLimitedValue();
1148 /// := 'localdynamic'
1149 /// := 'initialexec'
1151 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1152 switch (Lex.getKind()) {
1154 return TokError("expected localdynamic, initialexec or localexec");
1155 case lltok::kw_localdynamic:
1156 TLM = GlobalVariable::LocalDynamicTLSModel;
1158 case lltok::kw_initialexec:
1159 TLM = GlobalVariable::InitialExecTLSModel;
1161 case lltok::kw_localexec:
1162 TLM = GlobalVariable::LocalExecTLSModel;
1170 /// ParseOptionalThreadLocal
1172 /// := 'thread_local'
1173 /// := 'thread_local' '(' tlsmodel ')'
1174 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1175 TLM = GlobalVariable::NotThreadLocal;
1176 if (!EatIfPresent(lltok::kw_thread_local))
1179 TLM = GlobalVariable::GeneralDynamicTLSModel;
1180 if (Lex.getKind() == lltok::lparen) {
1182 return ParseTLSModel(TLM) ||
1183 ParseToken(lltok::rparen, "expected ')' after thread local model");
1188 /// ParseOptionalAddrSpace
1190 /// := 'addrspace' '(' uint32 ')'
1191 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1193 if (!EatIfPresent(lltok::kw_addrspace))
1195 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1196 ParseUInt32(AddrSpace) ||
1197 ParseToken(lltok::rparen, "expected ')' in address space");
1200 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1201 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1202 bool HaveError = false;
1207 lltok::Kind Token = Lex.getKind();
1209 default: // End of attributes.
1211 case lltok::kw_align: {
1213 if (ParseOptionalAlignment(Alignment))
1215 B.addAlignmentAttr(Alignment);
1218 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1219 case lltok::kw_dereferenceable: {
1221 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1223 B.addDereferenceableAttr(Bytes);
1226 case lltok::kw_dereferenceable_or_null: {
1228 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1230 B.addDereferenceableOrNullAttr(Bytes);
1233 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1234 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1235 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1236 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1237 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1238 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1239 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1240 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1241 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1242 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1243 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1244 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1246 case lltok::kw_alignstack:
1247 case lltok::kw_alwaysinline:
1248 case lltok::kw_builtin:
1249 case lltok::kw_inlinehint:
1250 case lltok::kw_jumptable:
1251 case lltok::kw_minsize:
1252 case lltok::kw_naked:
1253 case lltok::kw_nobuiltin:
1254 case lltok::kw_noduplicate:
1255 case lltok::kw_noimplicitfloat:
1256 case lltok::kw_noinline:
1257 case lltok::kw_nonlazybind:
1258 case lltok::kw_noredzone:
1259 case lltok::kw_noreturn:
1260 case lltok::kw_nounwind:
1261 case lltok::kw_optnone:
1262 case lltok::kw_optsize:
1263 case lltok::kw_returns_twice:
1264 case lltok::kw_sanitize_address:
1265 case lltok::kw_sanitize_memory:
1266 case lltok::kw_sanitize_thread:
1268 case lltok::kw_sspreq:
1269 case lltok::kw_sspstrong:
1270 case lltok::kw_uwtable:
1271 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1279 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1280 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1281 bool HaveError = false;
1286 lltok::Kind Token = Lex.getKind();
1288 default: // End of attributes.
1290 case lltok::kw_dereferenceable: {
1292 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
1294 B.addDereferenceableAttr(Bytes);
1297 case lltok::kw_dereferenceable_or_null: {
1299 if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
1301 B.addDereferenceableOrNullAttr(Bytes);
1304 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1305 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1306 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1307 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1308 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1311 case lltok::kw_align:
1312 case lltok::kw_byval:
1313 case lltok::kw_inalloca:
1314 case lltok::kw_nest:
1315 case lltok::kw_nocapture:
1316 case lltok::kw_returned:
1317 case lltok::kw_sret:
1318 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1321 case lltok::kw_alignstack:
1322 case lltok::kw_alwaysinline:
1323 case lltok::kw_builtin:
1324 case lltok::kw_cold:
1325 case lltok::kw_inlinehint:
1326 case lltok::kw_jumptable:
1327 case lltok::kw_minsize:
1328 case lltok::kw_naked:
1329 case lltok::kw_nobuiltin:
1330 case lltok::kw_noduplicate:
1331 case lltok::kw_noimplicitfloat:
1332 case lltok::kw_noinline:
1333 case lltok::kw_nonlazybind:
1334 case lltok::kw_noredzone:
1335 case lltok::kw_noreturn:
1336 case lltok::kw_nounwind:
1337 case lltok::kw_optnone:
1338 case lltok::kw_optsize:
1339 case lltok::kw_returns_twice:
1340 case lltok::kw_sanitize_address:
1341 case lltok::kw_sanitize_memory:
1342 case lltok::kw_sanitize_thread:
1344 case lltok::kw_sspreq:
1345 case lltok::kw_sspstrong:
1346 case lltok::kw_uwtable:
1347 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1350 case lltok::kw_readnone:
1351 case lltok::kw_readonly:
1352 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1359 /// ParseOptionalLinkage
1366 /// ::= 'linkonce_odr'
1367 /// ::= 'available_externally'
1370 /// ::= 'extern_weak'
1372 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1374 switch (Lex.getKind()) {
1375 default: Res=GlobalValue::ExternalLinkage; return false;
1376 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1377 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1378 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1379 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1380 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1381 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1382 case lltok::kw_available_externally:
1383 Res = GlobalValue::AvailableExternallyLinkage;
1385 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1386 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1387 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1388 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1395 /// ParseOptionalVisibility
1401 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1402 switch (Lex.getKind()) {
1403 default: Res = GlobalValue::DefaultVisibility; return false;
1404 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1405 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1406 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1412 /// ParseOptionalDLLStorageClass
1417 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1418 switch (Lex.getKind()) {
1419 default: Res = GlobalValue::DefaultStorageClass; return false;
1420 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1421 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1427 /// ParseOptionalCallingConv
1431 /// ::= 'intel_ocl_bicc'
1433 /// ::= 'x86_stdcallcc'
1434 /// ::= 'x86_fastcallcc'
1435 /// ::= 'x86_thiscallcc'
1436 /// ::= 'x86_vectorcallcc'
1437 /// ::= 'arm_apcscc'
1438 /// ::= 'arm_aapcscc'
1439 /// ::= 'arm_aapcs_vfpcc'
1440 /// ::= 'msp430_intrcc'
1441 /// ::= 'ptx_kernel'
1442 /// ::= 'ptx_device'
1444 /// ::= 'spir_kernel'
1445 /// ::= 'x86_64_sysvcc'
1446 /// ::= 'x86_64_win64cc'
1447 /// ::= 'webkit_jscc'
1449 /// ::= 'preserve_mostcc'
1450 /// ::= 'preserve_allcc'
1454 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1455 switch (Lex.getKind()) {
1456 default: CC = CallingConv::C; return false;
1457 case lltok::kw_ccc: CC = CallingConv::C; break;
1458 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1459 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1460 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1461 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1462 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1463 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1464 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1465 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1466 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1467 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1468 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1469 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1470 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1471 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1472 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1473 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1474 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1475 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1476 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1477 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1478 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1479 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1480 case lltok::kw_cc: {
1482 return ParseUInt32(CC);
1490 /// ParseMetadataAttachment
1492 bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
1493 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
1495 std::string Name = Lex.getStrVal();
1496 Kind = M->getMDKindID(Name);
1499 return ParseMDNode(MD);
1502 /// ParseInstructionMetadata
1503 /// ::= !dbg !42 (',' !dbg !57)*
1504 bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
1506 if (Lex.getKind() != lltok::MetadataVar)
1507 return TokError("expected metadata after comma");
1511 if (ParseMetadataAttachment(MDK, N))
1514 Inst.setMetadata(MDK, N);
1515 if (MDK == LLVMContext::MD_tbaa)
1516 InstsWithTBAATag.push_back(&Inst);
1518 // If this is the end of the list, we're done.
1519 } while (EatIfPresent(lltok::comma));
1523 /// ParseOptionalFunctionMetadata
1525 bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
1526 while (Lex.getKind() == lltok::MetadataVar) {
1529 if (ParseMetadataAttachment(MDK, N))
1532 F.setMetadata(MDK, N);
1537 /// ParseOptionalAlignment
1540 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1542 if (!EatIfPresent(lltok::kw_align))
1544 LocTy AlignLoc = Lex.getLoc();
1545 if (ParseUInt32(Alignment)) return true;
1546 if (!isPowerOf2_32(Alignment))
1547 return Error(AlignLoc, "alignment is not a power of two");
1548 if (Alignment > Value::MaximumAlignment)
1549 return Error(AlignLoc, "huge alignments are not supported yet");
1553 /// ParseOptionalDerefAttrBytes
1555 /// ::= AttrKind '(' 4 ')'
1557 /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
1558 bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
1560 assert((AttrKind == lltok::kw_dereferenceable ||
1561 AttrKind == lltok::kw_dereferenceable_or_null) &&
1565 if (!EatIfPresent(AttrKind))
1567 LocTy ParenLoc = Lex.getLoc();
1568 if (!EatIfPresent(lltok::lparen))
1569 return Error(ParenLoc, "expected '('");
1570 LocTy DerefLoc = Lex.getLoc();
1571 if (ParseUInt64(Bytes)) return true;
1572 ParenLoc = Lex.getLoc();
1573 if (!EatIfPresent(lltok::rparen))
1574 return Error(ParenLoc, "expected ')'");
1576 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1580 /// ParseOptionalCommaAlign
1584 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1586 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1587 bool &AteExtraComma) {
1588 AteExtraComma = false;
1589 while (EatIfPresent(lltok::comma)) {
1590 // Metadata at the end is an early exit.
1591 if (Lex.getKind() == lltok::MetadataVar) {
1592 AteExtraComma = true;
1596 if (Lex.getKind() != lltok::kw_align)
1597 return Error(Lex.getLoc(), "expected metadata or 'align'");
1599 if (ParseOptionalAlignment(Alignment)) return true;
1605 /// ParseScopeAndOrdering
1606 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1609 /// This sets Scope and Ordering to the parsed values.
1610 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1611 AtomicOrdering &Ordering) {
1615 Scope = CrossThread;
1616 if (EatIfPresent(lltok::kw_singlethread))
1617 Scope = SingleThread;
1619 return ParseOrdering(Ordering);
1623 /// ::= AtomicOrdering
1625 /// This sets Ordering to the parsed value.
1626 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1627 switch (Lex.getKind()) {
1628 default: return TokError("Expected ordering on atomic instruction");
1629 case lltok::kw_unordered: Ordering = Unordered; break;
1630 case lltok::kw_monotonic: Ordering = Monotonic; break;
1631 case lltok::kw_acquire: Ordering = Acquire; break;
1632 case lltok::kw_release: Ordering = Release; break;
1633 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1634 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1640 /// ParseOptionalStackAlignment
1642 /// ::= 'alignstack' '(' 4 ')'
1643 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1645 if (!EatIfPresent(lltok::kw_alignstack))
1647 LocTy ParenLoc = Lex.getLoc();
1648 if (!EatIfPresent(lltok::lparen))
1649 return Error(ParenLoc, "expected '('");
1650 LocTy AlignLoc = Lex.getLoc();
1651 if (ParseUInt32(Alignment)) return true;
1652 ParenLoc = Lex.getLoc();
1653 if (!EatIfPresent(lltok::rparen))
1654 return Error(ParenLoc, "expected ')'");
1655 if (!isPowerOf2_32(Alignment))
1656 return Error(AlignLoc, "stack alignment is not a power of two");
1660 /// ParseIndexList - This parses the index list for an insert/extractvalue
1661 /// instruction. This sets AteExtraComma in the case where we eat an extra
1662 /// comma at the end of the line and find that it is followed by metadata.
1663 /// Clients that don't allow metadata can call the version of this function that
1664 /// only takes one argument.
1667 /// ::= (',' uint32)+
1669 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1670 bool &AteExtraComma) {
1671 AteExtraComma = false;
1673 if (Lex.getKind() != lltok::comma)
1674 return TokError("expected ',' as start of index list");
1676 while (EatIfPresent(lltok::comma)) {
1677 if (Lex.getKind() == lltok::MetadataVar) {
1678 if (Indices.empty()) return TokError("expected index");
1679 AteExtraComma = true;
1683 if (ParseUInt32(Idx)) return true;
1684 Indices.push_back(Idx);
1690 //===----------------------------------------------------------------------===//
1692 //===----------------------------------------------------------------------===//
1694 /// ParseType - Parse a type.
1695 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1696 SMLoc TypeLoc = Lex.getLoc();
1697 switch (Lex.getKind()) {
1699 return TokError(Msg);
1701 // Type ::= 'float' | 'void' (etc)
1702 Result = Lex.getTyVal();
1706 // Type ::= StructType
1707 if (ParseAnonStructType(Result, false))
1710 case lltok::lsquare:
1711 // Type ::= '[' ... ']'
1712 Lex.Lex(); // eat the lsquare.
1713 if (ParseArrayVectorType(Result, false))
1716 case lltok::less: // Either vector or packed struct.
1717 // Type ::= '<' ... '>'
1719 if (Lex.getKind() == lltok::lbrace) {
1720 if (ParseAnonStructType(Result, true) ||
1721 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1723 } else if (ParseArrayVectorType(Result, true))
1726 case lltok::LocalVar: {
1728 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1730 // If the type hasn't been defined yet, create a forward definition and
1731 // remember where that forward def'n was seen (in case it never is defined).
1733 Entry.first = StructType::create(Context, Lex.getStrVal());
1734 Entry.second = Lex.getLoc();
1736 Result = Entry.first;
1741 case lltok::LocalVarID: {
1743 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1745 // If the type hasn't been defined yet, create a forward definition and
1746 // remember where that forward def'n was seen (in case it never is defined).
1748 Entry.first = StructType::create(Context);
1749 Entry.second = Lex.getLoc();
1751 Result = Entry.first;
1757 // Parse the type suffixes.
1759 switch (Lex.getKind()) {
1762 if (!AllowVoid && Result->isVoidTy())
1763 return Error(TypeLoc, "void type only allowed for function results");
1766 // Type ::= Type '*'
1768 if (Result->isLabelTy())
1769 return TokError("basic block pointers are invalid");
1770 if (Result->isVoidTy())
1771 return TokError("pointers to void are invalid - use i8* instead");
1772 if (!PointerType::isValidElementType(Result))
1773 return TokError("pointer to this type is invalid");
1774 Result = PointerType::getUnqual(Result);
1778 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1779 case lltok::kw_addrspace: {
1780 if (Result->isLabelTy())
1781 return TokError("basic block pointers are invalid");
1782 if (Result->isVoidTy())
1783 return TokError("pointers to void are invalid; use i8* instead");
1784 if (!PointerType::isValidElementType(Result))
1785 return TokError("pointer to this type is invalid");
1787 if (ParseOptionalAddrSpace(AddrSpace) ||
1788 ParseToken(lltok::star, "expected '*' in address space"))
1791 Result = PointerType::get(Result, AddrSpace);
1795 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1797 if (ParseFunctionType(Result))
1804 /// ParseParameterList
1806 /// ::= '(' Arg (',' Arg)* ')'
1808 /// ::= Type OptionalAttributes Value OptionalAttributes
1809 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1810 PerFunctionState &PFS, bool IsMustTailCall,
1811 bool InVarArgsFunc) {
1812 if (ParseToken(lltok::lparen, "expected '(' in call"))
1815 unsigned AttrIndex = 1;
1816 while (Lex.getKind() != lltok::rparen) {
1817 // If this isn't the first argument, we need a comma.
1818 if (!ArgList.empty() &&
1819 ParseToken(lltok::comma, "expected ',' in argument list"))
1822 // Parse an ellipsis if this is a musttail call in a variadic function.
1823 if (Lex.getKind() == lltok::dotdotdot) {
1824 const char *Msg = "unexpected ellipsis in argument list for ";
1825 if (!IsMustTailCall)
1826 return TokError(Twine(Msg) + "non-musttail call");
1828 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1829 Lex.Lex(); // Lex the '...', it is purely for readability.
1830 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1833 // Parse the argument.
1835 Type *ArgTy = nullptr;
1836 AttrBuilder ArgAttrs;
1838 if (ParseType(ArgTy, ArgLoc))
1841 if (ArgTy->isMetadataTy()) {
1842 if (ParseMetadataAsValue(V, PFS))
1845 // Otherwise, handle normal operands.
1846 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1849 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1854 if (IsMustTailCall && InVarArgsFunc)
1855 return TokError("expected '...' at end of argument list for musttail call "
1856 "in varargs function");
1858 Lex.Lex(); // Lex the ')'.
1864 /// ParseArgumentList - Parse the argument list for a function type or function
1866 /// ::= '(' ArgTypeListI ')'
1870 /// ::= ArgTypeList ',' '...'
1871 /// ::= ArgType (',' ArgType)*
1873 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1876 assert(Lex.getKind() == lltok::lparen);
1877 Lex.Lex(); // eat the (.
1879 if (Lex.getKind() == lltok::rparen) {
1881 } else if (Lex.getKind() == lltok::dotdotdot) {
1885 LocTy TypeLoc = Lex.getLoc();
1886 Type *ArgTy = nullptr;
1890 if (ParseType(ArgTy) ||
1891 ParseOptionalParamAttrs(Attrs)) return true;
1893 if (ArgTy->isVoidTy())
1894 return Error(TypeLoc, "argument can not have void type");
1896 if (Lex.getKind() == lltok::LocalVar) {
1897 Name = Lex.getStrVal();
1901 if (!FunctionType::isValidArgumentType(ArgTy))
1902 return Error(TypeLoc, "invalid type for function argument");
1904 unsigned AttrIndex = 1;
1905 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1906 AttributeSet::get(ArgTy->getContext(),
1907 AttrIndex++, Attrs), Name));
1909 while (EatIfPresent(lltok::comma)) {
1910 // Handle ... at end of arg list.
1911 if (EatIfPresent(lltok::dotdotdot)) {
1916 // Otherwise must be an argument type.
1917 TypeLoc = Lex.getLoc();
1918 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1920 if (ArgTy->isVoidTy())
1921 return Error(TypeLoc, "argument can not have void type");
1923 if (Lex.getKind() == lltok::LocalVar) {
1924 Name = Lex.getStrVal();
1930 if (!ArgTy->isFirstClassType())
1931 return Error(TypeLoc, "invalid type for function argument");
1933 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1934 AttributeSet::get(ArgTy->getContext(),
1935 AttrIndex++, Attrs),
1940 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1943 /// ParseFunctionType
1944 /// ::= Type ArgumentList OptionalAttrs
1945 bool LLParser::ParseFunctionType(Type *&Result) {
1946 assert(Lex.getKind() == lltok::lparen);
1948 if (!FunctionType::isValidReturnType(Result))
1949 return TokError("invalid function return type");
1951 SmallVector<ArgInfo, 8> ArgList;
1953 if (ParseArgumentList(ArgList, isVarArg))
1956 // Reject names on the arguments lists.
1957 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1958 if (!ArgList[i].Name.empty())
1959 return Error(ArgList[i].Loc, "argument name invalid in function type");
1960 if (ArgList[i].Attrs.hasAttributes(i + 1))
1961 return Error(ArgList[i].Loc,
1962 "argument attributes invalid in function type");
1965 SmallVector<Type*, 16> ArgListTy;
1966 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1967 ArgListTy.push_back(ArgList[i].Ty);
1969 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1973 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1975 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1976 SmallVector<Type*, 8> Elts;
1977 if (ParseStructBody(Elts)) return true;
1979 Result = StructType::get(Context, Elts, Packed);
1983 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1984 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1985 std::pair<Type*, LocTy> &Entry,
1987 // If the type was already defined, diagnose the redefinition.
1988 if (Entry.first && !Entry.second.isValid())
1989 return Error(TypeLoc, "redefinition of type");
1991 // If we have opaque, just return without filling in the definition for the
1992 // struct. This counts as a definition as far as the .ll file goes.
1993 if (EatIfPresent(lltok::kw_opaque)) {
1994 // This type is being defined, so clear the location to indicate this.
1995 Entry.second = SMLoc();
1997 // If this type number has never been uttered, create it.
1999 Entry.first = StructType::create(Context, Name);
2000 ResultTy = Entry.first;
2004 // If the type starts with '<', then it is either a packed struct or a vector.
2005 bool isPacked = EatIfPresent(lltok::less);
2007 // If we don't have a struct, then we have a random type alias, which we
2008 // accept for compatibility with old files. These types are not allowed to be
2009 // forward referenced and not allowed to be recursive.
2010 if (Lex.getKind() != lltok::lbrace) {
2012 return Error(TypeLoc, "forward references to non-struct type");
2016 return ParseArrayVectorType(ResultTy, true);
2017 return ParseType(ResultTy);
2020 // This type is being defined, so clear the location to indicate this.
2021 Entry.second = SMLoc();
2023 // If this type number has never been uttered, create it.
2025 Entry.first = StructType::create(Context, Name);
2027 StructType *STy = cast<StructType>(Entry.first);
2029 SmallVector<Type*, 8> Body;
2030 if (ParseStructBody(Body) ||
2031 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2034 STy->setBody(Body, isPacked);
2040 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2043 /// ::= '{' Type (',' Type)* '}'
2044 /// ::= '<' '{' '}' '>'
2045 /// ::= '<' '{' Type (',' Type)* '}' '>'
2046 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2047 assert(Lex.getKind() == lltok::lbrace);
2048 Lex.Lex(); // Consume the '{'
2050 // Handle the empty struct.
2051 if (EatIfPresent(lltok::rbrace))
2054 LocTy EltTyLoc = Lex.getLoc();
2056 if (ParseType(Ty)) return true;
2059 if (!StructType::isValidElementType(Ty))
2060 return Error(EltTyLoc, "invalid element type for struct");
2062 while (EatIfPresent(lltok::comma)) {
2063 EltTyLoc = Lex.getLoc();
2064 if (ParseType(Ty)) return true;
2066 if (!StructType::isValidElementType(Ty))
2067 return Error(EltTyLoc, "invalid element type for struct");
2072 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2075 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2076 /// token has already been consumed.
2078 /// ::= '[' APSINTVAL 'x' Types ']'
2079 /// ::= '<' APSINTVAL 'x' Types '>'
2080 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2081 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2082 Lex.getAPSIntVal().getBitWidth() > 64)
2083 return TokError("expected number in address space");
2085 LocTy SizeLoc = Lex.getLoc();
2086 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2089 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2092 LocTy TypeLoc = Lex.getLoc();
2093 Type *EltTy = nullptr;
2094 if (ParseType(EltTy)) return true;
2096 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2097 "expected end of sequential type"))
2102 return Error(SizeLoc, "zero element vector is illegal");
2103 if ((unsigned)Size != Size)
2104 return Error(SizeLoc, "size too large for vector");
2105 if (!VectorType::isValidElementType(EltTy))
2106 return Error(TypeLoc, "invalid vector element type");
2107 Result = VectorType::get(EltTy, unsigned(Size));
2109 if (!ArrayType::isValidElementType(EltTy))
2110 return Error(TypeLoc, "invalid array element type");
2111 Result = ArrayType::get(EltTy, Size);
2116 //===----------------------------------------------------------------------===//
2117 // Function Semantic Analysis.
2118 //===----------------------------------------------------------------------===//
2120 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2122 : P(p), F(f), FunctionNumber(functionNumber) {
2124 // Insert unnamed arguments into the NumberedVals list.
2125 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2128 NumberedVals.push_back(AI);
2131 LLParser::PerFunctionState::~PerFunctionState() {
2132 // If there were any forward referenced non-basicblock values, delete them.
2133 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2134 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2135 if (!isa<BasicBlock>(I->second.first)) {
2136 I->second.first->replaceAllUsesWith(
2137 UndefValue::get(I->second.first->getType()));
2138 delete I->second.first;
2139 I->second.first = nullptr;
2142 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2143 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2144 if (!isa<BasicBlock>(I->second.first)) {
2145 I->second.first->replaceAllUsesWith(
2146 UndefValue::get(I->second.first->getType()));
2147 delete I->second.first;
2148 I->second.first = nullptr;
2152 bool LLParser::PerFunctionState::FinishFunction() {
2153 if (!ForwardRefVals.empty())
2154 return P.Error(ForwardRefVals.begin()->second.second,
2155 "use of undefined value '%" + ForwardRefVals.begin()->first +
2157 if (!ForwardRefValIDs.empty())
2158 return P.Error(ForwardRefValIDs.begin()->second.second,
2159 "use of undefined value '%" +
2160 Twine(ForwardRefValIDs.begin()->first) + "'");
2165 /// GetVal - Get a value with the specified name or ID, creating a
2166 /// forward reference record if needed. This can return null if the value
2167 /// exists but does not have the right type.
2168 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2169 Type *Ty, LocTy Loc) {
2170 // Look this name up in the normal function symbol table.
2171 Value *Val = F.getValueSymbolTable().lookup(Name);
2173 // If this is a forward reference for the value, see if we already created a
2174 // forward ref record.
2176 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2177 I = ForwardRefVals.find(Name);
2178 if (I != ForwardRefVals.end())
2179 Val = I->second.first;
2182 // If we have the value in the symbol table or fwd-ref table, return it.
2184 if (Val->getType() == Ty) return Val;
2185 if (Ty->isLabelTy())
2186 P.Error(Loc, "'%" + Name + "' is not a basic block");
2188 P.Error(Loc, "'%" + Name + "' defined with type '" +
2189 getTypeString(Val->getType()) + "'");
2193 // Don't make placeholders with invalid type.
2194 if (!Ty->isFirstClassType()) {
2195 P.Error(Loc, "invalid use of a non-first-class type");
2199 // Otherwise, create a new forward reference for this value and remember it.
2201 if (Ty->isLabelTy())
2202 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2204 FwdVal = new Argument(Ty, Name);
2206 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2210 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2212 // Look this name up in the normal function symbol table.
2213 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2215 // If this is a forward reference for the value, see if we already created a
2216 // forward ref record.
2218 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2219 I = ForwardRefValIDs.find(ID);
2220 if (I != ForwardRefValIDs.end())
2221 Val = I->second.first;
2224 // If we have the value in the symbol table or fwd-ref table, return it.
2226 if (Val->getType() == Ty) return Val;
2227 if (Ty->isLabelTy())
2228 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2230 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2231 getTypeString(Val->getType()) + "'");
2235 if (!Ty->isFirstClassType()) {
2236 P.Error(Loc, "invalid use of a non-first-class type");
2240 // Otherwise, create a new forward reference for this value and remember it.
2242 if (Ty->isLabelTy())
2243 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2245 FwdVal = new Argument(Ty);
2247 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2251 /// SetInstName - After an instruction is parsed and inserted into its
2252 /// basic block, this installs its name.
2253 bool LLParser::PerFunctionState::SetInstName(int NameID,
2254 const std::string &NameStr,
2255 LocTy NameLoc, Instruction *Inst) {
2256 // If this instruction has void type, it cannot have a name or ID specified.
2257 if (Inst->getType()->isVoidTy()) {
2258 if (NameID != -1 || !NameStr.empty())
2259 return P.Error(NameLoc, "instructions returning void cannot have a name");
2263 // If this was a numbered instruction, verify that the instruction is the
2264 // expected value and resolve any forward references.
2265 if (NameStr.empty()) {
2266 // If neither a name nor an ID was specified, just use the next ID.
2268 NameID = NumberedVals.size();
2270 if (unsigned(NameID) != NumberedVals.size())
2271 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2272 Twine(NumberedVals.size()) + "'");
2274 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2275 ForwardRefValIDs.find(NameID);
2276 if (FI != ForwardRefValIDs.end()) {
2277 if (FI->second.first->getType() != Inst->getType())
2278 return P.Error(NameLoc, "instruction forward referenced with type '" +
2279 getTypeString(FI->second.first->getType()) + "'");
2280 FI->second.first->replaceAllUsesWith(Inst);
2281 delete FI->second.first;
2282 ForwardRefValIDs.erase(FI);
2285 NumberedVals.push_back(Inst);
2289 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2290 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2291 FI = ForwardRefVals.find(NameStr);
2292 if (FI != ForwardRefVals.end()) {
2293 if (FI->second.first->getType() != Inst->getType())
2294 return P.Error(NameLoc, "instruction forward referenced with type '" +
2295 getTypeString(FI->second.first->getType()) + "'");
2296 FI->second.first->replaceAllUsesWith(Inst);
2297 delete FI->second.first;
2298 ForwardRefVals.erase(FI);
2301 // Set the name on the instruction.
2302 Inst->setName(NameStr);
2304 if (Inst->getName() != NameStr)
2305 return P.Error(NameLoc, "multiple definition of local value named '" +
2310 /// GetBB - Get a basic block with the specified name or ID, creating a
2311 /// forward reference record if needed.
2312 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2314 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2315 Type::getLabelTy(F.getContext()), Loc));
2318 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2319 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2320 Type::getLabelTy(F.getContext()), Loc));
2323 /// DefineBB - Define the specified basic block, which is either named or
2324 /// unnamed. If there is an error, this returns null otherwise it returns
2325 /// the block being defined.
2326 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2330 BB = GetBB(NumberedVals.size(), Loc);
2332 BB = GetBB(Name, Loc);
2333 if (!BB) return nullptr; // Already diagnosed error.
2335 // Move the block to the end of the function. Forward ref'd blocks are
2336 // inserted wherever they happen to be referenced.
2337 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2339 // Remove the block from forward ref sets.
2341 ForwardRefValIDs.erase(NumberedVals.size());
2342 NumberedVals.push_back(BB);
2344 // BB forward references are already in the function symbol table.
2345 ForwardRefVals.erase(Name);
2351 //===----------------------------------------------------------------------===//
2353 //===----------------------------------------------------------------------===//
2355 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2356 /// type implied. For example, if we parse "4" we don't know what integer type
2357 /// it has. The value will later be combined with its type and checked for
2358 /// sanity. PFS is used to convert function-local operands of metadata (since
2359 /// metadata operands are not just parsed here but also converted to values).
2360 /// PFS can be null when we are not parsing metadata values inside a function.
2361 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2362 ID.Loc = Lex.getLoc();
2363 switch (Lex.getKind()) {
2364 default: return TokError("expected value token");
2365 case lltok::GlobalID: // @42
2366 ID.UIntVal = Lex.getUIntVal();
2367 ID.Kind = ValID::t_GlobalID;
2369 case lltok::GlobalVar: // @foo
2370 ID.StrVal = Lex.getStrVal();
2371 ID.Kind = ValID::t_GlobalName;
2373 case lltok::LocalVarID: // %42
2374 ID.UIntVal = Lex.getUIntVal();
2375 ID.Kind = ValID::t_LocalID;
2377 case lltok::LocalVar: // %foo
2378 ID.StrVal = Lex.getStrVal();
2379 ID.Kind = ValID::t_LocalName;
2382 ID.APSIntVal = Lex.getAPSIntVal();
2383 ID.Kind = ValID::t_APSInt;
2385 case lltok::APFloat:
2386 ID.APFloatVal = Lex.getAPFloatVal();
2387 ID.Kind = ValID::t_APFloat;
2389 case lltok::kw_true:
2390 ID.ConstantVal = ConstantInt::getTrue(Context);
2391 ID.Kind = ValID::t_Constant;
2393 case lltok::kw_false:
2394 ID.ConstantVal = ConstantInt::getFalse(Context);
2395 ID.Kind = ValID::t_Constant;
2397 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2398 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2399 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2401 case lltok::lbrace: {
2402 // ValID ::= '{' ConstVector '}'
2404 SmallVector<Constant*, 16> Elts;
2405 if (ParseGlobalValueVector(Elts) ||
2406 ParseToken(lltok::rbrace, "expected end of struct constant"))
2409 ID.ConstantStructElts = new Constant*[Elts.size()];
2410 ID.UIntVal = Elts.size();
2411 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2412 ID.Kind = ValID::t_ConstantStruct;
2416 // ValID ::= '<' ConstVector '>' --> Vector.
2417 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2419 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2421 SmallVector<Constant*, 16> Elts;
2422 LocTy FirstEltLoc = Lex.getLoc();
2423 if (ParseGlobalValueVector(Elts) ||
2425 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2426 ParseToken(lltok::greater, "expected end of constant"))
2429 if (isPackedStruct) {
2430 ID.ConstantStructElts = new Constant*[Elts.size()];
2431 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2432 ID.UIntVal = Elts.size();
2433 ID.Kind = ValID::t_PackedConstantStruct;
2438 return Error(ID.Loc, "constant vector must not be empty");
2440 if (!Elts[0]->getType()->isIntegerTy() &&
2441 !Elts[0]->getType()->isFloatingPointTy() &&
2442 !Elts[0]->getType()->isPointerTy())
2443 return Error(FirstEltLoc,
2444 "vector elements must have integer, pointer or floating point type");
2446 // Verify that all the vector elements have the same type.
2447 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2448 if (Elts[i]->getType() != Elts[0]->getType())
2449 return Error(FirstEltLoc,
2450 "vector element #" + Twine(i) +
2451 " is not of type '" + getTypeString(Elts[0]->getType()));
2453 ID.ConstantVal = ConstantVector::get(Elts);
2454 ID.Kind = ValID::t_Constant;
2457 case lltok::lsquare: { // Array Constant
2459 SmallVector<Constant*, 16> Elts;
2460 LocTy FirstEltLoc = Lex.getLoc();
2461 if (ParseGlobalValueVector(Elts) ||
2462 ParseToken(lltok::rsquare, "expected end of array constant"))
2465 // Handle empty element.
2467 // Use undef instead of an array because it's inconvenient to determine
2468 // the element type at this point, there being no elements to examine.
2469 ID.Kind = ValID::t_EmptyArray;
2473 if (!Elts[0]->getType()->isFirstClassType())
2474 return Error(FirstEltLoc, "invalid array element type: " +
2475 getTypeString(Elts[0]->getType()));
2477 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2479 // Verify all elements are correct type!
2480 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2481 if (Elts[i]->getType() != Elts[0]->getType())
2482 return Error(FirstEltLoc,
2483 "array element #" + Twine(i) +
2484 " is not of type '" + getTypeString(Elts[0]->getType()));
2487 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2488 ID.Kind = ValID::t_Constant;
2491 case lltok::kw_c: // c "foo"
2493 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2495 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2496 ID.Kind = ValID::t_Constant;
2499 case lltok::kw_asm: {
2500 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2502 bool HasSideEffect, AlignStack, AsmDialect;
2504 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2505 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2506 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2507 ParseStringConstant(ID.StrVal) ||
2508 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2509 ParseToken(lltok::StringConstant, "expected constraint string"))
2511 ID.StrVal2 = Lex.getStrVal();
2512 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2513 (unsigned(AsmDialect)<<2);
2514 ID.Kind = ValID::t_InlineAsm;
2518 case lltok::kw_blockaddress: {
2519 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2524 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2526 ParseToken(lltok::comma, "expected comma in block address expression")||
2527 ParseValID(Label) ||
2528 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2531 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2532 return Error(Fn.Loc, "expected function name in blockaddress");
2533 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2534 return Error(Label.Loc, "expected basic block name in blockaddress");
2536 // Try to find the function (but skip it if it's forward-referenced).
2537 GlobalValue *GV = nullptr;
2538 if (Fn.Kind == ValID::t_GlobalID) {
2539 if (Fn.UIntVal < NumberedVals.size())
2540 GV = NumberedVals[Fn.UIntVal];
2541 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2542 GV = M->getNamedValue(Fn.StrVal);
2544 Function *F = nullptr;
2546 // Confirm that it's actually a function with a definition.
2547 if (!isa<Function>(GV))
2548 return Error(Fn.Loc, "expected function name in blockaddress");
2549 F = cast<Function>(GV);
2550 if (F->isDeclaration())
2551 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2555 // Make a global variable as a placeholder for this reference.
2556 GlobalValue *&FwdRef =
2557 ForwardRefBlockAddresses.insert(std::make_pair(
2559 std::map<ValID, GlobalValue *>()))
2560 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2563 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2564 GlobalValue::InternalLinkage, nullptr, "");
2565 ID.ConstantVal = FwdRef;
2566 ID.Kind = ValID::t_Constant;
2570 // We found the function; now find the basic block. Don't use PFS, since we
2571 // might be inside a constant expression.
2573 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2574 if (Label.Kind == ValID::t_LocalID)
2575 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2577 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2579 return Error(Label.Loc, "referenced value is not a basic block");
2581 if (Label.Kind == ValID::t_LocalID)
2582 return Error(Label.Loc, "cannot take address of numeric label after "
2583 "the function is defined");
2584 BB = dyn_cast_or_null<BasicBlock>(
2585 F->getValueSymbolTable().lookup(Label.StrVal));
2587 return Error(Label.Loc, "referenced value is not a basic block");
2590 ID.ConstantVal = BlockAddress::get(F, BB);
2591 ID.Kind = ValID::t_Constant;
2595 case lltok::kw_trunc:
2596 case lltok::kw_zext:
2597 case lltok::kw_sext:
2598 case lltok::kw_fptrunc:
2599 case lltok::kw_fpext:
2600 case lltok::kw_bitcast:
2601 case lltok::kw_addrspacecast:
2602 case lltok::kw_uitofp:
2603 case lltok::kw_sitofp:
2604 case lltok::kw_fptoui:
2605 case lltok::kw_fptosi:
2606 case lltok::kw_inttoptr:
2607 case lltok::kw_ptrtoint: {
2608 unsigned Opc = Lex.getUIntVal();
2609 Type *DestTy = nullptr;
2612 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2613 ParseGlobalTypeAndValue(SrcVal) ||
2614 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2615 ParseType(DestTy) ||
2616 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2618 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2619 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2620 getTypeString(SrcVal->getType()) + "' to '" +
2621 getTypeString(DestTy) + "'");
2622 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2624 ID.Kind = ValID::t_Constant;
2627 case lltok::kw_extractvalue: {
2630 SmallVector<unsigned, 4> Indices;
2631 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2632 ParseGlobalTypeAndValue(Val) ||
2633 ParseIndexList(Indices) ||
2634 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2637 if (!Val->getType()->isAggregateType())
2638 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2639 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2640 return Error(ID.Loc, "invalid indices for extractvalue");
2641 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2642 ID.Kind = ValID::t_Constant;
2645 case lltok::kw_insertvalue: {
2647 Constant *Val0, *Val1;
2648 SmallVector<unsigned, 4> Indices;
2649 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2650 ParseGlobalTypeAndValue(Val0) ||
2651 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2652 ParseGlobalTypeAndValue(Val1) ||
2653 ParseIndexList(Indices) ||
2654 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2656 if (!Val0->getType()->isAggregateType())
2657 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2659 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2661 return Error(ID.Loc, "invalid indices for insertvalue");
2662 if (IndexedType != Val1->getType())
2663 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2664 getTypeString(Val1->getType()) +
2665 "' instead of '" + getTypeString(IndexedType) +
2667 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2668 ID.Kind = ValID::t_Constant;
2671 case lltok::kw_icmp:
2672 case lltok::kw_fcmp: {
2673 unsigned PredVal, Opc = Lex.getUIntVal();
2674 Constant *Val0, *Val1;
2676 if (ParseCmpPredicate(PredVal, Opc) ||
2677 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2678 ParseGlobalTypeAndValue(Val0) ||
2679 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2680 ParseGlobalTypeAndValue(Val1) ||
2681 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2684 if (Val0->getType() != Val1->getType())
2685 return Error(ID.Loc, "compare operands must have the same type");
2687 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2689 if (Opc == Instruction::FCmp) {
2690 if (!Val0->getType()->isFPOrFPVectorTy())
2691 return Error(ID.Loc, "fcmp requires floating point operands");
2692 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2694 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2695 if (!Val0->getType()->isIntOrIntVectorTy() &&
2696 !Val0->getType()->getScalarType()->isPointerTy())
2697 return Error(ID.Loc, "icmp requires pointer or integer operands");
2698 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2700 ID.Kind = ValID::t_Constant;
2704 // Binary Operators.
2706 case lltok::kw_fadd:
2708 case lltok::kw_fsub:
2710 case lltok::kw_fmul:
2711 case lltok::kw_udiv:
2712 case lltok::kw_sdiv:
2713 case lltok::kw_fdiv:
2714 case lltok::kw_urem:
2715 case lltok::kw_srem:
2716 case lltok::kw_frem:
2718 case lltok::kw_lshr:
2719 case lltok::kw_ashr: {
2723 unsigned Opc = Lex.getUIntVal();
2724 Constant *Val0, *Val1;
2726 LocTy ModifierLoc = Lex.getLoc();
2727 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2728 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2729 if (EatIfPresent(lltok::kw_nuw))
2731 if (EatIfPresent(lltok::kw_nsw)) {
2733 if (EatIfPresent(lltok::kw_nuw))
2736 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2737 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2738 if (EatIfPresent(lltok::kw_exact))
2741 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2742 ParseGlobalTypeAndValue(Val0) ||
2743 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2744 ParseGlobalTypeAndValue(Val1) ||
2745 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2747 if (Val0->getType() != Val1->getType())
2748 return Error(ID.Loc, "operands of constexpr must have same type");
2749 if (!Val0->getType()->isIntOrIntVectorTy()) {
2751 return Error(ModifierLoc, "nuw only applies to integer operations");
2753 return Error(ModifierLoc, "nsw only applies to integer operations");
2755 // Check that the type is valid for the operator.
2757 case Instruction::Add:
2758 case Instruction::Sub:
2759 case Instruction::Mul:
2760 case Instruction::UDiv:
2761 case Instruction::SDiv:
2762 case Instruction::URem:
2763 case Instruction::SRem:
2764 case Instruction::Shl:
2765 case Instruction::AShr:
2766 case Instruction::LShr:
2767 if (!Val0->getType()->isIntOrIntVectorTy())
2768 return Error(ID.Loc, "constexpr requires integer operands");
2770 case Instruction::FAdd:
2771 case Instruction::FSub:
2772 case Instruction::FMul:
2773 case Instruction::FDiv:
2774 case Instruction::FRem:
2775 if (!Val0->getType()->isFPOrFPVectorTy())
2776 return Error(ID.Loc, "constexpr requires fp operands");
2778 default: llvm_unreachable("Unknown binary operator!");
2781 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2782 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2783 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2784 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2786 ID.Kind = ValID::t_Constant;
2790 // Logical Operations
2793 case lltok::kw_xor: {
2794 unsigned Opc = Lex.getUIntVal();
2795 Constant *Val0, *Val1;
2797 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2798 ParseGlobalTypeAndValue(Val0) ||
2799 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2800 ParseGlobalTypeAndValue(Val1) ||
2801 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2803 if (Val0->getType() != Val1->getType())
2804 return Error(ID.Loc, "operands of constexpr must have same type");
2805 if (!Val0->getType()->isIntOrIntVectorTy())
2806 return Error(ID.Loc,
2807 "constexpr requires integer or integer vector operands");
2808 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2809 ID.Kind = ValID::t_Constant;
2813 case lltok::kw_getelementptr:
2814 case lltok::kw_shufflevector:
2815 case lltok::kw_insertelement:
2816 case lltok::kw_extractelement:
2817 case lltok::kw_select: {
2818 unsigned Opc = Lex.getUIntVal();
2819 SmallVector<Constant*, 16> Elts;
2820 bool InBounds = false;
2824 if (Opc == Instruction::GetElementPtr)
2825 InBounds = EatIfPresent(lltok::kw_inbounds);
2827 if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
2830 LocTy ExplicitTypeLoc = Lex.getLoc();
2831 if (Opc == Instruction::GetElementPtr) {
2832 if (ParseType(Ty) ||
2833 ParseToken(lltok::comma, "expected comma after getelementptr's type"))
2837 if (ParseGlobalValueVector(Elts) ||
2838 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2841 if (Opc == Instruction::GetElementPtr) {
2842 if (Elts.size() == 0 ||
2843 !Elts[0]->getType()->getScalarType()->isPointerTy())
2844 return Error(ID.Loc, "base of getelementptr must be a pointer");
2846 Type *BaseType = Elts[0]->getType();
2847 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
2848 if (Ty != BasePointerType->getElementType())
2851 "explicit pointee type doesn't match operand's pointee type");
2853 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2854 for (Constant *Val : Indices) {
2855 Type *ValTy = Val->getType();
2856 if (!ValTy->getScalarType()->isIntegerTy())
2857 return Error(ID.Loc, "getelementptr index must be an integer");
2858 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2859 return Error(ID.Loc, "getelementptr index type missmatch");
2860 if (ValTy->isVectorTy()) {
2861 unsigned ValNumEl = cast<VectorType>(ValTy)->getNumElements();
2862 unsigned PtrNumEl = cast<VectorType>(BaseType)->getNumElements();
2863 if (ValNumEl != PtrNumEl)
2866 "getelementptr vector index has a wrong number of elements");
2870 SmallPtrSet<const Type*, 4> Visited;
2871 if (!Indices.empty() && !Ty->isSized(&Visited))
2872 return Error(ID.Loc, "base element of getelementptr must be sized");
2874 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
2875 return Error(ID.Loc, "invalid getelementptr indices");
2877 ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
2878 } else if (Opc == Instruction::Select) {
2879 if (Elts.size() != 3)
2880 return Error(ID.Loc, "expected three operands to select");
2881 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2883 return Error(ID.Loc, Reason);
2884 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2885 } else if (Opc == Instruction::ShuffleVector) {
2886 if (Elts.size() != 3)
2887 return Error(ID.Loc, "expected three operands to shufflevector");
2888 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2889 return Error(ID.Loc, "invalid operands to shufflevector");
2891 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2892 } else if (Opc == Instruction::ExtractElement) {
2893 if (Elts.size() != 2)
2894 return Error(ID.Loc, "expected two operands to extractelement");
2895 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2896 return Error(ID.Loc, "invalid extractelement operands");
2897 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2899 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2900 if (Elts.size() != 3)
2901 return Error(ID.Loc, "expected three operands to insertelement");
2902 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2903 return Error(ID.Loc, "invalid insertelement operands");
2905 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2908 ID.Kind = ValID::t_Constant;
2917 /// ParseGlobalValue - Parse a global value with the specified type.
2918 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2922 bool Parsed = ParseValID(ID) ||
2923 ConvertValIDToValue(Ty, ID, V, nullptr);
2924 if (V && !(C = dyn_cast<Constant>(V)))
2925 return Error(ID.Loc, "global values must be constants");
2929 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2931 return ParseType(Ty) ||
2932 ParseGlobalValue(Ty, V);
2935 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2938 LocTy KwLoc = Lex.getLoc();
2939 if (!EatIfPresent(lltok::kw_comdat))
2942 if (EatIfPresent(lltok::lparen)) {
2943 if (Lex.getKind() != lltok::ComdatVar)
2944 return TokError("expected comdat variable");
2945 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2947 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2950 if (GlobalName.empty())
2951 return TokError("comdat cannot be unnamed");
2952 C = getComdat(GlobalName, KwLoc);
2958 /// ParseGlobalValueVector
2960 /// ::= TypeAndValue (',' TypeAndValue)*
2961 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2963 if (Lex.getKind() == lltok::rbrace ||
2964 Lex.getKind() == lltok::rsquare ||
2965 Lex.getKind() == lltok::greater ||
2966 Lex.getKind() == lltok::rparen)
2970 if (ParseGlobalTypeAndValue(C)) return true;
2973 while (EatIfPresent(lltok::comma)) {
2974 if (ParseGlobalTypeAndValue(C)) return true;
2981 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
2982 SmallVector<Metadata *, 16> Elts;
2983 if (ParseMDNodeVector(Elts))
2986 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
2993 /// ::= !DILocation(...)
2994 bool LLParser::ParseMDNode(MDNode *&N) {
2995 if (Lex.getKind() == lltok::MetadataVar)
2996 return ParseSpecializedMDNode(N);
2998 return ParseToken(lltok::exclaim, "expected '!' here") ||
3002 bool LLParser::ParseMDNodeTail(MDNode *&N) {
3004 if (Lex.getKind() == lltok::lbrace)
3005 return ParseMDTuple(N);
3008 return ParseMDNodeID(N);
3013 /// Structure to represent an optional metadata field.
3014 template <class FieldTy> struct MDFieldImpl {
3015 typedef MDFieldImpl ImplTy;
3019 void assign(FieldTy Val) {
3021 this->Val = std::move(Val);
3024 explicit MDFieldImpl(FieldTy Default)
3025 : Val(std::move(Default)), Seen(false) {}
3028 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
3031 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
3032 : ImplTy(Default), Max(Max) {}
3034 struct LineField : public MDUnsignedField {
3035 LineField() : MDUnsignedField(0, UINT32_MAX) {}
3037 struct ColumnField : public MDUnsignedField {
3038 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
3040 struct DwarfTagField : public MDUnsignedField {
3041 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
3042 DwarfTagField(dwarf::Tag DefaultTag)
3043 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
3045 struct DwarfAttEncodingField : public MDUnsignedField {
3046 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
3048 struct DwarfVirtualityField : public MDUnsignedField {
3049 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
3051 struct DwarfLangField : public MDUnsignedField {
3052 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
3055 struct DIFlagField : public MDUnsignedField {
3056 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3059 struct MDSignedField : public MDFieldImpl<int64_t> {
3063 MDSignedField(int64_t Default = 0)
3064 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3065 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3066 : ImplTy(Default), Min(Min), Max(Max) {}
3069 struct MDBoolField : public MDFieldImpl<bool> {
3070 MDBoolField(bool Default = false) : ImplTy(Default) {}
3072 struct MDField : public MDFieldImpl<Metadata *> {
3075 MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
3077 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3078 MDConstant() : ImplTy(nullptr) {}
3080 struct MDStringField : public MDFieldImpl<MDString *> {
3082 MDStringField(bool AllowEmpty = true)
3083 : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
3085 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3086 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3094 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3095 MDUnsignedField &Result) {
3096 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3097 return TokError("expected unsigned integer");
3099 auto &U = Lex.getAPSIntVal();
3100 if (U.ugt(Result.Max))
3101 return TokError("value for '" + Name + "' too large, limit is " +
3103 Result.assign(U.getZExtValue());
3104 assert(Result.Val <= Result.Max && "Expected value in range");
3110 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3111 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3114 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3115 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3119 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3120 if (Lex.getKind() == lltok::APSInt)
3121 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3123 if (Lex.getKind() != lltok::DwarfTag)
3124 return TokError("expected DWARF tag");
3126 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3127 if (Tag == dwarf::DW_TAG_invalid)
3128 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3129 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3137 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3138 DwarfVirtualityField &Result) {
3139 if (Lex.getKind() == lltok::APSInt)
3140 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3142 if (Lex.getKind() != lltok::DwarfVirtuality)
3143 return TokError("expected DWARF virtuality code");
3145 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3147 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3148 Lex.getStrVal() + "'");
3149 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3150 Result.assign(Virtuality);
3156 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3157 if (Lex.getKind() == lltok::APSInt)
3158 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3160 if (Lex.getKind() != lltok::DwarfLang)
3161 return TokError("expected DWARF language");
3163 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3165 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3167 assert(Lang <= Result.Max && "Expected valid DWARF language");
3168 Result.assign(Lang);
3174 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3175 DwarfAttEncodingField &Result) {
3176 if (Lex.getKind() == lltok::APSInt)
3177 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3179 if (Lex.getKind() != lltok::DwarfAttEncoding)
3180 return TokError("expected DWARF type attribute encoding");
3182 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3184 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3185 Lex.getStrVal() + "'");
3186 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3187 Result.assign(Encoding);
3194 /// ::= DIFlagVector
3195 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3197 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3198 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3200 // Parser for a single flag.
3201 auto parseFlag = [&](unsigned &Val) {
3202 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3203 return ParseUInt32(Val);
3205 if (Lex.getKind() != lltok::DIFlag)
3206 return TokError("expected debug info flag");
3208 Val = DINode::getFlag(Lex.getStrVal());
3210 return TokError(Twine("invalid debug info flag flag '") +
3211 Lex.getStrVal() + "'");
3216 // Parse the flags and combine them together.
3217 unsigned Combined = 0;
3223 } while (EatIfPresent(lltok::bar));
3225 Result.assign(Combined);
3230 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3231 MDSignedField &Result) {
3232 if (Lex.getKind() != lltok::APSInt)
3233 return TokError("expected signed integer");
3235 auto &S = Lex.getAPSIntVal();
3237 return TokError("value for '" + Name + "' too small, limit is " +
3240 return TokError("value for '" + Name + "' too large, limit is " +
3242 Result.assign(S.getExtValue());
3243 assert(Result.Val >= Result.Min && "Expected value in range");
3244 assert(Result.Val <= Result.Max && "Expected value in range");
3250 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3251 switch (Lex.getKind()) {
3253 return TokError("expected 'true' or 'false'");
3254 case lltok::kw_true:
3255 Result.assign(true);
3257 case lltok::kw_false:
3258 Result.assign(false);
3266 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3267 if (Lex.getKind() == lltok::kw_null) {
3268 if (!Result.AllowNull)
3269 return TokError("'" + Name + "' cannot be null");
3271 Result.assign(nullptr);
3276 if (ParseMetadata(MD, nullptr))
3284 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3286 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3289 Result.assign(cast<ConstantAsMetadata>(MD));
3294 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3295 LocTy ValueLoc = Lex.getLoc();
3297 if (ParseStringConstant(S))
3300 if (!Result.AllowEmpty && S.empty())
3301 return Error(ValueLoc, "'" + Name + "' cannot be empty");
3303 Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
3308 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3309 SmallVector<Metadata *, 4> MDs;
3310 if (ParseMDNodeVector(MDs))
3313 Result.assign(std::move(MDs));
3317 } // end namespace llvm
3319 template <class ParserTy>
3320 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3322 if (Lex.getKind() != lltok::LabelStr)
3323 return TokError("expected field label here");
3327 } while (EatIfPresent(lltok::comma));
3332 template <class ParserTy>
3333 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3334 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3337 if (ParseToken(lltok::lparen, "expected '(' here"))
3339 if (Lex.getKind() != lltok::rparen)
3340 if (ParseMDFieldsImplBody(parseField))
3343 ClosingLoc = Lex.getLoc();
3344 return ParseToken(lltok::rparen, "expected ')' here");
3347 template <class FieldTy>
3348 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3350 return TokError("field '" + Name + "' cannot be specified more than once");
3352 LocTy Loc = Lex.getLoc();
3354 return ParseMDField(Loc, Name, Result);
3357 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3358 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3360 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3361 if (Lex.getStrVal() == #CLASS) \
3362 return Parse##CLASS(N, IsDistinct);
3363 #include "llvm/IR/Metadata.def"
3365 return TokError("expected metadata type");
3368 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3369 #define NOP_FIELD(NAME, TYPE, INIT)
3370 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3372 return Error(ClosingLoc, "missing required field '" #NAME "'");
3373 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3374 if (Lex.getStrVal() == #NAME) \
3375 return ParseMDField(#NAME, NAME);
3376 #define PARSE_MD_FIELDS() \
3377 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3380 if (ParseMDFieldsImpl([&]() -> bool { \
3381 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3382 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3385 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3387 #define GET_OR_DISTINCT(CLASS, ARGS) \
3388 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3390 /// ParseDILocationFields:
3391 /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3392 bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
3393 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3394 OPTIONAL(line, LineField, ); \
3395 OPTIONAL(column, ColumnField, ); \
3396 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3397 OPTIONAL(inlinedAt, MDField, );
3399 #undef VISIT_MD_FIELDS
3401 Result = GET_OR_DISTINCT(
3402 DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
3406 /// ParseGenericDINode:
3407 /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
3408 bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
3409 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3410 REQUIRED(tag, DwarfTagField, ); \
3411 OPTIONAL(header, MDStringField, ); \
3412 OPTIONAL(operands, MDFieldList, );
3414 #undef VISIT_MD_FIELDS
3416 Result = GET_OR_DISTINCT(GenericDINode,
3417 (Context, tag.Val, header.Val, operands.Val));
3421 /// ParseDISubrange:
3422 /// ::= !DISubrange(count: 30, lowerBound: 2)
3423 bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
3424 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3425 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3426 OPTIONAL(lowerBound, MDSignedField, );
3428 #undef VISIT_MD_FIELDS
3430 Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
3434 /// ParseDIEnumerator:
3435 /// ::= !DIEnumerator(value: 30, name: "SomeKind")
3436 bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
3437 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3438 REQUIRED(name, MDStringField, ); \
3439 REQUIRED(value, MDSignedField, );
3441 #undef VISIT_MD_FIELDS
3443 Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
3447 /// ParseDIBasicType:
3448 /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3449 bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
3450 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3451 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3452 OPTIONAL(name, MDStringField, ); \
3453 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3454 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3455 OPTIONAL(encoding, DwarfAttEncodingField, );
3457 #undef VISIT_MD_FIELDS
3459 Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
3460 align.Val, encoding.Val));
3464 /// ParseDIDerivedType:
3465 /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3466 /// line: 7, scope: !1, baseType: !2, size: 32,
3467 /// align: 32, offset: 0, flags: 0, extraData: !3)
3468 bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
3469 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3470 REQUIRED(tag, DwarfTagField, ); \
3471 OPTIONAL(name, MDStringField, ); \
3472 OPTIONAL(file, MDField, ); \
3473 OPTIONAL(line, LineField, ); \
3474 OPTIONAL(scope, MDField, ); \
3475 REQUIRED(baseType, MDField, ); \
3476 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3477 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3478 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3479 OPTIONAL(flags, DIFlagField, ); \
3480 OPTIONAL(extraData, MDField, );
3482 #undef VISIT_MD_FIELDS
3484 Result = GET_OR_DISTINCT(DIDerivedType,
3485 (Context, tag.Val, name.Val, file.Val, line.Val,
3486 scope.Val, baseType.Val, size.Val, align.Val,
3487 offset.Val, flags.Val, extraData.Val));
3491 bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
3492 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3493 REQUIRED(tag, DwarfTagField, ); \
3494 OPTIONAL(name, MDStringField, ); \
3495 OPTIONAL(file, MDField, ); \
3496 OPTIONAL(line, LineField, ); \
3497 OPTIONAL(scope, MDField, ); \
3498 OPTIONAL(baseType, MDField, ); \
3499 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3500 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3501 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3502 OPTIONAL(flags, DIFlagField, ); \
3503 OPTIONAL(elements, MDField, ); \
3504 OPTIONAL(runtimeLang, DwarfLangField, ); \
3505 OPTIONAL(vtableHolder, MDField, ); \
3506 OPTIONAL(templateParams, MDField, ); \
3507 OPTIONAL(identifier, MDStringField, );
3509 #undef VISIT_MD_FIELDS
3511 Result = GET_OR_DISTINCT(
3513 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3514 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3515 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3519 bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
3520 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3521 OPTIONAL(flags, DIFlagField, ); \
3522 REQUIRED(types, MDField, );
3524 #undef VISIT_MD_FIELDS
3526 Result = GET_OR_DISTINCT(DISubroutineType, (Context, flags.Val, types.Val));
3530 /// ParseDIFileType:
3531 /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
3532 bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
3533 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3534 REQUIRED(filename, MDStringField, ); \
3535 REQUIRED(directory, MDStringField, );
3537 #undef VISIT_MD_FIELDS
3539 Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
3543 /// ParseDICompileUnit:
3544 /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3545 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3546 /// splitDebugFilename: "abc.debug", emissionKind: 1,
3547 /// enums: !1, retainedTypes: !2, subprograms: !3,
3548 /// globals: !4, imports: !5, dwoId: 0x0abcd)
3549 bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
3550 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3551 REQUIRED(language, DwarfLangField, ); \
3552 REQUIRED(file, MDField, (/* AllowNull */ false)); \
3553 OPTIONAL(producer, MDStringField, ); \
3554 OPTIONAL(isOptimized, MDBoolField, ); \
3555 OPTIONAL(flags, MDStringField, ); \
3556 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3557 OPTIONAL(splitDebugFilename, MDStringField, ); \
3558 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3559 OPTIONAL(enums, MDField, ); \
3560 OPTIONAL(retainedTypes, MDField, ); \
3561 OPTIONAL(subprograms, MDField, ); \
3562 OPTIONAL(globals, MDField, ); \
3563 OPTIONAL(imports, MDField, ); \
3564 OPTIONAL(dwoId, MDUnsignedField, );
3566 #undef VISIT_MD_FIELDS
3568 Result = GET_OR_DISTINCT(DICompileUnit,
3569 (Context, language.Val, file.Val, producer.Val,
3570 isOptimized.Val, flags.Val, runtimeVersion.Val,
3571 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3572 retainedTypes.Val, subprograms.Val, globals.Val,
3573 imports.Val, dwoId.Val));
3577 /// ParseDISubprogram:
3578 /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3579 /// file: !1, line: 7, type: !2, isLocal: false,
3580 /// isDefinition: true, scopeLine: 8, containingType: !3,
3581 /// virtuality: DW_VIRTUALTIY_pure_virtual,
3582 /// virtualIndex: 10, flags: 11,
3583 /// isOptimized: false, function: void ()* @_Z3foov,
3584 /// templateParams: !4, declaration: !5, variables: !6)
3585 bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
3586 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3587 OPTIONAL(scope, MDField, ); \
3588 OPTIONAL(name, MDStringField, ); \
3589 OPTIONAL(linkageName, MDStringField, ); \
3590 OPTIONAL(file, MDField, ); \
3591 OPTIONAL(line, LineField, ); \
3592 OPTIONAL(type, MDField, ); \
3593 OPTIONAL(isLocal, MDBoolField, ); \
3594 OPTIONAL(isDefinition, MDBoolField, (true)); \
3595 OPTIONAL(scopeLine, LineField, ); \
3596 OPTIONAL(containingType, MDField, ); \
3597 OPTIONAL(virtuality, DwarfVirtualityField, ); \
3598 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
3599 OPTIONAL(flags, DIFlagField, ); \
3600 OPTIONAL(isOptimized, MDBoolField, ); \
3601 OPTIONAL(function, MDConstant, ); \
3602 OPTIONAL(templateParams, MDField, ); \
3603 OPTIONAL(declaration, MDField, ); \
3604 OPTIONAL(variables, MDField, );
3606 #undef VISIT_MD_FIELDS
3608 Result = GET_OR_DISTINCT(
3609 DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3610 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3611 scopeLine.Val, containingType.Val, virtuality.Val,
3612 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3613 templateParams.Val, declaration.Val, variables.Val));
3617 /// ParseDILexicalBlock:
3618 /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3619 bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
3620 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3621 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3622 OPTIONAL(file, MDField, ); \
3623 OPTIONAL(line, LineField, ); \
3624 OPTIONAL(column, ColumnField, );
3626 #undef VISIT_MD_FIELDS
3628 Result = GET_OR_DISTINCT(
3629 DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3633 /// ParseDILexicalBlockFile:
3634 /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3635 bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3636 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3637 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3638 OPTIONAL(file, MDField, ); \
3639 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3641 #undef VISIT_MD_FIELDS
3643 Result = GET_OR_DISTINCT(DILexicalBlockFile,
3644 (Context, scope.Val, file.Val, discriminator.Val));
3648 /// ParseDINamespace:
3649 /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3650 bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
3651 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3652 REQUIRED(scope, MDField, ); \
3653 OPTIONAL(file, MDField, ); \
3654 OPTIONAL(name, MDStringField, ); \
3655 OPTIONAL(line, LineField, );
3657 #undef VISIT_MD_FIELDS
3659 Result = GET_OR_DISTINCT(DINamespace,
3660 (Context, scope.Val, file.Val, name.Val, line.Val));
3664 /// ParseDITemplateTypeParameter:
3665 /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
3666 bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3667 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3668 OPTIONAL(name, MDStringField, ); \
3669 REQUIRED(type, MDField, );
3671 #undef VISIT_MD_FIELDS
3674 GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
3678 /// ParseDITemplateValueParameter:
3679 /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
3680 /// name: "V", type: !1, value: i32 7)
3681 bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3682 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3683 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
3684 OPTIONAL(name, MDStringField, ); \
3685 OPTIONAL(type, MDField, ); \
3686 REQUIRED(value, MDField, );
3688 #undef VISIT_MD_FIELDS
3690 Result = GET_OR_DISTINCT(DITemplateValueParameter,
3691 (Context, tag.Val, name.Val, type.Val, value.Val));
3695 /// ParseDIGlobalVariable:
3696 /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3697 /// file: !1, line: 7, type: !2, isLocal: false,
3698 /// isDefinition: true, variable: i32* @foo,
3699 /// declaration: !3)
3700 bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
3701 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3702 REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
3703 OPTIONAL(scope, MDField, ); \
3704 OPTIONAL(linkageName, MDStringField, ); \
3705 OPTIONAL(file, MDField, ); \
3706 OPTIONAL(line, LineField, ); \
3707 OPTIONAL(type, MDField, ); \
3708 OPTIONAL(isLocal, MDBoolField, ); \
3709 OPTIONAL(isDefinition, MDBoolField, (true)); \
3710 OPTIONAL(variable, MDConstant, ); \
3711 OPTIONAL(declaration, MDField, );
3713 #undef VISIT_MD_FIELDS
3715 Result = GET_OR_DISTINCT(DIGlobalVariable,
3716 (Context, scope.Val, name.Val, linkageName.Val,
3717 file.Val, line.Val, type.Val, isLocal.Val,
3718 isDefinition.Val, variable.Val, declaration.Val));
3722 /// ParseDILocalVariable:
3723 /// ::= !DILocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
3724 /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
3725 bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
3726 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3727 REQUIRED(tag, DwarfTagField, ); \
3728 REQUIRED(scope, MDField, (/* AllowNull */ false)); \
3729 OPTIONAL(name, MDStringField, ); \
3730 OPTIONAL(file, MDField, ); \
3731 OPTIONAL(line, LineField, ); \
3732 OPTIONAL(type, MDField, ); \
3733 OPTIONAL(arg, MDUnsignedField, (0, UINT8_MAX)); \
3734 OPTIONAL(flags, DIFlagField, );
3736 #undef VISIT_MD_FIELDS
3738 Result = GET_OR_DISTINCT(DILocalVariable,
3739 (Context, tag.Val, scope.Val, name.Val, file.Val,
3740 line.Val, type.Val, arg.Val, flags.Val));
3744 /// ParseDIExpression:
3745 /// ::= !DIExpression(0, 7, -1)
3746 bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
3747 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3750 if (ParseToken(lltok::lparen, "expected '(' here"))
3753 SmallVector<uint64_t, 8> Elements;
3754 if (Lex.getKind() != lltok::rparen)
3756 if (Lex.getKind() == lltok::DwarfOp) {
3757 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3759 Elements.push_back(Op);
3762 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3765 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3766 return TokError("expected unsigned integer");
3768 auto &U = Lex.getAPSIntVal();
3769 if (U.ugt(UINT64_MAX))
3770 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3771 Elements.push_back(U.getZExtValue());
3773 } while (EatIfPresent(lltok::comma));
3775 if (ParseToken(lltok::rparen, "expected ')' here"))
3778 Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
3782 /// ParseDIObjCProperty:
3783 /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3784 /// getter: "getFoo", attributes: 7, type: !2)
3785 bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
3786 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3787 OPTIONAL(name, MDStringField, ); \
3788 OPTIONAL(file, MDField, ); \
3789 OPTIONAL(line, LineField, ); \
3790 OPTIONAL(setter, MDStringField, ); \
3791 OPTIONAL(getter, MDStringField, ); \
3792 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3793 OPTIONAL(type, MDField, );
3795 #undef VISIT_MD_FIELDS
3797 Result = GET_OR_DISTINCT(DIObjCProperty,
3798 (Context, name.Val, file.Val, line.Val, setter.Val,
3799 getter.Val, attributes.Val, type.Val));
3803 /// ParseDIImportedEntity:
3804 /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3805 /// line: 7, name: "foo")
3806 bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
3807 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3808 REQUIRED(tag, DwarfTagField, ); \
3809 REQUIRED(scope, MDField, ); \
3810 OPTIONAL(entity, MDField, ); \
3811 OPTIONAL(line, LineField, ); \
3812 OPTIONAL(name, MDStringField, );
3814 #undef VISIT_MD_FIELDS
3816 Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
3817 entity.Val, line.Val, name.Val));
3821 #undef PARSE_MD_FIELD
3823 #undef REQUIRE_FIELD
3824 #undef DECLARE_FIELD
3826 /// ParseMetadataAsValue
3827 /// ::= metadata i32 %local
3828 /// ::= metadata i32 @global
3829 /// ::= metadata i32 7
3831 /// ::= metadata !{...}
3832 /// ::= metadata !"string"
3833 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3834 // Note: the type 'metadata' has already been parsed.
3836 if (ParseMetadata(MD, &PFS))
3839 V = MetadataAsValue::get(Context, MD);
3843 /// ParseValueAsMetadata
3847 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3848 PerFunctionState *PFS) {
3851 if (ParseType(Ty, TypeMsg, Loc))
3853 if (Ty->isMetadataTy())
3854 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3857 if (ParseValue(Ty, V, PFS))
3860 MD = ValueAsMetadata::get(V);
3871 /// ::= !DILocation(...)
3872 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3873 if (Lex.getKind() == lltok::MetadataVar) {
3875 if (ParseSpecializedMDNode(N))
3883 if (Lex.getKind() != lltok::exclaim)
3884 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3887 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3891 // ::= '!' STRINGCONSTANT
3892 if (Lex.getKind() == lltok::StringConstant) {
3894 if (ParseMDString(S))
3904 if (ParseMDNodeTail(N))
3911 //===----------------------------------------------------------------------===//
3912 // Function Parsing.
3913 //===----------------------------------------------------------------------===//
3915 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3916 PerFunctionState *PFS) {
3917 if (Ty->isFunctionTy())
3918 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3921 case ValID::t_LocalID:
3922 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3923 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3924 return V == nullptr;
3925 case ValID::t_LocalName:
3926 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3927 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3928 return V == nullptr;
3929 case ValID::t_InlineAsm: {
3930 PointerType *PTy = dyn_cast<PointerType>(Ty);
3932 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3933 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3934 return Error(ID.Loc, "invalid type for inline asm constraint string");
3935 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3936 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3939 case ValID::t_GlobalName:
3940 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3941 return V == nullptr;
3942 case ValID::t_GlobalID:
3943 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3944 return V == nullptr;
3945 case ValID::t_APSInt:
3946 if (!Ty->isIntegerTy())
3947 return Error(ID.Loc, "integer constant must have integer type");
3948 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3949 V = ConstantInt::get(Context, ID.APSIntVal);
3951 case ValID::t_APFloat:
3952 if (!Ty->isFloatingPointTy() ||
3953 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3954 return Error(ID.Loc, "floating point constant invalid for type");
3956 // The lexer has no type info, so builds all half, float, and double FP
3957 // constants as double. Fix this here. Long double does not need this.
3958 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3961 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3963 else if (Ty->isFloatTy())
3964 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3967 V = ConstantFP::get(Context, ID.APFloatVal);
3969 if (V->getType() != Ty)
3970 return Error(ID.Loc, "floating point constant does not have type '" +
3971 getTypeString(Ty) + "'");
3975 if (!Ty->isPointerTy())
3976 return Error(ID.Loc, "null must be a pointer type");
3977 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3979 case ValID::t_Undef:
3980 // FIXME: LabelTy should not be a first-class type.
3981 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3982 return Error(ID.Loc, "invalid type for undef constant");
3983 V = UndefValue::get(Ty);
3985 case ValID::t_EmptyArray:
3986 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3987 return Error(ID.Loc, "invalid empty array initializer");
3988 V = UndefValue::get(Ty);
3991 // FIXME: LabelTy should not be a first-class type.
3992 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3993 return Error(ID.Loc, "invalid type for null constant");
3994 V = Constant::getNullValue(Ty);
3996 case ValID::t_Constant:
3997 if (ID.ConstantVal->getType() != Ty)
3998 return Error(ID.Loc, "constant expression type mismatch");
4002 case ValID::t_ConstantStruct:
4003 case ValID::t_PackedConstantStruct:
4004 if (StructType *ST = dyn_cast<StructType>(Ty)) {
4005 if (ST->getNumElements() != ID.UIntVal)
4006 return Error(ID.Loc,
4007 "initializer with struct type has wrong # elements");
4008 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
4009 return Error(ID.Loc, "packed'ness of initializer and type don't match");
4011 // Verify that the elements are compatible with the structtype.
4012 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
4013 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
4014 return Error(ID.Loc, "element " + Twine(i) +
4015 " of struct initializer doesn't match struct element type");
4017 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
4020 return Error(ID.Loc, "constant expression type mismatch");
4023 llvm_unreachable("Invalid ValID");
4026 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
4029 return ParseValID(ID, PFS) ||
4030 ConvertValIDToValue(Ty, ID, V, PFS);
4033 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
4035 return ParseType(Ty) ||
4036 ParseValue(Ty, V, PFS);
4039 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
4040 PerFunctionState &PFS) {
4043 if (ParseTypeAndValue(V, PFS)) return true;
4044 if (!isa<BasicBlock>(V))
4045 return Error(Loc, "expected a basic block");
4046 BB = cast<BasicBlock>(V);
4052 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
4053 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
4054 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue
4055 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
4056 // Parse the linkage.
4057 LocTy LinkageLoc = Lex.getLoc();
4060 unsigned Visibility;
4061 unsigned DLLStorageClass;
4062 AttrBuilder RetAttrs;
4064 Type *RetType = nullptr;
4065 LocTy RetTypeLoc = Lex.getLoc();
4066 if (ParseOptionalLinkage(Linkage) ||
4067 ParseOptionalVisibility(Visibility) ||
4068 ParseOptionalDLLStorageClass(DLLStorageClass) ||
4069 ParseOptionalCallingConv(CC) ||
4070 ParseOptionalReturnAttrs(RetAttrs) ||
4071 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4074 // Verify that the linkage is ok.
4075 switch ((GlobalValue::LinkageTypes)Linkage) {
4076 case GlobalValue::ExternalLinkage:
4077 break; // always ok.
4078 case GlobalValue::ExternalWeakLinkage:
4080 return Error(LinkageLoc, "invalid linkage for function definition");
4082 case GlobalValue::PrivateLinkage:
4083 case GlobalValue::InternalLinkage:
4084 case GlobalValue::AvailableExternallyLinkage:
4085 case GlobalValue::LinkOnceAnyLinkage:
4086 case GlobalValue::LinkOnceODRLinkage:
4087 case GlobalValue::WeakAnyLinkage:
4088 case GlobalValue::WeakODRLinkage:
4090 return Error(LinkageLoc, "invalid linkage for function declaration");
4092 case GlobalValue::AppendingLinkage:
4093 case GlobalValue::CommonLinkage:
4094 return Error(LinkageLoc, "invalid function linkage type");
4097 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4098 return Error(LinkageLoc,
4099 "symbol with local linkage must have default visibility");
4101 if (!FunctionType::isValidReturnType(RetType))
4102 return Error(RetTypeLoc, "invalid function return type");
4104 LocTy NameLoc = Lex.getLoc();
4106 std::string FunctionName;
4107 if (Lex.getKind() == lltok::GlobalVar) {
4108 FunctionName = Lex.getStrVal();
4109 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4110 unsigned NameID = Lex.getUIntVal();
4112 if (NameID != NumberedVals.size())
4113 return TokError("function expected to be numbered '%" +
4114 Twine(NumberedVals.size()) + "'");
4116 return TokError("expected function name");
4121 if (Lex.getKind() != lltok::lparen)
4122 return TokError("expected '(' in function argument list");
4124 SmallVector<ArgInfo, 8> ArgList;
4126 AttrBuilder FuncAttrs;
4127 std::vector<unsigned> FwdRefAttrGrps;
4129 std::string Section;
4133 LocTy UnnamedAddrLoc;
4134 Constant *Prefix = nullptr;
4135 Constant *Prologue = nullptr;
4138 if (ParseArgumentList(ArgList, isVarArg) ||
4139 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4141 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4143 (EatIfPresent(lltok::kw_section) &&
4144 ParseStringConstant(Section)) ||
4145 parseOptionalComdat(FunctionName, C) ||
4146 ParseOptionalAlignment(Alignment) ||
4147 (EatIfPresent(lltok::kw_gc) &&
4148 ParseStringConstant(GC)) ||
4149 (EatIfPresent(lltok::kw_prefix) &&
4150 ParseGlobalTypeAndValue(Prefix)) ||
4151 (EatIfPresent(lltok::kw_prologue) &&
4152 ParseGlobalTypeAndValue(Prologue)))
4155 if (FuncAttrs.contains(Attribute::Builtin))
4156 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4158 // If the alignment was parsed as an attribute, move to the alignment field.
4159 if (FuncAttrs.hasAlignmentAttr()) {
4160 Alignment = FuncAttrs.getAlignment();
4161 FuncAttrs.removeAttribute(Attribute::Alignment);
4164 // Okay, if we got here, the function is syntactically valid. Convert types
4165 // and do semantic checks.
4166 std::vector<Type*> ParamTypeList;
4167 SmallVector<AttributeSet, 8> Attrs;
4169 if (RetAttrs.hasAttributes())
4170 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4171 AttributeSet::ReturnIndex,
4174 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4175 ParamTypeList.push_back(ArgList[i].Ty);
4176 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4177 AttrBuilder B(ArgList[i].Attrs, i + 1);
4178 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4182 if (FuncAttrs.hasAttributes())
4183 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4184 AttributeSet::FunctionIndex,
4187 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4189 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4190 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4193 FunctionType::get(RetType, ParamTypeList, isVarArg);
4194 PointerType *PFT = PointerType::getUnqual(FT);
4197 if (!FunctionName.empty()) {
4198 // If this was a definition of a forward reference, remove the definition
4199 // from the forward reference table and fill in the forward ref.
4200 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4201 ForwardRefVals.find(FunctionName);
4202 if (FRVI != ForwardRefVals.end()) {
4203 Fn = M->getFunction(FunctionName);
4205 return Error(FRVI->second.second, "invalid forward reference to "
4206 "function as global value!");
4207 if (Fn->getType() != PFT)
4208 return Error(FRVI->second.second, "invalid forward reference to "
4209 "function '" + FunctionName + "' with wrong type!");
4211 ForwardRefVals.erase(FRVI);
4212 } else if ((Fn = M->getFunction(FunctionName))) {
4213 // Reject redefinitions.
4214 return Error(NameLoc, "invalid redefinition of function '" +
4215 FunctionName + "'");
4216 } else if (M->getNamedValue(FunctionName)) {
4217 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4221 // If this is a definition of a forward referenced function, make sure the
4223 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4224 = ForwardRefValIDs.find(NumberedVals.size());
4225 if (I != ForwardRefValIDs.end()) {
4226 Fn = cast<Function>(I->second.first);
4227 if (Fn->getType() != PFT)
4228 return Error(NameLoc, "type of definition and forward reference of '@" +
4229 Twine(NumberedVals.size()) + "' disagree");
4230 ForwardRefValIDs.erase(I);
4235 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4236 else // Move the forward-reference to the correct spot in the module.
4237 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4239 if (FunctionName.empty())
4240 NumberedVals.push_back(Fn);
4242 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4243 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4244 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4245 Fn->setCallingConv(CC);
4246 Fn->setAttributes(PAL);
4247 Fn->setUnnamedAddr(UnnamedAddr);
4248 Fn->setAlignment(Alignment);
4249 Fn->setSection(Section);
4251 if (!GC.empty()) Fn->setGC(GC.c_str());
4252 Fn->setPrefixData(Prefix);
4253 Fn->setPrologueData(Prologue);
4254 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4256 // Add all of the arguments we parsed to the function.
4257 Function::arg_iterator ArgIt = Fn->arg_begin();
4258 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4259 // If the argument has a name, insert it into the argument symbol table.
4260 if (ArgList[i].Name.empty()) continue;
4262 // Set the name, if it conflicted, it will be auto-renamed.
4263 ArgIt->setName(ArgList[i].Name);
4265 if (ArgIt->getName() != ArgList[i].Name)
4266 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4267 ArgList[i].Name + "'");
4273 // Check the declaration has no block address forward references.
4275 if (FunctionName.empty()) {
4276 ID.Kind = ValID::t_GlobalID;
4277 ID.UIntVal = NumberedVals.size() - 1;
4279 ID.Kind = ValID::t_GlobalName;
4280 ID.StrVal = FunctionName;
4282 auto Blocks = ForwardRefBlockAddresses.find(ID);
4283 if (Blocks != ForwardRefBlockAddresses.end())
4284 return Error(Blocks->first.Loc,
4285 "cannot take blockaddress inside a declaration");
4289 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4291 if (FunctionNumber == -1) {
4292 ID.Kind = ValID::t_GlobalName;
4293 ID.StrVal = F.getName();
4295 ID.Kind = ValID::t_GlobalID;
4296 ID.UIntVal = FunctionNumber;
4299 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4300 if (Blocks == P.ForwardRefBlockAddresses.end())
4303 for (const auto &I : Blocks->second) {
4304 const ValID &BBID = I.first;
4305 GlobalValue *GV = I.second;
4307 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4308 "Expected local id or name");
4310 if (BBID.Kind == ValID::t_LocalName)
4311 BB = GetBB(BBID.StrVal, BBID.Loc);
4313 BB = GetBB(BBID.UIntVal, BBID.Loc);
4315 return P.Error(BBID.Loc, "referenced value is not a basic block");
4317 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4318 GV->eraseFromParent();
4321 P.ForwardRefBlockAddresses.erase(Blocks);
4325 /// ParseFunctionBody
4326 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4327 bool LLParser::ParseFunctionBody(Function &Fn) {
4328 if (Lex.getKind() != lltok::lbrace)
4329 return TokError("expected '{' in function body");
4330 Lex.Lex(); // eat the {.
4332 int FunctionNumber = -1;
4333 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4335 PerFunctionState PFS(*this, Fn, FunctionNumber);
4337 // Resolve block addresses and allow basic blocks to be forward-declared
4338 // within this function.
4339 if (PFS.resolveForwardRefBlockAddresses())
4341 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4343 // We need at least one basic block.
4344 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4345 return TokError("function body requires at least one basic block");
4347 while (Lex.getKind() != lltok::rbrace &&
4348 Lex.getKind() != lltok::kw_uselistorder)
4349 if (ParseBasicBlock(PFS)) return true;
4351 while (Lex.getKind() != lltok::rbrace)
4352 if (ParseUseListOrder(&PFS))
4358 // Verify function is ok.
4359 return PFS.FinishFunction();
4363 /// ::= LabelStr? Instruction*
4364 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4365 // If this basic block starts out with a name, remember it.
4367 LocTy NameLoc = Lex.getLoc();
4368 if (Lex.getKind() == lltok::LabelStr) {
4369 Name = Lex.getStrVal();
4373 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4375 return Error(NameLoc,
4376 "unable to create block named '" + Name + "'");
4378 std::string NameStr;
4380 // Parse the instructions in this block until we get a terminator.
4383 // This instruction may have three possibilities for a name: a) none
4384 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4385 LocTy NameLoc = Lex.getLoc();
4389 if (Lex.getKind() == lltok::LocalVarID) {
4390 NameID = Lex.getUIntVal();
4392 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4394 } else if (Lex.getKind() == lltok::LocalVar) {
4395 NameStr = Lex.getStrVal();
4397 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4401 switch (ParseInstruction(Inst, BB, PFS)) {
4402 default: llvm_unreachable("Unknown ParseInstruction result!");
4403 case InstError: return true;
4405 BB->getInstList().push_back(Inst);
4407 // With a normal result, we check to see if the instruction is followed by
4408 // a comma and metadata.
4409 if (EatIfPresent(lltok::comma))
4410 if (ParseInstructionMetadata(*Inst))
4413 case InstExtraComma:
4414 BB->getInstList().push_back(Inst);
4416 // If the instruction parser ate an extra comma at the end of it, it
4417 // *must* be followed by metadata.
4418 if (ParseInstructionMetadata(*Inst))
4423 // Set the name on the instruction.
4424 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4425 } while (!isa<TerminatorInst>(Inst));
4430 //===----------------------------------------------------------------------===//
4431 // Instruction Parsing.
4432 //===----------------------------------------------------------------------===//
4434 /// ParseInstruction - Parse one of the many different instructions.
4436 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4437 PerFunctionState &PFS) {
4438 lltok::Kind Token = Lex.getKind();
4439 if (Token == lltok::Eof)
4440 return TokError("found end of file when expecting more instructions");
4441 LocTy Loc = Lex.getLoc();
4442 unsigned KeywordVal = Lex.getUIntVal();
4443 Lex.Lex(); // Eat the keyword.
4446 default: return Error(Loc, "expected instruction opcode");
4447 // Terminator Instructions.
4448 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4449 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4450 case lltok::kw_br: return ParseBr(Inst, PFS);
4451 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4452 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4453 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4454 case lltok::kw_resume: return ParseResume(Inst, PFS);
4455 // Binary Operators.
4459 case lltok::kw_shl: {
4460 bool NUW = EatIfPresent(lltok::kw_nuw);
4461 bool NSW = EatIfPresent(lltok::kw_nsw);
4462 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4464 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4466 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4467 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4470 case lltok::kw_fadd:
4471 case lltok::kw_fsub:
4472 case lltok::kw_fmul:
4473 case lltok::kw_fdiv:
4474 case lltok::kw_frem: {
4475 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4476 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4480 Inst->setFastMathFlags(FMF);
4484 case lltok::kw_sdiv:
4485 case lltok::kw_udiv:
4486 case lltok::kw_lshr:
4487 case lltok::kw_ashr: {
4488 bool Exact = EatIfPresent(lltok::kw_exact);
4490 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4491 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4495 case lltok::kw_urem:
4496 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4499 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
4500 case lltok::kw_icmp:
4501 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
4503 case lltok::kw_trunc:
4504 case lltok::kw_zext:
4505 case lltok::kw_sext:
4506 case lltok::kw_fptrunc:
4507 case lltok::kw_fpext:
4508 case lltok::kw_bitcast:
4509 case lltok::kw_addrspacecast:
4510 case lltok::kw_uitofp:
4511 case lltok::kw_sitofp:
4512 case lltok::kw_fptoui:
4513 case lltok::kw_fptosi:
4514 case lltok::kw_inttoptr:
4515 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
4517 case lltok::kw_select: return ParseSelect(Inst, PFS);
4518 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
4519 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4520 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4521 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4522 case lltok::kw_phi: return ParsePHI(Inst, PFS);
4523 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
4525 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4526 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4527 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4529 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
4530 case lltok::kw_load: return ParseLoad(Inst, PFS);
4531 case lltok::kw_store: return ParseStore(Inst, PFS);
4532 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4533 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
4534 case lltok::kw_fence: return ParseFence(Inst, PFS);
4535 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4536 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4537 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4541 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4542 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4543 if (Opc == Instruction::FCmp) {
4544 switch (Lex.getKind()) {
4545 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4546 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4547 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4548 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4549 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4550 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4551 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4552 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4553 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4554 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4555 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4556 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4557 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4558 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4559 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4560 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4561 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4564 switch (Lex.getKind()) {
4565 default: return TokError("expected icmp predicate (e.g. 'eq')");
4566 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4567 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4568 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4569 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4570 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4571 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4572 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4573 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4574 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4575 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4582 //===----------------------------------------------------------------------===//
4583 // Terminator Instructions.
4584 //===----------------------------------------------------------------------===//
4586 /// ParseRet - Parse a return instruction.
4587 /// ::= 'ret' void (',' !dbg, !1)*
4588 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
4589 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4590 PerFunctionState &PFS) {
4591 SMLoc TypeLoc = Lex.getLoc();
4593 if (ParseType(Ty, true /*void allowed*/)) return true;
4595 Type *ResType = PFS.getFunction().getReturnType();
4597 if (Ty->isVoidTy()) {
4598 if (!ResType->isVoidTy())
4599 return Error(TypeLoc, "value doesn't match function result type '" +
4600 getTypeString(ResType) + "'");
4602 Inst = ReturnInst::Create(Context);
4607 if (ParseValue(Ty, RV, PFS)) return true;
4609 if (ResType != RV->getType())
4610 return Error(TypeLoc, "value doesn't match function result type '" +
4611 getTypeString(ResType) + "'");
4613 Inst = ReturnInst::Create(Context, RV);
4619 /// ::= 'br' TypeAndValue
4620 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4621 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4624 BasicBlock *Op1, *Op2;
4625 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4627 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4628 Inst = BranchInst::Create(BB);
4632 if (Op0->getType() != Type::getInt1Ty(Context))
4633 return Error(Loc, "branch condition must have 'i1' type");
4635 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4636 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4637 ParseToken(lltok::comma, "expected ',' after true destination") ||
4638 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4641 Inst = BranchInst::Create(Op1, Op2, Op0);
4647 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4649 /// ::= (TypeAndValue ',' TypeAndValue)*
4650 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4651 LocTy CondLoc, BBLoc;
4653 BasicBlock *DefaultBB;
4654 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4655 ParseToken(lltok::comma, "expected ',' after switch condition") ||
4656 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4657 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4660 if (!Cond->getType()->isIntegerTy())
4661 return Error(CondLoc, "switch condition must have integer type");
4663 // Parse the jump table pairs.
4664 SmallPtrSet<Value*, 32> SeenCases;
4665 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4666 while (Lex.getKind() != lltok::rsquare) {
4670 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4671 ParseToken(lltok::comma, "expected ',' after case value") ||
4672 ParseTypeAndBasicBlock(DestBB, PFS))
4675 if (!SeenCases.insert(Constant).second)
4676 return Error(CondLoc, "duplicate case value in switch");
4677 if (!isa<ConstantInt>(Constant))
4678 return Error(CondLoc, "case value is not a constant integer");
4680 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4683 Lex.Lex(); // Eat the ']'.
4685 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4686 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4687 SI->addCase(Table[i].first, Table[i].second);
4694 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4695 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4698 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4699 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4700 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4703 if (!Address->getType()->isPointerTy())
4704 return Error(AddrLoc, "indirectbr address must have pointer type");
4706 // Parse the destination list.
4707 SmallVector<BasicBlock*, 16> DestList;
4709 if (Lex.getKind() != lltok::rsquare) {
4711 if (ParseTypeAndBasicBlock(DestBB, PFS))
4713 DestList.push_back(DestBB);
4715 while (EatIfPresent(lltok::comma)) {
4716 if (ParseTypeAndBasicBlock(DestBB, PFS))
4718 DestList.push_back(DestBB);
4722 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4725 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4726 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4727 IBI->addDestination(DestList[i]);
4734 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4735 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4736 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4737 LocTy CallLoc = Lex.getLoc();
4738 AttrBuilder RetAttrs, FnAttrs;
4739 std::vector<unsigned> FwdRefAttrGrps;
4742 Type *RetType = nullptr;
4745 SmallVector<ParamInfo, 16> ArgList;
4747 BasicBlock *NormalBB, *UnwindBB;
4748 if (ParseOptionalCallingConv(CC) ||
4749 ParseOptionalReturnAttrs(RetAttrs) ||
4750 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4751 ParseValID(CalleeID) ||
4752 ParseParameterList(ArgList, PFS) ||
4753 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4755 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4756 ParseTypeAndBasicBlock(NormalBB, PFS) ||
4757 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4758 ParseTypeAndBasicBlock(UnwindBB, PFS))
4761 // If RetType is a non-function pointer type, then this is the short syntax
4762 // for the call, which means that RetType is just the return type. Infer the
4763 // rest of the function argument types from the arguments that are present.
4764 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
4766 // Pull out the types of all of the arguments...
4767 std::vector<Type*> ParamTypes;
4768 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4769 ParamTypes.push_back(ArgList[i].V->getType());
4771 if (!FunctionType::isValidReturnType(RetType))
4772 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4774 Ty = FunctionType::get(RetType, ParamTypes, false);
4777 // Look up the callee.
4779 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
4782 // Set up the Attribute for the function.
4783 SmallVector<AttributeSet, 8> Attrs;
4784 if (RetAttrs.hasAttributes())
4785 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4786 AttributeSet::ReturnIndex,
4789 SmallVector<Value*, 8> Args;
4791 // Loop through FunctionType's arguments and ensure they are specified
4792 // correctly. Also, gather any parameter attributes.
4793 FunctionType::param_iterator I = Ty->param_begin();
4794 FunctionType::param_iterator E = Ty->param_end();
4795 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4796 Type *ExpectedTy = nullptr;
4799 } else if (!Ty->isVarArg()) {
4800 return Error(ArgList[i].Loc, "too many arguments specified");
4803 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4804 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4805 getTypeString(ExpectedTy) + "'");
4806 Args.push_back(ArgList[i].V);
4807 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4808 AttrBuilder B(ArgList[i].Attrs, i + 1);
4809 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4814 return Error(CallLoc, "not enough parameters specified for call");
4816 if (FnAttrs.hasAttributes()) {
4817 if (FnAttrs.hasAlignmentAttr())
4818 return Error(CallLoc, "invoke instructions may not have an alignment");
4820 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4821 AttributeSet::FunctionIndex,
4825 // Finish off the Attribute and check them
4826 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4828 InvokeInst *II = InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args);
4829 II->setCallingConv(CC);
4830 II->setAttributes(PAL);
4831 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4837 /// ::= 'resume' TypeAndValue
4838 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4839 Value *Exn; LocTy ExnLoc;
4840 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4843 ResumeInst *RI = ResumeInst::Create(Exn);
4848 //===----------------------------------------------------------------------===//
4849 // Binary Operators.
4850 //===----------------------------------------------------------------------===//
4853 /// ::= ArithmeticOps TypeAndValue ',' Value
4855 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4856 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4857 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4858 unsigned Opc, unsigned OperandType) {
4859 LocTy Loc; Value *LHS, *RHS;
4860 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4861 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4862 ParseValue(LHS->getType(), RHS, PFS))
4866 switch (OperandType) {
4867 default: llvm_unreachable("Unknown operand type!");
4868 case 0: // int or FP.
4869 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4870 LHS->getType()->isFPOrFPVectorTy();
4872 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4873 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4877 return Error(Loc, "invalid operand type for instruction");
4879 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4884 /// ::= ArithmeticOps TypeAndValue ',' Value {
4885 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4887 LocTy Loc; Value *LHS, *RHS;
4888 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4889 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4890 ParseValue(LHS->getType(), RHS, PFS))
4893 if (!LHS->getType()->isIntOrIntVectorTy())
4894 return Error(Loc,"instruction requires integer or integer vector operands");
4896 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4902 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
4903 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
4904 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4906 // Parse the integer/fp comparison predicate.
4910 if (ParseCmpPredicate(Pred, Opc) ||
4911 ParseTypeAndValue(LHS, Loc, PFS) ||
4912 ParseToken(lltok::comma, "expected ',' after compare value") ||
4913 ParseValue(LHS->getType(), RHS, PFS))
4916 if (Opc == Instruction::FCmp) {
4917 if (!LHS->getType()->isFPOrFPVectorTy())
4918 return Error(Loc, "fcmp requires floating point operands");
4919 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4921 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4922 if (!LHS->getType()->isIntOrIntVectorTy() &&
4923 !LHS->getType()->getScalarType()->isPointerTy())
4924 return Error(Loc, "icmp requires integer operands");
4925 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4930 //===----------------------------------------------------------------------===//
4931 // Other Instructions.
4932 //===----------------------------------------------------------------------===//
4936 /// ::= CastOpc TypeAndValue 'to' Type
4937 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4941 Type *DestTy = nullptr;
4942 if (ParseTypeAndValue(Op, Loc, PFS) ||
4943 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4947 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4948 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4949 return Error(Loc, "invalid cast opcode for cast from '" +
4950 getTypeString(Op->getType()) + "' to '" +
4951 getTypeString(DestTy) + "'");
4953 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4958 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4959 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4961 Value *Op0, *Op1, *Op2;
4962 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4963 ParseToken(lltok::comma, "expected ',' after select condition") ||
4964 ParseTypeAndValue(Op1, PFS) ||
4965 ParseToken(lltok::comma, "expected ',' after select value") ||
4966 ParseTypeAndValue(Op2, PFS))
4969 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4970 return Error(Loc, Reason);
4972 Inst = SelectInst::Create(Op0, Op1, Op2);
4977 /// ::= 'va_arg' TypeAndValue ',' Type
4978 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4980 Type *EltTy = nullptr;
4982 if (ParseTypeAndValue(Op, PFS) ||
4983 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4984 ParseType(EltTy, TypeLoc))
4987 if (!EltTy->isFirstClassType())
4988 return Error(TypeLoc, "va_arg requires operand with first class type");
4990 Inst = new VAArgInst(Op, EltTy);
4994 /// ParseExtractElement
4995 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4996 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4999 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5000 ParseToken(lltok::comma, "expected ',' after extract value") ||
5001 ParseTypeAndValue(Op1, PFS))
5004 if (!ExtractElementInst::isValidOperands(Op0, Op1))
5005 return Error(Loc, "invalid extractelement operands");
5007 Inst = ExtractElementInst::Create(Op0, Op1);
5011 /// ParseInsertElement
5012 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5013 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
5015 Value *Op0, *Op1, *Op2;
5016 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5017 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5018 ParseTypeAndValue(Op1, PFS) ||
5019 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5020 ParseTypeAndValue(Op2, PFS))
5023 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
5024 return Error(Loc, "invalid insertelement operands");
5026 Inst = InsertElementInst::Create(Op0, Op1, Op2);
5030 /// ParseShuffleVector
5031 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
5032 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
5034 Value *Op0, *Op1, *Op2;
5035 if (ParseTypeAndValue(Op0, Loc, PFS) ||
5036 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
5037 ParseTypeAndValue(Op1, PFS) ||
5038 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
5039 ParseTypeAndValue(Op2, PFS))
5042 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
5043 return Error(Loc, "invalid shufflevector operands");
5045 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
5050 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
5051 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
5052 Type *Ty = nullptr; LocTy TypeLoc;
5055 if (ParseType(Ty, TypeLoc) ||
5056 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5057 ParseValue(Ty, Op0, PFS) ||
5058 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5059 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5060 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5063 bool AteExtraComma = false;
5064 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5066 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5068 if (!EatIfPresent(lltok::comma))
5071 if (Lex.getKind() == lltok::MetadataVar) {
5072 AteExtraComma = true;
5076 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5077 ParseValue(Ty, Op0, PFS) ||
5078 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5079 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5080 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5084 if (!Ty->isFirstClassType())
5085 return Error(TypeLoc, "phi node must have first class type");
5087 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5088 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5089 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5091 return AteExtraComma ? InstExtraComma : InstNormal;
5095 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5097 /// ::= 'catch' TypeAndValue
5099 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5100 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5101 Type *Ty = nullptr; LocTy TyLoc;
5102 Value *PersFn; LocTy PersFnLoc;
5104 if (ParseType(Ty, TyLoc) ||
5105 ParseToken(lltok::kw_personality, "expected 'personality'") ||
5106 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
5109 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, PersFn, 0));
5110 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5112 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5113 LandingPadInst::ClauseType CT;
5114 if (EatIfPresent(lltok::kw_catch))
5115 CT = LandingPadInst::Catch;
5116 else if (EatIfPresent(lltok::kw_filter))
5117 CT = LandingPadInst::Filter;
5119 return TokError("expected 'catch' or 'filter' clause type");
5123 if (ParseTypeAndValue(V, VLoc, PFS))
5126 // A 'catch' type expects a non-array constant. A filter clause expects an
5128 if (CT == LandingPadInst::Catch) {
5129 if (isa<ArrayType>(V->getType()))
5130 Error(VLoc, "'catch' clause has an invalid type");
5132 if (!isa<ArrayType>(V->getType()))
5133 Error(VLoc, "'filter' clause has an invalid type");
5136 Constant *CV = dyn_cast<Constant>(V);
5138 return Error(VLoc, "clause argument must be a constant");
5142 Inst = LP.release();
5147 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5148 /// ParameterList OptionalAttrs
5149 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5150 /// ParameterList OptionalAttrs
5151 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5152 /// ParameterList OptionalAttrs
5153 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5154 CallInst::TailCallKind TCK) {
5155 AttrBuilder RetAttrs, FnAttrs;
5156 std::vector<unsigned> FwdRefAttrGrps;
5159 Type *RetType = nullptr;
5162 SmallVector<ParamInfo, 16> ArgList;
5163 LocTy CallLoc = Lex.getLoc();
5165 if ((TCK != CallInst::TCK_None &&
5166 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5167 ParseOptionalCallingConv(CC) ||
5168 ParseOptionalReturnAttrs(RetAttrs) ||
5169 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5170 ParseValID(CalleeID) ||
5171 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5172 PFS.getFunction().isVarArg()) ||
5173 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5177 // If RetType is a non-function pointer type, then this is the short syntax
5178 // for the call, which means that RetType is just the return type. Infer the
5179 // rest of the function argument types from the arguments that are present.
5180 FunctionType *Ty = dyn_cast<FunctionType>(RetType);
5182 // Pull out the types of all of the arguments...
5183 std::vector<Type*> ParamTypes;
5184 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5185 ParamTypes.push_back(ArgList[i].V->getType());
5187 if (!FunctionType::isValidReturnType(RetType))
5188 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5190 Ty = FunctionType::get(RetType, ParamTypes, false);
5193 // Look up the callee.
5195 if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
5198 // Set up the Attribute for the function.
5199 SmallVector<AttributeSet, 8> Attrs;
5200 if (RetAttrs.hasAttributes())
5201 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5202 AttributeSet::ReturnIndex,
5205 SmallVector<Value*, 8> Args;
5207 // Loop through FunctionType's arguments and ensure they are specified
5208 // correctly. Also, gather any parameter attributes.
5209 FunctionType::param_iterator I = Ty->param_begin();
5210 FunctionType::param_iterator E = Ty->param_end();
5211 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5212 Type *ExpectedTy = nullptr;
5215 } else if (!Ty->isVarArg()) {
5216 return Error(ArgList[i].Loc, "too many arguments specified");
5219 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5220 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5221 getTypeString(ExpectedTy) + "'");
5222 Args.push_back(ArgList[i].V);
5223 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5224 AttrBuilder B(ArgList[i].Attrs, i + 1);
5225 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5230 return Error(CallLoc, "not enough parameters specified for call");
5232 if (FnAttrs.hasAttributes()) {
5233 if (FnAttrs.hasAlignmentAttr())
5234 return Error(CallLoc, "call instructions may not have an alignment");
5236 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5237 AttributeSet::FunctionIndex,
5241 // Finish off the Attribute and check them
5242 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5244 CallInst *CI = CallInst::Create(Ty, Callee, Args);
5245 CI->setTailCallKind(TCK);
5246 CI->setCallingConv(CC);
5247 CI->setAttributes(PAL);
5248 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5253 //===----------------------------------------------------------------------===//
5254 // Memory Instructions.
5255 //===----------------------------------------------------------------------===//
5258 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5259 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5260 Value *Size = nullptr;
5261 LocTy SizeLoc, TyLoc;
5262 unsigned Alignment = 0;
5265 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5267 if (ParseType(Ty, TyLoc)) return true;
5269 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5270 return Error(TyLoc, "invalid type for alloca");
5272 bool AteExtraComma = false;
5273 if (EatIfPresent(lltok::comma)) {
5274 if (Lex.getKind() == lltok::kw_align) {
5275 if (ParseOptionalAlignment(Alignment)) return true;
5276 } else if (Lex.getKind() == lltok::MetadataVar) {
5277 AteExtraComma = true;
5279 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5280 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5285 if (Size && !Size->getType()->isIntegerTy())
5286 return Error(SizeLoc, "element count must have integer type");
5288 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5289 AI->setUsedWithInAlloca(IsInAlloca);
5291 return AteExtraComma ? InstExtraComma : InstNormal;
5295 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5296 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
5297 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5298 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5299 Value *Val; LocTy Loc;
5300 unsigned Alignment = 0;
5301 bool AteExtraComma = false;
5302 bool isAtomic = false;
5303 AtomicOrdering Ordering = NotAtomic;
5304 SynchronizationScope Scope = CrossThread;
5306 if (Lex.getKind() == lltok::kw_atomic) {
5311 bool isVolatile = false;
5312 if (Lex.getKind() == lltok::kw_volatile) {
5318 LocTy ExplicitTypeLoc = Lex.getLoc();
5319 if (ParseType(Ty) ||
5320 ParseToken(lltok::comma, "expected comma after load's type") ||
5321 ParseTypeAndValue(Val, Loc, PFS) ||
5322 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5323 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5326 if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
5327 return Error(Loc, "load operand must be a pointer to a first class type");
5328 if (isAtomic && !Alignment)
5329 return Error(Loc, "atomic load must have explicit non-zero alignment");
5330 if (Ordering == Release || Ordering == AcquireRelease)
5331 return Error(Loc, "atomic load cannot use Release ordering");
5333 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5334 return Error(ExplicitTypeLoc,
5335 "explicit pointee type doesn't match operand's pointee type");
5337 Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
5338 return AteExtraComma ? InstExtraComma : InstNormal;
5343 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5344 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5345 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5346 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5347 Value *Val, *Ptr; LocTy Loc, PtrLoc;
5348 unsigned Alignment = 0;
5349 bool AteExtraComma = false;
5350 bool isAtomic = false;
5351 AtomicOrdering Ordering = NotAtomic;
5352 SynchronizationScope Scope = CrossThread;
5354 if (Lex.getKind() == lltok::kw_atomic) {
5359 bool isVolatile = false;
5360 if (Lex.getKind() == lltok::kw_volatile) {
5365 if (ParseTypeAndValue(Val, Loc, PFS) ||
5366 ParseToken(lltok::comma, "expected ',' after store operand") ||
5367 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5368 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5369 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5372 if (!Ptr->getType()->isPointerTy())
5373 return Error(PtrLoc, "store operand must be a pointer");
5374 if (!Val->getType()->isFirstClassType())
5375 return Error(Loc, "store operand must be a first class value");
5376 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5377 return Error(Loc, "stored value and pointer type do not match");
5378 if (isAtomic && !Alignment)
5379 return Error(Loc, "atomic store must have explicit non-zero alignment");
5380 if (Ordering == Acquire || Ordering == AcquireRelease)
5381 return Error(Loc, "atomic store cannot use Acquire ordering");
5383 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5384 return AteExtraComma ? InstExtraComma : InstNormal;
5388 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5389 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5390 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5391 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5392 bool AteExtraComma = false;
5393 AtomicOrdering SuccessOrdering = NotAtomic;
5394 AtomicOrdering FailureOrdering = NotAtomic;
5395 SynchronizationScope Scope = CrossThread;
5396 bool isVolatile = false;
5397 bool isWeak = false;
5399 if (EatIfPresent(lltok::kw_weak))
5402 if (EatIfPresent(lltok::kw_volatile))
5405 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5406 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5407 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5408 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5409 ParseTypeAndValue(New, NewLoc, PFS) ||
5410 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5411 ParseOrdering(FailureOrdering))
5414 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5415 return TokError("cmpxchg cannot be unordered");
5416 if (SuccessOrdering < FailureOrdering)
5417 return TokError("cmpxchg must be at least as ordered on success as failure");
5418 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5419 return TokError("cmpxchg failure ordering cannot include release semantics");
5420 if (!Ptr->getType()->isPointerTy())
5421 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5422 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5423 return Error(CmpLoc, "compare value and pointer type do not match");
5424 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5425 return Error(NewLoc, "new value and pointer type do not match");
5426 if (!New->getType()->isIntegerTy())
5427 return Error(NewLoc, "cmpxchg operand must be an integer");
5428 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5429 if (Size < 8 || (Size & (Size - 1)))
5430 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5433 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5434 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5435 CXI->setVolatile(isVolatile);
5436 CXI->setWeak(isWeak);
5438 return AteExtraComma ? InstExtraComma : InstNormal;
5442 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5443 /// 'singlethread'? AtomicOrdering
5444 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5445 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5446 bool AteExtraComma = false;
5447 AtomicOrdering Ordering = NotAtomic;
5448 SynchronizationScope Scope = CrossThread;
5449 bool isVolatile = false;
5450 AtomicRMWInst::BinOp Operation;
5452 if (EatIfPresent(lltok::kw_volatile))
5455 switch (Lex.getKind()) {
5456 default: return TokError("expected binary operation in atomicrmw");
5457 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5458 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5459 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5460 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5461 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5462 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5463 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5464 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5465 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5466 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5467 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5469 Lex.Lex(); // Eat the operation.
5471 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5472 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5473 ParseTypeAndValue(Val, ValLoc, PFS) ||
5474 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5477 if (Ordering == Unordered)
5478 return TokError("atomicrmw cannot be unordered");
5479 if (!Ptr->getType()->isPointerTy())
5480 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5481 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5482 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5483 if (!Val->getType()->isIntegerTy())
5484 return Error(ValLoc, "atomicrmw operand must be an integer");
5485 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5486 if (Size < 8 || (Size & (Size - 1)))
5487 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5490 AtomicRMWInst *RMWI =
5491 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5492 RMWI->setVolatile(isVolatile);
5494 return AteExtraComma ? InstExtraComma : InstNormal;
5498 /// ::= 'fence' 'singlethread'? AtomicOrdering
5499 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5500 AtomicOrdering Ordering = NotAtomic;
5501 SynchronizationScope Scope = CrossThread;
5502 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5505 if (Ordering == Unordered)
5506 return TokError("fence cannot be unordered");
5507 if (Ordering == Monotonic)
5508 return TokError("fence cannot be monotonic");
5510 Inst = new FenceInst(Context, Ordering, Scope);
5514 /// ParseGetElementPtr
5515 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5516 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5517 Value *Ptr = nullptr;
5518 Value *Val = nullptr;
5521 bool InBounds = EatIfPresent(lltok::kw_inbounds);
5524 LocTy ExplicitTypeLoc = Lex.getLoc();
5525 if (ParseType(Ty) ||
5526 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5527 ParseTypeAndValue(Ptr, Loc, PFS))
5530 Type *BaseType = Ptr->getType();
5531 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5532 if (!BasePointerType)
5533 return Error(Loc, "base of getelementptr must be a pointer");
5535 if (Ty != BasePointerType->getElementType())
5536 return Error(ExplicitTypeLoc,
5537 "explicit pointee type doesn't match operand's pointee type");
5539 SmallVector<Value*, 16> Indices;
5540 bool AteExtraComma = false;
5541 while (EatIfPresent(lltok::comma)) {
5542 if (Lex.getKind() == lltok::MetadataVar) {
5543 AteExtraComma = true;
5546 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5547 if (!Val->getType()->getScalarType()->isIntegerTy())
5548 return Error(EltLoc, "getelementptr index must be an integer");
5549 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5550 return Error(EltLoc, "getelementptr index type missmatch");
5551 if (Val->getType()->isVectorTy()) {
5552 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5553 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5554 if (ValNumEl != PtrNumEl)
5555 return Error(EltLoc,
5556 "getelementptr vector index has a wrong number of elements");
5558 Indices.push_back(Val);
5561 SmallPtrSet<const Type*, 4> Visited;
5562 if (!Indices.empty() && !Ty->isSized(&Visited))
5563 return Error(Loc, "base element of getelementptr must be sized");
5565 if (!GetElementPtrInst::getIndexedType(Ty, Indices))
5566 return Error(Loc, "invalid getelementptr indices");
5567 Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
5569 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5570 return AteExtraComma ? InstExtraComma : InstNormal;
5573 /// ParseExtractValue
5574 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
5575 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5576 Value *Val; LocTy Loc;
5577 SmallVector<unsigned, 4> Indices;
5579 if (ParseTypeAndValue(Val, Loc, PFS) ||
5580 ParseIndexList(Indices, AteExtraComma))
5583 if (!Val->getType()->isAggregateType())
5584 return Error(Loc, "extractvalue operand must be aggregate type");
5586 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5587 return Error(Loc, "invalid indices for extractvalue");
5588 Inst = ExtractValueInst::Create(Val, Indices);
5589 return AteExtraComma ? InstExtraComma : InstNormal;
5592 /// ParseInsertValue
5593 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5594 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5595 Value *Val0, *Val1; LocTy Loc0, Loc1;
5596 SmallVector<unsigned, 4> Indices;
5598 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5599 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5600 ParseTypeAndValue(Val1, Loc1, PFS) ||
5601 ParseIndexList(Indices, AteExtraComma))
5604 if (!Val0->getType()->isAggregateType())
5605 return Error(Loc0, "insertvalue operand must be aggregate type");
5607 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5609 return Error(Loc0, "invalid indices for insertvalue");
5610 if (IndexedType != Val1->getType())
5611 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5612 getTypeString(Val1->getType()) + "' instead of '" +
5613 getTypeString(IndexedType) + "'");
5614 Inst = InsertValueInst::Create(Val0, Val1, Indices);
5615 return AteExtraComma ? InstExtraComma : InstNormal;
5618 //===----------------------------------------------------------------------===//
5619 // Embedded metadata.
5620 //===----------------------------------------------------------------------===//
5622 /// ParseMDNodeVector
5623 /// ::= { Element (',' Element)* }
5625 /// ::= 'null' | TypeAndValue
5626 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5627 if (ParseToken(lltok::lbrace, "expected '{' here"))
5630 // Check for an empty list.
5631 if (EatIfPresent(lltok::rbrace))
5635 // Null is a special case since it is typeless.
5636 if (EatIfPresent(lltok::kw_null)) {
5637 Elts.push_back(nullptr);
5642 if (ParseMetadata(MD, nullptr))
5645 } while (EatIfPresent(lltok::comma));
5647 return ParseToken(lltok::rbrace, "expected end of metadata node");
5650 //===----------------------------------------------------------------------===//
5651 // Use-list order directives.
5652 //===----------------------------------------------------------------------===//
5653 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5656 return Error(Loc, "value has no uses");
5658 unsigned NumUses = 0;
5659 SmallDenseMap<const Use *, unsigned, 16> Order;
5660 for (const Use &U : V->uses()) {
5661 if (++NumUses > Indexes.size())
5663 Order[&U] = Indexes[NumUses - 1];
5666 return Error(Loc, "value only has one use");
5667 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5668 return Error(Loc, "wrong number of indexes, expected " +
5669 Twine(std::distance(V->use_begin(), V->use_end())));
5671 V->sortUseList([&](const Use &L, const Use &R) {
5672 return Order.lookup(&L) < Order.lookup(&R);
5677 /// ParseUseListOrderIndexes
5678 /// ::= '{' uint32 (',' uint32)+ '}'
5679 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5680 SMLoc Loc = Lex.getLoc();
5681 if (ParseToken(lltok::lbrace, "expected '{' here"))
5683 if (Lex.getKind() == lltok::rbrace)
5684 return Lex.Error("expected non-empty list of uselistorder indexes");
5686 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5687 // indexes should be distinct numbers in the range [0, size-1], and should
5689 unsigned Offset = 0;
5691 bool IsOrdered = true;
5692 assert(Indexes.empty() && "Expected empty order vector");
5695 if (ParseUInt32(Index))
5698 // Update consistency checks.
5699 Offset += Index - Indexes.size();
5700 Max = std::max(Max, Index);
5701 IsOrdered &= Index == Indexes.size();
5703 Indexes.push_back(Index);
5704 } while (EatIfPresent(lltok::comma));
5706 if (ParseToken(lltok::rbrace, "expected '}' here"))
5709 if (Indexes.size() < 2)
5710 return Error(Loc, "expected >= 2 uselistorder indexes");
5711 if (Offset != 0 || Max >= Indexes.size())
5712 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5714 return Error(Loc, "expected uselistorder indexes to change the order");
5719 /// ParseUseListOrder
5720 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5721 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5722 SMLoc Loc = Lex.getLoc();
5723 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5727 SmallVector<unsigned, 16> Indexes;
5728 if (ParseTypeAndValue(V, PFS) ||
5729 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5730 ParseUseListOrderIndexes(Indexes))
5733 return sortUseListOrder(V, Indexes, Loc);
5736 /// ParseUseListOrderBB
5737 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5738 bool LLParser::ParseUseListOrderBB() {
5739 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5740 SMLoc Loc = Lex.getLoc();
5744 SmallVector<unsigned, 16> Indexes;
5745 if (ParseValID(Fn) ||
5746 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5747 ParseValID(Label) ||
5748 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5749 ParseUseListOrderIndexes(Indexes))
5752 // Check the function.
5754 if (Fn.Kind == ValID::t_GlobalName)
5755 GV = M->getNamedValue(Fn.StrVal);
5756 else if (Fn.Kind == ValID::t_GlobalID)
5757 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5759 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5761 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5762 auto *F = dyn_cast<Function>(GV);
5764 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5765 if (F->isDeclaration())
5766 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5768 // Check the basic block.
5769 if (Label.Kind == ValID::t_LocalID)
5770 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5771 if (Label.Kind != ValID::t_LocalName)
5772 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5773 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5775 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5776 if (!isa<BasicBlock>(V))
5777 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5779 return sortUseListOrder(V, Indexes, Loc);