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/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
30 static std::string getTypeString(Type *T) {
32 raw_string_ostream Tmp(Result);
37 /// Run: module ::= toplevelentity*
38 bool LLParser::Run() {
42 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
46 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48 bool LLParser::ValidateEndOfModule() {
49 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
57 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
60 if (SlotNo >= NumberedMetadata.size() ||
61 NumberedMetadata[SlotNo] == nullptr)
62 return Error(MDList[i].Loc, "use of undefined metadata '!" +
64 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
67 ForwardRefInstMetadata.clear();
70 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
71 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
73 // Handle any function attribute group forward references.
74 for (std::map<Value*, std::vector<unsigned> >::iterator
75 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
78 std::vector<unsigned> &Vec = I->second;
81 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
83 B.merge(NumberedAttrBuilders[*VI]);
85 if (Function *Fn = dyn_cast<Function>(V)) {
86 AttributeSet AS = Fn->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
93 // If the alignment was parsed as an attribute, move to the alignment
95 if (FnAttrs.hasAlignmentAttr()) {
96 Fn->setAlignment(FnAttrs.getAlignment());
97 FnAttrs.removeAttribute(Attribute::Alignment);
100 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
101 AttributeSet::get(Context,
102 AttributeSet::FunctionIndex,
104 Fn->setAttributes(AS);
105 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
106 AttributeSet AS = CI->getAttributes();
107 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
108 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
109 AS.getFnAttributes());
111 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
112 AttributeSet::get(Context,
113 AttributeSet::FunctionIndex,
115 CI->setAttributes(AS);
116 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
117 AttributeSet AS = II->getAttributes();
118 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120 AS.getFnAttributes());
122 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
123 AttributeSet::get(Context,
124 AttributeSet::FunctionIndex,
126 II->setAttributes(AS);
128 llvm_unreachable("invalid object with forward attribute group reference");
132 // If there are entries in ForwardRefBlockAddresses at this point, they are
133 // references after the function was defined. Resolve those now.
134 while (!ForwardRefBlockAddresses.empty()) {
135 // Okay, we are referencing an already-parsed function, resolve them now.
136 Function *TheFn = nullptr;
137 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
138 if (Fn.Kind == ValID::t_GlobalName)
139 TheFn = M->getFunction(Fn.StrVal);
140 else if (Fn.UIntVal < NumberedVals.size())
141 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
144 return Error(Fn.Loc, "unknown function referenced by blockaddress");
146 // Resolve all these references.
147 if (ResolveForwardRefBlockAddresses(TheFn,
148 ForwardRefBlockAddresses.begin()->second,
152 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
155 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
156 if (NumberedTypes[i].second.isValid())
157 return Error(NumberedTypes[i].second,
158 "use of undefined type '%" + Twine(i) + "'");
160 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
161 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
162 if (I->second.second.isValid())
163 return Error(I->second.second,
164 "use of undefined type named '" + I->getKey() + "'");
166 if (!ForwardRefComdats.empty())
167 return Error(ForwardRefComdats.begin()->second,
168 "use of undefined comdat '$" +
169 ForwardRefComdats.begin()->first + "'");
171 if (!ForwardRefVals.empty())
172 return Error(ForwardRefVals.begin()->second.second,
173 "use of undefined value '@" + ForwardRefVals.begin()->first +
176 if (!ForwardRefValIDs.empty())
177 return Error(ForwardRefValIDs.begin()->second.second,
178 "use of undefined value '@" +
179 Twine(ForwardRefValIDs.begin()->first) + "'");
181 if (!ForwardRefMDNodes.empty())
182 return Error(ForwardRefMDNodes.begin()->second.second,
183 "use of undefined metadata '!" +
184 Twine(ForwardRefMDNodes.begin()->first) + "'");
187 // Look for intrinsic functions and CallInst that need to be upgraded
188 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
189 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
191 UpgradeDebugInfo(*M);
196 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
197 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
198 PerFunctionState *PFS) {
199 // Loop over all the references, resolving them.
200 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
203 if (Refs[i].first.Kind == ValID::t_LocalName)
204 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
206 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
207 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
208 return Error(Refs[i].first.Loc,
209 "cannot take address of numeric label after the function is defined");
211 Res = dyn_cast_or_null<BasicBlock>(
212 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
216 return Error(Refs[i].first.Loc,
217 "referenced value is not a basic block");
219 // Get the BlockAddress for this and update references to use it.
220 BlockAddress *BA = BlockAddress::get(TheFn, Res);
221 Refs[i].second->replaceAllUsesWith(BA);
222 Refs[i].second->eraseFromParent();
228 //===----------------------------------------------------------------------===//
229 // Top-Level Entities
230 //===----------------------------------------------------------------------===//
232 bool LLParser::ParseTopLevelEntities() {
234 switch (Lex.getKind()) {
235 default: return TokError("expected top-level entity");
236 case lltok::Eof: return false;
237 case lltok::kw_declare: if (ParseDeclare()) return true; break;
238 case lltok::kw_define: if (ParseDefine()) return true; break;
239 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
240 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
241 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
242 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
243 case lltok::LocalVar: if (ParseNamedType()) return true; break;
244 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
245 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
246 case lltok::ComdatVar: if (parseComdat()) return true; break;
247 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
248 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
250 // The Global variable production with no name can have many different
251 // optional leading prefixes, the production is:
252 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
253 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
254 // ('constant'|'global') ...
255 case lltok::kw_private: // OptionalLinkage
256 case lltok::kw_internal: // OptionalLinkage
257 case lltok::kw_weak: // OptionalLinkage
258 case lltok::kw_weak_odr: // OptionalLinkage
259 case lltok::kw_linkonce: // OptionalLinkage
260 case lltok::kw_linkonce_odr: // OptionalLinkage
261 case lltok::kw_appending: // OptionalLinkage
262 case lltok::kw_common: // OptionalLinkage
263 case lltok::kw_extern_weak: // OptionalLinkage
264 case lltok::kw_external: // OptionalLinkage
265 case lltok::kw_default: // OptionalVisibility
266 case lltok::kw_hidden: // OptionalVisibility
267 case lltok::kw_protected: // OptionalVisibility
268 case lltok::kw_dllimport: // OptionalDLLStorageClass
269 case lltok::kw_dllexport: // OptionalDLLStorageClass
270 case lltok::kw_thread_local: // OptionalThreadLocal
271 case lltok::kw_addrspace: // OptionalAddrSpace
272 case lltok::kw_constant: // GlobalType
273 case lltok::kw_global: { // GlobalType
274 unsigned Linkage, Visibility, DLLStorageClass;
276 GlobalVariable::ThreadLocalMode TLM;
278 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
279 ParseOptionalVisibility(Visibility) ||
280 ParseOptionalDLLStorageClass(DLLStorageClass) ||
281 ParseOptionalThreadLocal(TLM) ||
282 parseOptionalUnnamedAddr(UnnamedAddr) ||
283 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
284 DLLStorageClass, TLM, UnnamedAddr))
289 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
296 /// ::= 'module' 'asm' STRINGCONSTANT
297 bool LLParser::ParseModuleAsm() {
298 assert(Lex.getKind() == lltok::kw_module);
302 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
303 ParseStringConstant(AsmStr)) return true;
305 M->appendModuleInlineAsm(AsmStr);
310 /// ::= 'target' 'triple' '=' STRINGCONSTANT
311 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
312 bool LLParser::ParseTargetDefinition() {
313 assert(Lex.getKind() == lltok::kw_target);
316 default: return TokError("unknown target property");
317 case lltok::kw_triple:
319 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
320 ParseStringConstant(Str))
322 M->setTargetTriple(Str);
324 case lltok::kw_datalayout:
326 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
327 ParseStringConstant(Str))
329 M->setDataLayout(Str);
335 /// ::= 'deplibs' '=' '[' ']'
336 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
337 /// FIXME: Remove in 4.0. Currently parse, but ignore.
338 bool LLParser::ParseDepLibs() {
339 assert(Lex.getKind() == lltok::kw_deplibs);
341 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
342 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
345 if (EatIfPresent(lltok::rsquare))
350 if (ParseStringConstant(Str)) return true;
351 } while (EatIfPresent(lltok::comma));
353 return ParseToken(lltok::rsquare, "expected ']' at end of list");
356 /// ParseUnnamedType:
357 /// ::= LocalVarID '=' 'type' type
358 bool LLParser::ParseUnnamedType() {
359 LocTy TypeLoc = Lex.getLoc();
360 unsigned TypeID = Lex.getUIntVal();
361 Lex.Lex(); // eat LocalVarID;
363 if (ParseToken(lltok::equal, "expected '=' after name") ||
364 ParseToken(lltok::kw_type, "expected 'type' after '='"))
367 if (TypeID >= NumberedTypes.size())
368 NumberedTypes.resize(TypeID+1);
370 Type *Result = nullptr;
371 if (ParseStructDefinition(TypeLoc, "",
372 NumberedTypes[TypeID], Result)) return true;
374 if (!isa<StructType>(Result)) {
375 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
377 return Error(TypeLoc, "non-struct types may not be recursive");
378 Entry.first = Result;
379 Entry.second = SMLoc();
387 /// ::= LocalVar '=' 'type' type
388 bool LLParser::ParseNamedType() {
389 std::string Name = Lex.getStrVal();
390 LocTy NameLoc = Lex.getLoc();
391 Lex.Lex(); // eat LocalVar.
393 if (ParseToken(lltok::equal, "expected '=' after name") ||
394 ParseToken(lltok::kw_type, "expected 'type' after name"))
397 Type *Result = nullptr;
398 if (ParseStructDefinition(NameLoc, Name,
399 NamedTypes[Name], Result)) return true;
401 if (!isa<StructType>(Result)) {
402 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
404 return Error(NameLoc, "non-struct types may not be recursive");
405 Entry.first = Result;
406 Entry.second = SMLoc();
414 /// ::= 'declare' FunctionHeader
415 bool LLParser::ParseDeclare() {
416 assert(Lex.getKind() == lltok::kw_declare);
420 return ParseFunctionHeader(F, false);
424 /// ::= 'define' FunctionHeader '{' ...
425 bool LLParser::ParseDefine() {
426 assert(Lex.getKind() == lltok::kw_define);
430 return ParseFunctionHeader(F, true) ||
431 ParseFunctionBody(*F);
437 bool LLParser::ParseGlobalType(bool &IsConstant) {
438 if (Lex.getKind() == lltok::kw_constant)
440 else if (Lex.getKind() == lltok::kw_global)
444 return TokError("expected 'global' or 'constant'");
450 /// ParseUnnamedGlobal:
451 /// OptionalVisibility ALIAS ...
452 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
453 /// ... -> global variable
454 /// GlobalID '=' OptionalVisibility ALIAS ...
455 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
456 /// ... -> global variable
457 bool LLParser::ParseUnnamedGlobal() {
458 unsigned VarID = NumberedVals.size();
460 LocTy NameLoc = Lex.getLoc();
462 // Handle the GlobalID form.
463 if (Lex.getKind() == lltok::GlobalID) {
464 if (Lex.getUIntVal() != VarID)
465 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
467 Lex.Lex(); // eat GlobalID;
469 if (ParseToken(lltok::equal, "expected '=' after name"))
474 unsigned Linkage, Visibility, DLLStorageClass;
475 GlobalVariable::ThreadLocalMode TLM;
477 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
478 ParseOptionalVisibility(Visibility) ||
479 ParseOptionalDLLStorageClass(DLLStorageClass) ||
480 ParseOptionalThreadLocal(TLM) ||
481 parseOptionalUnnamedAddr(UnnamedAddr))
484 if (Lex.getKind() != lltok::kw_alias)
485 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
486 DLLStorageClass, TLM, UnnamedAddr);
487 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
491 /// ParseNamedGlobal:
492 /// GlobalVar '=' OptionalVisibility ALIAS ...
493 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
494 /// ... -> global variable
495 bool LLParser::ParseNamedGlobal() {
496 assert(Lex.getKind() == lltok::GlobalVar);
497 LocTy NameLoc = Lex.getLoc();
498 std::string Name = Lex.getStrVal();
502 unsigned Linkage, Visibility, DLLStorageClass;
503 GlobalVariable::ThreadLocalMode TLM;
505 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
506 ParseOptionalLinkage(Linkage, HasLinkage) ||
507 ParseOptionalVisibility(Visibility) ||
508 ParseOptionalDLLStorageClass(DLLStorageClass) ||
509 ParseOptionalThreadLocal(TLM) ||
510 parseOptionalUnnamedAddr(UnnamedAddr))
513 if (Lex.getKind() != lltok::kw_alias)
514 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
515 DLLStorageClass, TLM, UnnamedAddr);
517 return ParseAlias(Name, NameLoc, Linkage, Visibility, DLLStorageClass, TLM,
521 bool LLParser::parseComdat() {
522 assert(Lex.getKind() == lltok::ComdatVar);
523 std::string Name = Lex.getStrVal();
524 LocTy NameLoc = Lex.getLoc();
527 if (ParseToken(lltok::equal, "expected '=' here"))
530 if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
531 return TokError("expected comdat type");
533 Comdat::SelectionKind SK;
534 switch (Lex.getKind()) {
536 return TokError("unknown selection kind");
540 case lltok::kw_exactmatch:
541 SK = Comdat::ExactMatch;
543 case lltok::kw_largest:
544 SK = Comdat::Largest;
546 case lltok::kw_noduplicates:
547 SK = Comdat::NoDuplicates;
549 case lltok::kw_samesize:
550 SK = Comdat::SameSize;
555 // See if the comdat was forward referenced, if so, use the comdat.
556 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
557 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
558 if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
559 return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
562 if (I != ComdatSymTab.end())
565 C = M->getOrInsertComdat(Name);
566 C->setSelectionKind(SK);
572 // ::= '!' STRINGCONSTANT
573 bool LLParser::ParseMDString(MDString *&Result) {
575 if (ParseStringConstant(Str)) return true;
576 llvm::UpgradeMDStringConstant(Str);
577 Result = MDString::get(Context, Str);
582 // ::= '!' MDNodeNumber
584 /// This version of ParseMDNodeID returns the slot number and null in the case
585 /// of a forward reference.
586 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
587 // !{ ..., !42, ... }
588 if (ParseUInt32(SlotNo)) return true;
590 // Check existing MDNode.
591 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
592 Result = NumberedMetadata[SlotNo];
598 bool LLParser::ParseMDNodeID(MDNode *&Result) {
599 // !{ ..., !42, ... }
601 if (ParseMDNodeID(Result, MID)) return true;
603 // If not a forward reference, just return it now.
604 if (Result) return false;
606 // Otherwise, create MDNode forward reference.
607 MDNode *FwdNode = MDNode::getTemporary(Context, None);
608 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
610 if (NumberedMetadata.size() <= MID)
611 NumberedMetadata.resize(MID+1);
612 NumberedMetadata[MID] = FwdNode;
617 /// ParseNamedMetadata:
618 /// !foo = !{ !1, !2 }
619 bool LLParser::ParseNamedMetadata() {
620 assert(Lex.getKind() == lltok::MetadataVar);
621 std::string Name = Lex.getStrVal();
624 if (ParseToken(lltok::equal, "expected '=' here") ||
625 ParseToken(lltok::exclaim, "Expected '!' here") ||
626 ParseToken(lltok::lbrace, "Expected '{' here"))
629 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
630 if (Lex.getKind() != lltok::rbrace)
632 if (ParseToken(lltok::exclaim, "Expected '!' here"))
636 if (ParseMDNodeID(N)) return true;
638 } while (EatIfPresent(lltok::comma));
640 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
646 /// ParseStandaloneMetadata:
648 bool LLParser::ParseStandaloneMetadata() {
649 assert(Lex.getKind() == lltok::exclaim);
651 unsigned MetadataID = 0;
655 SmallVector<Value *, 16> Elts;
656 if (ParseUInt32(MetadataID) ||
657 ParseToken(lltok::equal, "expected '=' here") ||
658 ParseType(Ty, TyLoc) ||
659 ParseToken(lltok::exclaim, "Expected '!' here") ||
660 ParseToken(lltok::lbrace, "Expected '{' here") ||
661 ParseMDNodeVector(Elts, nullptr) ||
662 ParseToken(lltok::rbrace, "expected end of metadata node"))
665 MDNode *Init = MDNode::get(Context, Elts);
667 // See if this was forward referenced, if so, handle it.
668 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
669 FI = ForwardRefMDNodes.find(MetadataID);
670 if (FI != ForwardRefMDNodes.end()) {
671 MDNode *Temp = FI->second.first;
672 Temp->replaceAllUsesWith(Init);
673 MDNode::deleteTemporary(Temp);
674 ForwardRefMDNodes.erase(FI);
676 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
678 if (MetadataID >= NumberedMetadata.size())
679 NumberedMetadata.resize(MetadataID+1);
681 if (NumberedMetadata[MetadataID] != nullptr)
682 return TokError("Metadata id is already used");
683 NumberedMetadata[MetadataID] = Init;
689 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
690 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
691 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
695 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
696 /// OptionalDLLStorageClass OptionalThreadLocal
697 /// OptionalUnNammedAddr 'alias' Aliasee
702 /// Everything through OptionalUnNammedAddr has already been parsed.
704 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc, unsigned L,
705 unsigned Visibility, unsigned DLLStorageClass,
706 GlobalVariable::ThreadLocalMode TLM,
708 assert(Lex.getKind() == lltok::kw_alias);
711 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
713 if(!GlobalAlias::isValidLinkage(Linkage))
714 return Error(NameLoc, "invalid linkage type for alias");
716 if (!isValidVisibilityForLinkage(Visibility, L))
717 return Error(NameLoc,
718 "symbol with local linkage must have default visibility");
721 LocTy AliaseeLoc = Lex.getLoc();
722 if (Lex.getKind() != lltok::kw_bitcast &&
723 Lex.getKind() != lltok::kw_getelementptr &&
724 Lex.getKind() != lltok::kw_addrspacecast &&
725 Lex.getKind() != lltok::kw_inttoptr) {
726 if (ParseGlobalTypeAndValue(Aliasee))
729 // The bitcast dest type is not present, it is implied by the dest type.
733 if (ID.Kind != ValID::t_Constant)
734 return Error(AliaseeLoc, "invalid aliasee");
735 Aliasee = ID.ConstantVal;
738 Type *AliaseeType = Aliasee->getType();
739 auto *PTy = dyn_cast<PointerType>(AliaseeType);
741 return Error(AliaseeLoc, "An alias must have pointer type");
742 Type *Ty = PTy->getElementType();
743 unsigned AddrSpace = PTy->getAddressSpace();
745 // Okay, create the alias but do not insert it into the module yet.
746 std::unique_ptr<GlobalAlias> GA(
747 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
748 Name, Aliasee, /*Parent*/ nullptr));
749 GA->setThreadLocalMode(TLM);
750 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
751 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
752 GA->setUnnamedAddr(UnnamedAddr);
754 // See if this value already exists in the symbol table. If so, it is either
755 // a redefinition or a definition of a forward reference.
756 if (GlobalValue *Val = M->getNamedValue(Name)) {
757 // See if this was a redefinition. If so, there is no entry in
759 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
760 I = ForwardRefVals.find(Name);
761 if (I == ForwardRefVals.end())
762 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
764 // Otherwise, this was a definition of forward ref. Verify that types
766 if (Val->getType() != GA->getType())
767 return Error(NameLoc,
768 "forward reference and definition of alias have different types");
770 // If they agree, just RAUW the old value with the alias and remove the
772 Val->replaceAllUsesWith(GA.get());
773 Val->eraseFromParent();
774 ForwardRefVals.erase(I);
777 // Insert into the module, we know its name won't collide now.
778 M->getAliasList().push_back(GA.get());
779 assert(GA->getName() == Name && "Should not be a name conflict!");
781 // The module owns this now
788 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
789 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
790 /// OptionalExternallyInitialized GlobalType Type Const
791 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
792 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
793 /// OptionalExternallyInitialized GlobalType Type Const
795 /// Everything up to and including OptionalUnNammedAddr has been parsed
798 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
799 unsigned Linkage, bool HasLinkage,
800 unsigned Visibility, unsigned DLLStorageClass,
801 GlobalVariable::ThreadLocalMode TLM,
803 if (!isValidVisibilityForLinkage(Visibility, Linkage))
804 return Error(NameLoc,
805 "symbol with local linkage must have default visibility");
808 bool IsConstant, IsExternallyInitialized;
809 LocTy IsExternallyInitializedLoc;
813 if (ParseOptionalAddrSpace(AddrSpace) ||
814 ParseOptionalToken(lltok::kw_externally_initialized,
815 IsExternallyInitialized,
816 &IsExternallyInitializedLoc) ||
817 ParseGlobalType(IsConstant) ||
818 ParseType(Ty, TyLoc))
821 // If the linkage is specified and is external, then no initializer is
823 Constant *Init = nullptr;
824 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
825 Linkage != GlobalValue::ExternalLinkage)) {
826 if (ParseGlobalValue(Ty, Init))
830 if (Ty->isFunctionTy() || Ty->isLabelTy())
831 return Error(TyLoc, "invalid type for global variable");
833 GlobalVariable *GV = nullptr;
835 // See if the global was forward referenced, if so, use the global.
837 if (GlobalValue *GVal = M->getNamedValue(Name)) {
838 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
839 return Error(NameLoc, "redefinition of global '@" + Name + "'");
840 GV = cast<GlobalVariable>(GVal);
843 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
844 I = ForwardRefValIDs.find(NumberedVals.size());
845 if (I != ForwardRefValIDs.end()) {
846 GV = cast<GlobalVariable>(I->second.first);
847 ForwardRefValIDs.erase(I);
852 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
853 Name, nullptr, GlobalVariable::NotThreadLocal,
856 if (GV->getType()->getElementType() != Ty)
858 "forward reference and definition of global have different types");
860 // Move the forward-reference to the correct spot in the module.
861 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
865 NumberedVals.push_back(GV);
867 // Set the parsed properties on the global.
869 GV->setInitializer(Init);
870 GV->setConstant(IsConstant);
871 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
872 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
873 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
874 GV->setExternallyInitialized(IsExternallyInitialized);
875 GV->setThreadLocalMode(TLM);
876 GV->setUnnamedAddr(UnnamedAddr);
878 // Parse attributes on the global.
879 while (Lex.getKind() == lltok::comma) {
882 if (Lex.getKind() == lltok::kw_section) {
884 GV->setSection(Lex.getStrVal());
885 if (ParseToken(lltok::StringConstant, "expected global section string"))
887 } else if (Lex.getKind() == lltok::kw_align) {
889 if (ParseOptionalAlignment(Alignment)) return true;
890 GV->setAlignment(Alignment);
893 if (parseOptionalComdat(C))
898 return TokError("unknown global variable property!");
905 /// ParseUnnamedAttrGrp
906 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
907 bool LLParser::ParseUnnamedAttrGrp() {
908 assert(Lex.getKind() == lltok::kw_attributes);
909 LocTy AttrGrpLoc = Lex.getLoc();
912 assert(Lex.getKind() == lltok::AttrGrpID);
913 unsigned VarID = Lex.getUIntVal();
914 std::vector<unsigned> unused;
918 if (ParseToken(lltok::equal, "expected '=' here") ||
919 ParseToken(lltok::lbrace, "expected '{' here") ||
920 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
922 ParseToken(lltok::rbrace, "expected end of attribute group"))
925 if (!NumberedAttrBuilders[VarID].hasAttributes())
926 return Error(AttrGrpLoc, "attribute group has no attributes");
931 /// ParseFnAttributeValuePairs
932 /// ::= <attr> | <attr> '=' <value>
933 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
934 std::vector<unsigned> &FwdRefAttrGrps,
935 bool inAttrGrp, LocTy &BuiltinLoc) {
936 bool HaveError = false;
941 lltok::Kind Token = Lex.getKind();
942 if (Token == lltok::kw_builtin)
943 BuiltinLoc = Lex.getLoc();
946 if (!inAttrGrp) return HaveError;
947 return Error(Lex.getLoc(), "unterminated attribute group");
952 case lltok::AttrGrpID: {
953 // Allow a function to reference an attribute group:
955 // define void @foo() #1 { ... }
959 "cannot have an attribute group reference in an attribute group");
961 unsigned AttrGrpNum = Lex.getUIntVal();
962 if (inAttrGrp) break;
964 // Save the reference to the attribute group. We'll fill it in later.
965 FwdRefAttrGrps.push_back(AttrGrpNum);
968 // Target-dependent attributes:
969 case lltok::StringConstant: {
970 std::string Attr = Lex.getStrVal();
973 if (EatIfPresent(lltok::equal) &&
974 ParseStringConstant(Val))
977 B.addAttribute(Attr, Val);
981 // Target-independent attributes:
982 case lltok::kw_align: {
983 // As a hack, we allow function alignment to be initially parsed as an
984 // attribute on a function declaration/definition or added to an attribute
985 // group and later moved to the alignment field.
989 if (ParseToken(lltok::equal, "expected '=' here") ||
990 ParseUInt32(Alignment))
993 if (ParseOptionalAlignment(Alignment))
996 B.addAlignmentAttr(Alignment);
999 case lltok::kw_alignstack: {
1003 if (ParseToken(lltok::equal, "expected '=' here") ||
1004 ParseUInt32(Alignment))
1007 if (ParseOptionalStackAlignment(Alignment))
1010 B.addStackAlignmentAttr(Alignment);
1013 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
1014 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
1015 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
1016 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
1017 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
1018 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
1019 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
1020 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
1021 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
1022 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
1023 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
1024 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
1025 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
1026 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
1027 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
1028 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
1029 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
1030 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1031 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1032 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
1033 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
1034 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
1035 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
1036 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
1037 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
1038 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
1039 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
1042 case lltok::kw_inreg:
1043 case lltok::kw_signext:
1044 case lltok::kw_zeroext:
1047 "invalid use of attribute on a function");
1049 case lltok::kw_byval:
1050 case lltok::kw_dereferenceable:
1051 case lltok::kw_inalloca:
1052 case lltok::kw_nest:
1053 case lltok::kw_noalias:
1054 case lltok::kw_nocapture:
1055 case lltok::kw_nonnull:
1056 case lltok::kw_returned:
1057 case lltok::kw_sret:
1060 "invalid use of parameter-only attribute on a function");
1068 //===----------------------------------------------------------------------===//
1069 // GlobalValue Reference/Resolution Routines.
1070 //===----------------------------------------------------------------------===//
1072 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1073 /// forward reference record if needed. This can return null if the value
1074 /// exists but does not have the right type.
1075 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1077 PointerType *PTy = dyn_cast<PointerType>(Ty);
1079 Error(Loc, "global variable reference must have pointer type");
1083 // Look this name up in the normal function symbol table.
1085 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1087 // If this is a forward reference for the value, see if we already created a
1088 // forward ref record.
1090 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1091 I = ForwardRefVals.find(Name);
1092 if (I != ForwardRefVals.end())
1093 Val = I->second.first;
1096 // If we have the value in the symbol table or fwd-ref table, return it.
1098 if (Val->getType() == Ty) return Val;
1099 Error(Loc, "'@" + Name + "' defined with type '" +
1100 getTypeString(Val->getType()) + "'");
1104 // Otherwise, create a new forward reference for this value and remember it.
1105 GlobalValue *FwdVal;
1106 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1107 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1109 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1110 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1111 nullptr, GlobalVariable::NotThreadLocal,
1112 PTy->getAddressSpace());
1114 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1118 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1119 PointerType *PTy = dyn_cast<PointerType>(Ty);
1121 Error(Loc, "global variable reference must have pointer type");
1125 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1127 // If this is a forward reference for the value, see if we already created a
1128 // forward ref record.
1130 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1131 I = ForwardRefValIDs.find(ID);
1132 if (I != ForwardRefValIDs.end())
1133 Val = I->second.first;
1136 // If we have the value in the symbol table or fwd-ref table, return it.
1138 if (Val->getType() == Ty) return Val;
1139 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1140 getTypeString(Val->getType()) + "'");
1144 // Otherwise, create a new forward reference for this value and remember it.
1145 GlobalValue *FwdVal;
1146 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1147 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1149 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1150 GlobalValue::ExternalWeakLinkage, nullptr, "");
1152 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1157 //===----------------------------------------------------------------------===//
1158 // Comdat Reference/Resolution Routines.
1159 //===----------------------------------------------------------------------===//
1161 Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
1162 // Look this name up in the comdat symbol table.
1163 Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
1164 Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
1165 if (I != ComdatSymTab.end())
1168 // Otherwise, create a new forward reference for this value and remember it.
1169 Comdat *C = M->getOrInsertComdat(Name);
1170 ForwardRefComdats[Name] = Loc;
1175 //===----------------------------------------------------------------------===//
1177 //===----------------------------------------------------------------------===//
1179 /// ParseToken - If the current token has the specified kind, eat it and return
1180 /// success. Otherwise, emit the specified error and return failure.
1181 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1182 if (Lex.getKind() != T)
1183 return TokError(ErrMsg);
1188 /// ParseStringConstant
1189 /// ::= StringConstant
1190 bool LLParser::ParseStringConstant(std::string &Result) {
1191 if (Lex.getKind() != lltok::StringConstant)
1192 return TokError("expected string constant");
1193 Result = Lex.getStrVal();
1200 bool LLParser::ParseUInt32(unsigned &Val) {
1201 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1202 return TokError("expected integer");
1203 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1204 if (Val64 != unsigned(Val64))
1205 return TokError("expected 32-bit integer (too large)");
1213 bool LLParser::ParseUInt64(uint64_t &Val) {
1214 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1215 return TokError("expected integer");
1216 Val = Lex.getAPSIntVal().getLimitedValue();
1222 /// := 'localdynamic'
1223 /// := 'initialexec'
1225 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1226 switch (Lex.getKind()) {
1228 return TokError("expected localdynamic, initialexec or localexec");
1229 case lltok::kw_localdynamic:
1230 TLM = GlobalVariable::LocalDynamicTLSModel;
1232 case lltok::kw_initialexec:
1233 TLM = GlobalVariable::InitialExecTLSModel;
1235 case lltok::kw_localexec:
1236 TLM = GlobalVariable::LocalExecTLSModel;
1244 /// ParseOptionalThreadLocal
1246 /// := 'thread_local'
1247 /// := 'thread_local' '(' tlsmodel ')'
1248 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1249 TLM = GlobalVariable::NotThreadLocal;
1250 if (!EatIfPresent(lltok::kw_thread_local))
1253 TLM = GlobalVariable::GeneralDynamicTLSModel;
1254 if (Lex.getKind() == lltok::lparen) {
1256 return ParseTLSModel(TLM) ||
1257 ParseToken(lltok::rparen, "expected ')' after thread local model");
1262 /// ParseOptionalAddrSpace
1264 /// := 'addrspace' '(' uint32 ')'
1265 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1267 if (!EatIfPresent(lltok::kw_addrspace))
1269 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1270 ParseUInt32(AddrSpace) ||
1271 ParseToken(lltok::rparen, "expected ')' in address space");
1274 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1275 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1276 bool HaveError = false;
1281 lltok::Kind Token = Lex.getKind();
1283 default: // End of attributes.
1285 case lltok::kw_align: {
1287 if (ParseOptionalAlignment(Alignment))
1289 B.addAlignmentAttr(Alignment);
1292 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1293 case lltok::kw_dereferenceable: {
1295 if (ParseOptionalDereferenceableBytes(Bytes))
1297 B.addDereferenceableAttr(Bytes);
1300 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1301 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1302 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1303 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1304 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1305 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1306 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1307 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1308 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1309 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1310 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1311 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1313 case lltok::kw_alignstack:
1314 case lltok::kw_alwaysinline:
1315 case lltok::kw_builtin:
1316 case lltok::kw_inlinehint:
1317 case lltok::kw_jumptable:
1318 case lltok::kw_minsize:
1319 case lltok::kw_naked:
1320 case lltok::kw_nobuiltin:
1321 case lltok::kw_noduplicate:
1322 case lltok::kw_noimplicitfloat:
1323 case lltok::kw_noinline:
1324 case lltok::kw_nonlazybind:
1325 case lltok::kw_noredzone:
1326 case lltok::kw_noreturn:
1327 case lltok::kw_nounwind:
1328 case lltok::kw_optnone:
1329 case lltok::kw_optsize:
1330 case lltok::kw_returns_twice:
1331 case lltok::kw_sanitize_address:
1332 case lltok::kw_sanitize_memory:
1333 case lltok::kw_sanitize_thread:
1335 case lltok::kw_sspreq:
1336 case lltok::kw_sspstrong:
1337 case lltok::kw_uwtable:
1338 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1346 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1347 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1348 bool HaveError = false;
1353 lltok::Kind Token = Lex.getKind();
1355 default: // End of attributes.
1357 case lltok::kw_dereferenceable: {
1359 if (ParseOptionalDereferenceableBytes(Bytes))
1361 B.addDereferenceableAttr(Bytes);
1364 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1365 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1366 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1367 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1368 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1371 case lltok::kw_align:
1372 case lltok::kw_byval:
1373 case lltok::kw_inalloca:
1374 case lltok::kw_nest:
1375 case lltok::kw_nocapture:
1376 case lltok::kw_returned:
1377 case lltok::kw_sret:
1378 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1381 case lltok::kw_alignstack:
1382 case lltok::kw_alwaysinline:
1383 case lltok::kw_builtin:
1384 case lltok::kw_cold:
1385 case lltok::kw_inlinehint:
1386 case lltok::kw_jumptable:
1387 case lltok::kw_minsize:
1388 case lltok::kw_naked:
1389 case lltok::kw_nobuiltin:
1390 case lltok::kw_noduplicate:
1391 case lltok::kw_noimplicitfloat:
1392 case lltok::kw_noinline:
1393 case lltok::kw_nonlazybind:
1394 case lltok::kw_noredzone:
1395 case lltok::kw_noreturn:
1396 case lltok::kw_nounwind:
1397 case lltok::kw_optnone:
1398 case lltok::kw_optsize:
1399 case lltok::kw_returns_twice:
1400 case lltok::kw_sanitize_address:
1401 case lltok::kw_sanitize_memory:
1402 case lltok::kw_sanitize_thread:
1404 case lltok::kw_sspreq:
1405 case lltok::kw_sspstrong:
1406 case lltok::kw_uwtable:
1407 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1410 case lltok::kw_readnone:
1411 case lltok::kw_readonly:
1412 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1419 /// ParseOptionalLinkage
1426 /// ::= 'linkonce_odr'
1427 /// ::= 'available_externally'
1430 /// ::= 'extern_weak'
1432 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1434 switch (Lex.getKind()) {
1435 default: Res=GlobalValue::ExternalLinkage; return false;
1436 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1437 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1438 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1439 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1440 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1441 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1442 case lltok::kw_available_externally:
1443 Res = GlobalValue::AvailableExternallyLinkage;
1445 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1446 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1447 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1448 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1455 /// ParseOptionalVisibility
1461 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1462 switch (Lex.getKind()) {
1463 default: Res = GlobalValue::DefaultVisibility; return false;
1464 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1465 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1466 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1472 /// ParseOptionalDLLStorageClass
1477 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1478 switch (Lex.getKind()) {
1479 default: Res = GlobalValue::DefaultStorageClass; return false;
1480 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1481 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1487 /// ParseOptionalCallingConv
1491 /// ::= 'kw_intel_ocl_bicc'
1493 /// ::= 'x86_stdcallcc'
1494 /// ::= 'x86_fastcallcc'
1495 /// ::= 'x86_thiscallcc'
1496 /// ::= 'arm_apcscc'
1497 /// ::= 'arm_aapcscc'
1498 /// ::= 'arm_aapcs_vfpcc'
1499 /// ::= 'msp430_intrcc'
1500 /// ::= 'ptx_kernel'
1501 /// ::= 'ptx_device'
1503 /// ::= 'spir_kernel'
1504 /// ::= 'x86_64_sysvcc'
1505 /// ::= 'x86_64_win64cc'
1506 /// ::= 'webkit_jscc'
1508 /// ::= 'preserve_mostcc'
1509 /// ::= 'preserve_allcc'
1512 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1513 switch (Lex.getKind()) {
1514 default: CC = CallingConv::C; return false;
1515 case lltok::kw_ccc: CC = CallingConv::C; break;
1516 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1517 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1518 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1519 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1520 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1521 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1522 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1523 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1524 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1525 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1526 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1527 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1528 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1529 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1530 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1531 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1532 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1533 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1534 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1535 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1536 case lltok::kw_cc: {
1537 unsigned ArbitraryCC;
1539 if (ParseUInt32(ArbitraryCC))
1541 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1550 /// ParseInstructionMetadata
1551 /// ::= !dbg !42 (',' !dbg !57)*
1552 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1553 PerFunctionState *PFS) {
1555 if (Lex.getKind() != lltok::MetadataVar)
1556 return TokError("expected metadata after comma");
1558 std::string Name = Lex.getStrVal();
1559 unsigned MDK = M->getMDKindID(Name);
1563 SMLoc Loc = Lex.getLoc();
1565 if (ParseToken(lltok::exclaim, "expected '!' here"))
1568 // This code is similar to that of ParseMetadataValue, however it needs to
1569 // have special-case code for a forward reference; see the comments on
1570 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1571 // at the top level here.
1572 if (Lex.getKind() == lltok::lbrace) {
1574 if (ParseMetadataListValue(ID, PFS))
1576 assert(ID.Kind == ValID::t_MDNode);
1577 Inst->setMetadata(MDK, ID.MDNodeVal);
1579 unsigned NodeID = 0;
1580 if (ParseMDNodeID(Node, NodeID))
1583 // If we got the node, add it to the instruction.
1584 Inst->setMetadata(MDK, Node);
1586 MDRef R = { Loc, MDK, NodeID };
1587 // Otherwise, remember that this should be resolved later.
1588 ForwardRefInstMetadata[Inst].push_back(R);
1592 if (MDK == LLVMContext::MD_tbaa)
1593 InstsWithTBAATag.push_back(Inst);
1595 // If this is the end of the list, we're done.
1596 } while (EatIfPresent(lltok::comma));
1600 /// ParseOptionalAlignment
1603 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1605 if (!EatIfPresent(lltok::kw_align))
1607 LocTy AlignLoc = Lex.getLoc();
1608 if (ParseUInt32(Alignment)) return true;
1609 if (!isPowerOf2_32(Alignment))
1610 return Error(AlignLoc, "alignment is not a power of two");
1611 if (Alignment > Value::MaximumAlignment)
1612 return Error(AlignLoc, "huge alignments are not supported yet");
1616 /// ParseOptionalDereferenceableBytes
1618 /// ::= 'dereferenceable' '(' 4 ')'
1619 bool LLParser::ParseOptionalDereferenceableBytes(uint64_t &Bytes) {
1621 if (!EatIfPresent(lltok::kw_dereferenceable))
1623 LocTy ParenLoc = Lex.getLoc();
1624 if (!EatIfPresent(lltok::lparen))
1625 return Error(ParenLoc, "expected '('");
1626 LocTy DerefLoc = Lex.getLoc();
1627 if (ParseUInt64(Bytes)) return true;
1628 ParenLoc = Lex.getLoc();
1629 if (!EatIfPresent(lltok::rparen))
1630 return Error(ParenLoc, "expected ')'");
1632 return Error(DerefLoc, "dereferenceable bytes must be non-zero");
1636 /// ParseOptionalCommaAlign
1640 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1642 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1643 bool &AteExtraComma) {
1644 AteExtraComma = false;
1645 while (EatIfPresent(lltok::comma)) {
1646 // Metadata at the end is an early exit.
1647 if (Lex.getKind() == lltok::MetadataVar) {
1648 AteExtraComma = true;
1652 if (Lex.getKind() != lltok::kw_align)
1653 return Error(Lex.getLoc(), "expected metadata or 'align'");
1655 if (ParseOptionalAlignment(Alignment)) return true;
1661 /// ParseScopeAndOrdering
1662 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1665 /// This sets Scope and Ordering to the parsed values.
1666 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1667 AtomicOrdering &Ordering) {
1671 Scope = CrossThread;
1672 if (EatIfPresent(lltok::kw_singlethread))
1673 Scope = SingleThread;
1675 return ParseOrdering(Ordering);
1679 /// ::= AtomicOrdering
1681 /// This sets Ordering to the parsed value.
1682 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1683 switch (Lex.getKind()) {
1684 default: return TokError("Expected ordering on atomic instruction");
1685 case lltok::kw_unordered: Ordering = Unordered; break;
1686 case lltok::kw_monotonic: Ordering = Monotonic; break;
1687 case lltok::kw_acquire: Ordering = Acquire; break;
1688 case lltok::kw_release: Ordering = Release; break;
1689 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1690 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1696 /// ParseOptionalStackAlignment
1698 /// ::= 'alignstack' '(' 4 ')'
1699 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1701 if (!EatIfPresent(lltok::kw_alignstack))
1703 LocTy ParenLoc = Lex.getLoc();
1704 if (!EatIfPresent(lltok::lparen))
1705 return Error(ParenLoc, "expected '('");
1706 LocTy AlignLoc = Lex.getLoc();
1707 if (ParseUInt32(Alignment)) return true;
1708 ParenLoc = Lex.getLoc();
1709 if (!EatIfPresent(lltok::rparen))
1710 return Error(ParenLoc, "expected ')'");
1711 if (!isPowerOf2_32(Alignment))
1712 return Error(AlignLoc, "stack alignment is not a power of two");
1716 /// ParseIndexList - This parses the index list for an insert/extractvalue
1717 /// instruction. This sets AteExtraComma in the case where we eat an extra
1718 /// comma at the end of the line and find that it is followed by metadata.
1719 /// Clients that don't allow metadata can call the version of this function that
1720 /// only takes one argument.
1723 /// ::= (',' uint32)+
1725 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1726 bool &AteExtraComma) {
1727 AteExtraComma = false;
1729 if (Lex.getKind() != lltok::comma)
1730 return TokError("expected ',' as start of index list");
1732 while (EatIfPresent(lltok::comma)) {
1733 if (Lex.getKind() == lltok::MetadataVar) {
1734 AteExtraComma = true;
1738 if (ParseUInt32(Idx)) return true;
1739 Indices.push_back(Idx);
1745 //===----------------------------------------------------------------------===//
1747 //===----------------------------------------------------------------------===//
1749 /// ParseType - Parse a type.
1750 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1751 SMLoc TypeLoc = Lex.getLoc();
1752 switch (Lex.getKind()) {
1754 return TokError("expected type");
1756 // Type ::= 'float' | 'void' (etc)
1757 Result = Lex.getTyVal();
1761 // Type ::= StructType
1762 if (ParseAnonStructType(Result, false))
1765 case lltok::lsquare:
1766 // Type ::= '[' ... ']'
1767 Lex.Lex(); // eat the lsquare.
1768 if (ParseArrayVectorType(Result, false))
1771 case lltok::less: // Either vector or packed struct.
1772 // Type ::= '<' ... '>'
1774 if (Lex.getKind() == lltok::lbrace) {
1775 if (ParseAnonStructType(Result, true) ||
1776 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1778 } else if (ParseArrayVectorType(Result, true))
1781 case lltok::LocalVar: {
1783 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1785 // If the type hasn't been defined yet, create a forward definition and
1786 // remember where that forward def'n was seen (in case it never is defined).
1788 Entry.first = StructType::create(Context, Lex.getStrVal());
1789 Entry.second = Lex.getLoc();
1791 Result = Entry.first;
1796 case lltok::LocalVarID: {
1798 if (Lex.getUIntVal() >= NumberedTypes.size())
1799 NumberedTypes.resize(Lex.getUIntVal()+1);
1800 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1802 // If the type hasn't been defined yet, create a forward definition and
1803 // remember where that forward def'n was seen (in case it never is defined).
1805 Entry.first = StructType::create(Context);
1806 Entry.second = Lex.getLoc();
1808 Result = Entry.first;
1814 // Parse the type suffixes.
1816 switch (Lex.getKind()) {
1819 if (!AllowVoid && Result->isVoidTy())
1820 return Error(TypeLoc, "void type only allowed for function results");
1823 // Type ::= Type '*'
1825 if (Result->isLabelTy())
1826 return TokError("basic block pointers are invalid");
1827 if (Result->isVoidTy())
1828 return TokError("pointers to void are invalid - use i8* instead");
1829 if (!PointerType::isValidElementType(Result))
1830 return TokError("pointer to this type is invalid");
1831 Result = PointerType::getUnqual(Result);
1835 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1836 case lltok::kw_addrspace: {
1837 if (Result->isLabelTy())
1838 return TokError("basic block pointers are invalid");
1839 if (Result->isVoidTy())
1840 return TokError("pointers to void are invalid; use i8* instead");
1841 if (!PointerType::isValidElementType(Result))
1842 return TokError("pointer to this type is invalid");
1844 if (ParseOptionalAddrSpace(AddrSpace) ||
1845 ParseToken(lltok::star, "expected '*' in address space"))
1848 Result = PointerType::get(Result, AddrSpace);
1852 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1854 if (ParseFunctionType(Result))
1861 /// ParseParameterList
1863 /// ::= '(' Arg (',' Arg)* ')'
1865 /// ::= Type OptionalAttributes Value OptionalAttributes
1866 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1867 PerFunctionState &PFS) {
1868 if (ParseToken(lltok::lparen, "expected '(' in call"))
1871 unsigned AttrIndex = 1;
1872 while (Lex.getKind() != lltok::rparen) {
1873 // If this isn't the first argument, we need a comma.
1874 if (!ArgList.empty() &&
1875 ParseToken(lltok::comma, "expected ',' in argument list"))
1878 // Parse the argument.
1880 Type *ArgTy = nullptr;
1881 AttrBuilder ArgAttrs;
1883 if (ParseType(ArgTy, ArgLoc))
1886 // Otherwise, handle normal operands.
1887 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1889 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1894 Lex.Lex(); // Lex the ')'.
1900 /// ParseArgumentList - Parse the argument list for a function type or function
1902 /// ::= '(' ArgTypeListI ')'
1906 /// ::= ArgTypeList ',' '...'
1907 /// ::= ArgType (',' ArgType)*
1909 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1912 assert(Lex.getKind() == lltok::lparen);
1913 Lex.Lex(); // eat the (.
1915 if (Lex.getKind() == lltok::rparen) {
1917 } else if (Lex.getKind() == lltok::dotdotdot) {
1921 LocTy TypeLoc = Lex.getLoc();
1922 Type *ArgTy = nullptr;
1926 if (ParseType(ArgTy) ||
1927 ParseOptionalParamAttrs(Attrs)) return true;
1929 if (ArgTy->isVoidTy())
1930 return Error(TypeLoc, "argument can not have void type");
1932 if (Lex.getKind() == lltok::LocalVar) {
1933 Name = Lex.getStrVal();
1937 if (!FunctionType::isValidArgumentType(ArgTy))
1938 return Error(TypeLoc, "invalid type for function argument");
1940 unsigned AttrIndex = 1;
1941 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1942 AttributeSet::get(ArgTy->getContext(),
1943 AttrIndex++, Attrs), Name));
1945 while (EatIfPresent(lltok::comma)) {
1946 // Handle ... at end of arg list.
1947 if (EatIfPresent(lltok::dotdotdot)) {
1952 // Otherwise must be an argument type.
1953 TypeLoc = Lex.getLoc();
1954 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1956 if (ArgTy->isVoidTy())
1957 return Error(TypeLoc, "argument can not have void type");
1959 if (Lex.getKind() == lltok::LocalVar) {
1960 Name = Lex.getStrVal();
1966 if (!ArgTy->isFirstClassType())
1967 return Error(TypeLoc, "invalid type for function argument");
1969 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1970 AttributeSet::get(ArgTy->getContext(),
1971 AttrIndex++, Attrs),
1976 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1979 /// ParseFunctionType
1980 /// ::= Type ArgumentList OptionalAttrs
1981 bool LLParser::ParseFunctionType(Type *&Result) {
1982 assert(Lex.getKind() == lltok::lparen);
1984 if (!FunctionType::isValidReturnType(Result))
1985 return TokError("invalid function return type");
1987 SmallVector<ArgInfo, 8> ArgList;
1989 if (ParseArgumentList(ArgList, isVarArg))
1992 // Reject names on the arguments lists.
1993 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1994 if (!ArgList[i].Name.empty())
1995 return Error(ArgList[i].Loc, "argument name invalid in function type");
1996 if (ArgList[i].Attrs.hasAttributes(i + 1))
1997 return Error(ArgList[i].Loc,
1998 "argument attributes invalid in function type");
2001 SmallVector<Type*, 16> ArgListTy;
2002 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
2003 ArgListTy.push_back(ArgList[i].Ty);
2005 Result = FunctionType::get(Result, ArgListTy, isVarArg);
2009 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
2011 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
2012 SmallVector<Type*, 8> Elts;
2013 if (ParseStructBody(Elts)) return true;
2015 Result = StructType::get(Context, Elts, Packed);
2019 /// ParseStructDefinition - Parse a struct in a 'type' definition.
2020 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
2021 std::pair<Type*, LocTy> &Entry,
2023 // If the type was already defined, diagnose the redefinition.
2024 if (Entry.first && !Entry.second.isValid())
2025 return Error(TypeLoc, "redefinition of type");
2027 // If we have opaque, just return without filling in the definition for the
2028 // struct. This counts as a definition as far as the .ll file goes.
2029 if (EatIfPresent(lltok::kw_opaque)) {
2030 // This type is being defined, so clear the location to indicate this.
2031 Entry.second = SMLoc();
2033 // If this type number has never been uttered, create it.
2035 Entry.first = StructType::create(Context, Name);
2036 ResultTy = Entry.first;
2040 // If the type starts with '<', then it is either a packed struct or a vector.
2041 bool isPacked = EatIfPresent(lltok::less);
2043 // If we don't have a struct, then we have a random type alias, which we
2044 // accept for compatibility with old files. These types are not allowed to be
2045 // forward referenced and not allowed to be recursive.
2046 if (Lex.getKind() != lltok::lbrace) {
2048 return Error(TypeLoc, "forward references to non-struct type");
2052 return ParseArrayVectorType(ResultTy, true);
2053 return ParseType(ResultTy);
2056 // This type is being defined, so clear the location to indicate this.
2057 Entry.second = SMLoc();
2059 // If this type number has never been uttered, create it.
2061 Entry.first = StructType::create(Context, Name);
2063 StructType *STy = cast<StructType>(Entry.first);
2065 SmallVector<Type*, 8> Body;
2066 if (ParseStructBody(Body) ||
2067 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
2070 STy->setBody(Body, isPacked);
2076 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
2079 /// ::= '{' Type (',' Type)* '}'
2080 /// ::= '<' '{' '}' '>'
2081 /// ::= '<' '{' Type (',' Type)* '}' '>'
2082 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
2083 assert(Lex.getKind() == lltok::lbrace);
2084 Lex.Lex(); // Consume the '{'
2086 // Handle the empty struct.
2087 if (EatIfPresent(lltok::rbrace))
2090 LocTy EltTyLoc = Lex.getLoc();
2092 if (ParseType(Ty)) return true;
2095 if (!StructType::isValidElementType(Ty))
2096 return Error(EltTyLoc, "invalid element type for struct");
2098 while (EatIfPresent(lltok::comma)) {
2099 EltTyLoc = Lex.getLoc();
2100 if (ParseType(Ty)) return true;
2102 if (!StructType::isValidElementType(Ty))
2103 return Error(EltTyLoc, "invalid element type for struct");
2108 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2111 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2112 /// token has already been consumed.
2114 /// ::= '[' APSINTVAL 'x' Types ']'
2115 /// ::= '<' APSINTVAL 'x' Types '>'
2116 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2117 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2118 Lex.getAPSIntVal().getBitWidth() > 64)
2119 return TokError("expected number in address space");
2121 LocTy SizeLoc = Lex.getLoc();
2122 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2125 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2128 LocTy TypeLoc = Lex.getLoc();
2129 Type *EltTy = nullptr;
2130 if (ParseType(EltTy)) return true;
2132 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2133 "expected end of sequential type"))
2138 return Error(SizeLoc, "zero element vector is illegal");
2139 if ((unsigned)Size != Size)
2140 return Error(SizeLoc, "size too large for vector");
2141 if (!VectorType::isValidElementType(EltTy))
2142 return Error(TypeLoc, "invalid vector element type");
2143 Result = VectorType::get(EltTy, unsigned(Size));
2145 if (!ArrayType::isValidElementType(EltTy))
2146 return Error(TypeLoc, "invalid array element type");
2147 Result = ArrayType::get(EltTy, Size);
2152 //===----------------------------------------------------------------------===//
2153 // Function Semantic Analysis.
2154 //===----------------------------------------------------------------------===//
2156 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2158 : P(p), F(f), FunctionNumber(functionNumber) {
2160 // Insert unnamed arguments into the NumberedVals list.
2161 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2164 NumberedVals.push_back(AI);
2167 LLParser::PerFunctionState::~PerFunctionState() {
2168 // If there were any forward referenced non-basicblock values, delete them.
2169 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2170 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2171 if (!isa<BasicBlock>(I->second.first)) {
2172 I->second.first->replaceAllUsesWith(
2173 UndefValue::get(I->second.first->getType()));
2174 delete I->second.first;
2175 I->second.first = nullptr;
2178 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2179 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2180 if (!isa<BasicBlock>(I->second.first)) {
2181 I->second.first->replaceAllUsesWith(
2182 UndefValue::get(I->second.first->getType()));
2183 delete I->second.first;
2184 I->second.first = nullptr;
2188 bool LLParser::PerFunctionState::FinishFunction() {
2189 // Check to see if someone took the address of labels in this block.
2190 if (!P.ForwardRefBlockAddresses.empty()) {
2192 if (!F.getName().empty()) {
2193 FunctionID.Kind = ValID::t_GlobalName;
2194 FunctionID.StrVal = F.getName();
2196 FunctionID.Kind = ValID::t_GlobalID;
2197 FunctionID.UIntVal = FunctionNumber;
2200 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2201 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2202 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2203 // Resolve all these references.
2204 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2207 P.ForwardRefBlockAddresses.erase(FRBAI);
2211 if (!ForwardRefVals.empty())
2212 return P.Error(ForwardRefVals.begin()->second.second,
2213 "use of undefined value '%" + ForwardRefVals.begin()->first +
2215 if (!ForwardRefValIDs.empty())
2216 return P.Error(ForwardRefValIDs.begin()->second.second,
2217 "use of undefined value '%" +
2218 Twine(ForwardRefValIDs.begin()->first) + "'");
2223 /// GetVal - Get a value with the specified name or ID, creating a
2224 /// forward reference record if needed. This can return null if the value
2225 /// exists but does not have the right type.
2226 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2227 Type *Ty, LocTy Loc) {
2228 // Look this name up in the normal function symbol table.
2229 Value *Val = F.getValueSymbolTable().lookup(Name);
2231 // If this is a forward reference for the value, see if we already created a
2232 // forward ref record.
2234 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2235 I = ForwardRefVals.find(Name);
2236 if (I != ForwardRefVals.end())
2237 Val = I->second.first;
2240 // If we have the value in the symbol table or fwd-ref table, return it.
2242 if (Val->getType() == Ty) return Val;
2243 if (Ty->isLabelTy())
2244 P.Error(Loc, "'%" + Name + "' is not a basic block");
2246 P.Error(Loc, "'%" + Name + "' defined with type '" +
2247 getTypeString(Val->getType()) + "'");
2251 // Don't make placeholders with invalid type.
2252 if (!Ty->isFirstClassType()) {
2253 P.Error(Loc, "invalid use of a non-first-class type");
2257 // Otherwise, create a new forward reference for this value and remember it.
2259 if (Ty->isLabelTy())
2260 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2262 FwdVal = new Argument(Ty, Name);
2264 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2268 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2270 // Look this name up in the normal function symbol table.
2271 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2273 // If this is a forward reference for the value, see if we already created a
2274 // forward ref record.
2276 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2277 I = ForwardRefValIDs.find(ID);
2278 if (I != ForwardRefValIDs.end())
2279 Val = I->second.first;
2282 // If we have the value in the symbol table or fwd-ref table, return it.
2284 if (Val->getType() == Ty) return Val;
2285 if (Ty->isLabelTy())
2286 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2288 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2289 getTypeString(Val->getType()) + "'");
2293 if (!Ty->isFirstClassType()) {
2294 P.Error(Loc, "invalid use of a non-first-class type");
2298 // Otherwise, create a new forward reference for this value and remember it.
2300 if (Ty->isLabelTy())
2301 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2303 FwdVal = new Argument(Ty);
2305 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2309 /// SetInstName - After an instruction is parsed and inserted into its
2310 /// basic block, this installs its name.
2311 bool LLParser::PerFunctionState::SetInstName(int NameID,
2312 const std::string &NameStr,
2313 LocTy NameLoc, Instruction *Inst) {
2314 // If this instruction has void type, it cannot have a name or ID specified.
2315 if (Inst->getType()->isVoidTy()) {
2316 if (NameID != -1 || !NameStr.empty())
2317 return P.Error(NameLoc, "instructions returning void cannot have a name");
2321 // If this was a numbered instruction, verify that the instruction is the
2322 // expected value and resolve any forward references.
2323 if (NameStr.empty()) {
2324 // If neither a name nor an ID was specified, just use the next ID.
2326 NameID = NumberedVals.size();
2328 if (unsigned(NameID) != NumberedVals.size())
2329 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2330 Twine(NumberedVals.size()) + "'");
2332 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2333 ForwardRefValIDs.find(NameID);
2334 if (FI != ForwardRefValIDs.end()) {
2335 if (FI->second.first->getType() != Inst->getType())
2336 return P.Error(NameLoc, "instruction forward referenced with type '" +
2337 getTypeString(FI->second.first->getType()) + "'");
2338 FI->second.first->replaceAllUsesWith(Inst);
2339 delete FI->second.first;
2340 ForwardRefValIDs.erase(FI);
2343 NumberedVals.push_back(Inst);
2347 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2348 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2349 FI = ForwardRefVals.find(NameStr);
2350 if (FI != ForwardRefVals.end()) {
2351 if (FI->second.first->getType() != Inst->getType())
2352 return P.Error(NameLoc, "instruction forward referenced with type '" +
2353 getTypeString(FI->second.first->getType()) + "'");
2354 FI->second.first->replaceAllUsesWith(Inst);
2355 delete FI->second.first;
2356 ForwardRefVals.erase(FI);
2359 // Set the name on the instruction.
2360 Inst->setName(NameStr);
2362 if (Inst->getName() != NameStr)
2363 return P.Error(NameLoc, "multiple definition of local value named '" +
2368 /// GetBB - Get a basic block with the specified name or ID, creating a
2369 /// forward reference record if needed.
2370 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2372 return cast_or_null<BasicBlock>(GetVal(Name,
2373 Type::getLabelTy(F.getContext()), Loc));
2376 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2377 return cast_or_null<BasicBlock>(GetVal(ID,
2378 Type::getLabelTy(F.getContext()), Loc));
2381 /// DefineBB - Define the specified basic block, which is either named or
2382 /// unnamed. If there is an error, this returns null otherwise it returns
2383 /// the block being defined.
2384 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2388 BB = GetBB(NumberedVals.size(), Loc);
2390 BB = GetBB(Name, Loc);
2391 if (!BB) return nullptr; // Already diagnosed error.
2393 // Move the block to the end of the function. Forward ref'd blocks are
2394 // inserted wherever they happen to be referenced.
2395 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2397 // Remove the block from forward ref sets.
2399 ForwardRefValIDs.erase(NumberedVals.size());
2400 NumberedVals.push_back(BB);
2402 // BB forward references are already in the function symbol table.
2403 ForwardRefVals.erase(Name);
2409 //===----------------------------------------------------------------------===//
2411 //===----------------------------------------------------------------------===//
2413 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2414 /// type implied. For example, if we parse "4" we don't know what integer type
2415 /// it has. The value will later be combined with its type and checked for
2416 /// sanity. PFS is used to convert function-local operands of metadata (since
2417 /// metadata operands are not just parsed here but also converted to values).
2418 /// PFS can be null when we are not parsing metadata values inside a function.
2419 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2420 ID.Loc = Lex.getLoc();
2421 switch (Lex.getKind()) {
2422 default: return TokError("expected value token");
2423 case lltok::GlobalID: // @42
2424 ID.UIntVal = Lex.getUIntVal();
2425 ID.Kind = ValID::t_GlobalID;
2427 case lltok::GlobalVar: // @foo
2428 ID.StrVal = Lex.getStrVal();
2429 ID.Kind = ValID::t_GlobalName;
2431 case lltok::LocalVarID: // %42
2432 ID.UIntVal = Lex.getUIntVal();
2433 ID.Kind = ValID::t_LocalID;
2435 case lltok::LocalVar: // %foo
2436 ID.StrVal = Lex.getStrVal();
2437 ID.Kind = ValID::t_LocalName;
2439 case lltok::exclaim: // !42, !{...}, or !"foo"
2440 return ParseMetadataValue(ID, PFS);
2442 ID.APSIntVal = Lex.getAPSIntVal();
2443 ID.Kind = ValID::t_APSInt;
2445 case lltok::APFloat:
2446 ID.APFloatVal = Lex.getAPFloatVal();
2447 ID.Kind = ValID::t_APFloat;
2449 case lltok::kw_true:
2450 ID.ConstantVal = ConstantInt::getTrue(Context);
2451 ID.Kind = ValID::t_Constant;
2453 case lltok::kw_false:
2454 ID.ConstantVal = ConstantInt::getFalse(Context);
2455 ID.Kind = ValID::t_Constant;
2457 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2458 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2459 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2461 case lltok::lbrace: {
2462 // ValID ::= '{' ConstVector '}'
2464 SmallVector<Constant*, 16> Elts;
2465 if (ParseGlobalValueVector(Elts) ||
2466 ParseToken(lltok::rbrace, "expected end of struct constant"))
2469 ID.ConstantStructElts = new Constant*[Elts.size()];
2470 ID.UIntVal = Elts.size();
2471 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2472 ID.Kind = ValID::t_ConstantStruct;
2476 // ValID ::= '<' ConstVector '>' --> Vector.
2477 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2479 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2481 SmallVector<Constant*, 16> Elts;
2482 LocTy FirstEltLoc = Lex.getLoc();
2483 if (ParseGlobalValueVector(Elts) ||
2485 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2486 ParseToken(lltok::greater, "expected end of constant"))
2489 if (isPackedStruct) {
2490 ID.ConstantStructElts = new Constant*[Elts.size()];
2491 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2492 ID.UIntVal = Elts.size();
2493 ID.Kind = ValID::t_PackedConstantStruct;
2498 return Error(ID.Loc, "constant vector must not be empty");
2500 if (!Elts[0]->getType()->isIntegerTy() &&
2501 !Elts[0]->getType()->isFloatingPointTy() &&
2502 !Elts[0]->getType()->isPointerTy())
2503 return Error(FirstEltLoc,
2504 "vector elements must have integer, pointer or floating point type");
2506 // Verify that all the vector elements have the same type.
2507 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2508 if (Elts[i]->getType() != Elts[0]->getType())
2509 return Error(FirstEltLoc,
2510 "vector element #" + Twine(i) +
2511 " is not of type '" + getTypeString(Elts[0]->getType()));
2513 ID.ConstantVal = ConstantVector::get(Elts);
2514 ID.Kind = ValID::t_Constant;
2517 case lltok::lsquare: { // Array Constant
2519 SmallVector<Constant*, 16> Elts;
2520 LocTy FirstEltLoc = Lex.getLoc();
2521 if (ParseGlobalValueVector(Elts) ||
2522 ParseToken(lltok::rsquare, "expected end of array constant"))
2525 // Handle empty element.
2527 // Use undef instead of an array because it's inconvenient to determine
2528 // the element type at this point, there being no elements to examine.
2529 ID.Kind = ValID::t_EmptyArray;
2533 if (!Elts[0]->getType()->isFirstClassType())
2534 return Error(FirstEltLoc, "invalid array element type: " +
2535 getTypeString(Elts[0]->getType()));
2537 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2539 // Verify all elements are correct type!
2540 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2541 if (Elts[i]->getType() != Elts[0]->getType())
2542 return Error(FirstEltLoc,
2543 "array element #" + Twine(i) +
2544 " is not of type '" + getTypeString(Elts[0]->getType()));
2547 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2548 ID.Kind = ValID::t_Constant;
2551 case lltok::kw_c: // c "foo"
2553 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2555 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2556 ID.Kind = ValID::t_Constant;
2559 case lltok::kw_asm: {
2560 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2562 bool HasSideEffect, AlignStack, AsmDialect;
2564 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2565 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2566 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2567 ParseStringConstant(ID.StrVal) ||
2568 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2569 ParseToken(lltok::StringConstant, "expected constraint string"))
2571 ID.StrVal2 = Lex.getStrVal();
2572 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2573 (unsigned(AsmDialect)<<2);
2574 ID.Kind = ValID::t_InlineAsm;
2578 case lltok::kw_blockaddress: {
2579 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2584 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2586 ParseToken(lltok::comma, "expected comma in block address expression")||
2587 ParseValID(Label) ||
2588 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2591 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2592 return Error(Fn.Loc, "expected function name in blockaddress");
2593 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2594 return Error(Label.Loc, "expected basic block name in blockaddress");
2596 // Make a global variable as a placeholder for this reference.
2597 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2598 false, GlobalValue::InternalLinkage,
2600 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2601 ID.ConstantVal = FwdRef;
2602 ID.Kind = ValID::t_Constant;
2606 case lltok::kw_trunc:
2607 case lltok::kw_zext:
2608 case lltok::kw_sext:
2609 case lltok::kw_fptrunc:
2610 case lltok::kw_fpext:
2611 case lltok::kw_bitcast:
2612 case lltok::kw_addrspacecast:
2613 case lltok::kw_uitofp:
2614 case lltok::kw_sitofp:
2615 case lltok::kw_fptoui:
2616 case lltok::kw_fptosi:
2617 case lltok::kw_inttoptr:
2618 case lltok::kw_ptrtoint: {
2619 unsigned Opc = Lex.getUIntVal();
2620 Type *DestTy = nullptr;
2623 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2624 ParseGlobalTypeAndValue(SrcVal) ||
2625 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2626 ParseType(DestTy) ||
2627 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2629 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2630 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2631 getTypeString(SrcVal->getType()) + "' to '" +
2632 getTypeString(DestTy) + "'");
2633 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2635 ID.Kind = ValID::t_Constant;
2638 case lltok::kw_extractvalue: {
2641 SmallVector<unsigned, 4> Indices;
2642 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2643 ParseGlobalTypeAndValue(Val) ||
2644 ParseIndexList(Indices) ||
2645 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2648 if (!Val->getType()->isAggregateType())
2649 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2650 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2651 return Error(ID.Loc, "invalid indices for extractvalue");
2652 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2653 ID.Kind = ValID::t_Constant;
2656 case lltok::kw_insertvalue: {
2658 Constant *Val0, *Val1;
2659 SmallVector<unsigned, 4> Indices;
2660 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2661 ParseGlobalTypeAndValue(Val0) ||
2662 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2663 ParseGlobalTypeAndValue(Val1) ||
2664 ParseIndexList(Indices) ||
2665 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2667 if (!Val0->getType()->isAggregateType())
2668 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2669 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2670 return Error(ID.Loc, "invalid indices for insertvalue");
2671 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2672 ID.Kind = ValID::t_Constant;
2675 case lltok::kw_icmp:
2676 case lltok::kw_fcmp: {
2677 unsigned PredVal, Opc = Lex.getUIntVal();
2678 Constant *Val0, *Val1;
2680 if (ParseCmpPredicate(PredVal, Opc) ||
2681 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2682 ParseGlobalTypeAndValue(Val0) ||
2683 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2684 ParseGlobalTypeAndValue(Val1) ||
2685 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2688 if (Val0->getType() != Val1->getType())
2689 return Error(ID.Loc, "compare operands must have the same type");
2691 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2693 if (Opc == Instruction::FCmp) {
2694 if (!Val0->getType()->isFPOrFPVectorTy())
2695 return Error(ID.Loc, "fcmp requires floating point operands");
2696 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2698 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2699 if (!Val0->getType()->isIntOrIntVectorTy() &&
2700 !Val0->getType()->getScalarType()->isPointerTy())
2701 return Error(ID.Loc, "icmp requires pointer or integer operands");
2702 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2704 ID.Kind = ValID::t_Constant;
2708 // Binary Operators.
2710 case lltok::kw_fadd:
2712 case lltok::kw_fsub:
2714 case lltok::kw_fmul:
2715 case lltok::kw_udiv:
2716 case lltok::kw_sdiv:
2717 case lltok::kw_fdiv:
2718 case lltok::kw_urem:
2719 case lltok::kw_srem:
2720 case lltok::kw_frem:
2722 case lltok::kw_lshr:
2723 case lltok::kw_ashr: {
2727 unsigned Opc = Lex.getUIntVal();
2728 Constant *Val0, *Val1;
2730 LocTy ModifierLoc = Lex.getLoc();
2731 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2732 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2733 if (EatIfPresent(lltok::kw_nuw))
2735 if (EatIfPresent(lltok::kw_nsw)) {
2737 if (EatIfPresent(lltok::kw_nuw))
2740 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2741 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2742 if (EatIfPresent(lltok::kw_exact))
2745 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2746 ParseGlobalTypeAndValue(Val0) ||
2747 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2748 ParseGlobalTypeAndValue(Val1) ||
2749 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2751 if (Val0->getType() != Val1->getType())
2752 return Error(ID.Loc, "operands of constexpr must have same type");
2753 if (!Val0->getType()->isIntOrIntVectorTy()) {
2755 return Error(ModifierLoc, "nuw only applies to integer operations");
2757 return Error(ModifierLoc, "nsw only applies to integer operations");
2759 // Check that the type is valid for the operator.
2761 case Instruction::Add:
2762 case Instruction::Sub:
2763 case Instruction::Mul:
2764 case Instruction::UDiv:
2765 case Instruction::SDiv:
2766 case Instruction::URem:
2767 case Instruction::SRem:
2768 case Instruction::Shl:
2769 case Instruction::AShr:
2770 case Instruction::LShr:
2771 if (!Val0->getType()->isIntOrIntVectorTy())
2772 return Error(ID.Loc, "constexpr requires integer operands");
2774 case Instruction::FAdd:
2775 case Instruction::FSub:
2776 case Instruction::FMul:
2777 case Instruction::FDiv:
2778 case Instruction::FRem:
2779 if (!Val0->getType()->isFPOrFPVectorTy())
2780 return Error(ID.Loc, "constexpr requires fp operands");
2782 default: llvm_unreachable("Unknown binary operator!");
2785 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2786 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2787 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2788 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2790 ID.Kind = ValID::t_Constant;
2794 // Logical Operations
2797 case lltok::kw_xor: {
2798 unsigned Opc = Lex.getUIntVal();
2799 Constant *Val0, *Val1;
2801 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2802 ParseGlobalTypeAndValue(Val0) ||
2803 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2804 ParseGlobalTypeAndValue(Val1) ||
2805 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2807 if (Val0->getType() != Val1->getType())
2808 return Error(ID.Loc, "operands of constexpr must have same type");
2809 if (!Val0->getType()->isIntOrIntVectorTy())
2810 return Error(ID.Loc,
2811 "constexpr requires integer or integer vector operands");
2812 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2813 ID.Kind = ValID::t_Constant;
2817 case lltok::kw_getelementptr:
2818 case lltok::kw_shufflevector:
2819 case lltok::kw_insertelement:
2820 case lltok::kw_extractelement:
2821 case lltok::kw_select: {
2822 unsigned Opc = Lex.getUIntVal();
2823 SmallVector<Constant*, 16> Elts;
2824 bool InBounds = false;
2826 if (Opc == Instruction::GetElementPtr)
2827 InBounds = EatIfPresent(lltok::kw_inbounds);
2828 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2829 ParseGlobalValueVector(Elts) ||
2830 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2833 if (Opc == Instruction::GetElementPtr) {
2834 if (Elts.size() == 0 ||
2835 !Elts[0]->getType()->getScalarType()->isPointerTy())
2836 return Error(ID.Loc, "getelementptr requires pointer operand");
2838 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2839 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2840 return Error(ID.Loc, "invalid indices for getelementptr");
2841 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2843 } else if (Opc == Instruction::Select) {
2844 if (Elts.size() != 3)
2845 return Error(ID.Loc, "expected three operands to select");
2846 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2848 return Error(ID.Loc, Reason);
2849 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2850 } else if (Opc == Instruction::ShuffleVector) {
2851 if (Elts.size() != 3)
2852 return Error(ID.Loc, "expected three operands to shufflevector");
2853 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2854 return Error(ID.Loc, "invalid operands to shufflevector");
2856 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2857 } else if (Opc == Instruction::ExtractElement) {
2858 if (Elts.size() != 2)
2859 return Error(ID.Loc, "expected two operands to extractelement");
2860 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2861 return Error(ID.Loc, "invalid extractelement operands");
2862 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2864 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2865 if (Elts.size() != 3)
2866 return Error(ID.Loc, "expected three operands to insertelement");
2867 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2868 return Error(ID.Loc, "invalid insertelement operands");
2870 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2873 ID.Kind = ValID::t_Constant;
2882 /// ParseGlobalValue - Parse a global value with the specified type.
2883 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2887 bool Parsed = ParseValID(ID) ||
2888 ConvertValIDToValue(Ty, ID, V, nullptr);
2889 if (V && !(C = dyn_cast<Constant>(V)))
2890 return Error(ID.Loc, "global values must be constants");
2894 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2896 return ParseType(Ty) ||
2897 ParseGlobalValue(Ty, V);
2900 bool LLParser::parseOptionalComdat(Comdat *&C) {
2902 if (!EatIfPresent(lltok::kw_comdat))
2904 if (Lex.getKind() != lltok::ComdatVar)
2905 return TokError("expected comdat variable");
2906 LocTy Loc = Lex.getLoc();
2907 StringRef Name = Lex.getStrVal();
2908 C = getComdat(Name, Loc);
2913 /// ParseGlobalValueVector
2915 /// ::= TypeAndValue (',' TypeAndValue)*
2916 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2918 if (Lex.getKind() == lltok::rbrace ||
2919 Lex.getKind() == lltok::rsquare ||
2920 Lex.getKind() == lltok::greater ||
2921 Lex.getKind() == lltok::rparen)
2925 if (ParseGlobalTypeAndValue(C)) return true;
2928 while (EatIfPresent(lltok::comma)) {
2929 if (ParseGlobalTypeAndValue(C)) return true;
2936 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2937 assert(Lex.getKind() == lltok::lbrace);
2940 SmallVector<Value*, 16> Elts;
2941 if (ParseMDNodeVector(Elts, PFS) ||
2942 ParseToken(lltok::rbrace, "expected end of metadata node"))
2945 ID.MDNodeVal = MDNode::get(Context, Elts);
2946 ID.Kind = ValID::t_MDNode;
2950 /// ParseMetadataValue
2954 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2955 assert(Lex.getKind() == lltok::exclaim);
2960 if (Lex.getKind() == lltok::lbrace)
2961 return ParseMetadataListValue(ID, PFS);
2963 // Standalone metadata reference
2965 if (Lex.getKind() == lltok::APSInt) {
2966 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2967 ID.Kind = ValID::t_MDNode;
2972 // ::= '!' STRINGCONSTANT
2973 if (ParseMDString(ID.MDStringVal)) return true;
2974 ID.Kind = ValID::t_MDString;
2979 //===----------------------------------------------------------------------===//
2980 // Function Parsing.
2981 //===----------------------------------------------------------------------===//
2983 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2984 PerFunctionState *PFS) {
2985 if (Ty->isFunctionTy())
2986 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2989 case ValID::t_LocalID:
2990 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2991 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2992 return V == nullptr;
2993 case ValID::t_LocalName:
2994 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2995 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2996 return V == nullptr;
2997 case ValID::t_InlineAsm: {
2998 PointerType *PTy = dyn_cast<PointerType>(Ty);
3000 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
3001 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
3002 return Error(ID.Loc, "invalid type for inline asm constraint string");
3003 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
3004 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
3007 case ValID::t_MDNode:
3008 if (!Ty->isMetadataTy())
3009 return Error(ID.Loc, "metadata value must have metadata type");
3012 case ValID::t_MDString:
3013 if (!Ty->isMetadataTy())
3014 return Error(ID.Loc, "metadata value must have metadata type");
3017 case ValID::t_GlobalName:
3018 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
3019 return V == nullptr;
3020 case ValID::t_GlobalID:
3021 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
3022 return V == nullptr;
3023 case ValID::t_APSInt:
3024 if (!Ty->isIntegerTy())
3025 return Error(ID.Loc, "integer constant must have integer type");
3026 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
3027 V = ConstantInt::get(Context, ID.APSIntVal);
3029 case ValID::t_APFloat:
3030 if (!Ty->isFloatingPointTy() ||
3031 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
3032 return Error(ID.Loc, "floating point constant invalid for type");
3034 // The lexer has no type info, so builds all half, float, and double FP
3035 // constants as double. Fix this here. Long double does not need this.
3036 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
3039 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
3041 else if (Ty->isFloatTy())
3042 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
3045 V = ConstantFP::get(Context, ID.APFloatVal);
3047 if (V->getType() != Ty)
3048 return Error(ID.Loc, "floating point constant does not have type '" +
3049 getTypeString(Ty) + "'");
3053 if (!Ty->isPointerTy())
3054 return Error(ID.Loc, "null must be a pointer type");
3055 V = ConstantPointerNull::get(cast<PointerType>(Ty));
3057 case ValID::t_Undef:
3058 // FIXME: LabelTy should not be a first-class type.
3059 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3060 return Error(ID.Loc, "invalid type for undef constant");
3061 V = UndefValue::get(Ty);
3063 case ValID::t_EmptyArray:
3064 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
3065 return Error(ID.Loc, "invalid empty array initializer");
3066 V = UndefValue::get(Ty);
3069 // FIXME: LabelTy should not be a first-class type.
3070 if (!Ty->isFirstClassType() || Ty->isLabelTy())
3071 return Error(ID.Loc, "invalid type for null constant");
3072 V = Constant::getNullValue(Ty);
3074 case ValID::t_Constant:
3075 if (ID.ConstantVal->getType() != Ty)
3076 return Error(ID.Loc, "constant expression type mismatch");
3080 case ValID::t_ConstantStruct:
3081 case ValID::t_PackedConstantStruct:
3082 if (StructType *ST = dyn_cast<StructType>(Ty)) {
3083 if (ST->getNumElements() != ID.UIntVal)
3084 return Error(ID.Loc,
3085 "initializer with struct type has wrong # elements");
3086 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
3087 return Error(ID.Loc, "packed'ness of initializer and type don't match");
3089 // Verify that the elements are compatible with the structtype.
3090 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
3091 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
3092 return Error(ID.Loc, "element " + Twine(i) +
3093 " of struct initializer doesn't match struct element type");
3095 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
3098 return Error(ID.Loc, "constant expression type mismatch");
3101 llvm_unreachable("Invalid ValID");
3104 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
3107 return ParseValID(ID, PFS) ||
3108 ConvertValIDToValue(Ty, ID, V, PFS);
3111 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
3113 return ParseType(Ty) ||
3114 ParseValue(Ty, V, PFS);
3117 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3118 PerFunctionState &PFS) {
3121 if (ParseTypeAndValue(V, PFS)) return true;
3122 if (!isa<BasicBlock>(V))
3123 return Error(Loc, "expected a basic block");
3124 BB = cast<BasicBlock>(V);
3130 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3131 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3132 /// OptionalAlign OptGC OptionalPrefix
3133 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3134 // Parse the linkage.
3135 LocTy LinkageLoc = Lex.getLoc();
3138 unsigned Visibility;
3139 unsigned DLLStorageClass;
3140 AttrBuilder RetAttrs;
3142 Type *RetType = nullptr;
3143 LocTy RetTypeLoc = Lex.getLoc();
3144 if (ParseOptionalLinkage(Linkage) ||
3145 ParseOptionalVisibility(Visibility) ||
3146 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3147 ParseOptionalCallingConv(CC) ||
3148 ParseOptionalReturnAttrs(RetAttrs) ||
3149 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3152 // Verify that the linkage is ok.
3153 switch ((GlobalValue::LinkageTypes)Linkage) {
3154 case GlobalValue::ExternalLinkage:
3155 break; // always ok.
3156 case GlobalValue::ExternalWeakLinkage:
3158 return Error(LinkageLoc, "invalid linkage for function definition");
3160 case GlobalValue::PrivateLinkage:
3161 case GlobalValue::InternalLinkage:
3162 case GlobalValue::AvailableExternallyLinkage:
3163 case GlobalValue::LinkOnceAnyLinkage:
3164 case GlobalValue::LinkOnceODRLinkage:
3165 case GlobalValue::WeakAnyLinkage:
3166 case GlobalValue::WeakODRLinkage:
3168 return Error(LinkageLoc, "invalid linkage for function declaration");
3170 case GlobalValue::AppendingLinkage:
3171 case GlobalValue::CommonLinkage:
3172 return Error(LinkageLoc, "invalid function linkage type");
3175 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3176 return Error(LinkageLoc,
3177 "symbol with local linkage must have default visibility");
3179 if (!FunctionType::isValidReturnType(RetType))
3180 return Error(RetTypeLoc, "invalid function return type");
3182 LocTy NameLoc = Lex.getLoc();
3184 std::string FunctionName;
3185 if (Lex.getKind() == lltok::GlobalVar) {
3186 FunctionName = Lex.getStrVal();
3187 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3188 unsigned NameID = Lex.getUIntVal();
3190 if (NameID != NumberedVals.size())
3191 return TokError("function expected to be numbered '%" +
3192 Twine(NumberedVals.size()) + "'");
3194 return TokError("expected function name");
3199 if (Lex.getKind() != lltok::lparen)
3200 return TokError("expected '(' in function argument list");
3202 SmallVector<ArgInfo, 8> ArgList;
3204 AttrBuilder FuncAttrs;
3205 std::vector<unsigned> FwdRefAttrGrps;
3207 std::string Section;
3211 LocTy UnnamedAddrLoc;
3212 Constant *Prefix = nullptr;
3215 if (ParseArgumentList(ArgList, isVarArg) ||
3216 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3218 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3220 (EatIfPresent(lltok::kw_section) &&
3221 ParseStringConstant(Section)) ||
3222 parseOptionalComdat(C) ||
3223 ParseOptionalAlignment(Alignment) ||
3224 (EatIfPresent(lltok::kw_gc) &&
3225 ParseStringConstant(GC)) ||
3226 (EatIfPresent(lltok::kw_prefix) &&
3227 ParseGlobalTypeAndValue(Prefix)))
3230 if (FuncAttrs.contains(Attribute::Builtin))
3231 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3233 // If the alignment was parsed as an attribute, move to the alignment field.
3234 if (FuncAttrs.hasAlignmentAttr()) {
3235 Alignment = FuncAttrs.getAlignment();
3236 FuncAttrs.removeAttribute(Attribute::Alignment);
3239 // Okay, if we got here, the function is syntactically valid. Convert types
3240 // and do semantic checks.
3241 std::vector<Type*> ParamTypeList;
3242 SmallVector<AttributeSet, 8> Attrs;
3244 if (RetAttrs.hasAttributes())
3245 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3246 AttributeSet::ReturnIndex,
3249 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3250 ParamTypeList.push_back(ArgList[i].Ty);
3251 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3252 AttrBuilder B(ArgList[i].Attrs, i + 1);
3253 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3257 if (FuncAttrs.hasAttributes())
3258 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3259 AttributeSet::FunctionIndex,
3262 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3264 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3265 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3268 FunctionType::get(RetType, ParamTypeList, isVarArg);
3269 PointerType *PFT = PointerType::getUnqual(FT);
3272 if (!FunctionName.empty()) {
3273 // If this was a definition of a forward reference, remove the definition
3274 // from the forward reference table and fill in the forward ref.
3275 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3276 ForwardRefVals.find(FunctionName);
3277 if (FRVI != ForwardRefVals.end()) {
3278 Fn = M->getFunction(FunctionName);
3280 return Error(FRVI->second.second, "invalid forward reference to "
3281 "function as global value!");
3282 if (Fn->getType() != PFT)
3283 return Error(FRVI->second.second, "invalid forward reference to "
3284 "function '" + FunctionName + "' with wrong type!");
3286 ForwardRefVals.erase(FRVI);
3287 } else if ((Fn = M->getFunction(FunctionName))) {
3288 // Reject redefinitions.
3289 return Error(NameLoc, "invalid redefinition of function '" +
3290 FunctionName + "'");
3291 } else if (M->getNamedValue(FunctionName)) {
3292 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3296 // If this is a definition of a forward referenced function, make sure the
3298 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3299 = ForwardRefValIDs.find(NumberedVals.size());
3300 if (I != ForwardRefValIDs.end()) {
3301 Fn = cast<Function>(I->second.first);
3302 if (Fn->getType() != PFT)
3303 return Error(NameLoc, "type of definition and forward reference of '@" +
3304 Twine(NumberedVals.size()) + "' disagree");
3305 ForwardRefValIDs.erase(I);
3310 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3311 else // Move the forward-reference to the correct spot in the module.
3312 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3314 if (FunctionName.empty())
3315 NumberedVals.push_back(Fn);
3317 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3318 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3319 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3320 Fn->setCallingConv(CC);
3321 Fn->setAttributes(PAL);
3322 Fn->setUnnamedAddr(UnnamedAddr);
3323 Fn->setAlignment(Alignment);
3324 Fn->setSection(Section);
3326 if (!GC.empty()) Fn->setGC(GC.c_str());
3327 Fn->setPrefixData(Prefix);
3328 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3330 // Add all of the arguments we parsed to the function.
3331 Function::arg_iterator ArgIt = Fn->arg_begin();
3332 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3333 // If the argument has a name, insert it into the argument symbol table.
3334 if (ArgList[i].Name.empty()) continue;
3336 // Set the name, if it conflicted, it will be auto-renamed.
3337 ArgIt->setName(ArgList[i].Name);
3339 if (ArgIt->getName() != ArgList[i].Name)
3340 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3341 ArgList[i].Name + "'");
3348 /// ParseFunctionBody
3349 /// ::= '{' BasicBlock+ '}'
3351 bool LLParser::ParseFunctionBody(Function &Fn) {
3352 if (Lex.getKind() != lltok::lbrace)
3353 return TokError("expected '{' in function body");
3354 Lex.Lex(); // eat the {.
3356 int FunctionNumber = -1;
3357 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3359 PerFunctionState PFS(*this, Fn, FunctionNumber);
3361 // We need at least one basic block.
3362 if (Lex.getKind() == lltok::rbrace)
3363 return TokError("function body requires at least one basic block");
3365 while (Lex.getKind() != lltok::rbrace)
3366 if (ParseBasicBlock(PFS)) return true;
3371 // Verify function is ok.
3372 return PFS.FinishFunction();
3376 /// ::= LabelStr? Instruction*
3377 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3378 // If this basic block starts out with a name, remember it.
3380 LocTy NameLoc = Lex.getLoc();
3381 if (Lex.getKind() == lltok::LabelStr) {
3382 Name = Lex.getStrVal();
3386 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3387 if (!BB) return true;
3389 std::string NameStr;
3391 // Parse the instructions in this block until we get a terminator.
3394 // This instruction may have three possibilities for a name: a) none
3395 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3396 LocTy NameLoc = Lex.getLoc();
3400 if (Lex.getKind() == lltok::LocalVarID) {
3401 NameID = Lex.getUIntVal();
3403 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3405 } else if (Lex.getKind() == lltok::LocalVar) {
3406 NameStr = Lex.getStrVal();
3408 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3412 switch (ParseInstruction(Inst, BB, PFS)) {
3413 default: llvm_unreachable("Unknown ParseInstruction result!");
3414 case InstError: return true;
3416 BB->getInstList().push_back(Inst);
3418 // With a normal result, we check to see if the instruction is followed by
3419 // a comma and metadata.
3420 if (EatIfPresent(lltok::comma))
3421 if (ParseInstructionMetadata(Inst, &PFS))
3424 case InstExtraComma:
3425 BB->getInstList().push_back(Inst);
3427 // If the instruction parser ate an extra comma at the end of it, it
3428 // *must* be followed by metadata.
3429 if (ParseInstructionMetadata(Inst, &PFS))
3434 // Set the name on the instruction.
3435 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3436 } while (!isa<TerminatorInst>(Inst));
3441 //===----------------------------------------------------------------------===//
3442 // Instruction Parsing.
3443 //===----------------------------------------------------------------------===//
3445 /// ParseInstruction - Parse one of the many different instructions.
3447 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3448 PerFunctionState &PFS) {
3449 lltok::Kind Token = Lex.getKind();
3450 if (Token == lltok::Eof)
3451 return TokError("found end of file when expecting more instructions");
3452 LocTy Loc = Lex.getLoc();
3453 unsigned KeywordVal = Lex.getUIntVal();
3454 Lex.Lex(); // Eat the keyword.
3457 default: return Error(Loc, "expected instruction opcode");
3458 // Terminator Instructions.
3459 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3460 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3461 case lltok::kw_br: return ParseBr(Inst, PFS);
3462 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3463 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3464 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3465 case lltok::kw_resume: return ParseResume(Inst, PFS);
3466 // Binary Operators.
3470 case lltok::kw_shl: {
3471 bool NUW = EatIfPresent(lltok::kw_nuw);
3472 bool NSW = EatIfPresent(lltok::kw_nsw);
3473 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3475 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3477 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3478 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3481 case lltok::kw_fadd:
3482 case lltok::kw_fsub:
3483 case lltok::kw_fmul:
3484 case lltok::kw_fdiv:
3485 case lltok::kw_frem: {
3486 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3487 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3491 Inst->setFastMathFlags(FMF);
3495 case lltok::kw_sdiv:
3496 case lltok::kw_udiv:
3497 case lltok::kw_lshr:
3498 case lltok::kw_ashr: {
3499 bool Exact = EatIfPresent(lltok::kw_exact);
3501 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3502 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3506 case lltok::kw_urem:
3507 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3510 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3511 case lltok::kw_icmp:
3512 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3514 case lltok::kw_trunc:
3515 case lltok::kw_zext:
3516 case lltok::kw_sext:
3517 case lltok::kw_fptrunc:
3518 case lltok::kw_fpext:
3519 case lltok::kw_bitcast:
3520 case lltok::kw_addrspacecast:
3521 case lltok::kw_uitofp:
3522 case lltok::kw_sitofp:
3523 case lltok::kw_fptoui:
3524 case lltok::kw_fptosi:
3525 case lltok::kw_inttoptr:
3526 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3528 case lltok::kw_select: return ParseSelect(Inst, PFS);
3529 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3530 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3531 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3532 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3533 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3534 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3536 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3537 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3538 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3540 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3541 case lltok::kw_load: return ParseLoad(Inst, PFS);
3542 case lltok::kw_store: return ParseStore(Inst, PFS);
3543 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3544 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3545 case lltok::kw_fence: return ParseFence(Inst, PFS);
3546 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3547 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3548 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3552 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3553 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3554 if (Opc == Instruction::FCmp) {
3555 switch (Lex.getKind()) {
3556 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3557 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3558 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3559 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3560 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3561 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3562 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3563 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3564 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3565 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3566 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3567 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3568 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3569 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3570 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3571 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3572 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3575 switch (Lex.getKind()) {
3576 default: return TokError("expected icmp predicate (e.g. 'eq')");
3577 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3578 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3579 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3580 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3581 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3582 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3583 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3584 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3585 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3586 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3593 //===----------------------------------------------------------------------===//
3594 // Terminator Instructions.
3595 //===----------------------------------------------------------------------===//
3597 /// ParseRet - Parse a return instruction.
3598 /// ::= 'ret' void (',' !dbg, !1)*
3599 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3600 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3601 PerFunctionState &PFS) {
3602 SMLoc TypeLoc = Lex.getLoc();
3604 if (ParseType(Ty, true /*void allowed*/)) return true;
3606 Type *ResType = PFS.getFunction().getReturnType();
3608 if (Ty->isVoidTy()) {
3609 if (!ResType->isVoidTy())
3610 return Error(TypeLoc, "value doesn't match function result type '" +
3611 getTypeString(ResType) + "'");
3613 Inst = ReturnInst::Create(Context);
3618 if (ParseValue(Ty, RV, PFS)) return true;
3620 if (ResType != RV->getType())
3621 return Error(TypeLoc, "value doesn't match function result type '" +
3622 getTypeString(ResType) + "'");
3624 Inst = ReturnInst::Create(Context, RV);
3630 /// ::= 'br' TypeAndValue
3631 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3632 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3635 BasicBlock *Op1, *Op2;
3636 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3638 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3639 Inst = BranchInst::Create(BB);
3643 if (Op0->getType() != Type::getInt1Ty(Context))
3644 return Error(Loc, "branch condition must have 'i1' type");
3646 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3647 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3648 ParseToken(lltok::comma, "expected ',' after true destination") ||
3649 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3652 Inst = BranchInst::Create(Op1, Op2, Op0);
3658 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3660 /// ::= (TypeAndValue ',' TypeAndValue)*
3661 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3662 LocTy CondLoc, BBLoc;
3664 BasicBlock *DefaultBB;
3665 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3666 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3667 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3668 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3671 if (!Cond->getType()->isIntegerTy())
3672 return Error(CondLoc, "switch condition must have integer type");
3674 // Parse the jump table pairs.
3675 SmallPtrSet<Value*, 32> SeenCases;
3676 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3677 while (Lex.getKind() != lltok::rsquare) {
3681 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3682 ParseToken(lltok::comma, "expected ',' after case value") ||
3683 ParseTypeAndBasicBlock(DestBB, PFS))
3686 if (!SeenCases.insert(Constant))
3687 return Error(CondLoc, "duplicate case value in switch");
3688 if (!isa<ConstantInt>(Constant))
3689 return Error(CondLoc, "case value is not a constant integer");
3691 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3694 Lex.Lex(); // Eat the ']'.
3696 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3697 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3698 SI->addCase(Table[i].first, Table[i].second);
3705 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3706 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3709 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3710 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3711 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3714 if (!Address->getType()->isPointerTy())
3715 return Error(AddrLoc, "indirectbr address must have pointer type");
3717 // Parse the destination list.
3718 SmallVector<BasicBlock*, 16> DestList;
3720 if (Lex.getKind() != lltok::rsquare) {
3722 if (ParseTypeAndBasicBlock(DestBB, PFS))
3724 DestList.push_back(DestBB);
3726 while (EatIfPresent(lltok::comma)) {
3727 if (ParseTypeAndBasicBlock(DestBB, PFS))
3729 DestList.push_back(DestBB);
3733 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3736 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3737 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3738 IBI->addDestination(DestList[i]);
3745 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3746 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3747 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3748 LocTy CallLoc = Lex.getLoc();
3749 AttrBuilder RetAttrs, FnAttrs;
3750 std::vector<unsigned> FwdRefAttrGrps;
3753 Type *RetType = nullptr;
3756 SmallVector<ParamInfo, 16> ArgList;
3758 BasicBlock *NormalBB, *UnwindBB;
3759 if (ParseOptionalCallingConv(CC) ||
3760 ParseOptionalReturnAttrs(RetAttrs) ||
3761 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3762 ParseValID(CalleeID) ||
3763 ParseParameterList(ArgList, PFS) ||
3764 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3766 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3767 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3768 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3769 ParseTypeAndBasicBlock(UnwindBB, PFS))
3772 // If RetType is a non-function pointer type, then this is the short syntax
3773 // for the call, which means that RetType is just the return type. Infer the
3774 // rest of the function argument types from the arguments that are present.
3775 PointerType *PFTy = nullptr;
3776 FunctionType *Ty = nullptr;
3777 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3778 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3779 // Pull out the types of all of the arguments...
3780 std::vector<Type*> ParamTypes;
3781 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3782 ParamTypes.push_back(ArgList[i].V->getType());
3784 if (!FunctionType::isValidReturnType(RetType))
3785 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3787 Ty = FunctionType::get(RetType, ParamTypes, false);
3788 PFTy = PointerType::getUnqual(Ty);
3791 // Look up the callee.
3793 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3795 // Set up the Attribute for the function.
3796 SmallVector<AttributeSet, 8> Attrs;
3797 if (RetAttrs.hasAttributes())
3798 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3799 AttributeSet::ReturnIndex,
3802 SmallVector<Value*, 8> Args;
3804 // Loop through FunctionType's arguments and ensure they are specified
3805 // correctly. Also, gather any parameter attributes.
3806 FunctionType::param_iterator I = Ty->param_begin();
3807 FunctionType::param_iterator E = Ty->param_end();
3808 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3809 Type *ExpectedTy = nullptr;
3812 } else if (!Ty->isVarArg()) {
3813 return Error(ArgList[i].Loc, "too many arguments specified");
3816 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3817 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3818 getTypeString(ExpectedTy) + "'");
3819 Args.push_back(ArgList[i].V);
3820 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3821 AttrBuilder B(ArgList[i].Attrs, i + 1);
3822 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3827 return Error(CallLoc, "not enough parameters specified for call");
3829 if (FnAttrs.hasAttributes())
3830 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3831 AttributeSet::FunctionIndex,
3834 // Finish off the Attribute and check them
3835 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3837 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3838 II->setCallingConv(CC);
3839 II->setAttributes(PAL);
3840 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3846 /// ::= 'resume' TypeAndValue
3847 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3848 Value *Exn; LocTy ExnLoc;
3849 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3852 ResumeInst *RI = ResumeInst::Create(Exn);
3857 //===----------------------------------------------------------------------===//
3858 // Binary Operators.
3859 //===----------------------------------------------------------------------===//
3862 /// ::= ArithmeticOps TypeAndValue ',' Value
3864 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3865 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3866 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3867 unsigned Opc, unsigned OperandType) {
3868 LocTy Loc; Value *LHS, *RHS;
3869 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3870 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3871 ParseValue(LHS->getType(), RHS, PFS))
3875 switch (OperandType) {
3876 default: llvm_unreachable("Unknown operand type!");
3877 case 0: // int or FP.
3878 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3879 LHS->getType()->isFPOrFPVectorTy();
3881 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3882 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3886 return Error(Loc, "invalid operand type for instruction");
3888 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3893 /// ::= ArithmeticOps TypeAndValue ',' Value {
3894 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3896 LocTy Loc; Value *LHS, *RHS;
3897 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3898 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3899 ParseValue(LHS->getType(), RHS, PFS))
3902 if (!LHS->getType()->isIntOrIntVectorTy())
3903 return Error(Loc,"instruction requires integer or integer vector operands");
3905 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3911 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3912 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3913 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3915 // Parse the integer/fp comparison predicate.
3919 if (ParseCmpPredicate(Pred, Opc) ||
3920 ParseTypeAndValue(LHS, Loc, PFS) ||
3921 ParseToken(lltok::comma, "expected ',' after compare value") ||
3922 ParseValue(LHS->getType(), RHS, PFS))
3925 if (Opc == Instruction::FCmp) {
3926 if (!LHS->getType()->isFPOrFPVectorTy())
3927 return Error(Loc, "fcmp requires floating point operands");
3928 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3930 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3931 if (!LHS->getType()->isIntOrIntVectorTy() &&
3932 !LHS->getType()->getScalarType()->isPointerTy())
3933 return Error(Loc, "icmp requires integer operands");
3934 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3939 //===----------------------------------------------------------------------===//
3940 // Other Instructions.
3941 //===----------------------------------------------------------------------===//
3945 /// ::= CastOpc TypeAndValue 'to' Type
3946 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3950 Type *DestTy = nullptr;
3951 if (ParseTypeAndValue(Op, Loc, PFS) ||
3952 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3956 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3957 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3958 return Error(Loc, "invalid cast opcode for cast from '" +
3959 getTypeString(Op->getType()) + "' to '" +
3960 getTypeString(DestTy) + "'");
3962 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3967 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3968 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3970 Value *Op0, *Op1, *Op2;
3971 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3972 ParseToken(lltok::comma, "expected ',' after select condition") ||
3973 ParseTypeAndValue(Op1, PFS) ||
3974 ParseToken(lltok::comma, "expected ',' after select value") ||
3975 ParseTypeAndValue(Op2, PFS))
3978 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3979 return Error(Loc, Reason);
3981 Inst = SelectInst::Create(Op0, Op1, Op2);
3986 /// ::= 'va_arg' TypeAndValue ',' Type
3987 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3989 Type *EltTy = nullptr;
3991 if (ParseTypeAndValue(Op, PFS) ||
3992 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3993 ParseType(EltTy, TypeLoc))
3996 if (!EltTy->isFirstClassType())
3997 return Error(TypeLoc, "va_arg requires operand with first class type");
3999 Inst = new VAArgInst(Op, EltTy);
4003 /// ParseExtractElement
4004 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
4005 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
4008 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4009 ParseToken(lltok::comma, "expected ',' after extract value") ||
4010 ParseTypeAndValue(Op1, PFS))
4013 if (!ExtractElementInst::isValidOperands(Op0, Op1))
4014 return Error(Loc, "invalid extractelement operands");
4016 Inst = ExtractElementInst::Create(Op0, Op1);
4020 /// ParseInsertElement
4021 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4022 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
4024 Value *Op0, *Op1, *Op2;
4025 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4026 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4027 ParseTypeAndValue(Op1, PFS) ||
4028 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4029 ParseTypeAndValue(Op2, PFS))
4032 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
4033 return Error(Loc, "invalid insertelement operands");
4035 Inst = InsertElementInst::Create(Op0, Op1, Op2);
4039 /// ParseShuffleVector
4040 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
4041 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
4043 Value *Op0, *Op1, *Op2;
4044 if (ParseTypeAndValue(Op0, Loc, PFS) ||
4045 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
4046 ParseTypeAndValue(Op1, PFS) ||
4047 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
4048 ParseTypeAndValue(Op2, PFS))
4051 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
4052 return Error(Loc, "invalid shufflevector operands");
4054 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
4059 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
4060 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
4061 Type *Ty = nullptr; LocTy TypeLoc;
4064 if (ParseType(Ty, TypeLoc) ||
4065 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4066 ParseValue(Ty, Op0, PFS) ||
4067 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4068 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4069 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4072 bool AteExtraComma = false;
4073 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
4075 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
4077 if (!EatIfPresent(lltok::comma))
4080 if (Lex.getKind() == lltok::MetadataVar) {
4081 AteExtraComma = true;
4085 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
4086 ParseValue(Ty, Op0, PFS) ||
4087 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
4088 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
4089 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
4093 if (!Ty->isFirstClassType())
4094 return Error(TypeLoc, "phi node must have first class type");
4096 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
4097 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
4098 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
4100 return AteExtraComma ? InstExtraComma : InstNormal;
4104 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
4106 /// ::= 'catch' TypeAndValue
4108 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
4109 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
4110 Type *Ty = nullptr; LocTy TyLoc;
4111 Value *PersFn; LocTy PersFnLoc;
4113 if (ParseType(Ty, TyLoc) ||
4114 ParseToken(lltok::kw_personality, "expected 'personality'") ||
4115 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
4118 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4119 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4121 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4122 LandingPadInst::ClauseType CT;
4123 if (EatIfPresent(lltok::kw_catch))
4124 CT = LandingPadInst::Catch;
4125 else if (EatIfPresent(lltok::kw_filter))
4126 CT = LandingPadInst::Filter;
4128 return TokError("expected 'catch' or 'filter' clause type");
4132 if (ParseTypeAndValue(V, VLoc, PFS)) {
4137 // A 'catch' type expects a non-array constant. A filter clause expects an
4139 if (CT == LandingPadInst::Catch) {
4140 if (isa<ArrayType>(V->getType()))
4141 Error(VLoc, "'catch' clause has an invalid type");
4143 if (!isa<ArrayType>(V->getType()))
4144 Error(VLoc, "'filter' clause has an invalid type");
4147 LP->addClause(cast<Constant>(V));
4155 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4156 /// ParameterList OptionalAttrs
4157 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4158 /// ParameterList OptionalAttrs
4159 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4160 /// ParameterList OptionalAttrs
4161 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4162 CallInst::TailCallKind TCK) {
4163 AttrBuilder RetAttrs, FnAttrs;
4164 std::vector<unsigned> FwdRefAttrGrps;
4167 Type *RetType = nullptr;
4170 SmallVector<ParamInfo, 16> ArgList;
4171 LocTy CallLoc = Lex.getLoc();
4173 if ((TCK != CallInst::TCK_None &&
4174 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4175 ParseOptionalCallingConv(CC) ||
4176 ParseOptionalReturnAttrs(RetAttrs) ||
4177 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4178 ParseValID(CalleeID) ||
4179 ParseParameterList(ArgList, PFS) ||
4180 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4184 // If RetType is a non-function pointer type, then this is the short syntax
4185 // for the call, which means that RetType is just the return type. Infer the
4186 // rest of the function argument types from the arguments that are present.
4187 PointerType *PFTy = nullptr;
4188 FunctionType *Ty = nullptr;
4189 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4190 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4191 // Pull out the types of all of the arguments...
4192 std::vector<Type*> ParamTypes;
4193 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4194 ParamTypes.push_back(ArgList[i].V->getType());
4196 if (!FunctionType::isValidReturnType(RetType))
4197 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4199 Ty = FunctionType::get(RetType, ParamTypes, false);
4200 PFTy = PointerType::getUnqual(Ty);
4203 // Look up the callee.
4205 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4207 // Set up the Attribute for the function.
4208 SmallVector<AttributeSet, 8> Attrs;
4209 if (RetAttrs.hasAttributes())
4210 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4211 AttributeSet::ReturnIndex,
4214 SmallVector<Value*, 8> Args;
4216 // Loop through FunctionType's arguments and ensure they are specified
4217 // correctly. Also, gather any parameter attributes.
4218 FunctionType::param_iterator I = Ty->param_begin();
4219 FunctionType::param_iterator E = Ty->param_end();
4220 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4221 Type *ExpectedTy = nullptr;
4224 } else if (!Ty->isVarArg()) {
4225 return Error(ArgList[i].Loc, "too many arguments specified");
4228 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4229 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4230 getTypeString(ExpectedTy) + "'");
4231 Args.push_back(ArgList[i].V);
4232 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4233 AttrBuilder B(ArgList[i].Attrs, i + 1);
4234 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4239 return Error(CallLoc, "not enough parameters specified for call");
4241 if (FnAttrs.hasAttributes())
4242 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4243 AttributeSet::FunctionIndex,
4246 // Finish off the Attribute and check them
4247 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4249 CallInst *CI = CallInst::Create(Callee, Args);
4250 CI->setTailCallKind(TCK);
4251 CI->setCallingConv(CC);
4252 CI->setAttributes(PAL);
4253 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4258 //===----------------------------------------------------------------------===//
4259 // Memory Instructions.
4260 //===----------------------------------------------------------------------===//
4263 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4264 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4265 Value *Size = nullptr;
4267 unsigned Alignment = 0;
4270 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4272 if (ParseType(Ty)) return true;
4274 bool AteExtraComma = false;
4275 if (EatIfPresent(lltok::comma)) {
4276 if (Lex.getKind() == lltok::kw_align) {
4277 if (ParseOptionalAlignment(Alignment)) return true;
4278 } else if (Lex.getKind() == lltok::MetadataVar) {
4279 AteExtraComma = true;
4281 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4282 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4287 if (Size && !Size->getType()->isIntegerTy())
4288 return Error(SizeLoc, "element count must have integer type");
4290 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4291 AI->setUsedWithInAlloca(IsInAlloca);
4293 return AteExtraComma ? InstExtraComma : InstNormal;
4297 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4298 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4299 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4300 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4301 Value *Val; LocTy Loc;
4302 unsigned Alignment = 0;
4303 bool AteExtraComma = false;
4304 bool isAtomic = false;
4305 AtomicOrdering Ordering = NotAtomic;
4306 SynchronizationScope Scope = CrossThread;
4308 if (Lex.getKind() == lltok::kw_atomic) {
4313 bool isVolatile = false;
4314 if (Lex.getKind() == lltok::kw_volatile) {
4319 if (ParseTypeAndValue(Val, Loc, PFS) ||
4320 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4321 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4324 if (!Val->getType()->isPointerTy() ||
4325 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4326 return Error(Loc, "load operand must be a pointer to a first class type");
4327 if (isAtomic && !Alignment)
4328 return Error(Loc, "atomic load must have explicit non-zero alignment");
4329 if (Ordering == Release || Ordering == AcquireRelease)
4330 return Error(Loc, "atomic load cannot use Release ordering");
4332 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4333 return AteExtraComma ? InstExtraComma : InstNormal;
4338 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4339 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4340 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4341 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4342 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4343 unsigned Alignment = 0;
4344 bool AteExtraComma = false;
4345 bool isAtomic = false;
4346 AtomicOrdering Ordering = NotAtomic;
4347 SynchronizationScope Scope = CrossThread;
4349 if (Lex.getKind() == lltok::kw_atomic) {
4354 bool isVolatile = false;
4355 if (Lex.getKind() == lltok::kw_volatile) {
4360 if (ParseTypeAndValue(Val, Loc, PFS) ||
4361 ParseToken(lltok::comma, "expected ',' after store operand") ||
4362 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4363 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4364 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4367 if (!Ptr->getType()->isPointerTy())
4368 return Error(PtrLoc, "store operand must be a pointer");
4369 if (!Val->getType()->isFirstClassType())
4370 return Error(Loc, "store operand must be a first class value");
4371 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4372 return Error(Loc, "stored value and pointer type do not match");
4373 if (isAtomic && !Alignment)
4374 return Error(Loc, "atomic store must have explicit non-zero alignment");
4375 if (Ordering == Acquire || Ordering == AcquireRelease)
4376 return Error(Loc, "atomic store cannot use Acquire ordering");
4378 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4379 return AteExtraComma ? InstExtraComma : InstNormal;
4383 /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
4384 /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
4385 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4386 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4387 bool AteExtraComma = false;
4388 AtomicOrdering SuccessOrdering = NotAtomic;
4389 AtomicOrdering FailureOrdering = NotAtomic;
4390 SynchronizationScope Scope = CrossThread;
4391 bool isVolatile = false;
4392 bool isWeak = false;
4394 if (EatIfPresent(lltok::kw_weak))
4397 if (EatIfPresent(lltok::kw_volatile))
4400 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4401 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4402 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4403 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4404 ParseTypeAndValue(New, NewLoc, PFS) ||
4405 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4406 ParseOrdering(FailureOrdering))
4409 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4410 return TokError("cmpxchg cannot be unordered");
4411 if (SuccessOrdering < FailureOrdering)
4412 return TokError("cmpxchg must be at least as ordered on success as failure");
4413 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4414 return TokError("cmpxchg failure ordering cannot include release semantics");
4415 if (!Ptr->getType()->isPointerTy())
4416 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4417 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4418 return Error(CmpLoc, "compare value and pointer type do not match");
4419 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4420 return Error(NewLoc, "new value and pointer type do not match");
4421 if (!New->getType()->isIntegerTy())
4422 return Error(NewLoc, "cmpxchg operand must be an integer");
4423 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4424 if (Size < 8 || (Size & (Size - 1)))
4425 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4428 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
4429 Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
4430 CXI->setVolatile(isVolatile);
4431 CXI->setWeak(isWeak);
4433 return AteExtraComma ? InstExtraComma : InstNormal;
4437 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4438 /// 'singlethread'? AtomicOrdering
4439 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4440 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4441 bool AteExtraComma = false;
4442 AtomicOrdering Ordering = NotAtomic;
4443 SynchronizationScope Scope = CrossThread;
4444 bool isVolatile = false;
4445 AtomicRMWInst::BinOp Operation;
4447 if (EatIfPresent(lltok::kw_volatile))
4450 switch (Lex.getKind()) {
4451 default: return TokError("expected binary operation in atomicrmw");
4452 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4453 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4454 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4455 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4456 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4457 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4458 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4459 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4460 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4461 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4462 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4464 Lex.Lex(); // Eat the operation.
4466 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4467 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4468 ParseTypeAndValue(Val, ValLoc, PFS) ||
4469 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4472 if (Ordering == Unordered)
4473 return TokError("atomicrmw cannot be unordered");
4474 if (!Ptr->getType()->isPointerTy())
4475 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4476 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4477 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4478 if (!Val->getType()->isIntegerTy())
4479 return Error(ValLoc, "atomicrmw operand must be an integer");
4480 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4481 if (Size < 8 || (Size & (Size - 1)))
4482 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4485 AtomicRMWInst *RMWI =
4486 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4487 RMWI->setVolatile(isVolatile);
4489 return AteExtraComma ? InstExtraComma : InstNormal;
4493 /// ::= 'fence' 'singlethread'? AtomicOrdering
4494 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4495 AtomicOrdering Ordering = NotAtomic;
4496 SynchronizationScope Scope = CrossThread;
4497 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4500 if (Ordering == Unordered)
4501 return TokError("fence cannot be unordered");
4502 if (Ordering == Monotonic)
4503 return TokError("fence cannot be monotonic");
4505 Inst = new FenceInst(Context, Ordering, Scope);
4509 /// ParseGetElementPtr
4510 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4511 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4512 Value *Ptr = nullptr;
4513 Value *Val = nullptr;
4516 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4518 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4520 Type *BaseType = Ptr->getType();
4521 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4522 if (!BasePointerType)
4523 return Error(Loc, "base of getelementptr must be a pointer");
4525 SmallVector<Value*, 16> Indices;
4526 bool AteExtraComma = false;
4527 while (EatIfPresent(lltok::comma)) {
4528 if (Lex.getKind() == lltok::MetadataVar) {
4529 AteExtraComma = true;
4532 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4533 if (!Val->getType()->getScalarType()->isIntegerTy())
4534 return Error(EltLoc, "getelementptr index must be an integer");
4535 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4536 return Error(EltLoc, "getelementptr index type missmatch");
4537 if (Val->getType()->isVectorTy()) {
4538 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4539 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4540 if (ValNumEl != PtrNumEl)
4541 return Error(EltLoc,
4542 "getelementptr vector index has a wrong number of elements");
4544 Indices.push_back(Val);
4547 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4548 return Error(Loc, "base element of getelementptr must be sized");
4550 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4551 return Error(Loc, "invalid getelementptr indices");
4552 Inst = GetElementPtrInst::Create(Ptr, Indices);
4554 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4555 return AteExtraComma ? InstExtraComma : InstNormal;
4558 /// ParseExtractValue
4559 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4560 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4561 Value *Val; LocTy Loc;
4562 SmallVector<unsigned, 4> Indices;
4564 if (ParseTypeAndValue(Val, Loc, PFS) ||
4565 ParseIndexList(Indices, AteExtraComma))
4568 if (!Val->getType()->isAggregateType())
4569 return Error(Loc, "extractvalue operand must be aggregate type");
4571 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4572 return Error(Loc, "invalid indices for extractvalue");
4573 Inst = ExtractValueInst::Create(Val, Indices);
4574 return AteExtraComma ? InstExtraComma : InstNormal;
4577 /// ParseInsertValue
4578 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4579 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4580 Value *Val0, *Val1; LocTy Loc0, Loc1;
4581 SmallVector<unsigned, 4> Indices;
4583 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4584 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4585 ParseTypeAndValue(Val1, Loc1, PFS) ||
4586 ParseIndexList(Indices, AteExtraComma))
4589 if (!Val0->getType()->isAggregateType())
4590 return Error(Loc0, "insertvalue operand must be aggregate type");
4592 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4593 return Error(Loc0, "invalid indices for insertvalue");
4594 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4595 return AteExtraComma ? InstExtraComma : InstNormal;
4598 //===----------------------------------------------------------------------===//
4599 // Embedded metadata.
4600 //===----------------------------------------------------------------------===//
4602 /// ParseMDNodeVector
4603 /// ::= Element (',' Element)*
4605 /// ::= 'null' | TypeAndValue
4606 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4607 PerFunctionState *PFS) {
4608 // Check for an empty list.
4609 if (Lex.getKind() == lltok::rbrace)
4613 // Null is a special case since it is typeless.
4614 if (EatIfPresent(lltok::kw_null)) {
4615 Elts.push_back(nullptr);
4620 if (ParseTypeAndValue(V, PFS)) return true;
4622 } while (EatIfPresent(lltok::comma));