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 '{' ...
364 bool LLParser::ParseDefine() {
365 assert(Lex.getKind() == lltok::kw_define);
369 return ParseFunctionHeader(F, true) ||
370 ParseFunctionBody(*F);
376 bool LLParser::ParseGlobalType(bool &IsConstant) {
377 if (Lex.getKind() == lltok::kw_constant)
379 else if (Lex.getKind() == lltok::kw_global)
383 return TokError("expected 'global' or 'constant'");
389 /// ParseUnnamedGlobal:
390 /// OptionalVisibility ALIAS ...
391 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
392 /// ... -> global variable
393 /// GlobalID '=' OptionalVisibility ALIAS ...
394 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
395 /// ... -> global variable
396 bool LLParser::ParseUnnamedGlobal() {
397 unsigned VarID = NumberedVals.size();
399 LocTy NameLoc = Lex.getLoc();
401 // Handle the GlobalID form.
402 if (Lex.getKind() == lltok::GlobalID) {
403 if (Lex.getUIntVal() != VarID)
404 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
406 Lex.Lex(); // eat GlobalID;
408 if (ParseToken(lltok::equal, "expected '=' after name"))
413 unsigned Linkage, Visibility, DLLStorageClass;
414 GlobalVariable::ThreadLocalMode TLM;
416 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
417 ParseOptionalVisibility(Visibility) ||
418 ParseOptionalDLLStorageClass(DLLStorageClass) ||
419 ParseOptionalThreadLocal(TLM) ||
420 parseOptionalUnnamedAddr(UnnamedAddr))
423 if (Lex.getKind() != lltok::kw_alias)
424 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
425 DLLStorageClass, TLM, UnnamedAddr);
426 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
430 /// ParseNamedGlobal:
431 /// GlobalVar '=' OptionalVisibility ALIAS ...
432 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
433 /// ... -> global variable
434 bool LLParser::ParseNamedGlobal() {
435 assert(Lex.getKind() == lltok::GlobalVar);
436 LocTy NameLoc = Lex.getLoc();
437 std::string Name = Lex.getStrVal();
441 unsigned Linkage, Visibility, DLLStorageClass;
442 GlobalVariable::ThreadLocalMode TLM;
444 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
445 ParseOptionalLinkage(Linkage, HasLinkage) ||
446 ParseOptionalVisibility(Visibility) ||
447 ParseOptionalDLLStorageClass(DLLStorageClass) ||
448 ParseOptionalThreadLocal(TLM) ||
449 parseOptionalUnnamedAddr(UnnamedAddr))
452 if (Lex.getKind() != lltok::kw_alias)
453 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
454 DLLStorageClass, TLM, UnnamedAddr);
456 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
460 bool LLParser::parseComdat() {
461 assert(Lex.getKind() == lltok::ComdatVar);
462 std::string Name = Lex.getStrVal();
463 LocTy NameLoc = Lex.getLoc();
466 if (ParseToken(lltok::equal, "expected '=' here"))
469 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
470 return TokError("expected comdat type");
472 Comdat::SelectionKind SK;
473 switch (Lex.getKind()) {
475 return TokError("unknown selection kind");
479 case lltok::kw_exactmatch:
480 SK = Comdat::ExactMatch;
482 case lltok::kw_largest:
483 SK = Comdat::Largest;
485 case lltok::kw_noduplicates:
486 SK = Comdat::NoDuplicates;
488 case lltok::kw_samesize:
489 SK = Comdat::SameSize;
494 // See if the comdat was forward referenced, if so, use the comdat.
495 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
496 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
497 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
498 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
501 if (I != ComdatSymTab.end())
504 C = M->getOrInsertComdat(Name);
505 C->setSelectionKind(SK);
511 // ::= '!' STRINGCONSTANT
512 bool LLParser::ParseMDString(MDString *&Result) {
514 if (ParseStringConstant(Str)) return true;
515 llvm::UpgradeMDStringConstant(Str);
516 Result = MDString::get(Context, Str);
521 // ::= '!' MDNodeNumber
522 bool LLParser::ParseMDNodeID(MDNode *&Result) {
523 // !{ ..., !42, ... }
525 if (ParseUInt32(MID))
528 // If not a forward reference, just return it now.
529 if (NumberedMetadata.count(MID)) {
530 Result = NumberedMetadata[MID];
534 // Otherwise, create MDNode forward reference.
535 auto &FwdRef = ForwardRefMDNodes[MID];
536 FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), Lex.getLoc());
538 Result = FwdRef.first.get();
539 NumberedMetadata[MID].reset(Result);
543 /// ParseNamedMetadata:
544 /// !foo = !{ !1, !2 }
545 bool LLParser::ParseNamedMetadata() {
546 assert(Lex.getKind() == lltok::MetadataVar);
547 std::string Name = Lex.getStrVal();
550 if (ParseToken(lltok::equal, "expected '=' here") ||
551 ParseToken(lltok::exclaim, "Expected '!' here") ||
552 ParseToken(lltok::lbrace, "Expected '{' here"))
555 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
556 if (Lex.getKind() != lltok::rbrace)
558 if (ParseToken(lltok::exclaim, "Expected '!' here"))
562 if (ParseMDNodeID(N)) return true;
564 } while (EatIfPresent(lltok::comma));
566 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
572 /// ParseStandaloneMetadata:
574 bool LLParser::ParseStandaloneMetadata() {
575 assert(Lex.getKind() == lltok::exclaim);
577 unsigned MetadataID = 0;
580 if (ParseUInt32(MetadataID) ||
581 ParseToken(lltok::equal, "expected '=' here"))
584 // Detect common error, from old metadata syntax.
585 if (Lex.getKind() == lltok::Type)
586 return TokError("unexpected type in metadata definition");
588 bool IsDistinct = EatIfPresent(lltok::kw_distinct);
589 if (Lex.getKind() == lltok::MetadataVar) {
590 if (ParseSpecializedMDNode(Init, IsDistinct))
592 } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
593 ParseMDTuple(Init, IsDistinct))
596 // See if this was forward referenced, if so, handle it.
597 auto FI = ForwardRefMDNodes.find(MetadataID);
598 if (FI != ForwardRefMDNodes.end()) {
599 FI->second.first->replaceAllUsesWith(Init);
600 ForwardRefMDNodes.erase(FI);
602 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
604 if (NumberedMetadata.count(MetadataID))
605 return TokError("Metadata id is already used");
606 NumberedMetadata[MetadataID].reset(Init);
612 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
613 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
614 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
618 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
619 /// OptionalDLLStorageClass OptionalThreadLocal
620 /// OptionalUnNammedAddr 'alias' Aliasee
625 /// Everything through OptionalUnNammedAddr has already been parsed.
627 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
628 unsigned Visibility, unsigned DLLStorageClass,
629 GlobalVariable::ThreadLocalMode TLM,
631 assert(Lex.getKind() == lltok::kw_alias);
634 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
636 if(!GlobalAlias::isValidLinkage(Linkage))
637 return Error(NameLoc, "invalid linkage type for alias");
639 if (!isValidVisibilityForLinkage(Visibility, L))
640 return Error(NameLoc,
641 "symbol with local linkage must have default visibility");
644 LocTy AliaseeLoc = Lex.getLoc();
645 if (Lex.getKind() != lltok::kw_bitcast &&
646 Lex.getKind() != lltok::kw_getelementptr &&
647 Lex.getKind() != lltok::kw_addrspacecast &&
648 Lex.getKind() != lltok::kw_inttoptr) {
649 if (ParseGlobalTypeAndValue(Aliasee))
652 // The bitcast dest type is not present, it is implied by the dest type.
656 if (ID.Kind != ValID::t_Constant)
657 return Error(AliaseeLoc, "invalid aliasee");
658 Aliasee = ID.ConstantVal;
661 Type *AliaseeType = Aliasee->getType();
662 auto *PTy = dyn_cast<PointerType>(AliaseeType);
664 return Error(AliaseeLoc, "An alias must have pointer type");
665 Type *Ty = PTy->getElementType();
666 unsigned AddrSpace = PTy->getAddressSpace();
668 // Okay, create the alias but do not insert it into the module yet.
669 std::unique_ptr<GlobalAlias> GA(
670 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
671 Name, Aliasee, /*Parent*/ nullptr));
672 GA->setThreadLocalMode(TLM);
673 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
674 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
675 GA->setUnnamedAddr(UnnamedAddr);
677 // See if this value already exists in the symbol table. If so, it is either
678 // a redefinition or a definition of a forward reference.
679 if (GlobalValue *Val = M->getNamedValue(Name)) {
680 // See if this was a redefinition. If so, there is no entry in
682 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
683 I = ForwardRefVals.find(Name);
684 if (I == ForwardRefVals.end())
685 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
687 // Otherwise, this was a definition of forward ref. Verify that types
689 if (Val->getType() != GA->getType())
690 return Error(NameLoc,
691 "forward reference and definition of alias have different types");
693 // If they agree, just RAUW the old value with the alias and remove the
695 Val->replaceAllUsesWith(GA.get());
696 Val->eraseFromParent();
697 ForwardRefVals.erase(I);
700 // Insert into the module, we know its name won't collide now.
701 M->getAliasList().push_back(GA.get());
702 assert(GA->getName() == Name && "Should not be a name conflict!");
704 // The module owns this now
711 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
712 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
713 /// OptionalExternallyInitialized GlobalType Type Const
714 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
715 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
716 /// OptionalExternallyInitialized GlobalType Type Const
718 /// Everything up to and including OptionalUnNammedAddr has been parsed
721 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
722 unsigned Linkage, bool HasLinkage,
723 unsigned Visibility, unsigned DLLStorageClass,
724 GlobalVariable::ThreadLocalMode TLM,
726 if (!isValidVisibilityForLinkage(Visibility, Linkage))
727 return Error(NameLoc,
728 "symbol with local linkage must have default visibility");
731 bool IsConstant, IsExternallyInitialized;
732 LocTy IsExternallyInitializedLoc;
736 if (ParseOptionalAddrSpace(AddrSpace) ||
737 ParseOptionalToken(lltok::kw_externally_initialized,
738 IsExternallyInitialized,
739 &IsExternallyInitializedLoc) ||
740 ParseGlobalType(IsConstant) ||
741 ParseType(Ty, TyLoc))
744 // If the linkage is specified and is external, then no initializer is
746 Constant *Init = nullptr;
747 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
748 Linkage != GlobalValue::ExternalLinkage)) {
749 if (ParseGlobalValue(Ty, Init))
753 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
754 return Error(TyLoc, "invalid type for global variable");
756 GlobalValue *GVal = nullptr;
758 // See if the global was forward referenced, if so, use the global.
760 GVal = M->getNamedValue(Name);
762 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
763 return Error(NameLoc, "redefinition of global '@" + Name + "'");
766 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
767 I = ForwardRefValIDs.find(NumberedVals.size());
768 if (I != ForwardRefValIDs.end()) {
769 GVal = I->second.first;
770 ForwardRefValIDs.erase(I);
776 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
777 Name, nullptr, GlobalVariable::NotThreadLocal,
780 if (GVal->getType()->getElementType() != Ty)
782 "forward reference and definition of global have different types");
784 GV = cast<GlobalVariable>(GVal);
786 // Move the forward-reference to the correct spot in the module.
787 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
791 NumberedVals.push_back(GV);
793 // Set the parsed properties on the global.
795 GV->setInitializer(Init);
796 GV->setConstant(IsConstant);
797 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
798 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
799 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
800 GV->setExternallyInitialized(IsExternallyInitialized);
801 GV->setThreadLocalMode(TLM);
802 GV->setUnnamedAddr(UnnamedAddr);
804 // Parse attributes on the global.
805 while (Lex.getKind() == lltok::comma) {
808 if (Lex.getKind() == lltok::kw_section) {
810 GV->setSection(Lex.getStrVal());
811 if (ParseToken(lltok::StringConstant, "expected global section string"))
813 } else if (Lex.getKind() == lltok::kw_align) {
815 if (ParseOptionalAlignment(Alignment)) return true;
816 GV->setAlignment(Alignment);
819 if (parseOptionalComdat(Name, C))
824 return TokError("unknown global variable property!");
831 /// ParseUnnamedAttrGrp
832 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
833 bool LLParser::ParseUnnamedAttrGrp() {
834 assert(Lex.getKind() == lltok::kw_attributes);
835 LocTy AttrGrpLoc = Lex.getLoc();
838 if (Lex.getKind() != lltok::AttrGrpID)
839 return TokError("expected attribute group id");
841 unsigned VarID = Lex.getUIntVal();
842 std::vector<unsigned> unused;
846 if (ParseToken(lltok::equal, "expected '=' here") ||
847 ParseToken(lltok::lbrace, "expected '{' here") ||
848 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
850 ParseToken(lltok::rbrace, "expected end of attribute group"))
853 if (!NumberedAttrBuilders[VarID].hasAttributes())
854 return Error(AttrGrpLoc, "attribute group has no attributes");
859 /// ParseFnAttributeValuePairs
860 /// ::= <attr> | <attr> '=' <value>
861 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
862 std::vector<unsigned> &FwdRefAttrGrps,
863 bool inAttrGrp, LocTy &BuiltinLoc) {
864 bool HaveError = false;
869 lltok::Kind Token = Lex.getKind();
870 if (Token == lltok::kw_builtin)
871 BuiltinLoc = Lex.getLoc();
874 if (!inAttrGrp) return HaveError;
875 return Error(Lex.getLoc(), "unterminated attribute group");
880 case lltok::AttrGrpID: {
881 // Allow a function to reference an attribute group:
883 // define void @foo() #1 { ... }
887 "cannot have an attribute group reference in an attribute group");
889 unsigned AttrGrpNum = Lex.getUIntVal();
890 if (inAttrGrp) break;
892 // Save the reference to the attribute group. We'll fill it in later.
893 FwdRefAttrGrps.push_back(AttrGrpNum);
896 // Target-dependent attributes:
897 case lltok::StringConstant: {
898 std::string Attr = Lex.getStrVal();
901 if (EatIfPresent(lltok::equal) &&
902 ParseStringConstant(Val))
905 B.addAttribute(Attr, Val);
909 // Target-independent attributes:
910 case lltok::kw_align: {
911 // As a hack, we allow function alignment to be initially parsed as an
912 // attribute on a function declaration/definition or added to an attribute
913 // group and later moved to the alignment field.
917 if (ParseToken(lltok::equal, "expected '=' here") ||
918 ParseUInt32(Alignment))
921 if (ParseOptionalAlignment(Alignment))
924 B.addAlignmentAttr(Alignment);
927 case lltok::kw_alignstack: {
931 if (ParseToken(lltok::equal, "expected '=' here") ||
932 ParseUInt32(Alignment))
935 if (ParseOptionalStackAlignment(Alignment))
938 B.addStackAlignmentAttr(Alignment);
941 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
942 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
943 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
944 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
945 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
946 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
947 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
948 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
949 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
950 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
951 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
952 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
953 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
954 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
955 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
956 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
957 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
958 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
959 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
960 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
961 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
962 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
963 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
964 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
965 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
966 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
967 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
970 case lltok::kw_inreg:
971 case lltok::kw_signext:
972 case lltok::kw_zeroext:
975 "invalid use of attribute on a function");
977 case lltok::kw_byval:
978 case lltok::kw_dereferenceable:
979 case lltok::kw_inalloca:
981 case lltok::kw_noalias:
982 case lltok::kw_nocapture:
983 case lltok::kw_nonnull:
984 case lltok::kw_returned:
988 "invalid use of parameter-only attribute on a function");
996 //===----------------------------------------------------------------------===//
997 // GlobalValue Reference/Resolution Routines.
998 //===----------------------------------------------------------------------===//
1000 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1001 /// forward reference record if needed. This can return null if the value
1002 /// exists but does not have the right type.
1003 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1005 PointerType *PTy = dyn_cast<PointerType>(Ty);
1007 Error(Loc, "global variable reference must have pointer type");
1011 // Look this name up in the normal function symbol table.
1013 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1015 // If this is a forward reference for the value, see if we already created a
1016 // forward ref record.
1018 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1019 I = ForwardRefVals.find(Name);
1020 if (I != ForwardRefVals.end())
1021 Val = I->second.first;
1024 // If we have the value in the symbol table or fwd-ref table, return it.
1026 if (Val->getType() == Ty) return Val;
1027 Error(Loc, "'@" + Name + "' defined with type '" +
1028 getTypeString(Val->getType()) + "'");
1032 // Otherwise, create a new forward reference for this value and remember it.
1033 GlobalValue *FwdVal;
1034 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1035 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1037 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1038 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1039 nullptr, GlobalVariable::NotThreadLocal,
1040 PTy->getAddressSpace());
1042 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1046 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1047 PointerType *PTy = dyn_cast<PointerType>(Ty);
1049 Error(Loc, "global variable reference must have pointer type");
1053 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1055 // If this is a forward reference for the value, see if we already created a
1056 // forward ref record.
1058 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1059 I = ForwardRefValIDs.find(ID);
1060 if (I != ForwardRefValIDs.end())
1061 Val = I->second.first;
1064 // If we have the value in the symbol table or fwd-ref table, return it.
1066 if (Val->getType() == Ty) return Val;
1067 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1068 getTypeString(Val->getType()) + "'");
1072 // Otherwise, create a new forward reference for this value and remember it.
1073 GlobalValue *FwdVal;
1074 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1075 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1077 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1078 GlobalValue::ExternalWeakLinkage, nullptr, "");
1080 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1085 //===----------------------------------------------------------------------===//
1086 // Comdat Reference/Resolution Routines.
1087 //===----------------------------------------------------------------------===//
1089 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1090 // Look this name up in the comdat symbol table.
1091 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1092 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1093 if (I != ComdatSymTab.end())
1096 // Otherwise, create a new forward reference for this value and remember it.
1097 Comdat *C = M->getOrInsertComdat(Name);
1098 ForwardRefComdats[Name] = Loc;
1103 //===----------------------------------------------------------------------===//
1105 //===----------------------------------------------------------------------===//
1107 /// ParseToken - If the current token has the specified kind, eat it and return
1108 /// success. Otherwise, emit the specified error and return failure.
1109 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1110 if (Lex.getKind() != T)
1111 return TokError(ErrMsg);
1116 /// ParseStringConstant
1117 /// ::= StringConstant
1118 bool LLParser::ParseStringConstant(std::string &Result) {
1119 if (Lex.getKind() != lltok::StringConstant)
1120 return TokError("expected string constant");
1121 Result = Lex.getStrVal();
1128 bool LLParser::ParseUInt32(unsigned &Val) {
1129 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1130 return TokError("expected integer");
1131 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1132 if (Val64 != unsigned(Val64))
1133 return TokError("expected 32-bit integer (too large)");
1141 bool LLParser::ParseUInt64(uint64_t &Val) {
1142 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1143 return TokError("expected integer");
1144 Val = Lex.getAPSIntVal().getLimitedValue();
1150 /// := 'localdynamic'
1151 /// := 'initialexec'
1153 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1154 switch (Lex.getKind()) {
1156 return TokError("expected localdynamic, initialexec or localexec");
1157 case lltok::kw_localdynamic:
1158 TLM = GlobalVariable::LocalDynamicTLSModel;
1160 case lltok::kw_initialexec:
1161 TLM = GlobalVariable::InitialExecTLSModel;
1163 case lltok::kw_localexec:
1164 TLM = GlobalVariable::LocalExecTLSModel;
1172 /// ParseOptionalThreadLocal
1174 /// := 'thread_local'
1175 /// := 'thread_local' '(' tlsmodel ')'
1176 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1177 TLM = GlobalVariable::NotThreadLocal;
1178 if (!EatIfPresent(lltok::kw_thread_local))
1181 TLM = GlobalVariable::GeneralDynamicTLSModel;
1182 if (Lex.getKind() == lltok::lparen) {
1184 return ParseTLSModel(TLM) ||
1185 ParseToken(lltok::rparen, "expected ')' after thread local model");
1190 /// ParseOptionalAddrSpace
1192 /// := 'addrspace' '(' uint32 ')'
1193 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1195 if (!EatIfPresent(lltok::kw_addrspace))
1197 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1198 ParseUInt32(AddrSpace) ||
1199 ParseToken(lltok::rparen, "expected ')' in address space");
1202 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1203 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1204 bool HaveError = false;
1209 lltok::Kind Token = Lex.getKind();
1211 default: // End of attributes.
1213 case lltok::kw_align: {
1215 if (ParseOptionalAlignment(Alignment))
1217 B.addAlignmentAttr(Alignment);
1220 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1221 case lltok::kw_dereferenceable: {
1223 if (ParseOptionalDereferenceableBytes(Bytes))
1225 B.addDereferenceableAttr(Bytes);
1228 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1229 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1230 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1231 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1232 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1233 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1234 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1235 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1236 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1237 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1238 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1239 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1241 case lltok::kw_alignstack:
1242 case lltok::kw_alwaysinline:
1243 case lltok::kw_builtin:
1244 case lltok::kw_inlinehint:
1245 case lltok::kw_jumptable:
1246 case lltok::kw_minsize:
1247 case lltok::kw_naked:
1248 case lltok::kw_nobuiltin:
1249 case lltok::kw_noduplicate:
1250 case lltok::kw_noimplicitfloat:
1251 case lltok::kw_noinline:
1252 case lltok::kw_nonlazybind:
1253 case lltok::kw_noredzone:
1254 case lltok::kw_noreturn:
1255 case lltok::kw_nounwind:
1256 case lltok::kw_optnone:
1257 case lltok::kw_optsize:
1258 case lltok::kw_returns_twice:
1259 case lltok::kw_sanitize_address:
1260 case lltok::kw_sanitize_memory:
1261 case lltok::kw_sanitize_thread:
1263 case lltok::kw_sspreq:
1264 case lltok::kw_sspstrong:
1265 case lltok::kw_uwtable:
1266 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1274 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1275 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1276 bool HaveError = false;
1281 lltok::Kind Token = Lex.getKind();
1283 default: // End of attributes.
1285 case lltok::kw_dereferenceable: {
1287 if (ParseOptionalDereferenceableBytes(Bytes))
1289 B.addDereferenceableAttr(Bytes);
1292 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1293 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1294 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1295 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1296 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1299 case lltok::kw_align:
1300 case lltok::kw_byval:
1301 case lltok::kw_inalloca:
1302 case lltok::kw_nest:
1303 case lltok::kw_nocapture:
1304 case lltok::kw_returned:
1305 case lltok::kw_sret:
1306 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1309 case lltok::kw_alignstack:
1310 case lltok::kw_alwaysinline:
1311 case lltok::kw_builtin:
1312 case lltok::kw_cold:
1313 case lltok::kw_inlinehint:
1314 case lltok::kw_jumptable:
1315 case lltok::kw_minsize:
1316 case lltok::kw_naked:
1317 case lltok::kw_nobuiltin:
1318 case lltok::kw_noduplicate:
1319 case lltok::kw_noimplicitfloat:
1320 case lltok::kw_noinline:
1321 case lltok::kw_nonlazybind:
1322 case lltok::kw_noredzone:
1323 case lltok::kw_noreturn:
1324 case lltok::kw_nounwind:
1325 case lltok::kw_optnone:
1326 case lltok::kw_optsize:
1327 case lltok::kw_returns_twice:
1328 case lltok::kw_sanitize_address:
1329 case lltok::kw_sanitize_memory:
1330 case lltok::kw_sanitize_thread:
1332 case lltok::kw_sspreq:
1333 case lltok::kw_sspstrong:
1334 case lltok::kw_uwtable:
1335 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1338 case lltok::kw_readnone:
1339 case lltok::kw_readonly:
1340 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1347 /// ParseOptionalLinkage
1354 /// ::= 'linkonce_odr'
1355 /// ::= 'available_externally'
1358 /// ::= 'extern_weak'
1360 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1362 switch (Lex.getKind()) {
1363 default: Res=GlobalValue::ExternalLinkage; return false;
1364 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1365 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1366 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1367 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1368 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1369 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1370 case lltok::kw_available_externally:
1371 Res = GlobalValue::AvailableExternallyLinkage;
1373 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1374 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1375 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1376 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1383 /// ParseOptionalVisibility
1389 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1390 switch (Lex.getKind()) {
1391 default: Res = GlobalValue::DefaultVisibility; return false;
1392 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1393 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1394 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1400 /// ParseOptionalDLLStorageClass
1405 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1406 switch (Lex.getKind()) {
1407 default: Res = GlobalValue::DefaultStorageClass; return false;
1408 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1409 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1415 /// ParseOptionalCallingConv
1419 /// ::= 'intel_ocl_bicc'
1421 /// ::= 'x86_stdcallcc'
1422 /// ::= 'x86_fastcallcc'
1423 /// ::= 'x86_thiscallcc'
1424 /// ::= 'x86_vectorcallcc'
1425 /// ::= 'arm_apcscc'
1426 /// ::= 'arm_aapcscc'
1427 /// ::= 'arm_aapcs_vfpcc'
1428 /// ::= 'msp430_intrcc'
1429 /// ::= 'ptx_kernel'
1430 /// ::= 'ptx_device'
1432 /// ::= 'spir_kernel'
1433 /// ::= 'x86_64_sysvcc'
1434 /// ::= 'x86_64_win64cc'
1435 /// ::= 'webkit_jscc'
1437 /// ::= 'preserve_mostcc'
1438 /// ::= 'preserve_allcc'
1442 bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
1443 switch (Lex.getKind()) {
1444 default: CC = CallingConv::C; return false;
1445 case lltok::kw_ccc: CC = CallingConv::C; break;
1446 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1447 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1448 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1449 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1450 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1451 case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
1452 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1453 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1454 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1455 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1456 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1457 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1458 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1459 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1460 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1461 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1462 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1463 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1464 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1465 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1466 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1467 case lltok::kw_ghccc: CC = CallingConv::GHC; break;
1468 case lltok::kw_cc: {
1470 return ParseUInt32(CC);
1478 /// ParseInstructionMetadata
1479 /// ::= !dbg !42 (',' !dbg !57)*
1480 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1481 PerFunctionState *PFS) {
1483 if (Lex.getKind() != lltok::MetadataVar)
1484 return TokError("expected metadata after comma");
1486 std::string Name = Lex.getStrVal();
1487 unsigned MDK = M->getMDKindID(Name);
1494 Inst->setMetadata(MDK, N);
1495 if (MDK == LLVMContext::MD_tbaa)
1496 InstsWithTBAATag.push_back(Inst);
1498 // If this is the end of the list, we're done.
1499 } while (EatIfPresent(lltok::comma));
1503 /// ParseOptionalAlignment
1506 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1508 if (!EatIfPresent(lltok::kw_align))
1510 LocTy AlignLoc = Lex.getLoc();
1511 if (ParseUInt32(Alignment)) return true;
1512 if (!isPowerOf2_32(Alignment))
1513 return Error(AlignLoc, "alignment is not a power of two");
1514 if (Alignment > Value::MaximumAlignment)
1515 return Error(AlignLoc, "huge alignments are not supported yet");
1519 /// ParseOptionalDereferenceableBytes
1521 /// ::= 'dereferenceable' '(' 4 ')'
1522 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1524 if (!EatIfPresent(lltok::kw_dereferenceable))
1526 LocTy ParenLoc = Lex.getLoc();
1527 if (!EatIfPresent(lltok::lparen))
1528 return Error(ParenLoc, "expected '('");
1529 LocTy DerefLoc = Lex.getLoc();
1530 if (ParseUInt64(Bytes)) return true;
1531 ParenLoc = Lex.getLoc();
1532 if (!EatIfPresent(lltok::rparen))
1533 return Error(ParenLoc, "expected ')'");
1535 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1539 /// ParseOptionalCommaAlign
1543 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1545 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1546 bool &AteExtraComma) {
1547 AteExtraComma = false;
1548 while (EatIfPresent(lltok::comma)) {
1549 // Metadata at the end is an early exit.
1550 if (Lex.getKind() == lltok::MetadataVar) {
1551 AteExtraComma = true;
1555 if (Lex.getKind() != lltok::kw_align)
1556 return Error(Lex.getLoc(), "expected metadata or 'align'");
1558 if (ParseOptionalAlignment(Alignment)) return true;
1564 /// ParseScopeAndOrdering
1565 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1568 /// This sets Scope and Ordering to the parsed values.
1569 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1570 AtomicOrdering &Ordering) {
1574 Scope = CrossThread;
1575 if (EatIfPresent(lltok::kw_singlethread))
1576 Scope = SingleThread;
1578 return ParseOrdering(Ordering);
1582 /// ::= AtomicOrdering
1584 /// This sets Ordering to the parsed value.
1585 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1586 switch (Lex.getKind()) {
1587 default: return TokError("Expected ordering on atomic instruction");
1588 case lltok::kw_unordered: Ordering = Unordered; break;
1589 case lltok::kw_monotonic: Ordering = Monotonic; break;
1590 case lltok::kw_acquire: Ordering = Acquire; break;
1591 case lltok::kw_release: Ordering = Release; break;
1592 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1593 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1599 /// ParseOptionalStackAlignment
1601 /// ::= 'alignstack' '(' 4 ')'
1602 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1604 if (!EatIfPresent(lltok::kw_alignstack))
1606 LocTy ParenLoc = Lex.getLoc();
1607 if (!EatIfPresent(lltok::lparen))
1608 return Error(ParenLoc, "expected '('");
1609 LocTy AlignLoc = Lex.getLoc();
1610 if (ParseUInt32(Alignment)) return true;
1611 ParenLoc = Lex.getLoc();
1612 if (!EatIfPresent(lltok::rparen))
1613 return Error(ParenLoc, "expected ')'");
1614 if (!isPowerOf2_32(Alignment))
1615 return Error(AlignLoc, "stack alignment is not a power of two");
1619 /// ParseIndexList - This parses the index list for an insert/extractvalue
1620 /// instruction. This sets AteExtraComma in the case where we eat an extra
1621 /// comma at the end of the line and find that it is followed by metadata.
1622 /// Clients that don't allow metadata can call the version of this function that
1623 /// only takes one argument.
1626 /// ::= (',' uint32)+
1628 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1629 bool &AteExtraComma) {
1630 AteExtraComma = false;
1632 if (Lex.getKind() != lltok::comma)
1633 return TokError("expected ',' as start of index list");
1635 while (EatIfPresent(lltok::comma)) {
1636 if (Lex.getKind() == lltok::MetadataVar) {
1637 if (Indices.empty()) return TokError("expected index");
1638 AteExtraComma = true;
1642 if (ParseUInt32(Idx)) return true;
1643 Indices.push_back(Idx);
1649 //===----------------------------------------------------------------------===//
1651 //===----------------------------------------------------------------------===//
1653 /// ParseType - Parse a type.
1654 bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
1655 SMLoc TypeLoc = Lex.getLoc();
1656 switch (Lex.getKind()) {
1658 return TokError(Msg);
1660 // Type ::= 'float' | 'void' (etc)
1661 Result = Lex.getTyVal();
1665 // Type ::= StructType
1666 if (ParseAnonStructType(Result, false))
1669 case lltok::lsquare:
1670 // Type ::= '[' ... ']'
1671 Lex.Lex(); // eat the lsquare.
1672 if (ParseArrayVectorType(Result, false))
1675 case lltok::less: // Either vector or packed struct.
1676 // Type ::= '<' ... '>'
1678 if (Lex.getKind() == lltok::lbrace) {
1679 if (ParseAnonStructType(Result, true) ||
1680 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1682 } else if (ParseArrayVectorType(Result, true))
1685 case lltok::LocalVar: {
1687 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1689 // If the type hasn't been defined yet, create a forward definition and
1690 // remember where that forward def'n was seen (in case it never is defined).
1692 Entry.first = StructType::create(Context, Lex.getStrVal());
1693 Entry.second = Lex.getLoc();
1695 Result = Entry.first;
1700 case lltok::LocalVarID: {
1702 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1704 // If the type hasn't been defined yet, create a forward definition and
1705 // remember where that forward def'n was seen (in case it never is defined).
1707 Entry.first = StructType::create(Context);
1708 Entry.second = Lex.getLoc();
1710 Result = Entry.first;
1716 // Parse the type suffixes.
1718 switch (Lex.getKind()) {
1721 if (!AllowVoid && Result->isVoidTy())
1722 return Error(TypeLoc, "void type only allowed for function results");
1725 // Type ::= Type '*'
1727 if (Result->isLabelTy())
1728 return TokError("basic block pointers are invalid");
1729 if (Result->isVoidTy())
1730 return TokError("pointers to void are invalid - use i8* instead");
1731 if (!PointerType::isValidElementType(Result))
1732 return TokError("pointer to this type is invalid");
1733 Result = PointerType::getUnqual(Result);
1737 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1738 case lltok::kw_addrspace: {
1739 if (Result->isLabelTy())
1740 return TokError("basic block pointers are invalid");
1741 if (Result->isVoidTy())
1742 return TokError("pointers to void are invalid; use i8* instead");
1743 if (!PointerType::isValidElementType(Result))
1744 return TokError("pointer to this type is invalid");
1746 if (ParseOptionalAddrSpace(AddrSpace) ||
1747 ParseToken(lltok::star, "expected '*' in address space"))
1750 Result = PointerType::get(Result, AddrSpace);
1754 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1756 if (ParseFunctionType(Result))
1763 /// ParseParameterList
1765 /// ::= '(' Arg (',' Arg)* ')'
1767 /// ::= Type OptionalAttributes Value OptionalAttributes
1768 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1769 PerFunctionState &PFS, bool IsMustTailCall,
1770 bool InVarArgsFunc) {
1771 if (ParseToken(lltok::lparen, "expected '(' in call"))
1774 unsigned AttrIndex = 1;
1775 while (Lex.getKind() != lltok::rparen) {
1776 // If this isn't the first argument, we need a comma.
1777 if (!ArgList.empty() &&
1778 ParseToken(lltok::comma, "expected ',' in argument list"))
1781 // Parse an ellipsis if this is a musttail call in a variadic function.
1782 if (Lex.getKind() == lltok::dotdotdot) {
1783 const char *Msg = "unexpected ellipsis in argument list for ";
1784 if (!IsMustTailCall)
1785 return TokError(Twine(Msg) + "non-musttail call");
1787 return TokError(Twine(Msg) + "musttail call in non-varargs function");
1788 Lex.Lex(); // Lex the '...', it is purely for readability.
1789 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1792 // Parse the argument.
1794 Type *ArgTy = nullptr;
1795 AttrBuilder ArgAttrs;
1797 if (ParseType(ArgTy, ArgLoc))
1800 if (ArgTy->isMetadataTy()) {
1801 if (ParseMetadataAsValue(V, PFS))
1804 // Otherwise, handle normal operands.
1805 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1808 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1813 if (IsMustTailCall && InVarArgsFunc)
1814 return TokError("expected '...' at end of argument list for musttail call "
1815 "in varargs function");
1817 Lex.Lex(); // Lex the ')'.
1823 /// ParseArgumentList - Parse the argument list for a function type or function
1825 /// ::= '(' ArgTypeListI ')'
1829 /// ::= ArgTypeList ',' '...'
1830 /// ::= ArgType (',' ArgType)*
1832 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1835 assert(Lex.getKind() == lltok::lparen);
1836 Lex.Lex(); // eat the (.
1838 if (Lex.getKind() == lltok::rparen) {
1840 } else if (Lex.getKind() == lltok::dotdotdot) {
1844 LocTy TypeLoc = Lex.getLoc();
1845 Type *ArgTy = nullptr;
1849 if (ParseType(ArgTy) ||
1850 ParseOptionalParamAttrs(Attrs)) return true;
1852 if (ArgTy->isVoidTy())
1853 return Error(TypeLoc, "argument can not have void type");
1855 if (Lex.getKind() == lltok::LocalVar) {
1856 Name = Lex.getStrVal();
1860 if (!FunctionType::isValidArgumentType(ArgTy))
1861 return Error(TypeLoc, "invalid type for function argument");
1863 unsigned AttrIndex = 1;
1864 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1865 AttributeSet::get(ArgTy->getContext(),
1866 AttrIndex++, Attrs), Name));
1868 while (EatIfPresent(lltok::comma)) {
1869 // Handle ... at end of arg list.
1870 if (EatIfPresent(lltok::dotdotdot)) {
1875 // Otherwise must be an argument type.
1876 TypeLoc = Lex.getLoc();
1877 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1879 if (ArgTy->isVoidTy())
1880 return Error(TypeLoc, "argument can not have void type");
1882 if (Lex.getKind() == lltok::LocalVar) {
1883 Name = Lex.getStrVal();
1889 if (!ArgTy->isFirstClassType())
1890 return Error(TypeLoc, "invalid type for function argument");
1892 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1893 AttributeSet::get(ArgTy->getContext(),
1894 AttrIndex++, Attrs),
1899 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1902 /// ParseFunctionType
1903 /// ::= Type ArgumentList OptionalAttrs
1904 bool LLParser::ParseFunctionType(Type *&Result) {
1905 assert(Lex.getKind() == lltok::lparen);
1907 if (!FunctionType::isValidReturnType(Result))
1908 return TokError("invalid function return type");
1910 SmallVector<ArgInfo, 8> ArgList;
1912 if (ParseArgumentList(ArgList, isVarArg))
1915 // Reject names on the arguments lists.
1916 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1917 if (!ArgList[i].Name.empty())
1918 return Error(ArgList[i].Loc, "argument name invalid in function type");
1919 if (ArgList[i].Attrs.hasAttributes(i + 1))
1920 return Error(ArgList[i].Loc,
1921 "argument attributes invalid in function type");
1924 SmallVector<Type*, 16> ArgListTy;
1925 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1926 ArgListTy.push_back(ArgList[i].Ty);
1928 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1932 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1934 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1935 SmallVector<Type*, 8> Elts;
1936 if (ParseStructBody(Elts)) return true;
1938 Result = StructType::get(Context, Elts, Packed);
1942 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1943 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1944 std::pair<Type*, LocTy> &Entry,
1946 // If the type was already defined, diagnose the redefinition.
1947 if (Entry.first && !Entry.second.isValid())
1948 return Error(TypeLoc, "redefinition of type");
1950 // If we have opaque, just return without filling in the definition for the
1951 // struct. This counts as a definition as far as the .ll file goes.
1952 if (EatIfPresent(lltok::kw_opaque)) {
1953 // This type is being defined, so clear the location to indicate this.
1954 Entry.second = SMLoc();
1956 // If this type number has never been uttered, create it.
1958 Entry.first = StructType::create(Context, Name);
1959 ResultTy = Entry.first;
1963 // If the type starts with '<', then it is either a packed struct or a vector.
1964 bool isPacked = EatIfPresent(lltok::less);
1966 // If we don't have a struct, then we have a random type alias, which we
1967 // accept for compatibility with old files. These types are not allowed to be
1968 // forward referenced and not allowed to be recursive.
1969 if (Lex.getKind() != lltok::lbrace) {
1971 return Error(TypeLoc, "forward references to non-struct type");
1975 return ParseArrayVectorType(ResultTy, true);
1976 return ParseType(ResultTy);
1979 // This type is being defined, so clear the location to indicate this.
1980 Entry.second = SMLoc();
1982 // If this type number has never been uttered, create it.
1984 Entry.first = StructType::create(Context, Name);
1986 StructType *STy = cast<StructType>(Entry.first);
1988 SmallVector<Type*, 8> Body;
1989 if (ParseStructBody(Body) ||
1990 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1993 STy->setBody(Body, isPacked);
1999 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2002 /// ::= '{' Type (',' Type)* '}'
2003 /// ::= '<' '{' '}' '>'
2004 /// ::= '<' '{' Type (',' Type)* '}' '>'
2005 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2006 assert(Lex.getKind() == lltok::lbrace);
2007 Lex.Lex(); // Consume the '{'
2009 // Handle the empty struct.
2010 if (EatIfPresent(lltok::rbrace))
2013 LocTy EltTyLoc = Lex.getLoc();
2015 if (ParseType(Ty)) return true;
2018 if (!StructType::isValidElementType(Ty))
2019 return Error(EltTyLoc, "invalid element type for struct");
2021 while (EatIfPresent(lltok::comma)) {
2022 EltTyLoc = Lex.getLoc();
2023 if (ParseType(Ty)) return true;
2025 if (!StructType::isValidElementType(Ty))
2026 return Error(EltTyLoc, "invalid element type for struct");
2031 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2034 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2035 /// token has already been consumed.
2037 /// ::= '[' APSINTVAL 'x' Types ']'
2038 /// ::= '<' APSINTVAL 'x' Types '>'
2039 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2040 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2041 Lex.getAPSIntVal().getBitWidth() > 64)
2042 return TokError("expected number in address space");
2044 LocTy SizeLoc = Lex.getLoc();
2045 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2048 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2051 LocTy TypeLoc = Lex.getLoc();
2052 Type *EltTy = nullptr;
2053 if (ParseType(EltTy)) return true;
2055 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2056 "expected end of sequential type"))
2061 return Error(SizeLoc, "zero element vector is illegal");
2062 if ((unsigned)Size != Size)
2063 return Error(SizeLoc, "size too large for vector");
2064 if (!VectorType::isValidElementType(EltTy))
2065 return Error(TypeLoc, "invalid vector element type");
2066 Result = VectorType::get(EltTy, unsigned(Size));
2068 if (!ArrayType::isValidElementType(EltTy))
2069 return Error(TypeLoc, "invalid array element type");
2070 Result = ArrayType::get(EltTy, Size);
2075 //===----------------------------------------------------------------------===//
2076 // Function Semantic Analysis.
2077 //===----------------------------------------------------------------------===//
2079 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2081 : P(p), F(f), FunctionNumber(functionNumber) {
2083 // Insert unnamed arguments into the NumberedVals list.
2084 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2087 NumberedVals.push_back(AI);
2090 LLParser::PerFunctionState::~PerFunctionState() {
2091 // If there were any forward referenced non-basicblock values, delete them.
2092 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2093 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2094 if (!isa<BasicBlock>(I->second.first)) {
2095 I->second.first->replaceAllUsesWith(
2096 UndefValue::get(I->second.first->getType()));
2097 delete I->second.first;
2098 I->second.first = nullptr;
2101 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2102 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2103 if (!isa<BasicBlock>(I->second.first)) {
2104 I->second.first->replaceAllUsesWith(
2105 UndefValue::get(I->second.first->getType()));
2106 delete I->second.first;
2107 I->second.first = nullptr;
2111 bool LLParser::PerFunctionState::FinishFunction() {
2112 if (!ForwardRefVals.empty())
2113 return P.Error(ForwardRefVals.begin()->second.second,
2114 "use of undefined value '%" + ForwardRefVals.begin()->first +
2116 if (!ForwardRefValIDs.empty())
2117 return P.Error(ForwardRefValIDs.begin()->second.second,
2118 "use of undefined value '%" +
2119 Twine(ForwardRefValIDs.begin()->first) + "'");
2124 /// GetVal - Get a value with the specified name or ID, creating a
2125 /// forward reference record if needed. This can return null if the value
2126 /// exists but does not have the right type.
2127 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2128 Type *Ty, LocTy Loc) {
2129 // Look this name up in the normal function symbol table.
2130 Value *Val = F.getValueSymbolTable().lookup(Name);
2132 // If this is a forward reference for the value, see if we already created a
2133 // forward ref record.
2135 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2136 I = ForwardRefVals.find(Name);
2137 if (I != ForwardRefVals.end())
2138 Val = I->second.first;
2141 // If we have the value in the symbol table or fwd-ref table, return it.
2143 if (Val->getType() == Ty) return Val;
2144 if (Ty->isLabelTy())
2145 P.Error(Loc, "'%" + Name + "' is not a basic block");
2147 P.Error(Loc, "'%" + Name + "' defined with type '" +
2148 getTypeString(Val->getType()) + "'");
2152 // Don't make placeholders with invalid type.
2153 if (!Ty->isFirstClassType()) {
2154 P.Error(Loc, "invalid use of a non-first-class type");
2158 // Otherwise, create a new forward reference for this value and remember it.
2160 if (Ty->isLabelTy())
2161 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2163 FwdVal = new Argument(Ty, Name);
2165 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2169 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2171 // Look this name up in the normal function symbol table.
2172 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2174 // If this is a forward reference for the value, see if we already created a
2175 // forward ref record.
2177 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2178 I = ForwardRefValIDs.find(ID);
2179 if (I != ForwardRefValIDs.end())
2180 Val = I->second.first;
2183 // If we have the value in the symbol table or fwd-ref table, return it.
2185 if (Val->getType() == Ty) return Val;
2186 if (Ty->isLabelTy())
2187 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2189 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2190 getTypeString(Val->getType()) + "'");
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(), "", &F);
2204 FwdVal = new Argument(Ty);
2206 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2210 /// SetInstName - After an instruction is parsed and inserted into its
2211 /// basic block, this installs its name.
2212 bool LLParser::PerFunctionState::SetInstName(int NameID,
2213 const std::string &NameStr,
2214 LocTy NameLoc, Instruction *Inst) {
2215 // If this instruction has void type, it cannot have a name or ID specified.
2216 if (Inst->getType()->isVoidTy()) {
2217 if (NameID != -1 || !NameStr.empty())
2218 return P.Error(NameLoc, "instructions returning void cannot have a name");
2222 // If this was a numbered instruction, verify that the instruction is the
2223 // expected value and resolve any forward references.
2224 if (NameStr.empty()) {
2225 // If neither a name nor an ID was specified, just use the next ID.
2227 NameID = NumberedVals.size();
2229 if (unsigned(NameID) != NumberedVals.size())
2230 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2231 Twine(NumberedVals.size()) + "'");
2233 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2234 ForwardRefValIDs.find(NameID);
2235 if (FI != ForwardRefValIDs.end()) {
2236 if (FI->second.first->getType() != Inst->getType())
2237 return P.Error(NameLoc, "instruction forward referenced with type '" +
2238 getTypeString(FI->second.first->getType()) + "'");
2239 FI->second.first->replaceAllUsesWith(Inst);
2240 delete FI->second.first;
2241 ForwardRefValIDs.erase(FI);
2244 NumberedVals.push_back(Inst);
2248 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2249 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2250 FI = ForwardRefVals.find(NameStr);
2251 if (FI != ForwardRefVals.end()) {
2252 if (FI->second.first->getType() != Inst->getType())
2253 return P.Error(NameLoc, "instruction forward referenced with type '" +
2254 getTypeString(FI->second.first->getType()) + "'");
2255 FI->second.first->replaceAllUsesWith(Inst);
2256 delete FI->second.first;
2257 ForwardRefVals.erase(FI);
2260 // Set the name on the instruction.
2261 Inst->setName(NameStr);
2263 if (Inst->getName() != NameStr)
2264 return P.Error(NameLoc, "multiple definition of local value named '" +
2269 /// GetBB - Get a basic block with the specified name or ID, creating a
2270 /// forward reference record if needed.
2271 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2273 return dyn_cast_or_null<BasicBlock>(GetVal(Name,
2274 Type::getLabelTy(F.getContext()), Loc));
2277 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2278 return dyn_cast_or_null<BasicBlock>(GetVal(ID,
2279 Type::getLabelTy(F.getContext()), Loc));
2282 /// DefineBB - Define the specified basic block, which is either named or
2283 /// unnamed. If there is an error, this returns null otherwise it returns
2284 /// the block being defined.
2285 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2289 BB = GetBB(NumberedVals.size(), Loc);
2291 BB = GetBB(Name, Loc);
2292 if (!BB) return nullptr; // Already diagnosed error.
2294 // Move the block to the end of the function. Forward ref'd blocks are
2295 // inserted wherever they happen to be referenced.
2296 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2298 // Remove the block from forward ref sets.
2300 ForwardRefValIDs.erase(NumberedVals.size());
2301 NumberedVals.push_back(BB);
2303 // BB forward references are already in the function symbol table.
2304 ForwardRefVals.erase(Name);
2310 //===----------------------------------------------------------------------===//
2312 //===----------------------------------------------------------------------===//
2314 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2315 /// type implied. For example, if we parse "4" we don't know what integer type
2316 /// it has. The value will later be combined with its type and checked for
2317 /// sanity. PFS is used to convert function-local operands of metadata (since
2318 /// metadata operands are not just parsed here but also converted to values).
2319 /// PFS can be null when we are not parsing metadata values inside a function.
2320 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2321 ID.Loc = Lex.getLoc();
2322 switch (Lex.getKind()) {
2323 default: return TokError("expected value token");
2324 case lltok::GlobalID: // @42
2325 ID.UIntVal = Lex.getUIntVal();
2326 ID.Kind = ValID::t_GlobalID;
2328 case lltok::GlobalVar: // @foo
2329 ID.StrVal = Lex.getStrVal();
2330 ID.Kind = ValID::t_GlobalName;
2332 case lltok::LocalVarID: // %42
2333 ID.UIntVal = Lex.getUIntVal();
2334 ID.Kind = ValID::t_LocalID;
2336 case lltok::LocalVar: // %foo
2337 ID.StrVal = Lex.getStrVal();
2338 ID.Kind = ValID::t_LocalName;
2341 ID.APSIntVal = Lex.getAPSIntVal();
2342 ID.Kind = ValID::t_APSInt;
2344 case lltok::APFloat:
2345 ID.APFloatVal = Lex.getAPFloatVal();
2346 ID.Kind = ValID::t_APFloat;
2348 case lltok::kw_true:
2349 ID.ConstantVal = ConstantInt::getTrue(Context);
2350 ID.Kind = ValID::t_Constant;
2352 case lltok::kw_false:
2353 ID.ConstantVal = ConstantInt::getFalse(Context);
2354 ID.Kind = ValID::t_Constant;
2356 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2357 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2358 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2360 case lltok::lbrace: {
2361 // ValID ::= '{' ConstVector '}'
2363 SmallVector<Constant*, 16> Elts;
2364 if (ParseGlobalValueVector(Elts) ||
2365 ParseToken(lltok::rbrace, "expected end of struct constant"))
2368 ID.ConstantStructElts = new Constant*[Elts.size()];
2369 ID.UIntVal = Elts.size();
2370 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2371 ID.Kind = ValID::t_ConstantStruct;
2375 // ValID ::= '<' ConstVector '>' --> Vector.
2376 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2378 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2380 SmallVector<Constant*, 16> Elts;
2381 LocTy FirstEltLoc = Lex.getLoc();
2382 if (ParseGlobalValueVector(Elts) ||
2384 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2385 ParseToken(lltok::greater, "expected end of constant"))
2388 if (isPackedStruct) {
2389 ID.ConstantStructElts = new Constant*[Elts.size()];
2390 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2391 ID.UIntVal = Elts.size();
2392 ID.Kind = ValID::t_PackedConstantStruct;
2397 return Error(ID.Loc, "constant vector must not be empty");
2399 if (!Elts[0]->getType()->isIntegerTy() &&
2400 !Elts[0]->getType()->isFloatingPointTy() &&
2401 !Elts[0]->getType()->isPointerTy())
2402 return Error(FirstEltLoc,
2403 "vector elements must have integer, pointer or floating point type");
2405 // Verify that all the vector elements have the same type.
2406 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2407 if (Elts[i]->getType() != Elts[0]->getType())
2408 return Error(FirstEltLoc,
2409 "vector element #" + Twine(i) +
2410 " is not of type '" + getTypeString(Elts[0]->getType()));
2412 ID.ConstantVal = ConstantVector::get(Elts);
2413 ID.Kind = ValID::t_Constant;
2416 case lltok::lsquare: { // Array Constant
2418 SmallVector<Constant*, 16> Elts;
2419 LocTy FirstEltLoc = Lex.getLoc();
2420 if (ParseGlobalValueVector(Elts) ||
2421 ParseToken(lltok::rsquare, "expected end of array constant"))
2424 // Handle empty element.
2426 // Use undef instead of an array because it's inconvenient to determine
2427 // the element type at this point, there being no elements to examine.
2428 ID.Kind = ValID::t_EmptyArray;
2432 if (!Elts[0]->getType()->isFirstClassType())
2433 return Error(FirstEltLoc, "invalid array element type: " +
2434 getTypeString(Elts[0]->getType()));
2436 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2438 // Verify all elements are correct type!
2439 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2440 if (Elts[i]->getType() != Elts[0]->getType())
2441 return Error(FirstEltLoc,
2442 "array element #" + Twine(i) +
2443 " is not of type '" + getTypeString(Elts[0]->getType()));
2446 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2447 ID.Kind = ValID::t_Constant;
2450 case lltok::kw_c: // c "foo"
2452 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2454 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2455 ID.Kind = ValID::t_Constant;
2458 case lltok::kw_asm: {
2459 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2461 bool HasSideEffect, AlignStack, AsmDialect;
2463 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2464 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2465 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2466 ParseStringConstant(ID.StrVal) ||
2467 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2468 ParseToken(lltok::StringConstant, "expected constraint string"))
2470 ID.StrVal2 = Lex.getStrVal();
2471 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2472 (unsigned(AsmDialect)<<2);
2473 ID.Kind = ValID::t_InlineAsm;
2477 case lltok::kw_blockaddress: {
2478 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2483 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2485 ParseToken(lltok::comma, "expected comma in block address expression")||
2486 ParseValID(Label) ||
2487 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2490 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2491 return Error(Fn.Loc, "expected function name in blockaddress");
2492 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2493 return Error(Label.Loc, "expected basic block name in blockaddress");
2495 // Try to find the function (but skip it if it's forward-referenced).
2496 GlobalValue *GV = nullptr;
2497 if (Fn.Kind == ValID::t_GlobalID) {
2498 if (Fn.UIntVal < NumberedVals.size())
2499 GV = NumberedVals[Fn.UIntVal];
2500 } else if (!ForwardRefVals.count(Fn.StrVal)) {
2501 GV = M->getNamedValue(Fn.StrVal);
2503 Function *F = nullptr;
2505 // Confirm that it's actually a function with a definition.
2506 if (!isa<Function>(GV))
2507 return Error(Fn.Loc, "expected function name in blockaddress");
2508 F = cast<Function>(GV);
2509 if (F->isDeclaration())
2510 return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
2514 // Make a global variable as a placeholder for this reference.
2515 GlobalValue *&FwdRef =
2516 ForwardRefBlockAddresses.insert(std::make_pair(
2518 std::map<ValID, GlobalValue *>()))
2519 .first->second.insert(std::make_pair(std::move(Label), nullptr))
2522 FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
2523 GlobalValue::InternalLinkage, nullptr, "");
2524 ID.ConstantVal = FwdRef;
2525 ID.Kind = ValID::t_Constant;
2529 // We found the function; now find the basic block. Don't use PFS, since we
2530 // might be inside a constant expression.
2532 if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
2533 if (Label.Kind == ValID::t_LocalID)
2534 BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
2536 BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
2538 return Error(Label.Loc, "referenced value is not a basic block");
2540 if (Label.Kind == ValID::t_LocalID)
2541 return Error(Label.Loc, "cannot take address of numeric label after "
2542 "the function is defined");
2543 BB = dyn_cast_or_null<BasicBlock>(
2544 F->getValueSymbolTable().lookup(Label.StrVal));
2546 return Error(Label.Loc, "referenced value is not a basic block");
2549 ID.ConstantVal = BlockAddress::get(F, BB);
2550 ID.Kind = ValID::t_Constant;
2554 case lltok::kw_trunc:
2555 case lltok::kw_zext:
2556 case lltok::kw_sext:
2557 case lltok::kw_fptrunc:
2558 case lltok::kw_fpext:
2559 case lltok::kw_bitcast:
2560 case lltok::kw_addrspacecast:
2561 case lltok::kw_uitofp:
2562 case lltok::kw_sitofp:
2563 case lltok::kw_fptoui:
2564 case lltok::kw_fptosi:
2565 case lltok::kw_inttoptr:
2566 case lltok::kw_ptrtoint: {
2567 unsigned Opc = Lex.getUIntVal();
2568 Type *DestTy = nullptr;
2571 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2572 ParseGlobalTypeAndValue(SrcVal) ||
2573 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2574 ParseType(DestTy) ||
2575 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2577 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2578 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2579 getTypeString(SrcVal->getType()) + "' to '" +
2580 getTypeString(DestTy) + "'");
2581 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2583 ID.Kind = ValID::t_Constant;
2586 case lltok::kw_extractvalue: {
2589 SmallVector<unsigned, 4> Indices;
2590 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2591 ParseGlobalTypeAndValue(Val) ||
2592 ParseIndexList(Indices) ||
2593 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2596 if (!Val->getType()->isAggregateType())
2597 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2598 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2599 return Error(ID.Loc, "invalid indices for extractvalue");
2600 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2601 ID.Kind = ValID::t_Constant;
2604 case lltok::kw_insertvalue: {
2606 Constant *Val0, *Val1;
2607 SmallVector<unsigned, 4> Indices;
2608 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2609 ParseGlobalTypeAndValue(Val0) ||
2610 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2611 ParseGlobalTypeAndValue(Val1) ||
2612 ParseIndexList(Indices) ||
2613 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2615 if (!Val0->getType()->isAggregateType())
2616 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2618 ExtractValueInst::getIndexedType(Val0->getType(), Indices);
2620 return Error(ID.Loc, "invalid indices for insertvalue");
2621 if (IndexedType != Val1->getType())
2622 return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
2623 getTypeString(Val1->getType()) +
2624 "' instead of '" + getTypeString(IndexedType) +
2626 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2627 ID.Kind = ValID::t_Constant;
2630 case lltok::kw_icmp:
2631 case lltok::kw_fcmp: {
2632 unsigned PredVal, Opc = Lex.getUIntVal();
2633 Constant *Val0, *Val1;
2635 if (ParseCmpPredicate(PredVal, Opc) ||
2636 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2637 ParseGlobalTypeAndValue(Val0) ||
2638 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2639 ParseGlobalTypeAndValue(Val1) ||
2640 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2643 if (Val0->getType() != Val1->getType())
2644 return Error(ID.Loc, "compare operands must have the same type");
2646 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2648 if (Opc == Instruction::FCmp) {
2649 if (!Val0->getType()->isFPOrFPVectorTy())
2650 return Error(ID.Loc, "fcmp requires floating point operands");
2651 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2653 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2654 if (!Val0->getType()->isIntOrIntVectorTy() &&
2655 !Val0->getType()->getScalarType()->isPointerTy())
2656 return Error(ID.Loc, "icmp requires pointer or integer operands");
2657 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2659 ID.Kind = ValID::t_Constant;
2663 // Binary Operators.
2665 case lltok::kw_fadd:
2667 case lltok::kw_fsub:
2669 case lltok::kw_fmul:
2670 case lltok::kw_udiv:
2671 case lltok::kw_sdiv:
2672 case lltok::kw_fdiv:
2673 case lltok::kw_urem:
2674 case lltok::kw_srem:
2675 case lltok::kw_frem:
2677 case lltok::kw_lshr:
2678 case lltok::kw_ashr: {
2682 unsigned Opc = Lex.getUIntVal();
2683 Constant *Val0, *Val1;
2685 LocTy ModifierLoc = Lex.getLoc();
2686 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2687 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2688 if (EatIfPresent(lltok::kw_nuw))
2690 if (EatIfPresent(lltok::kw_nsw)) {
2692 if (EatIfPresent(lltok::kw_nuw))
2695 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2696 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2697 if (EatIfPresent(lltok::kw_exact))
2700 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2701 ParseGlobalTypeAndValue(Val0) ||
2702 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2703 ParseGlobalTypeAndValue(Val1) ||
2704 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2706 if (Val0->getType() != Val1->getType())
2707 return Error(ID.Loc, "operands of constexpr must have same type");
2708 if (!Val0->getType()->isIntOrIntVectorTy()) {
2710 return Error(ModifierLoc, "nuw only applies to integer operations");
2712 return Error(ModifierLoc, "nsw only applies to integer operations");
2714 // Check that the type is valid for the operator.
2716 case Instruction::Add:
2717 case Instruction::Sub:
2718 case Instruction::Mul:
2719 case Instruction::UDiv:
2720 case Instruction::SDiv:
2721 case Instruction::URem:
2722 case Instruction::SRem:
2723 case Instruction::Shl:
2724 case Instruction::AShr:
2725 case Instruction::LShr:
2726 if (!Val0->getType()->isIntOrIntVectorTy())
2727 return Error(ID.Loc, "constexpr requires integer operands");
2729 case Instruction::FAdd:
2730 case Instruction::FSub:
2731 case Instruction::FMul:
2732 case Instruction::FDiv:
2733 case Instruction::FRem:
2734 if (!Val0->getType()->isFPOrFPVectorTy())
2735 return Error(ID.Loc, "constexpr requires fp operands");
2737 default: llvm_unreachable("Unknown binary operator!");
2740 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2741 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2742 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2743 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2745 ID.Kind = ValID::t_Constant;
2749 // Logical Operations
2752 case lltok::kw_xor: {
2753 unsigned Opc = Lex.getUIntVal();
2754 Constant *Val0, *Val1;
2756 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2757 ParseGlobalTypeAndValue(Val0) ||
2758 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2759 ParseGlobalTypeAndValue(Val1) ||
2760 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2762 if (Val0->getType() != Val1->getType())
2763 return Error(ID.Loc, "operands of constexpr must have same type");
2764 if (!Val0->getType()->isIntOrIntVectorTy())
2765 return Error(ID.Loc,
2766 "constexpr requires integer or integer vector operands");
2767 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2768 ID.Kind = ValID::t_Constant;
2772 case lltok::kw_getelementptr:
2773 case lltok::kw_shufflevector:
2774 case lltok::kw_insertelement:
2775 case lltok::kw_extractelement:
2776 case lltok::kw_select: {
2777 unsigned Opc = Lex.getUIntVal();
2778 SmallVector<Constant*, 16> Elts;
2779 bool InBounds = false;
2781 if (Opc == Instruction::GetElementPtr)
2782 InBounds = EatIfPresent(lltok::kw_inbounds);
2783 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2784 ParseGlobalValueVector(Elts) ||
2785 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2788 if (Opc == Instruction::GetElementPtr) {
2789 if (Elts.size() == 0 ||
2790 !Elts[0]->getType()->getScalarType()->isPointerTy())
2791 return Error(ID.Loc, "base of getelementptr must be a pointer");
2793 Type *BaseType = Elts[0]->getType();
2794 auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
2796 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2797 for (Constant *Val : Indices) {
2798 Type *ValTy = Val->getType();
2799 if (!ValTy->getScalarType()->isIntegerTy())
2800 return Error(ID.Loc, "getelementptr index must be an integer");
2801 if (ValTy->isVectorTy() != BaseType->isVectorTy())
2802 return Error(ID.Loc, "getelementptr index type missmatch");
2803 if (ValTy->isVectorTy()) {
2804 unsigned ValNumEl = cast<VectorType>(ValTy)->getNumElements();
2805 unsigned PtrNumEl = cast<VectorType>(BaseType)->getNumElements();
2806 if (ValNumEl != PtrNumEl)
2809 "getelementptr vector index has a wrong number of elements");
2813 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
2814 return Error(ID.Loc, "base element of getelementptr must be sized");
2816 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2817 return Error(ID.Loc, "invalid getelementptr indices");
2818 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2820 } else if (Opc == Instruction::Select) {
2821 if (Elts.size() != 3)
2822 return Error(ID.Loc, "expected three operands to select");
2823 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2825 return Error(ID.Loc, Reason);
2826 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2827 } else if (Opc == Instruction::ShuffleVector) {
2828 if (Elts.size() != 3)
2829 return Error(ID.Loc, "expected three operands to shufflevector");
2830 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2831 return Error(ID.Loc, "invalid operands to shufflevector");
2833 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2834 } else if (Opc == Instruction::ExtractElement) {
2835 if (Elts.size() != 2)
2836 return Error(ID.Loc, "expected two operands to extractelement");
2837 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2838 return Error(ID.Loc, "invalid extractelement operands");
2839 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2841 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2842 if (Elts.size() != 3)
2843 return Error(ID.Loc, "expected three operands to insertelement");
2844 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2845 return Error(ID.Loc, "invalid insertelement operands");
2847 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2850 ID.Kind = ValID::t_Constant;
2859 /// ParseGlobalValue - Parse a global value with the specified type.
2860 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2864 bool Parsed = ParseValID(ID) ||
2865 ConvertValIDToValue(Ty, ID, V, nullptr);
2866 if (V && !(C = dyn_cast<Constant>(V)))
2867 return Error(ID.Loc, "global values must be constants");
2871 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2873 return ParseType(Ty) ||
2874 ParseGlobalValue(Ty, V);
2877 bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
2880 LocTy KwLoc = Lex.getLoc();
2881 if (!EatIfPresent(lltok::kw_comdat))
2884 if (EatIfPresent(lltok::lparen)) {
2885 if (Lex.getKind() != lltok::ComdatVar)
2886 return TokError("expected comdat variable");
2887 C = getComdat(Lex.getStrVal(), Lex.getLoc());
2889 if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
2892 if (GlobalName.empty())
2893 return TokError("comdat cannot be unnamed");
2894 C = getComdat(GlobalName, KwLoc);
2900 /// ParseGlobalValueVector
2902 /// ::= TypeAndValue (',' TypeAndValue)*
2903 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
2905 if (Lex.getKind() == lltok::rbrace ||
2906 Lex.getKind() == lltok::rsquare ||
2907 Lex.getKind() == lltok::greater ||
2908 Lex.getKind() == lltok::rparen)
2912 if (ParseGlobalTypeAndValue(C)) return true;
2915 while (EatIfPresent(lltok::comma)) {
2916 if (ParseGlobalTypeAndValue(C)) return true;
2923 bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
2924 SmallVector<Metadata *, 16> Elts;
2925 if (ParseMDNodeVector(Elts))
2928 MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
2935 /// ::= !MDLocation(...)
2936 bool LLParser::ParseMDNode(MDNode *&N) {
2937 if (Lex.getKind() == lltok::MetadataVar)
2938 return ParseSpecializedMDNode(N);
2940 return ParseToken(lltok::exclaim, "expected '!' here") ||
2944 bool LLParser::ParseMDNodeTail(MDNode *&N) {
2946 if (Lex.getKind() == lltok::lbrace)
2947 return ParseMDTuple(N);
2950 return ParseMDNodeID(N);
2955 /// Structure to represent an optional metadata field.
2956 template <class FieldTy> struct MDFieldImpl {
2957 typedef MDFieldImpl ImplTy;
2961 void assign(FieldTy Val) {
2963 this->Val = std::move(Val);
2966 explicit MDFieldImpl(FieldTy Default)
2967 : Val(std::move(Default)), Seen(false) {}
2970 struct MDUnsignedField : public MDFieldImpl<uint64_t> {
2973 MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
2974 : ImplTy(Default), Max(Max) {}
2976 struct LineField : public MDUnsignedField {
2977 LineField() : MDUnsignedField(0, UINT32_MAX) {}
2979 struct ColumnField : public MDUnsignedField {
2980 ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
2982 struct DwarfTagField : public MDUnsignedField {
2983 DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
2984 DwarfTagField(dwarf::Tag DefaultTag)
2985 : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
2987 struct DwarfAttEncodingField : public MDUnsignedField {
2988 DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
2990 struct DwarfVirtualityField : public MDUnsignedField {
2991 DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
2993 struct DwarfLangField : public MDUnsignedField {
2994 DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
2997 struct DIFlagField : public MDUnsignedField {
2998 DIFlagField() : MDUnsignedField(0, UINT32_MAX) {}
3001 struct MDSignedField : public MDFieldImpl<int64_t> {
3005 MDSignedField(int64_t Default = 0)
3006 : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
3007 MDSignedField(int64_t Default, int64_t Min, int64_t Max)
3008 : ImplTy(Default), Min(Min), Max(Max) {}
3011 struct MDBoolField : public MDFieldImpl<bool> {
3012 MDBoolField(bool Default = false) : ImplTy(Default) {}
3014 struct MDField : public MDFieldImpl<Metadata *> {
3015 MDField() : ImplTy(nullptr) {}
3017 struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
3018 MDConstant() : ImplTy(nullptr) {}
3020 struct MDStringField : public MDFieldImpl<std::string> {
3021 MDStringField() : ImplTy(std::string()) {}
3023 struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
3024 MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
3032 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3033 MDUnsignedField &Result) {
3034 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3035 return TokError("expected unsigned integer");
3037 auto &U = Lex.getAPSIntVal();
3038 if (U.ugt(Result.Max))
3039 return TokError("value for '" + Name + "' too large, limit is " +
3041 Result.assign(U.getZExtValue());
3042 assert(Result.Val <= Result.Max && "Expected value in range");
3048 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
3049 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3052 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
3053 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3057 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
3058 if (Lex.getKind() == lltok::APSInt)
3059 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3061 if (Lex.getKind() != lltok::DwarfTag)
3062 return TokError("expected DWARF tag");
3064 unsigned Tag = dwarf::getTag(Lex.getStrVal());
3065 if (Tag == dwarf::DW_TAG_invalid)
3066 return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
3067 assert(Tag <= Result.Max && "Expected valid DWARF tag");
3075 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3076 DwarfVirtualityField &Result) {
3077 if (Lex.getKind() == lltok::APSInt)
3078 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3080 if (Lex.getKind() != lltok::DwarfVirtuality)
3081 return TokError("expected DWARF virtuality code");
3083 unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
3085 return TokError("invalid DWARF virtuality code" + Twine(" '") +
3086 Lex.getStrVal() + "'");
3087 assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
3088 Result.assign(Virtuality);
3094 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
3095 if (Lex.getKind() == lltok::APSInt)
3096 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3098 if (Lex.getKind() != lltok::DwarfLang)
3099 return TokError("expected DWARF language");
3101 unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
3103 return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
3105 assert(Lang <= Result.Max && "Expected valid DWARF language");
3106 Result.assign(Lang);
3112 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3113 DwarfAttEncodingField &Result) {
3114 if (Lex.getKind() == lltok::APSInt)
3115 return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
3117 if (Lex.getKind() != lltok::DwarfAttEncoding)
3118 return TokError("expected DWARF type attribute encoding");
3120 unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
3122 return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
3123 Lex.getStrVal() + "'");
3124 assert(Encoding <= Result.Max && "Expected valid DWARF language");
3125 Result.assign(Encoding);
3132 /// ::= DIFlagVector
3133 /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
3135 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
3136 assert(Result.Max == UINT32_MAX && "Expected only 32-bits");
3138 // Parser for a single flag.
3139 auto parseFlag = [&](unsigned &Val) {
3140 if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned())
3141 return ParseUInt32(Val);
3143 if (Lex.getKind() != lltok::DIFlag)
3144 return TokError("expected debug info flag");
3146 Val = DIDescriptor::getFlag(Lex.getStrVal());
3148 return TokError(Twine("invalid debug info flag flag '") +
3149 Lex.getStrVal() + "'");
3154 // Parse the flags and combine them together.
3155 unsigned Combined = 0;
3161 } while (EatIfPresent(lltok::bar));
3163 Result.assign(Combined);
3168 bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
3169 MDSignedField &Result) {
3170 if (Lex.getKind() != lltok::APSInt)
3171 return TokError("expected signed integer");
3173 auto &S = Lex.getAPSIntVal();
3175 return TokError("value for '" + Name + "' too small, limit is " +
3178 return TokError("value for '" + Name + "' too large, limit is " +
3180 Result.assign(S.getExtValue());
3181 assert(Result.Val >= Result.Min && "Expected value in range");
3182 assert(Result.Val <= Result.Max && "Expected value in range");
3188 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
3189 switch (Lex.getKind()) {
3191 return TokError("expected 'true' or 'false'");
3192 case lltok::kw_true:
3193 Result.assign(true);
3195 case lltok::kw_false:
3196 Result.assign(false);
3204 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
3205 if (Lex.getKind() == lltok::kw_null) {
3207 Result.assign(nullptr);
3212 if (ParseMetadata(MD, nullptr))
3220 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
3222 if (ParseValueAsMetadata(MD, "expected constant", nullptr))
3225 Result.assign(cast<ConstantAsMetadata>(MD));
3230 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
3232 if (ParseStringConstant(S))
3235 Result.assign(std::move(S));
3240 bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
3241 SmallVector<Metadata *, 4> MDs;
3242 if (ParseMDNodeVector(MDs))
3245 Result.assign(std::move(MDs));
3249 } // end namespace llvm
3251 template <class ParserTy>
3252 bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
3254 if (Lex.getKind() != lltok::LabelStr)
3255 return TokError("expected field label here");
3259 } while (EatIfPresent(lltok::comma));
3264 template <class ParserTy>
3265 bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
3266 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3269 if (ParseToken(lltok::lparen, "expected '(' here"))
3271 if (Lex.getKind() != lltok::rparen)
3272 if (ParseMDFieldsImplBody(parseField))
3275 ClosingLoc = Lex.getLoc();
3276 return ParseToken(lltok::rparen, "expected ')' here");
3279 template <class FieldTy>
3280 bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
3282 return TokError("field '" + Name + "' cannot be specified more than once");
3284 LocTy Loc = Lex.getLoc();
3286 return ParseMDField(Loc, Name, Result);
3289 bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
3290 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3292 #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
3293 if (Lex.getStrVal() == #CLASS) \
3294 return Parse##CLASS(N, IsDistinct);
3295 #include "llvm/IR/Metadata.def"
3297 return TokError("expected metadata type");
3300 #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
3301 #define NOP_FIELD(NAME, TYPE, INIT)
3302 #define REQUIRE_FIELD(NAME, TYPE, INIT) \
3304 return Error(ClosingLoc, "missing required field '" #NAME "'");
3305 #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
3306 if (Lex.getStrVal() == #NAME) \
3307 return ParseMDField(#NAME, NAME);
3308 #define PARSE_MD_FIELDS() \
3309 VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
3312 if (ParseMDFieldsImpl([&]() -> bool { \
3313 VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
3314 return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
3317 VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
3319 #define GET_OR_DISTINCT(CLASS, ARGS) \
3320 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
3322 /// ParseMDLocationFields:
3323 /// ::= !MDLocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
3324 bool LLParser::ParseMDLocation(MDNode *&Result, bool IsDistinct) {
3325 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3326 OPTIONAL(line, LineField, ); \
3327 OPTIONAL(column, ColumnField, ); \
3328 REQUIRED(scope, MDField, ); \
3329 OPTIONAL(inlinedAt, MDField, );
3331 #undef VISIT_MD_FIELDS
3333 auto get = (IsDistinct ? MDLocation::getDistinct : MDLocation::get);
3334 Result = get(Context, line.Val, column.Val, scope.Val, inlinedAt.Val);
3338 /// ParseGenericDebugNode:
3339 /// ::= !GenericDebugNode(tag: 15, header: "...", operands: {...})
3340 bool LLParser::ParseGenericDebugNode(MDNode *&Result, bool IsDistinct) {
3341 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3342 REQUIRED(tag, DwarfTagField, ); \
3343 OPTIONAL(header, MDStringField, ); \
3344 OPTIONAL(operands, MDFieldList, );
3346 #undef VISIT_MD_FIELDS
3348 Result = GET_OR_DISTINCT(GenericDebugNode,
3349 (Context, tag.Val, header.Val, operands.Val));
3353 /// ParseMDSubrange:
3354 /// ::= !MDSubrange(count: 30, lowerBound: 2)
3355 bool LLParser::ParseMDSubrange(MDNode *&Result, bool IsDistinct) {
3356 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3357 REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
3358 OPTIONAL(lowerBound, MDSignedField, );
3360 #undef VISIT_MD_FIELDS
3362 Result = GET_OR_DISTINCT(MDSubrange, (Context, count.Val, lowerBound.Val));
3366 /// ParseMDEnumerator:
3367 /// ::= !MDEnumerator(value: 30, name: "SomeKind")
3368 bool LLParser::ParseMDEnumerator(MDNode *&Result, bool IsDistinct) {
3369 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3370 REQUIRED(name, MDStringField, ); \
3371 REQUIRED(value, MDSignedField, );
3373 #undef VISIT_MD_FIELDS
3375 Result = GET_OR_DISTINCT(MDEnumerator, (Context, value.Val, name.Val));
3379 /// ParseMDBasicType:
3380 /// ::= !MDBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
3381 bool LLParser::ParseMDBasicType(MDNode *&Result, bool IsDistinct) {
3382 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3383 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
3384 OPTIONAL(name, MDStringField, ); \
3385 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3386 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3387 OPTIONAL(encoding, DwarfAttEncodingField, );
3389 #undef VISIT_MD_FIELDS
3391 Result = GET_OR_DISTINCT(MDBasicType, (Context, tag.Val, name.Val, size.Val,
3392 align.Val, encoding.Val));
3396 /// ParseMDDerivedType:
3397 /// ::= !MDDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
3398 /// line: 7, scope: !1, baseType: !2, size: 32,
3399 /// align: 32, offset: 0, flags: 0, extraData: !3)
3400 bool LLParser::ParseMDDerivedType(MDNode *&Result, bool IsDistinct) {
3401 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3402 REQUIRED(tag, DwarfTagField, ); \
3403 OPTIONAL(name, MDStringField, ); \
3404 OPTIONAL(file, MDField, ); \
3405 OPTIONAL(line, LineField, ); \
3406 OPTIONAL(scope, MDField, ); \
3407 REQUIRED(baseType, MDField, ); \
3408 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3409 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3410 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3411 OPTIONAL(flags, DIFlagField, ); \
3412 OPTIONAL(extraData, MDField, );
3414 #undef VISIT_MD_FIELDS
3416 Result = GET_OR_DISTINCT(MDDerivedType,
3417 (Context, tag.Val, name.Val, file.Val, line.Val,
3418 scope.Val, baseType.Val, size.Val, align.Val,
3419 offset.Val, flags.Val, extraData.Val));
3423 bool LLParser::ParseMDCompositeType(MDNode *&Result, bool IsDistinct) {
3424 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3425 REQUIRED(tag, DwarfTagField, ); \
3426 OPTIONAL(name, MDStringField, ); \
3427 OPTIONAL(file, MDField, ); \
3428 OPTIONAL(line, LineField, ); \
3429 OPTIONAL(scope, MDField, ); \
3430 OPTIONAL(baseType, MDField, ); \
3431 OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
3432 OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
3433 OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
3434 OPTIONAL(flags, DIFlagField, ); \
3435 OPTIONAL(elements, MDField, ); \
3436 OPTIONAL(runtimeLang, DwarfLangField, ); \
3437 OPTIONAL(vtableHolder, MDField, ); \
3438 OPTIONAL(templateParams, MDField, ); \
3439 OPTIONAL(identifier, MDStringField, );
3441 #undef VISIT_MD_FIELDS
3443 Result = GET_OR_DISTINCT(
3445 (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
3446 size.Val, align.Val, offset.Val, flags.Val, elements.Val,
3447 runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
3451 bool LLParser::ParseMDSubroutineType(MDNode *&Result, bool IsDistinct) {
3452 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3453 OPTIONAL(flags, DIFlagField, ); \
3454 REQUIRED(types, MDField, );
3456 #undef VISIT_MD_FIELDS
3458 Result = GET_OR_DISTINCT(MDSubroutineType, (Context, flags.Val, types.Val));
3462 /// ParseMDFileType:
3463 /// ::= !MDFileType(filename: "path/to/file", directory: "/path/to/dir")
3464 bool LLParser::ParseMDFile(MDNode *&Result, bool IsDistinct) {
3465 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3466 REQUIRED(filename, MDStringField, ); \
3467 REQUIRED(directory, MDStringField, );
3469 #undef VISIT_MD_FIELDS
3471 Result = GET_OR_DISTINCT(MDFile, (Context, filename.Val, directory.Val));
3475 /// ParseMDCompileUnit:
3476 /// ::= !MDCompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
3477 /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
3478 /// splitDebugFilename: "abc.debug", emissionKind: 1,
3479 /// enums: !1, retainedTypes: !2, subprograms: !3,
3480 /// globals: !4, imports: !5)
3481 bool LLParser::ParseMDCompileUnit(MDNode *&Result, bool IsDistinct) {
3482 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3483 REQUIRED(language, DwarfLangField, ); \
3484 REQUIRED(file, MDField, ); \
3485 OPTIONAL(producer, MDStringField, ); \
3486 OPTIONAL(isOptimized, MDBoolField, ); \
3487 OPTIONAL(flags, MDStringField, ); \
3488 OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
3489 OPTIONAL(splitDebugFilename, MDStringField, ); \
3490 OPTIONAL(emissionKind, MDUnsignedField, (0, UINT32_MAX)); \
3491 OPTIONAL(enums, MDField, ); \
3492 OPTIONAL(retainedTypes, MDField, ); \
3493 OPTIONAL(subprograms, MDField, ); \
3494 OPTIONAL(globals, MDField, ); \
3495 OPTIONAL(imports, MDField, );
3497 #undef VISIT_MD_FIELDS
3499 Result = GET_OR_DISTINCT(MDCompileUnit,
3500 (Context, language.Val, file.Val, producer.Val,
3501 isOptimized.Val, flags.Val, runtimeVersion.Val,
3502 splitDebugFilename.Val, emissionKind.Val, enums.Val,
3503 retainedTypes.Val, subprograms.Val, globals.Val,
3508 /// ParseMDSubprogram:
3509 /// ::= !MDSubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
3510 /// file: !1, line: 7, type: !2, isLocal: false,
3511 /// isDefinition: true, scopeLine: 8, containingType: !3,
3512 /// virtuality: DW_VIRTUALTIY_pure_virtual,
3513 /// virtualIndex: 10, flags: 11,
3514 /// isOptimized: false, function: void ()* @_Z3foov,
3515 /// templateParams: !4, declaration: !5, variables: !6)
3516 bool LLParser::ParseMDSubprogram(MDNode *&Result, bool IsDistinct) {
3517 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3518 OPTIONAL(scope, MDField, ); \
3519 REQUIRED(name, MDStringField, ); \
3520 OPTIONAL(linkageName, MDStringField, ); \
3521 OPTIONAL(file, MDField, ); \
3522 OPTIONAL(line, LineField, ); \
3523 OPTIONAL(type, MDField, ); \
3524 OPTIONAL(isLocal, MDBoolField, ); \
3525 OPTIONAL(isDefinition, MDBoolField, (true)); \
3526 OPTIONAL(scopeLine, LineField, ); \
3527 OPTIONAL(containingType, MDField, ); \
3528 OPTIONAL(virtuality, DwarfVirtualityField, ); \
3529 OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
3530 OPTIONAL(flags, DIFlagField, ); \
3531 OPTIONAL(isOptimized, MDBoolField, ); \
3532 OPTIONAL(function, MDConstant, ); \
3533 OPTIONAL(templateParams, MDField, ); \
3534 OPTIONAL(declaration, MDField, ); \
3535 OPTIONAL(variables, MDField, );
3537 #undef VISIT_MD_FIELDS
3539 Result = GET_OR_DISTINCT(
3540 MDSubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
3541 line.Val, type.Val, isLocal.Val, isDefinition.Val,
3542 scopeLine.Val, containingType.Val, virtuality.Val,
3543 virtualIndex.Val, flags.Val, isOptimized.Val, function.Val,
3544 templateParams.Val, declaration.Val, variables.Val));
3548 /// ParseMDLexicalBlock:
3549 /// ::= !MDLexicalBlock(scope: !0, file: !2, line: 7, column: 9)
3550 bool LLParser::ParseMDLexicalBlock(MDNode *&Result, bool IsDistinct) {
3551 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3552 REQUIRED(scope, MDField, ); \
3553 OPTIONAL(file, MDField, ); \
3554 OPTIONAL(line, LineField, ); \
3555 OPTIONAL(column, ColumnField, );
3557 #undef VISIT_MD_FIELDS
3559 Result = GET_OR_DISTINCT(
3560 MDLexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
3564 /// ParseMDLexicalBlockFile:
3565 /// ::= !MDLexicalBlockFile(scope: !0, file: !2, discriminator: 9)
3566 bool LLParser::ParseMDLexicalBlockFile(MDNode *&Result, bool IsDistinct) {
3567 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3568 REQUIRED(scope, MDField, ); \
3569 OPTIONAL(file, MDField, ); \
3570 REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
3572 #undef VISIT_MD_FIELDS
3574 Result = GET_OR_DISTINCT(MDLexicalBlockFile,
3575 (Context, scope.Val, file.Val, discriminator.Val));
3579 /// ParseMDNamespace:
3580 /// ::= !MDNamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
3581 bool LLParser::ParseMDNamespace(MDNode *&Result, bool IsDistinct) {
3582 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3583 REQUIRED(scope, MDField, ); \
3584 OPTIONAL(file, MDField, ); \
3585 OPTIONAL(name, MDStringField, ); \
3586 OPTIONAL(line, LineField, );
3588 #undef VISIT_MD_FIELDS
3590 Result = GET_OR_DISTINCT(MDNamespace,
3591 (Context, scope.Val, file.Val, name.Val, line.Val));
3595 /// ParseMDTemplateTypeParameter:
3596 /// ::= !MDTemplateTypeParameter(name: "Ty", type: !1)
3597 bool LLParser::ParseMDTemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
3598 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3599 OPTIONAL(name, MDStringField, ); \
3600 REQUIRED(type, MDField, );
3602 #undef VISIT_MD_FIELDS
3605 GET_OR_DISTINCT(MDTemplateTypeParameter, (Context, name.Val, type.Val));
3609 /// ParseMDTemplateValueParameter:
3610 /// ::= !MDTemplateValueParameter(tag: DW_TAG_template_value_parameter,
3611 /// name: "V", type: !1, value: i32 7)
3612 bool LLParser::ParseMDTemplateValueParameter(MDNode *&Result, bool IsDistinct) {
3613 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3614 OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
3615 OPTIONAL(name, MDStringField, ); \
3616 OPTIONAL(type, MDField, ); \
3617 REQUIRED(value, MDField, );
3619 #undef VISIT_MD_FIELDS
3621 Result = GET_OR_DISTINCT(MDTemplateValueParameter,
3622 (Context, tag.Val, name.Val, type.Val, value.Val));
3626 /// ParseMDGlobalVariable:
3627 /// ::= !MDGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
3628 /// file: !1, line: 7, type: !2, isLocal: false,
3629 /// isDefinition: true, variable: i32* @foo,
3630 /// declaration: !3)
3631 bool LLParser::ParseMDGlobalVariable(MDNode *&Result, bool IsDistinct) {
3632 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3633 OPTIONAL(scope, MDField, ); \
3634 REQUIRED(name, MDStringField, ); \
3635 OPTIONAL(linkageName, MDStringField, ); \
3636 OPTIONAL(file, MDField, ); \
3637 OPTIONAL(line, LineField, ); \
3638 OPTIONAL(type, MDField, ); \
3639 OPTIONAL(isLocal, MDBoolField, ); \
3640 OPTIONAL(isDefinition, MDBoolField, (true)); \
3641 OPTIONAL(variable, MDConstant, ); \
3642 OPTIONAL(declaration, MDField, );
3644 #undef VISIT_MD_FIELDS
3646 Result = GET_OR_DISTINCT(MDGlobalVariable,
3647 (Context, scope.Val, name.Val, linkageName.Val,
3648 file.Val, line.Val, type.Val, isLocal.Val,
3649 isDefinition.Val, variable.Val, declaration.Val));
3653 /// ParseMDLocalVariable:
3654 /// ::= !MDLocalVariable(tag: DW_TAG_arg_variable, scope: !0, name: "foo",
3655 /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
3657 bool LLParser::ParseMDLocalVariable(MDNode *&Result, bool IsDistinct) {
3658 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3659 REQUIRED(tag, DwarfTagField, ); \
3660 OPTIONAL(scope, MDField, ); \
3661 OPTIONAL(name, MDStringField, ); \
3662 OPTIONAL(file, MDField, ); \
3663 OPTIONAL(line, LineField, ); \
3664 OPTIONAL(type, MDField, ); \
3665 OPTIONAL(arg, MDUnsignedField, (0, UINT8_MAX)); \
3666 OPTIONAL(flags, DIFlagField, ); \
3667 OPTIONAL(inlinedAt, MDField, );
3669 #undef VISIT_MD_FIELDS
3671 Result = GET_OR_DISTINCT(
3672 MDLocalVariable, (Context, tag.Val, scope.Val, name.Val, file.Val,
3673 line.Val, type.Val, arg.Val, flags.Val, inlinedAt.Val));
3677 /// ParseMDExpression:
3678 /// ::= !MDExpression(0, 7, -1)
3679 bool LLParser::ParseMDExpression(MDNode *&Result, bool IsDistinct) {
3680 assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
3683 if (ParseToken(lltok::lparen, "expected '(' here"))
3686 SmallVector<uint64_t, 8> Elements;
3687 if (Lex.getKind() != lltok::rparen)
3689 if (Lex.getKind() == lltok::DwarfOp) {
3690 if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
3692 Elements.push_back(Op);
3695 return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
3698 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
3699 return TokError("expected unsigned integer");
3701 auto &U = Lex.getAPSIntVal();
3702 if (U.ugt(UINT64_MAX))
3703 return TokError("element too large, limit is " + Twine(UINT64_MAX));
3704 Elements.push_back(U.getZExtValue());
3706 } while (EatIfPresent(lltok::comma));
3708 if (ParseToken(lltok::rparen, "expected ')' here"))
3711 Result = GET_OR_DISTINCT(MDExpression, (Context, Elements));
3715 /// ParseMDObjCProperty:
3716 /// ::= !MDObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
3717 /// getter: "getFoo", attributes: 7, type: !2)
3718 bool LLParser::ParseMDObjCProperty(MDNode *&Result, bool IsDistinct) {
3719 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3720 REQUIRED(name, MDStringField, ); \
3721 OPTIONAL(file, MDField, ); \
3722 OPTIONAL(line, LineField, ); \
3723 OPTIONAL(setter, MDStringField, ); \
3724 OPTIONAL(getter, MDStringField, ); \
3725 OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
3726 OPTIONAL(type, MDField, );
3728 #undef VISIT_MD_FIELDS
3730 Result = GET_OR_DISTINCT(MDObjCProperty,
3731 (Context, name.Val, file.Val, line.Val, setter.Val,
3732 getter.Val, attributes.Val, type.Val));
3736 /// ParseMDImportedEntity:
3737 /// ::= !MDImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
3738 /// line: 7, name: "foo")
3739 bool LLParser::ParseMDImportedEntity(MDNode *&Result, bool IsDistinct) {
3740 #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
3741 REQUIRED(tag, DwarfTagField, ); \
3742 REQUIRED(scope, MDField, ); \
3743 OPTIONAL(entity, MDField, ); \
3744 OPTIONAL(line, LineField, ); \
3745 OPTIONAL(name, MDStringField, );
3747 #undef VISIT_MD_FIELDS
3749 Result = GET_OR_DISTINCT(MDImportedEntity, (Context, tag.Val, scope.Val,
3750 entity.Val, line.Val, name.Val));
3754 #undef PARSE_MD_FIELD
3756 #undef REQUIRE_FIELD
3757 #undef DECLARE_FIELD
3759 /// ParseMetadataAsValue
3760 /// ::= metadata i32 %local
3761 /// ::= metadata i32 @global
3762 /// ::= metadata i32 7
3764 /// ::= metadata !{...}
3765 /// ::= metadata !"string"
3766 bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
3767 // Note: the type 'metadata' has already been parsed.
3769 if (ParseMetadata(MD, &PFS))
3772 V = MetadataAsValue::get(Context, MD);
3776 /// ParseValueAsMetadata
3780 bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
3781 PerFunctionState *PFS) {
3784 if (ParseType(Ty, TypeMsg, Loc))
3786 if (Ty->isMetadataTy())
3787 return Error(Loc, "invalid metadata-value-metadata roundtrip");
3790 if (ParseValue(Ty, V, PFS))
3793 MD = ValueAsMetadata::get(V);
3804 /// ::= !MDLocation(...)
3805 bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
3806 if (Lex.getKind() == lltok::MetadataVar) {
3808 if (ParseSpecializedMDNode(N))
3816 if (Lex.getKind() != lltok::exclaim)
3817 return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
3820 assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
3824 // ::= '!' STRINGCONSTANT
3825 if (Lex.getKind() == lltok::StringConstant) {
3827 if (ParseMDString(S))
3837 if (ParseMDNodeTail(N))
3844 //===----------------------------------------------------------------------===//
3845 // Function Parsing.
3846 //===----------------------------------------------------------------------===//
3848 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
3849 PerFunctionState *PFS) {
3850 if (Ty->isFunctionTy())
3851 return Error(ID.Loc, "functions are not values, refer to them as pointers");
3854 case ValID::t_LocalID:
3855 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3856 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
3857 return V == nullptr;
3858 case ValID::t_LocalName:
3859 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
3860 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
3861 return V == nullptr;
3862 case ValID::t_InlineAsm: {
3863 PointerType *PTy = dyn_cast<PointerType>(Ty);
3865 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3866 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3867 return Error(ID.Loc, "invalid type for inline asm constraint string");
3868 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3869 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3872 case ValID::t_GlobalName:
3873 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3874 return V == nullptr;
3875 case ValID::t_GlobalID:
3876 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3877 return V == nullptr;
3878 case ValID::t_APSInt:
3879 if (!Ty->isIntegerTy())
3880 return Error(ID.Loc, "integer constant must have integer type");
3881 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3882 V = ConstantInt::get(Context, ID.APSIntVal);
3884 case ValID::t_APFloat:
3885 if (!Ty->isFloatingPointTy() ||
3886 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3887 return Error(ID.Loc, "floating point constant invalid for type");
3889 // The lexer has no type info, so builds all half, float, and double FP
3890 // constants as double. Fix this here. Long double does not need this.
3891 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3894 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3896 else if (Ty->isFloatTy())
3897 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3900 V = ConstantFP::get(Context, ID.APFloatVal);
3902 if (V->getType() != Ty)
3903 return Error(ID.Loc, "floating point constant does not have type '" +
3904 getTypeString(Ty) + "'");
3908 if (!Ty->isPointerTy())
3909 return Error(ID.Loc, "null must be a pointer type");
3910 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3912 case ValID::t_Undef:
3913 // FIXME: LabelTy should not be a first-class type.
3914 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3915 return Error(ID.Loc, "invalid type for undef constant");
3916 V = UndefValue::get(Ty);
3918 case ValID::t_EmptyArray:
3919 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3920 return Error(ID.Loc, "invalid empty array initializer");
3921 V = UndefValue::get(Ty);
3924 // FIXME: LabelTy should not be a first-class type.
3925 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3926 return Error(ID.Loc, "invalid type for null constant");
3927 V = Constant::getNullValue(Ty);
3929 case ValID::t_Constant:
3930 if (ID.ConstantVal->getType() != Ty)
3931 return Error(ID.Loc, "constant expression type mismatch");
3935 case ValID::t_ConstantStruct:
3936 case ValID::t_PackedConstantStruct:
3937 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3938 if (ST->getNumElements() != ID.UIntVal)
3939 return Error(ID.Loc,
3940 "initializer with struct type has wrong # elements");
3941 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3942 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3944 // Verify that the elements are compatible with the structtype.
3945 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3946 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3947 return Error(ID.Loc, "element " + Twine(i) +
3948 " of struct initializer doesn't match struct element type");
3950 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3953 return Error(ID.Loc, "constant expression type mismatch");
3956 llvm_unreachable("Invalid ValID");
3959 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3962 return ParseValID(ID, PFS) ||
3963 ConvertValIDToValue(Ty, ID, V, PFS);
3966 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3968 return ParseType(Ty) ||
3969 ParseValue(Ty, V, PFS);
3972 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3973 PerFunctionState &PFS) {
3976 if (ParseTypeAndValue(V, PFS)) return true;
3977 if (!isa<BasicBlock>(V))
3978 return Error(Loc, "expected a basic block");
3979 BB = cast<BasicBlock>(V);
3985 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3986 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3987 /// OptionalAlign OptGC OptionalPrefix OptionalPrologue
3988 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3989 // Parse the linkage.
3990 LocTy LinkageLoc = Lex.getLoc();
3993 unsigned Visibility;
3994 unsigned DLLStorageClass;
3995 AttrBuilder RetAttrs;
3997 Type *RetType = nullptr;
3998 LocTy RetTypeLoc = Lex.getLoc();
3999 if (ParseOptionalLinkage(Linkage) ||
4000 ParseOptionalVisibility(Visibility) ||
4001 ParseOptionalDLLStorageClass(DLLStorageClass) ||
4002 ParseOptionalCallingConv(CC) ||
4003 ParseOptionalReturnAttrs(RetAttrs) ||
4004 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
4007 // Verify that the linkage is ok.
4008 switch ((GlobalValue::LinkageTypes)Linkage) {
4009 case GlobalValue::ExternalLinkage:
4010 break; // always ok.
4011 case GlobalValue::ExternalWeakLinkage:
4013 return Error(LinkageLoc, "invalid linkage for function definition");
4015 case GlobalValue::PrivateLinkage:
4016 case GlobalValue::InternalLinkage:
4017 case GlobalValue::AvailableExternallyLinkage:
4018 case GlobalValue::LinkOnceAnyLinkage:
4019 case GlobalValue::LinkOnceODRLinkage:
4020 case GlobalValue::WeakAnyLinkage:
4021 case GlobalValue::WeakODRLinkage:
4023 return Error(LinkageLoc, "invalid linkage for function declaration");
4025 case GlobalValue::AppendingLinkage:
4026 case GlobalValue::CommonLinkage:
4027 return Error(LinkageLoc, "invalid function linkage type");
4030 if (!isValidVisibilityForLinkage(Visibility, Linkage))
4031 return Error(LinkageLoc,
4032 "symbol with local linkage must have default visibility");
4034 if (!FunctionType::isValidReturnType(RetType))
4035 return Error(RetTypeLoc, "invalid function return type");
4037 LocTy NameLoc = Lex.getLoc();
4039 std::string FunctionName;
4040 if (Lex.getKind() == lltok::GlobalVar) {
4041 FunctionName = Lex.getStrVal();
4042 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
4043 unsigned NameID = Lex.getUIntVal();
4045 if (NameID != NumberedVals.size())
4046 return TokError("function expected to be numbered '%" +
4047 Twine(NumberedVals.size()) + "'");
4049 return TokError("expected function name");
4054 if (Lex.getKind() != lltok::lparen)
4055 return TokError("expected '(' in function argument list");
4057 SmallVector<ArgInfo, 8> ArgList;
4059 AttrBuilder FuncAttrs;
4060 std::vector<unsigned> FwdRefAttrGrps;
4062 std::string Section;
4066 LocTy UnnamedAddrLoc;
4067 Constant *Prefix = nullptr;
4068 Constant *Prologue = nullptr;
4071 if (ParseArgumentList(ArgList, isVarArg) ||
4072 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
4074 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
4076 (EatIfPresent(lltok::kw_section) &&
4077 ParseStringConstant(Section)) ||
4078 parseOptionalComdat(FunctionName, C) ||
4079 ParseOptionalAlignment(Alignment) ||
4080 (EatIfPresent(lltok::kw_gc) &&
4081 ParseStringConstant(GC)) ||
4082 (EatIfPresent(lltok::kw_prefix) &&
4083 ParseGlobalTypeAndValue(Prefix)) ||
4084 (EatIfPresent(lltok::kw_prologue) &&
4085 ParseGlobalTypeAndValue(Prologue)))
4088 if (FuncAttrs.contains(Attribute::Builtin))
4089 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
4091 // If the alignment was parsed as an attribute, move to the alignment field.
4092 if (FuncAttrs.hasAlignmentAttr()) {
4093 Alignment = FuncAttrs.getAlignment();
4094 FuncAttrs.removeAttribute(Attribute::Alignment);
4097 // Okay, if we got here, the function is syntactically valid. Convert types
4098 // and do semantic checks.
4099 std::vector<Type*> ParamTypeList;
4100 SmallVector<AttributeSet, 8> Attrs;
4102 if (RetAttrs.hasAttributes())
4103 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4104 AttributeSet::ReturnIndex,
4107 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4108 ParamTypeList.push_back(ArgList[i].Ty);
4109 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4110 AttrBuilder B(ArgList[i].Attrs, i + 1);
4111 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4115 if (FuncAttrs.hasAttributes())
4116 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4117 AttributeSet::FunctionIndex,
4120 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4122 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
4123 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
4126 FunctionType::get(RetType, ParamTypeList, isVarArg);
4127 PointerType *PFT = PointerType::getUnqual(FT);
4130 if (!FunctionName.empty()) {
4131 // If this was a definition of a forward reference, remove the definition
4132 // from the forward reference table and fill in the forward ref.
4133 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
4134 ForwardRefVals.find(FunctionName);
4135 if (FRVI != ForwardRefVals.end()) {
4136 Fn = M->getFunction(FunctionName);
4138 return Error(FRVI->second.second, "invalid forward reference to "
4139 "function as global value!");
4140 if (Fn->getType() != PFT)
4141 return Error(FRVI->second.second, "invalid forward reference to "
4142 "function '" + FunctionName + "' with wrong type!");
4144 ForwardRefVals.erase(FRVI);
4145 } else if ((Fn = M->getFunction(FunctionName))) {
4146 // Reject redefinitions.
4147 return Error(NameLoc, "invalid redefinition of function '" +
4148 FunctionName + "'");
4149 } else if (M->getNamedValue(FunctionName)) {
4150 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
4154 // If this is a definition of a forward referenced function, make sure the
4156 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
4157 = ForwardRefValIDs.find(NumberedVals.size());
4158 if (I != ForwardRefValIDs.end()) {
4159 Fn = cast<Function>(I->second.first);
4160 if (Fn->getType() != PFT)
4161 return Error(NameLoc, "type of definition and forward reference of '@" +
4162 Twine(NumberedVals.size()) + "' disagree");
4163 ForwardRefValIDs.erase(I);
4168 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
4169 else // Move the forward-reference to the correct spot in the module.
4170 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
4172 if (FunctionName.empty())
4173 NumberedVals.push_back(Fn);
4175 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
4176 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
4177 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
4178 Fn->setCallingConv(CC);
4179 Fn->setAttributes(PAL);
4180 Fn->setUnnamedAddr(UnnamedAddr);
4181 Fn->setAlignment(Alignment);
4182 Fn->setSection(Section);
4184 if (!GC.empty()) Fn->setGC(GC.c_str());
4185 Fn->setPrefixData(Prefix);
4186 Fn->setPrologueData(Prologue);
4187 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
4189 // Add all of the arguments we parsed to the function.
4190 Function::arg_iterator ArgIt = Fn->arg_begin();
4191 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
4192 // If the argument has a name, insert it into the argument symbol table.
4193 if (ArgList[i].Name.empty()) continue;
4195 // Set the name, if it conflicted, it will be auto-renamed.
4196 ArgIt->setName(ArgList[i].Name);
4198 if (ArgIt->getName() != ArgList[i].Name)
4199 return Error(ArgList[i].Loc, "redefinition of argument '%" +
4200 ArgList[i].Name + "'");
4206 // Check the declaration has no block address forward references.
4208 if (FunctionName.empty()) {
4209 ID.Kind = ValID::t_GlobalID;
4210 ID.UIntVal = NumberedVals.size() - 1;
4212 ID.Kind = ValID::t_GlobalName;
4213 ID.StrVal = FunctionName;
4215 auto Blocks = ForwardRefBlockAddresses.find(ID);
4216 if (Blocks != ForwardRefBlockAddresses.end())
4217 return Error(Blocks->first.Loc,
4218 "cannot take blockaddress inside a declaration");
4222 bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
4224 if (FunctionNumber == -1) {
4225 ID.Kind = ValID::t_GlobalName;
4226 ID.StrVal = F.getName();
4228 ID.Kind = ValID::t_GlobalID;
4229 ID.UIntVal = FunctionNumber;
4232 auto Blocks = P.ForwardRefBlockAddresses.find(ID);
4233 if (Blocks == P.ForwardRefBlockAddresses.end())
4236 for (const auto &I : Blocks->second) {
4237 const ValID &BBID = I.first;
4238 GlobalValue *GV = I.second;
4240 assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
4241 "Expected local id or name");
4243 if (BBID.Kind == ValID::t_LocalName)
4244 BB = GetBB(BBID.StrVal, BBID.Loc);
4246 BB = GetBB(BBID.UIntVal, BBID.Loc);
4248 return P.Error(BBID.Loc, "referenced value is not a basic block");
4250 GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
4251 GV->eraseFromParent();
4254 P.ForwardRefBlockAddresses.erase(Blocks);
4258 /// ParseFunctionBody
4259 /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
4260 bool LLParser::ParseFunctionBody(Function &Fn) {
4261 if (Lex.getKind() != lltok::lbrace)
4262 return TokError("expected '{' in function body");
4263 Lex.Lex(); // eat the {.
4265 int FunctionNumber = -1;
4266 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
4268 PerFunctionState PFS(*this, Fn, FunctionNumber);
4270 // Resolve block addresses and allow basic blocks to be forward-declared
4271 // within this function.
4272 if (PFS.resolveForwardRefBlockAddresses())
4274 SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
4276 // We need at least one basic block.
4277 if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
4278 return TokError("function body requires at least one basic block");
4280 while (Lex.getKind() != lltok::rbrace &&
4281 Lex.getKind() != lltok::kw_uselistorder)
4282 if (ParseBasicBlock(PFS)) return true;
4284 while (Lex.getKind() != lltok::rbrace)
4285 if (ParseUseListOrder(&PFS))
4291 // Verify function is ok.
4292 return PFS.FinishFunction();
4296 /// ::= LabelStr? Instruction*
4297 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
4298 // If this basic block starts out with a name, remember it.
4300 LocTy NameLoc = Lex.getLoc();
4301 if (Lex.getKind() == lltok::LabelStr) {
4302 Name = Lex.getStrVal();
4306 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
4308 return Error(NameLoc,
4309 "unable to create block named '" + Name + "'");
4311 std::string NameStr;
4313 // Parse the instructions in this block until we get a terminator.
4316 // This instruction may have three possibilities for a name: a) none
4317 // specified, b) name specified "%foo =", c) number specified: "%4 =".
4318 LocTy NameLoc = Lex.getLoc();
4322 if (Lex.getKind() == lltok::LocalVarID) {
4323 NameID = Lex.getUIntVal();
4325 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
4327 } else if (Lex.getKind() == lltok::LocalVar) {
4328 NameStr = Lex.getStrVal();
4330 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
4334 switch (ParseInstruction(Inst, BB, PFS)) {
4335 default: llvm_unreachable("Unknown ParseInstruction result!");
4336 case InstError: return true;
4338 BB->getInstList().push_back(Inst);
4340 // With a normal result, we check to see if the instruction is followed by
4341 // a comma and metadata.
4342 if (EatIfPresent(lltok::comma))
4343 if (ParseInstructionMetadata(Inst, &PFS))
4346 case InstExtraComma:
4347 BB->getInstList().push_back(Inst);
4349 // If the instruction parser ate an extra comma at the end of it, it
4350 // *must* be followed by metadata.
4351 if (ParseInstructionMetadata(Inst, &PFS))
4356 // Set the name on the instruction.
4357 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
4358 } while (!isa<TerminatorInst>(Inst));
4363 //===----------------------------------------------------------------------===//
4364 // Instruction Parsing.
4365 //===----------------------------------------------------------------------===//
4367 /// ParseInstruction - Parse one of the many different instructions.
4369 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
4370 PerFunctionState &PFS) {
4371 lltok::Kind Token = Lex.getKind();
4372 if (Token == lltok::Eof)
4373 return TokError("found end of file when expecting more instructions");
4374 LocTy Loc = Lex.getLoc();
4375 unsigned KeywordVal = Lex.getUIntVal();
4376 Lex.Lex(); // Eat the keyword.
4379 default: return Error(Loc, "expected instruction opcode");
4380 // Terminator Instructions.
4381 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
4382 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
4383 case lltok::kw_br: return ParseBr(Inst, PFS);
4384 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
4385 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
4386 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
4387 case lltok::kw_resume: return ParseResume(Inst, PFS);
4388 // Binary Operators.
4392 case lltok::kw_shl: {
4393 bool NUW = EatIfPresent(lltok::kw_nuw);
4394 bool NSW = EatIfPresent(lltok::kw_nsw);
4395 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
4397 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4399 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
4400 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
4403 case lltok::kw_fadd:
4404 case lltok::kw_fsub:
4405 case lltok::kw_fmul:
4406 case lltok::kw_fdiv:
4407 case lltok::kw_frem: {
4408 FastMathFlags FMF = EatFastMathFlagsIfPresent();
4409 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
4413 Inst->setFastMathFlags(FMF);
4417 case lltok::kw_sdiv:
4418 case lltok::kw_udiv:
4419 case lltok::kw_lshr:
4420 case lltok::kw_ashr: {
4421 bool Exact = EatIfPresent(lltok::kw_exact);
4423 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
4424 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
4428 case lltok::kw_urem:
4429 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
4432 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
4433 case lltok::kw_icmp:
4434 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
4436 case lltok::kw_trunc:
4437 case lltok::kw_zext:
4438 case lltok::kw_sext:
4439 case lltok::kw_fptrunc:
4440 case lltok::kw_fpext:
4441 case lltok::kw_bitcast:
4442 case lltok::kw_addrspacecast:
4443 case lltok::kw_uitofp:
4444 case lltok::kw_sitofp:
4445 case lltok::kw_fptoui:
4446 case lltok::kw_fptosi:
4447 case lltok::kw_inttoptr:
4448 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
4450 case lltok::kw_select: return ParseSelect(Inst, PFS);
4451 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
4452 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
4453 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
4454 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
4455 case lltok::kw_phi: return ParsePHI(Inst, PFS);
4456 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
4458 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
4459 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
4460 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
4462 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
4463 case lltok::kw_load: return ParseLoad(Inst, PFS);
4464 case lltok::kw_store: return ParseStore(Inst, PFS);
4465 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
4466 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
4467 case lltok::kw_fence: return ParseFence(Inst, PFS);
4468 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
4469 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
4470 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
4474 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
4475 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
4476 if (Opc == Instruction::FCmp) {
4477 switch (Lex.getKind()) {
4478 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
4479 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
4480 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
4481 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
4482 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
4483 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
4484 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
4485 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
4486 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
4487 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
4488 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
4489 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
4490 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
4491 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
4492 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
4493 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
4494 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
4497 switch (Lex.getKind()) {
4498 default: return TokError("expected icmp predicate (e.g. 'eq')");
4499 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
4500 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
4501 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
4502 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
4503 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
4504 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
4505 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
4506 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
4507 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
4508 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
4515 //===----------------------------------------------------------------------===//
4516 // Terminator Instructions.
4517 //===----------------------------------------------------------------------===//
4519 /// ParseRet - Parse a return instruction.
4520 /// ::= 'ret' void (',' !dbg, !1)*
4521 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
4522 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
4523 PerFunctionState &PFS) {
4524 SMLoc TypeLoc = Lex.getLoc();
4526 if (ParseType(Ty, true /*void allowed*/)) return true;
4528 Type *ResType = PFS.getFunction().getReturnType();
4530 if (Ty->isVoidTy()) {
4531 if (!ResType->isVoidTy())
4532 return Error(TypeLoc, "value doesn't match function result type '" +
4533 getTypeString(ResType) + "'");
4535 Inst = ReturnInst::Create(Context);
4540 if (ParseValue(Ty, RV, PFS)) return true;
4542 if (ResType != RV->getType())
4543 return Error(TypeLoc, "value doesn't match function result type '" +
4544 getTypeString(ResType) + "'");
4546 Inst = ReturnInst::Create(Context, RV);
4552 /// ::= 'br' TypeAndValue
4553 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4554 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
4557 BasicBlock *Op1, *Op2;
4558 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
4560 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
4561 Inst = BranchInst::Create(BB);
4565 if (Op0->getType() != Type::getInt1Ty(Context))
4566 return Error(Loc, "branch condition must have 'i1' type");
4568 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
4569 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
4570 ParseToken(lltok::comma, "expected ',' after true destination") ||
4571 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
4574 Inst = BranchInst::Create(Op1, Op2, Op0);
4580 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
4582 /// ::= (TypeAndValue ',' TypeAndValue)*
4583 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
4584 LocTy CondLoc, BBLoc;
4586 BasicBlock *DefaultBB;
4587 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
4588 ParseToken(lltok::comma, "expected ',' after switch condition") ||
4589 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
4590 ParseToken(lltok::lsquare, "expected '[' with switch table"))
4593 if (!Cond->getType()->isIntegerTy())
4594 return Error(CondLoc, "switch condition must have integer type");
4596 // Parse the jump table pairs.
4597 SmallPtrSet<Value*, 32> SeenCases;
4598 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
4599 while (Lex.getKind() != lltok::rsquare) {
4603 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
4604 ParseToken(lltok::comma, "expected ',' after case value") ||
4605 ParseTypeAndBasicBlock(DestBB, PFS))
4608 if (!SeenCases.insert(Constant).second)
4609 return Error(CondLoc, "duplicate case value in switch");
4610 if (!isa<ConstantInt>(Constant))
4611 return Error(CondLoc, "case value is not a constant integer");
4613 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
4616 Lex.Lex(); // Eat the ']'.
4618 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
4619 for (unsigned i = 0, e = Table.size(); i != e; ++i)
4620 SI->addCase(Table[i].first, Table[i].second);
4627 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
4628 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
4631 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
4632 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
4633 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
4636 if (!Address->getType()->isPointerTy())
4637 return Error(AddrLoc, "indirectbr address must have pointer type");
4639 // Parse the destination list.
4640 SmallVector<BasicBlock*, 16> DestList;
4642 if (Lex.getKind() != lltok::rsquare) {
4644 if (ParseTypeAndBasicBlock(DestBB, PFS))
4646 DestList.push_back(DestBB);
4648 while (EatIfPresent(lltok::comma)) {
4649 if (ParseTypeAndBasicBlock(DestBB, PFS))
4651 DestList.push_back(DestBB);
4655 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
4658 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
4659 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
4660 IBI->addDestination(DestList[i]);
4667 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
4668 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
4669 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
4670 LocTy CallLoc = Lex.getLoc();
4671 AttrBuilder RetAttrs, FnAttrs;
4672 std::vector<unsigned> FwdRefAttrGrps;
4675 Type *RetType = nullptr;
4678 SmallVector<ParamInfo, 16> ArgList;
4680 BasicBlock *NormalBB, *UnwindBB;
4681 if (ParseOptionalCallingConv(CC) ||
4682 ParseOptionalReturnAttrs(RetAttrs) ||
4683 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4684 ParseValID(CalleeID) ||
4685 ParseParameterList(ArgList, PFS) ||
4686 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4688 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
4689 ParseTypeAndBasicBlock(NormalBB, PFS) ||
4690 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
4691 ParseTypeAndBasicBlock(UnwindBB, PFS))
4694 // If RetType is a non-function pointer type, then this is the short syntax
4695 // for the call, which means that RetType is just the return type. Infer the
4696 // rest of the function argument types from the arguments that are present.
4697 PointerType *PFTy = nullptr;
4698 FunctionType *Ty = nullptr;
4699 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4700 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4701 // Pull out the types of all of the arguments...
4702 std::vector<Type*> ParamTypes;
4703 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4704 ParamTypes.push_back(ArgList[i].V->getType());
4706 if (!FunctionType::isValidReturnType(RetType))
4707 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4709 Ty = FunctionType::get(RetType, ParamTypes, false);
4710 PFTy = PointerType::getUnqual(Ty);
4713 // Look up the callee.
4715 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4717 // Set up the Attribute for the function.
4718 SmallVector<AttributeSet, 8> Attrs;
4719 if (RetAttrs.hasAttributes())
4720 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4721 AttributeSet::ReturnIndex,
4724 SmallVector<Value*, 8> Args;
4726 // Loop through FunctionType's arguments and ensure they are specified
4727 // correctly. Also, gather any parameter attributes.
4728 FunctionType::param_iterator I = Ty->param_begin();
4729 FunctionType::param_iterator E = Ty->param_end();
4730 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4731 Type *ExpectedTy = nullptr;
4734 } else if (!Ty->isVarArg()) {
4735 return Error(ArgList[i].Loc, "too many arguments specified");
4738 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4739 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4740 getTypeString(ExpectedTy) + "'");
4741 Args.push_back(ArgList[i].V);
4742 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4743 AttrBuilder B(ArgList[i].Attrs, i + 1);
4744 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4749 return Error(CallLoc, "not enough parameters specified for call");
4751 if (FnAttrs.hasAttributes()) {
4752 if (FnAttrs.hasAlignmentAttr())
4753 return Error(CallLoc, "invoke instructions may not have an alignment");
4755 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4756 AttributeSet::FunctionIndex,
4760 // Finish off the Attribute and check them
4761 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4763 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
4764 II->setCallingConv(CC);
4765 II->setAttributes(PAL);
4766 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
4772 /// ::= 'resume' TypeAndValue
4773 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
4774 Value *Exn; LocTy ExnLoc;
4775 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
4778 ResumeInst *RI = ResumeInst::Create(Exn);
4783 //===----------------------------------------------------------------------===//
4784 // Binary Operators.
4785 //===----------------------------------------------------------------------===//
4788 /// ::= ArithmeticOps TypeAndValue ',' Value
4790 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
4791 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
4792 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
4793 unsigned Opc, unsigned OperandType) {
4794 LocTy Loc; Value *LHS, *RHS;
4795 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4796 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
4797 ParseValue(LHS->getType(), RHS, PFS))
4801 switch (OperandType) {
4802 default: llvm_unreachable("Unknown operand type!");
4803 case 0: // int or FP.
4804 Valid = LHS->getType()->isIntOrIntVectorTy() ||
4805 LHS->getType()->isFPOrFPVectorTy();
4807 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
4808 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
4812 return Error(Loc, "invalid operand type for instruction");
4814 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4819 /// ::= ArithmeticOps TypeAndValue ',' Value {
4820 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
4822 LocTy Loc; Value *LHS, *RHS;
4823 if (ParseTypeAndValue(LHS, Loc, PFS) ||
4824 ParseToken(lltok::comma, "expected ',' in logical operation") ||
4825 ParseValue(LHS->getType(), RHS, PFS))
4828 if (!LHS->getType()->isIntOrIntVectorTy())
4829 return Error(Loc,"instruction requires integer or integer vector operands");
4831 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4837 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
4838 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
4839 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
4841 // Parse the integer/fp comparison predicate.
4845 if (ParseCmpPredicate(Pred, Opc) ||
4846 ParseTypeAndValue(LHS, Loc, PFS) ||
4847 ParseToken(lltok::comma, "expected ',' after compare value") ||
4848 ParseValue(LHS->getType(), RHS, PFS))
4851 if (Opc == Instruction::FCmp) {
4852 if (!LHS->getType()->isFPOrFPVectorTy())
4853 return Error(Loc, "fcmp requires floating point operands");
4854 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4856 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
4857 if (!LHS->getType()->isIntOrIntVectorTy() &&
4858 !LHS->getType()->getScalarType()->isPointerTy())
4859 return Error(Loc, "icmp requires integer operands");
4860 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
4865 //===----------------------------------------------------------------------===//
4866 // Other Instructions.
4867 //===----------------------------------------------------------------------===//
4871 /// ::= CastOpc TypeAndValue 'to' Type
4872 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
4876 Type *DestTy = nullptr;
4877 if (ParseTypeAndValue(Op, Loc, PFS) ||
4878 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
4882 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
4883 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
4884 return Error(Loc, "invalid cast opcode for cast from '" +
4885 getTypeString(Op->getType()) + "' to '" +
4886 getTypeString(DestTy) + "'");
4888 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
4893 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4894 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
4896 Value *Op0, *Op1, *Op2;
4897 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4898 ParseToken(lltok::comma, "expected ',' after select condition") ||
4899 ParseTypeAndValue(Op1, PFS) ||
4900 ParseToken(lltok::comma, "expected ',' after select value") ||
4901 ParseTypeAndValue(Op2, PFS))
4904 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
4905 return Error(Loc, Reason);
4907 Inst = SelectInst::Create(Op0, Op1, Op2);
4912 /// ::= 'va_arg' TypeAndValue ',' Type
4913 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
4915 Type *EltTy = nullptr;
4917 if (ParseTypeAndValue(Op, PFS) ||
4918 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
4919 ParseType(EltTy, TypeLoc))
4922 if (!EltTy->isFirstClassType())
4923 return Error(TypeLoc, "va_arg requires operand with first class type");
4925 Inst = new VAArgInst(Op, EltTy);
4929 /// ParseExtractElement
4930 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4931 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4934 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4935 ParseToken(lltok::comma, "expected ',' after extract value") ||
4936 ParseTypeAndValue(Op1, PFS))
4939 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4940 return Error(Loc, "invalid extractelement operands");
4942 Inst = ExtractElementInst::Create(Op0, Op1);
4946 /// ParseInsertElement
4947 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4948 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4950 Value *Op0, *Op1, *Op2;
4951 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4952 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4953 ParseTypeAndValue(Op1, PFS) ||
4954 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4955 ParseTypeAndValue(Op2, PFS))
4958 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4959 return Error(Loc, "invalid insertelement operands");
4961 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4965 /// ParseShuffleVector
4966 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4967 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4969 Value *Op0, *Op1, *Op2;
4970 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4971 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4972 ParseTypeAndValue(Op1, PFS) ||
4973 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4974 ParseTypeAndValue(Op2, PFS))
4977 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4978 return Error(Loc, "invalid shufflevector operands");
4980 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4985 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4986 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4987 Type *Ty = nullptr; LocTy TypeLoc;
4990 if (ParseType(Ty, TypeLoc) ||
4991 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4992 ParseValue(Ty, Op0, PFS) ||
4993 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4994 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4995 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4998 bool AteExtraComma = false;
4999 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
5001 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
5003 if (!EatIfPresent(lltok::comma))
5006 if (Lex.getKind() == lltok::MetadataVar) {
5007 AteExtraComma = true;
5011 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
5012 ParseValue(Ty, Op0, PFS) ||
5013 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
5014 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
5015 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
5019 if (!Ty->isFirstClassType())
5020 return Error(TypeLoc, "phi node must have first class type");
5022 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
5023 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
5024 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
5026 return AteExtraComma ? InstExtraComma : InstNormal;
5030 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
5032 /// ::= 'catch' TypeAndValue
5034 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
5035 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
5036 Type *Ty = nullptr; LocTy TyLoc;
5037 Value *PersFn; LocTy PersFnLoc;
5039 if (ParseType(Ty, TyLoc) ||
5040 ParseToken(lltok::kw_personality, "expected 'personality'") ||
5041 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
5044 std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, PersFn, 0));
5045 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
5047 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
5048 LandingPadInst::ClauseType CT;
5049 if (EatIfPresent(lltok::kw_catch))
5050 CT = LandingPadInst::Catch;
5051 else if (EatIfPresent(lltok::kw_filter))
5052 CT = LandingPadInst::Filter;
5054 return TokError("expected 'catch' or 'filter' clause type");
5058 if (ParseTypeAndValue(V, VLoc, PFS))
5061 // A 'catch' type expects a non-array constant. A filter clause expects an
5063 if (CT == LandingPadInst::Catch) {
5064 if (isa<ArrayType>(V->getType()))
5065 Error(VLoc, "'catch' clause has an invalid type");
5067 if (!isa<ArrayType>(V->getType()))
5068 Error(VLoc, "'filter' clause has an invalid type");
5071 Constant *CV = dyn_cast<Constant>(V);
5073 return Error(VLoc, "clause argument must be a constant");
5077 Inst = LP.release();
5082 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
5083 /// ParameterList OptionalAttrs
5084 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
5085 /// ParameterList OptionalAttrs
5086 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
5087 /// ParameterList OptionalAttrs
5088 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
5089 CallInst::TailCallKind TCK) {
5090 AttrBuilder RetAttrs, FnAttrs;
5091 std::vector<unsigned> FwdRefAttrGrps;
5094 Type *RetType = nullptr;
5097 SmallVector<ParamInfo, 16> ArgList;
5098 LocTy CallLoc = Lex.getLoc();
5100 if ((TCK != CallInst::TCK_None &&
5101 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
5102 ParseOptionalCallingConv(CC) ||
5103 ParseOptionalReturnAttrs(RetAttrs) ||
5104 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
5105 ParseValID(CalleeID) ||
5106 ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
5107 PFS.getFunction().isVarArg()) ||
5108 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
5112 // If RetType is a non-function pointer type, then this is the short syntax
5113 // for the call, which means that RetType is just the return type. Infer the
5114 // rest of the function argument types from the arguments that are present.
5115 PointerType *PFTy = nullptr;
5116 FunctionType *Ty = nullptr;
5117 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
5118 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
5119 // Pull out the types of all of the arguments...
5120 std::vector<Type*> ParamTypes;
5121 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
5122 ParamTypes.push_back(ArgList[i].V->getType());
5124 if (!FunctionType::isValidReturnType(RetType))
5125 return Error(RetTypeLoc, "Invalid result type for LLVM function");
5127 Ty = FunctionType::get(RetType, ParamTypes, false);
5128 PFTy = PointerType::getUnqual(Ty);
5131 // Look up the callee.
5133 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
5135 // Set up the Attribute for the function.
5136 SmallVector<AttributeSet, 8> Attrs;
5137 if (RetAttrs.hasAttributes())
5138 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5139 AttributeSet::ReturnIndex,
5142 SmallVector<Value*, 8> Args;
5144 // Loop through FunctionType's arguments and ensure they are specified
5145 // correctly. Also, gather any parameter attributes.
5146 FunctionType::param_iterator I = Ty->param_begin();
5147 FunctionType::param_iterator E = Ty->param_end();
5148 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
5149 Type *ExpectedTy = nullptr;
5152 } else if (!Ty->isVarArg()) {
5153 return Error(ArgList[i].Loc, "too many arguments specified");
5156 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
5157 return Error(ArgList[i].Loc, "argument is not of expected type '" +
5158 getTypeString(ExpectedTy) + "'");
5159 Args.push_back(ArgList[i].V);
5160 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
5161 AttrBuilder B(ArgList[i].Attrs, i + 1);
5162 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
5167 return Error(CallLoc, "not enough parameters specified for call");
5169 if (FnAttrs.hasAttributes()) {
5170 if (FnAttrs.hasAlignmentAttr())
5171 return Error(CallLoc, "call instructions may not have an alignment");
5173 Attrs.push_back(AttributeSet::get(RetType->getContext(),
5174 AttributeSet::FunctionIndex,
5178 // Finish off the Attribute and check them
5179 AttributeSet PAL = AttributeSet::get(Context, Attrs);
5181 CallInst *CI = CallInst::Create(Callee, Args);
5182 CI->setTailCallKind(TCK);
5183 CI->setCallingConv(CC);
5184 CI->setAttributes(PAL);
5185 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
5190 //===----------------------------------------------------------------------===//
5191 // Memory Instructions.
5192 //===----------------------------------------------------------------------===//
5195 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
5196 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
5197 Value *Size = nullptr;
5198 LocTy SizeLoc, TyLoc;
5199 unsigned Alignment = 0;
5202 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
5204 if (ParseType(Ty, TyLoc)) return true;
5206 if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
5207 return Error(TyLoc, "invalid type for alloca");
5209 bool AteExtraComma = false;
5210 if (EatIfPresent(lltok::comma)) {
5211 if (Lex.getKind() == lltok::kw_align) {
5212 if (ParseOptionalAlignment(Alignment)) return true;
5213 } else if (Lex.getKind() == lltok::MetadataVar) {
5214 AteExtraComma = true;
5216 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
5217 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5222 if (Size && !Size->getType()->isIntegerTy())
5223 return Error(SizeLoc, "element count must have integer type");
5225 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
5226 AI->setUsedWithInAlloca(IsInAlloca);
5228 return AteExtraComma ? InstExtraComma : InstNormal;
5232 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
5233 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
5234 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5235 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
5236 Value *Val; LocTy Loc;
5237 unsigned Alignment = 0;
5238 bool AteExtraComma = false;
5239 bool isAtomic = false;
5240 AtomicOrdering Ordering = NotAtomic;
5241 SynchronizationScope Scope = CrossThread;
5243 if (Lex.getKind() == lltok::kw_atomic) {
5248 bool isVolatile = false;
5249 if (Lex.getKind() == lltok::kw_volatile) {
5255 LocTy ExplicitTypeLoc = Lex.getLoc();
5256 if (ParseType(Ty) ||
5257 ParseToken(lltok::comma, "expected comma after load's type") ||
5258 ParseTypeAndValue(Val, Loc, PFS) ||
5259 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5260 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5263 if (!Val->getType()->isPointerTy() ||
5264 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
5265 return Error(Loc, "load operand must be a pointer to a first class type");
5266 if (isAtomic && !Alignment)
5267 return Error(Loc, "atomic load must have explicit non-zero alignment");
5268 if (Ordering == Release || Ordering == AcquireRelease)
5269 return Error(Loc, "atomic load cannot use Release ordering");
5271 if (Ty != cast<PointerType>(Val->getType())->getElementType())
5272 return Error(ExplicitTypeLoc,
5273 "explicit pointee type doesn't match operand's pointee type");
5275 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
5276 return AteExtraComma ? InstExtraComma : InstNormal;
5281 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
5282 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
5283 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
5284 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
5285 Value *Val, *Ptr; LocTy Loc, PtrLoc;
5286 unsigned Alignment = 0;
5287 bool AteExtraComma = false;
5288 bool isAtomic = false;
5289 AtomicOrdering Ordering = NotAtomic;
5290 SynchronizationScope Scope = CrossThread;
5292 if (Lex.getKind() == lltok::kw_atomic) {
5297 bool isVolatile = false;
5298 if (Lex.getKind() == lltok::kw_volatile) {
5303 if (ParseTypeAndValue(Val, Loc, PFS) ||
5304 ParseToken(lltok::comma, "expected ',' after store operand") ||
5305 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5306 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
5307 ParseOptionalCommaAlign(Alignment, AteExtraComma))
5310 if (!Ptr->getType()->isPointerTy())
5311 return Error(PtrLoc, "store operand must be a pointer");
5312 if (!Val->getType()->isFirstClassType())
5313 return Error(Loc, "store operand must be a first class value");
5314 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5315 return Error(Loc, "stored value and pointer type do not match");
5316 if (isAtomic && !Alignment)
5317 return Error(Loc, "atomic store must have explicit non-zero alignment");
5318 if (Ordering == Acquire || Ordering == AcquireRelease)
5319 return Error(Loc, "atomic store cannot use Acquire ordering");
5321 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
5322 return AteExtraComma ? InstExtraComma : InstNormal;
5326 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
5327 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
5328 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
5329 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
5330 bool AteExtraComma = false;
5331 AtomicOrdering SuccessOrdering = NotAtomic;
5332 AtomicOrdering FailureOrdering = NotAtomic;
5333 SynchronizationScope Scope = CrossThread;
5334 bool isVolatile = false;
5335 bool isWeak = false;
5337 if (EatIfPresent(lltok::kw_weak))
5340 if (EatIfPresent(lltok::kw_volatile))
5343 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5344 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
5345 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
5346 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
5347 ParseTypeAndValue(New, NewLoc, PFS) ||
5348 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
5349 ParseOrdering(FailureOrdering))
5352 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
5353 return TokError("cmpxchg cannot be unordered");
5354 if (SuccessOrdering < FailureOrdering)
5355 return TokError("cmpxchg must be at least as ordered on success as failure");
5356 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
5357 return TokError("cmpxchg failure ordering cannot include release semantics");
5358 if (!Ptr->getType()->isPointerTy())
5359 return Error(PtrLoc, "cmpxchg operand must be a pointer");
5360 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
5361 return Error(CmpLoc, "compare value and pointer type do not match");
5362 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
5363 return Error(NewLoc, "new value and pointer type do not match");
5364 if (!New->getType()->isIntegerTy())
5365 return Error(NewLoc, "cmpxchg operand must be an integer");
5366 unsigned Size = New->getType()->getPrimitiveSizeInBits();
5367 if (Size < 8 || (Size & (Size - 1)))
5368 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
5371 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
5372 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
5373 CXI->setVolatile(isVolatile);
5374 CXI->setWeak(isWeak);
5376 return AteExtraComma ? InstExtraComma : InstNormal;
5380 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
5381 /// 'singlethread'? AtomicOrdering
5382 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
5383 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
5384 bool AteExtraComma = false;
5385 AtomicOrdering Ordering = NotAtomic;
5386 SynchronizationScope Scope = CrossThread;
5387 bool isVolatile = false;
5388 AtomicRMWInst::BinOp Operation;
5390 if (EatIfPresent(lltok::kw_volatile))
5393 switch (Lex.getKind()) {
5394 default: return TokError("expected binary operation in atomicrmw");
5395 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
5396 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
5397 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
5398 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
5399 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
5400 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
5401 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
5402 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
5403 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
5404 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
5405 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
5407 Lex.Lex(); // Eat the operation.
5409 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
5410 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
5411 ParseTypeAndValue(Val, ValLoc, PFS) ||
5412 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5415 if (Ordering == Unordered)
5416 return TokError("atomicrmw cannot be unordered");
5417 if (!Ptr->getType()->isPointerTy())
5418 return Error(PtrLoc, "atomicrmw operand must be a pointer");
5419 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
5420 return Error(ValLoc, "atomicrmw value and pointer type do not match");
5421 if (!Val->getType()->isIntegerTy())
5422 return Error(ValLoc, "atomicrmw operand must be an integer");
5423 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
5424 if (Size < 8 || (Size & (Size - 1)))
5425 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
5428 AtomicRMWInst *RMWI =
5429 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
5430 RMWI->setVolatile(isVolatile);
5432 return AteExtraComma ? InstExtraComma : InstNormal;
5436 /// ::= 'fence' 'singlethread'? AtomicOrdering
5437 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
5438 AtomicOrdering Ordering = NotAtomic;
5439 SynchronizationScope Scope = CrossThread;
5440 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
5443 if (Ordering == Unordered)
5444 return TokError("fence cannot be unordered");
5445 if (Ordering == Monotonic)
5446 return TokError("fence cannot be monotonic");
5448 Inst = new FenceInst(Context, Ordering, Scope);
5452 /// ParseGetElementPtr
5453 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
5454 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
5455 Value *Ptr = nullptr;
5456 Value *Val = nullptr;
5459 bool InBounds = EatIfPresent(lltok::kw_inbounds);
5462 LocTy ExplicitTypeLoc = Lex.getLoc();
5463 if (ParseType(Ty) ||
5464 ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
5465 ParseTypeAndValue(Ptr, Loc, PFS))
5468 Type *PtrTy = Ptr->getType();
5469 if (VectorType *VT = dyn_cast<VectorType>(PtrTy))
5470 PtrTy = VT->getElementType();
5471 SequentialType *SeqPtrTy = dyn_cast<SequentialType>(PtrTy);
5473 return Error(Loc, "pointer type is not valid");
5474 if (Ty != SeqPtrTy->getElementType())
5475 return Error(ExplicitTypeLoc,
5476 "explicit pointee type doesn't match operand's pointee type");
5478 Type *BaseType = Ptr->getType();
5479 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
5480 if (!BasePointerType)
5481 return Error(Loc, "base of getelementptr must be a pointer");
5483 SmallVector<Value*, 16> Indices;
5484 bool AteExtraComma = false;
5485 while (EatIfPresent(lltok::comma)) {
5486 if (Lex.getKind() == lltok::MetadataVar) {
5487 AteExtraComma = true;
5490 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
5491 if (!Val->getType()->getScalarType()->isIntegerTy())
5492 return Error(EltLoc, "getelementptr index must be an integer");
5493 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
5494 return Error(EltLoc, "getelementptr index type missmatch");
5495 if (Val->getType()->isVectorTy()) {
5496 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
5497 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
5498 if (ValNumEl != PtrNumEl)
5499 return Error(EltLoc,
5500 "getelementptr vector index has a wrong number of elements");
5502 Indices.push_back(Val);
5505 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
5506 return Error(Loc, "base element of getelementptr must be sized");
5508 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
5509 return Error(Loc, "invalid getelementptr indices");
5510 Inst = GetElementPtrInst::Create(Ptr, Indices);
5512 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
5513 return AteExtraComma ? InstExtraComma : InstNormal;
5516 /// ParseExtractValue
5517 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
5518 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
5519 Value *Val; LocTy Loc;
5520 SmallVector<unsigned, 4> Indices;
5522 if (ParseTypeAndValue(Val, Loc, PFS) ||
5523 ParseIndexList(Indices, AteExtraComma))
5526 if (!Val->getType()->isAggregateType())
5527 return Error(Loc, "extractvalue operand must be aggregate type");
5529 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
5530 return Error(Loc, "invalid indices for extractvalue");
5531 Inst = ExtractValueInst::Create(Val, Indices);
5532 return AteExtraComma ? InstExtraComma : InstNormal;
5535 /// ParseInsertValue
5536 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
5537 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
5538 Value *Val0, *Val1; LocTy Loc0, Loc1;
5539 SmallVector<unsigned, 4> Indices;
5541 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
5542 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
5543 ParseTypeAndValue(Val1, Loc1, PFS) ||
5544 ParseIndexList(Indices, AteExtraComma))
5547 if (!Val0->getType()->isAggregateType())
5548 return Error(Loc0, "insertvalue operand must be aggregate type");
5550 Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
5552 return Error(Loc0, "invalid indices for insertvalue");
5553 if (IndexedType != Val1->getType())
5554 return Error(Loc1, "insertvalue operand and field disagree in type: '" +
5555 getTypeString(Val1->getType()) + "' instead of '" +
5556 getTypeString(IndexedType) + "'");
5557 Inst = InsertValueInst::Create(Val0, Val1, Indices);
5558 return AteExtraComma ? InstExtraComma : InstNormal;
5561 //===----------------------------------------------------------------------===//
5562 // Embedded metadata.
5563 //===----------------------------------------------------------------------===//
5565 /// ParseMDNodeVector
5566 /// ::= { Element (',' Element)* }
5568 /// ::= 'null' | TypeAndValue
5569 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
5570 if (ParseToken(lltok::lbrace, "expected '{' here"))
5573 // Check for an empty list.
5574 if (EatIfPresent(lltok::rbrace))
5578 // Null is a special case since it is typeless.
5579 if (EatIfPresent(lltok::kw_null)) {
5580 Elts.push_back(nullptr);
5585 if (ParseMetadata(MD, nullptr))
5588 } while (EatIfPresent(lltok::comma));
5590 return ParseToken(lltok::rbrace, "expected end of metadata node");
5593 //===----------------------------------------------------------------------===//
5594 // Use-list order directives.
5595 //===----------------------------------------------------------------------===//
5596 bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
5599 return Error(Loc, "value has no uses");
5601 unsigned NumUses = 0;
5602 SmallDenseMap<const Use *, unsigned, 16> Order;
5603 for (const Use &U : V->uses()) {
5604 if (++NumUses > Indexes.size())
5606 Order[&U] = Indexes[NumUses - 1];
5609 return Error(Loc, "value only has one use");
5610 if (Order.size() != Indexes.size() || NumUses > Indexes.size())
5611 return Error(Loc, "wrong number of indexes, expected " +
5612 Twine(std::distance(V->use_begin(), V->use_end())));
5614 V->sortUseList([&](const Use &L, const Use &R) {
5615 return Order.lookup(&L) < Order.lookup(&R);
5620 /// ParseUseListOrderIndexes
5621 /// ::= '{' uint32 (',' uint32)+ '}'
5622 bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
5623 SMLoc Loc = Lex.getLoc();
5624 if (ParseToken(lltok::lbrace, "expected '{' here"))
5626 if (Lex.getKind() == lltok::rbrace)
5627 return Lex.Error("expected non-empty list of uselistorder indexes");
5629 // Use Offset, Max, and IsOrdered to check consistency of indexes. The
5630 // indexes should be distinct numbers in the range [0, size-1], and should
5632 unsigned Offset = 0;
5634 bool IsOrdered = true;
5635 assert(Indexes.empty() && "Expected empty order vector");
5638 if (ParseUInt32(Index))
5641 // Update consistency checks.
5642 Offset += Index - Indexes.size();
5643 Max = std::max(Max, Index);
5644 IsOrdered &= Index == Indexes.size();
5646 Indexes.push_back(Index);
5647 } while (EatIfPresent(lltok::comma));
5649 if (ParseToken(lltok::rbrace, "expected '}' here"))
5652 if (Indexes.size() < 2)
5653 return Error(Loc, "expected >= 2 uselistorder indexes");
5654 if (Offset != 0 || Max >= Indexes.size())
5655 return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
5657 return Error(Loc, "expected uselistorder indexes to change the order");
5662 /// ParseUseListOrder
5663 /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
5664 bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
5665 SMLoc Loc = Lex.getLoc();
5666 if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
5670 SmallVector<unsigned, 16> Indexes;
5671 if (ParseTypeAndValue(V, PFS) ||
5672 ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
5673 ParseUseListOrderIndexes(Indexes))
5676 return sortUseListOrder(V, Indexes, Loc);
5679 /// ParseUseListOrderBB
5680 /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
5681 bool LLParser::ParseUseListOrderBB() {
5682 assert(Lex.getKind() == lltok::kw_uselistorder_bb);
5683 SMLoc Loc = Lex.getLoc();
5687 SmallVector<unsigned, 16> Indexes;
5688 if (ParseValID(Fn) ||
5689 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5690 ParseValID(Label) ||
5691 ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
5692 ParseUseListOrderIndexes(Indexes))
5695 // Check the function.
5697 if (Fn.Kind == ValID::t_GlobalName)
5698 GV = M->getNamedValue(Fn.StrVal);
5699 else if (Fn.Kind == ValID::t_GlobalID)
5700 GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
5702 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5704 return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
5705 auto *F = dyn_cast<Function>(GV);
5707 return Error(Fn.Loc, "expected function name in uselistorder_bb");
5708 if (F->isDeclaration())
5709 return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
5711 // Check the basic block.
5712 if (Label.Kind == ValID::t_LocalID)
5713 return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
5714 if (Label.Kind != ValID::t_LocalName)
5715 return Error(Label.Loc, "expected basic block name in uselistorder_bb");
5716 Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
5718 return Error(Label.Loc, "invalid basic block in uselistorder_bb");
5719 if (!isa<BasicBlock>(V))
5720 return Error(Label.Loc, "expected basic block in uselistorder_bb");
5722 return sortUseListOrder(V, Indexes, Loc);