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 (!ForwardRefVals.empty())
167 return Error(ForwardRefVals.begin()->second.second,
168 "use of undefined value '@" + ForwardRefVals.begin()->first +
171 if (!ForwardRefValIDs.empty())
172 return Error(ForwardRefValIDs.begin()->second.second,
173 "use of undefined value '@" +
174 Twine(ForwardRefValIDs.begin()->first) + "'");
176 if (!ForwardRefMDNodes.empty())
177 return Error(ForwardRefMDNodes.begin()->second.second,
178 "use of undefined metadata '!" +
179 Twine(ForwardRefMDNodes.begin()->first) + "'");
182 // Look for intrinsic functions and CallInst that need to be upgraded
183 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
184 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
186 UpgradeDebugInfo(*M);
191 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
192 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
193 PerFunctionState *PFS) {
194 // Loop over all the references, resolving them.
195 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
198 if (Refs[i].first.Kind == ValID::t_LocalName)
199 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
201 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
202 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
203 return Error(Refs[i].first.Loc,
204 "cannot take address of numeric label after the function is defined");
206 Res = dyn_cast_or_null<BasicBlock>(
207 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
211 return Error(Refs[i].first.Loc,
212 "referenced value is not a basic block");
214 // Get the BlockAddress for this and update references to use it.
215 BlockAddress *BA = BlockAddress::get(TheFn, Res);
216 Refs[i].second->replaceAllUsesWith(BA);
217 Refs[i].second->eraseFromParent();
223 //===----------------------------------------------------------------------===//
224 // Top-Level Entities
225 //===----------------------------------------------------------------------===//
227 bool LLParser::ParseTopLevelEntities() {
229 switch (Lex.getKind()) {
230 default: return TokError("expected top-level entity");
231 case lltok::Eof: return false;
232 case lltok::kw_declare: if (ParseDeclare()) return true; break;
233 case lltok::kw_define: if (ParseDefine()) return true; break;
234 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
235 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
236 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
237 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
238 case lltok::LocalVar: if (ParseNamedType()) return true; break;
239 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
240 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
241 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
242 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
244 // The Global variable production with no name can have many different
245 // optional leading prefixes, the production is:
246 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
247 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
248 // ('constant'|'global') ...
249 case lltok::kw_private: // OptionalLinkage
250 case lltok::kw_internal: // OptionalLinkage
251 case lltok::kw_linker_private: // Obsolete OptionalLinkage
252 case lltok::kw_linker_private_weak: // Obsolete OptionalLinkage
253 case lltok::kw_weak: // OptionalLinkage
254 case lltok::kw_weak_odr: // OptionalLinkage
255 case lltok::kw_linkonce: // OptionalLinkage
256 case lltok::kw_linkonce_odr: // OptionalLinkage
257 case lltok::kw_appending: // OptionalLinkage
258 case lltok::kw_common: // OptionalLinkage
259 case lltok::kw_extern_weak: // OptionalLinkage
260 case lltok::kw_external: { // OptionalLinkage
261 unsigned Linkage, Visibility, DLLStorageClass;
262 if (ParseOptionalLinkage(Linkage) ||
263 ParseOptionalVisibility(Visibility) ||
264 ParseOptionalDLLStorageClass(DLLStorageClass) ||
265 ParseGlobal("", SMLoc(), Linkage, true, Visibility, DLLStorageClass))
269 case lltok::kw_default: // OptionalVisibility
270 case lltok::kw_hidden: // OptionalVisibility
271 case lltok::kw_protected: { // OptionalVisibility
272 unsigned Visibility, DLLStorageClass;
273 if (ParseOptionalVisibility(Visibility) ||
274 ParseOptionalDLLStorageClass(DLLStorageClass) ||
275 ParseGlobal("", SMLoc(), 0, false, Visibility, DLLStorageClass))
280 case lltok::kw_thread_local: // OptionalThreadLocal
281 case lltok::kw_addrspace: // OptionalAddrSpace
282 case lltok::kw_constant: // GlobalType
283 case lltok::kw_global: // GlobalType
284 if (ParseGlobal("", SMLoc(), 0, false, 0, 0)) return true;
287 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
294 /// ::= 'module' 'asm' STRINGCONSTANT
295 bool LLParser::ParseModuleAsm() {
296 assert(Lex.getKind() == lltok::kw_module);
300 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
301 ParseStringConstant(AsmStr)) return true;
303 M->appendModuleInlineAsm(AsmStr);
308 /// ::= 'target' 'triple' '=' STRINGCONSTANT
309 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
310 bool LLParser::ParseTargetDefinition() {
311 assert(Lex.getKind() == lltok::kw_target);
314 default: return TokError("unknown target property");
315 case lltok::kw_triple:
317 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
318 ParseStringConstant(Str))
320 M->setTargetTriple(Str);
322 case lltok::kw_datalayout:
324 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
325 ParseStringConstant(Str))
327 M->setDataLayout(Str);
333 /// ::= 'deplibs' '=' '[' ']'
334 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
335 /// FIXME: Remove in 4.0. Currently parse, but ignore.
336 bool LLParser::ParseDepLibs() {
337 assert(Lex.getKind() == lltok::kw_deplibs);
339 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
340 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
343 if (EatIfPresent(lltok::rsquare))
348 if (ParseStringConstant(Str)) return true;
349 } while (EatIfPresent(lltok::comma));
351 return ParseToken(lltok::rsquare, "expected ']' at end of list");
354 /// ParseUnnamedType:
355 /// ::= LocalVarID '=' 'type' type
356 bool LLParser::ParseUnnamedType() {
357 LocTy TypeLoc = Lex.getLoc();
358 unsigned TypeID = Lex.getUIntVal();
359 Lex.Lex(); // eat LocalVarID;
361 if (ParseToken(lltok::equal, "expected '=' after name") ||
362 ParseToken(lltok::kw_type, "expected 'type' after '='"))
365 if (TypeID >= NumberedTypes.size())
366 NumberedTypes.resize(TypeID+1);
368 Type *Result = nullptr;
369 if (ParseStructDefinition(TypeLoc, "",
370 NumberedTypes[TypeID], Result)) return true;
372 if (!isa<StructType>(Result)) {
373 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
375 return Error(TypeLoc, "non-struct types may not be recursive");
376 Entry.first = Result;
377 Entry.second = SMLoc();
385 /// ::= LocalVar '=' 'type' type
386 bool LLParser::ParseNamedType() {
387 std::string Name = Lex.getStrVal();
388 LocTy NameLoc = Lex.getLoc();
389 Lex.Lex(); // eat LocalVar.
391 if (ParseToken(lltok::equal, "expected '=' after name") ||
392 ParseToken(lltok::kw_type, "expected 'type' after name"))
395 Type *Result = nullptr;
396 if (ParseStructDefinition(NameLoc, Name,
397 NamedTypes[Name], Result)) return true;
399 if (!isa<StructType>(Result)) {
400 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
402 return Error(NameLoc, "non-struct types may not be recursive");
403 Entry.first = Result;
404 Entry.second = SMLoc();
412 /// ::= 'declare' FunctionHeader
413 bool LLParser::ParseDeclare() {
414 assert(Lex.getKind() == lltok::kw_declare);
418 return ParseFunctionHeader(F, false);
422 /// ::= 'define' FunctionHeader '{' ...
423 bool LLParser::ParseDefine() {
424 assert(Lex.getKind() == lltok::kw_define);
428 return ParseFunctionHeader(F, true) ||
429 ParseFunctionBody(*F);
435 bool LLParser::ParseGlobalType(bool &IsConstant) {
436 if (Lex.getKind() == lltok::kw_constant)
438 else if (Lex.getKind() == lltok::kw_global)
442 return TokError("expected 'global' or 'constant'");
448 /// ParseUnnamedGlobal:
449 /// OptionalVisibility ALIAS ...
450 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
451 /// ... -> global variable
452 /// GlobalID '=' OptionalVisibility ALIAS ...
453 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
454 /// ... -> global variable
455 bool LLParser::ParseUnnamedGlobal() {
456 unsigned VarID = NumberedVals.size();
458 LocTy NameLoc = Lex.getLoc();
460 // Handle the GlobalID form.
461 if (Lex.getKind() == lltok::GlobalID) {
462 if (Lex.getUIntVal() != VarID)
463 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
465 Lex.Lex(); // eat GlobalID;
467 if (ParseToken(lltok::equal, "expected '=' after name"))
472 unsigned Linkage, Visibility, DLLStorageClass;
473 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
474 ParseOptionalVisibility(Visibility) ||
475 ParseOptionalDLLStorageClass(DLLStorageClass))
478 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
479 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
481 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
484 /// ParseNamedGlobal:
485 /// GlobalVar '=' OptionalVisibility ALIAS ...
486 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
487 /// ... -> global variable
488 bool LLParser::ParseNamedGlobal() {
489 assert(Lex.getKind() == lltok::GlobalVar);
490 LocTy NameLoc = Lex.getLoc();
491 std::string Name = Lex.getStrVal();
495 unsigned Linkage, Visibility, DLLStorageClass;
496 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
497 ParseOptionalLinkage(Linkage, HasLinkage) ||
498 ParseOptionalVisibility(Visibility) ||
499 ParseOptionalDLLStorageClass(DLLStorageClass))
502 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
503 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
505 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
509 // ::= '!' STRINGCONSTANT
510 bool LLParser::ParseMDString(MDString *&Result) {
512 if (ParseStringConstant(Str)) return true;
513 Result = MDString::get(Context, Str);
518 // ::= '!' MDNodeNumber
520 /// This version of ParseMDNodeID returns the slot number and null in the case
521 /// of a forward reference.
522 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
523 // !{ ..., !42, ... }
524 if (ParseUInt32(SlotNo)) return true;
526 // Check existing MDNode.
527 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
528 Result = NumberedMetadata[SlotNo];
534 bool LLParser::ParseMDNodeID(MDNode *&Result) {
535 // !{ ..., !42, ... }
537 if (ParseMDNodeID(Result, MID)) return true;
539 // If not a forward reference, just return it now.
540 if (Result) return false;
542 // Otherwise, create MDNode forward reference.
543 MDNode *FwdNode = MDNode::getTemporary(Context, None);
544 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
546 if (NumberedMetadata.size() <= MID)
547 NumberedMetadata.resize(MID+1);
548 NumberedMetadata[MID] = FwdNode;
553 /// ParseNamedMetadata:
554 /// !foo = !{ !1, !2 }
555 bool LLParser::ParseNamedMetadata() {
556 assert(Lex.getKind() == lltok::MetadataVar);
557 std::string Name = Lex.getStrVal();
560 if (ParseToken(lltok::equal, "expected '=' here") ||
561 ParseToken(lltok::exclaim, "Expected '!' here") ||
562 ParseToken(lltok::lbrace, "Expected '{' here"))
565 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
566 if (Lex.getKind() != lltok::rbrace)
568 if (ParseToken(lltok::exclaim, "Expected '!' here"))
572 if (ParseMDNodeID(N)) return true;
574 } while (EatIfPresent(lltok::comma));
576 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
582 /// ParseStandaloneMetadata:
584 bool LLParser::ParseStandaloneMetadata() {
585 assert(Lex.getKind() == lltok::exclaim);
587 unsigned MetadataID = 0;
591 SmallVector<Value *, 16> Elts;
592 if (ParseUInt32(MetadataID) ||
593 ParseToken(lltok::equal, "expected '=' here") ||
594 ParseType(Ty, TyLoc) ||
595 ParseToken(lltok::exclaim, "Expected '!' here") ||
596 ParseToken(lltok::lbrace, "Expected '{' here") ||
597 ParseMDNodeVector(Elts, nullptr) ||
598 ParseToken(lltok::rbrace, "expected end of metadata node"))
601 MDNode *Init = MDNode::get(Context, Elts);
603 // See if this was forward referenced, if so, handle it.
604 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
605 FI = ForwardRefMDNodes.find(MetadataID);
606 if (FI != ForwardRefMDNodes.end()) {
607 MDNode *Temp = FI->second.first;
608 Temp->replaceAllUsesWith(Init);
609 MDNode::deleteTemporary(Temp);
610 ForwardRefMDNodes.erase(FI);
612 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
614 if (MetadataID >= NumberedMetadata.size())
615 NumberedMetadata.resize(MetadataID+1);
617 if (NumberedMetadata[MetadataID] != nullptr)
618 return TokError("Metadata id is already used");
619 NumberedMetadata[MetadataID] = Init;
626 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
627 /// OptionalLinkage Aliasee
630 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
631 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
633 /// Everything through DLL storage class has already been parsed.
635 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
636 unsigned Visibility, unsigned DLLStorageClass) {
637 assert(Lex.getKind() == lltok::kw_alias);
639 LocTy LinkageLoc = Lex.getLoc();
641 if (ParseOptionalLinkage(L))
644 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
646 if(!GlobalAlias::isValidLinkage(Linkage))
647 return Error(LinkageLoc, "invalid linkage type for alias");
650 LocTy AliaseeLoc = Lex.getLoc();
651 if (Lex.getKind() != lltok::kw_bitcast &&
652 Lex.getKind() != lltok::kw_getelementptr) {
653 if (ParseGlobalTypeAndValue(Aliasee)) return true;
655 // The bitcast dest type is not present, it is implied by the dest type.
657 if (ParseValID(ID)) return true;
658 if (ID.Kind != ValID::t_Constant)
659 return Error(AliaseeLoc, "invalid aliasee");
660 Aliasee = ID.ConstantVal;
663 if (!Aliasee->getType()->isPointerTy())
664 return Error(AliaseeLoc, "alias must have pointer type");
666 // Okay, create the alias but do not insert it into the module yet.
667 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
668 (GlobalValue::LinkageTypes)Linkage, Name,
670 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
671 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
673 // See if this value already exists in the symbol table. If so, it is either
674 // a redefinition or a definition of a forward reference.
675 if (GlobalValue *Val = M->getNamedValue(Name)) {
676 // See if this was a redefinition. If so, there is no entry in
678 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
679 I = ForwardRefVals.find(Name);
680 if (I == ForwardRefVals.end())
681 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
683 // Otherwise, this was a definition of forward ref. Verify that types
685 if (Val->getType() != GA->getType())
686 return Error(NameLoc,
687 "forward reference and definition of alias have different types");
689 // If they agree, just RAUW the old value with the alias and remove the
691 Val->replaceAllUsesWith(GA);
692 Val->eraseFromParent();
693 ForwardRefVals.erase(I);
696 // Insert into the module, we know its name won't collide now.
697 M->getAliasList().push_back(GA);
698 assert(GA->getName() == Name && "Should not be a name conflict!");
704 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
705 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
706 /// OptionalExternallyInitialized GlobalType Type Const
707 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
708 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
709 /// OptionalExternallyInitialized GlobalType Type Const
711 /// Everything up to and including OptionalDLLStorageClass has been parsed
714 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
715 unsigned Linkage, bool HasLinkage,
716 unsigned Visibility, unsigned DLLStorageClass) {
718 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
719 GlobalVariable::ThreadLocalMode TLM;
720 LocTy UnnamedAddrLoc;
721 LocTy IsExternallyInitializedLoc;
725 if (ParseOptionalThreadLocal(TLM) ||
726 ParseOptionalAddrSpace(AddrSpace) ||
727 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
729 ParseOptionalToken(lltok::kw_externally_initialized,
730 IsExternallyInitialized,
731 &IsExternallyInitializedLoc) ||
732 ParseGlobalType(IsConstant) ||
733 ParseType(Ty, TyLoc))
736 // If the linkage is specified and is external, then no initializer is
738 Constant *Init = nullptr;
739 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
740 Linkage != GlobalValue::ExternalLinkage)) {
741 if (ParseGlobalValue(Ty, Init))
745 if (Ty->isFunctionTy() || Ty->isLabelTy())
746 return Error(TyLoc, "invalid type for global variable");
748 GlobalVariable *GV = nullptr;
750 // See if the global was forward referenced, if so, use the global.
752 if (GlobalValue *GVal = M->getNamedValue(Name)) {
753 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
754 return Error(NameLoc, "redefinition of global '@" + Name + "'");
755 GV = cast<GlobalVariable>(GVal);
758 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
759 I = ForwardRefValIDs.find(NumberedVals.size());
760 if (I != ForwardRefValIDs.end()) {
761 GV = cast<GlobalVariable>(I->second.first);
762 ForwardRefValIDs.erase(I);
767 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
768 Name, nullptr, GlobalVariable::NotThreadLocal,
771 if (GV->getType()->getElementType() != Ty)
773 "forward reference and definition of global have different types");
775 // Move the forward-reference to the correct spot in the module.
776 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
780 NumberedVals.push_back(GV);
782 // Set the parsed properties on the global.
784 GV->setInitializer(Init);
785 GV->setConstant(IsConstant);
786 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
787 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
788 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
789 GV->setExternallyInitialized(IsExternallyInitialized);
790 GV->setThreadLocalMode(TLM);
791 GV->setUnnamedAddr(UnnamedAddr);
793 // Parse attributes on the global.
794 while (Lex.getKind() == lltok::comma) {
797 if (Lex.getKind() == lltok::kw_section) {
799 GV->setSection(Lex.getStrVal());
800 if (ParseToken(lltok::StringConstant, "expected global section string"))
802 } else if (Lex.getKind() == lltok::kw_align) {
804 if (ParseOptionalAlignment(Alignment)) return true;
805 GV->setAlignment(Alignment);
807 TokError("unknown global variable property!");
814 /// ParseUnnamedAttrGrp
815 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
816 bool LLParser::ParseUnnamedAttrGrp() {
817 assert(Lex.getKind() == lltok::kw_attributes);
818 LocTy AttrGrpLoc = Lex.getLoc();
821 assert(Lex.getKind() == lltok::AttrGrpID);
822 unsigned VarID = Lex.getUIntVal();
823 std::vector<unsigned> unused;
827 if (ParseToken(lltok::equal, "expected '=' here") ||
828 ParseToken(lltok::lbrace, "expected '{' here") ||
829 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
831 ParseToken(lltok::rbrace, "expected end of attribute group"))
834 if (!NumberedAttrBuilders[VarID].hasAttributes())
835 return Error(AttrGrpLoc, "attribute group has no attributes");
840 /// ParseFnAttributeValuePairs
841 /// ::= <attr> | <attr> '=' <value>
842 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
843 std::vector<unsigned> &FwdRefAttrGrps,
844 bool inAttrGrp, LocTy &BuiltinLoc) {
845 bool HaveError = false;
850 lltok::Kind Token = Lex.getKind();
851 if (Token == lltok::kw_builtin)
852 BuiltinLoc = Lex.getLoc();
855 if (!inAttrGrp) return HaveError;
856 return Error(Lex.getLoc(), "unterminated attribute group");
861 case lltok::AttrGrpID: {
862 // Allow a function to reference an attribute group:
864 // define void @foo() #1 { ... }
868 "cannot have an attribute group reference in an attribute group");
870 unsigned AttrGrpNum = Lex.getUIntVal();
871 if (inAttrGrp) break;
873 // Save the reference to the attribute group. We'll fill it in later.
874 FwdRefAttrGrps.push_back(AttrGrpNum);
877 // Target-dependent attributes:
878 case lltok::StringConstant: {
879 std::string Attr = Lex.getStrVal();
882 if (EatIfPresent(lltok::equal) &&
883 ParseStringConstant(Val))
886 B.addAttribute(Attr, Val);
890 // Target-independent attributes:
891 case lltok::kw_align: {
892 // As a hack, we allow function alignment to be initially parsed as an
893 // attribute on a function declaration/definition or added to an attribute
894 // group and later moved to the alignment field.
898 if (ParseToken(lltok::equal, "expected '=' here") ||
899 ParseUInt32(Alignment))
902 if (ParseOptionalAlignment(Alignment))
905 B.addAlignmentAttr(Alignment);
908 case lltok::kw_alignstack: {
912 if (ParseToken(lltok::equal, "expected '=' here") ||
913 ParseUInt32(Alignment))
916 if (ParseOptionalStackAlignment(Alignment))
919 B.addStackAlignmentAttr(Alignment);
922 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
923 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
924 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
925 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
926 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
927 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
928 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
929 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
930 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
931 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
932 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
933 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
934 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
935 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
936 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
937 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
938 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
939 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
940 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
941 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
942 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
943 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
944 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
945 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
946 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
947 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
950 case lltok::kw_inreg:
951 case lltok::kw_signext:
952 case lltok::kw_zeroext:
955 "invalid use of attribute on a function");
957 case lltok::kw_byval:
958 case lltok::kw_inalloca:
960 case lltok::kw_noalias:
961 case lltok::kw_nocapture:
962 case lltok::kw_returned:
966 "invalid use of parameter-only attribute on a function");
974 //===----------------------------------------------------------------------===//
975 // GlobalValue Reference/Resolution Routines.
976 //===----------------------------------------------------------------------===//
978 /// GetGlobalVal - Get a value with the specified name or ID, creating a
979 /// forward reference record if needed. This can return null if the value
980 /// exists but does not have the right type.
981 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
983 PointerType *PTy = dyn_cast<PointerType>(Ty);
985 Error(Loc, "global variable reference must have pointer type");
989 // Look this name up in the normal function symbol table.
991 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
993 // If this is a forward reference for the value, see if we already created a
994 // forward ref record.
996 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
997 I = ForwardRefVals.find(Name);
998 if (I != ForwardRefVals.end())
999 Val = I->second.first;
1002 // If we have the value in the symbol table or fwd-ref table, return it.
1004 if (Val->getType() == Ty) return Val;
1005 Error(Loc, "'@" + Name + "' defined with type '" +
1006 getTypeString(Val->getType()) + "'");
1010 // Otherwise, create a new forward reference for this value and remember it.
1011 GlobalValue *FwdVal;
1012 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1013 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1015 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1016 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1017 nullptr, GlobalVariable::NotThreadLocal,
1018 PTy->getAddressSpace());
1020 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1024 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1025 PointerType *PTy = dyn_cast<PointerType>(Ty);
1027 Error(Loc, "global variable reference must have pointer type");
1031 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1033 // If this is a forward reference for the value, see if we already created a
1034 // forward ref record.
1036 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1037 I = ForwardRefValIDs.find(ID);
1038 if (I != ForwardRefValIDs.end())
1039 Val = I->second.first;
1042 // If we have the value in the symbol table or fwd-ref table, return it.
1044 if (Val->getType() == Ty) return Val;
1045 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1046 getTypeString(Val->getType()) + "'");
1050 // Otherwise, create a new forward reference for this value and remember it.
1051 GlobalValue *FwdVal;
1052 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1053 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1055 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1056 GlobalValue::ExternalWeakLinkage, nullptr, "");
1058 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1063 //===----------------------------------------------------------------------===//
1065 //===----------------------------------------------------------------------===//
1067 /// ParseToken - If the current token has the specified kind, eat it and return
1068 /// success. Otherwise, emit the specified error and return failure.
1069 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1070 if (Lex.getKind() != T)
1071 return TokError(ErrMsg);
1076 /// ParseStringConstant
1077 /// ::= StringConstant
1078 bool LLParser::ParseStringConstant(std::string &Result) {
1079 if (Lex.getKind() != lltok::StringConstant)
1080 return TokError("expected string constant");
1081 Result = Lex.getStrVal();
1088 bool LLParser::ParseUInt32(unsigned &Val) {
1089 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1090 return TokError("expected integer");
1091 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1092 if (Val64 != unsigned(Val64))
1093 return TokError("expected 32-bit integer (too large)");
1100 /// := 'localdynamic'
1101 /// := 'initialexec'
1103 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1104 switch (Lex.getKind()) {
1106 return TokError("expected localdynamic, initialexec or localexec");
1107 case lltok::kw_localdynamic:
1108 TLM = GlobalVariable::LocalDynamicTLSModel;
1110 case lltok::kw_initialexec:
1111 TLM = GlobalVariable::InitialExecTLSModel;
1113 case lltok::kw_localexec:
1114 TLM = GlobalVariable::LocalExecTLSModel;
1122 /// ParseOptionalThreadLocal
1124 /// := 'thread_local'
1125 /// := 'thread_local' '(' tlsmodel ')'
1126 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1127 TLM = GlobalVariable::NotThreadLocal;
1128 if (!EatIfPresent(lltok::kw_thread_local))
1131 TLM = GlobalVariable::GeneralDynamicTLSModel;
1132 if (Lex.getKind() == lltok::lparen) {
1134 return ParseTLSModel(TLM) ||
1135 ParseToken(lltok::rparen, "expected ')' after thread local model");
1140 /// ParseOptionalAddrSpace
1142 /// := 'addrspace' '(' uint32 ')'
1143 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1145 if (!EatIfPresent(lltok::kw_addrspace))
1147 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1148 ParseUInt32(AddrSpace) ||
1149 ParseToken(lltok::rparen, "expected ')' in address space");
1152 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1153 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1154 bool HaveError = false;
1159 lltok::Kind Token = Lex.getKind();
1161 default: // End of attributes.
1163 case lltok::kw_align: {
1165 if (ParseOptionalAlignment(Alignment))
1167 B.addAlignmentAttr(Alignment);
1170 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1171 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1172 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1173 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1174 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1175 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1176 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1177 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1178 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1179 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1180 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1181 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1183 case lltok::kw_alignstack:
1184 case lltok::kw_alwaysinline:
1185 case lltok::kw_builtin:
1186 case lltok::kw_inlinehint:
1187 case lltok::kw_minsize:
1188 case lltok::kw_naked:
1189 case lltok::kw_nobuiltin:
1190 case lltok::kw_noduplicate:
1191 case lltok::kw_noimplicitfloat:
1192 case lltok::kw_noinline:
1193 case lltok::kw_nonlazybind:
1194 case lltok::kw_noredzone:
1195 case lltok::kw_noreturn:
1196 case lltok::kw_nounwind:
1197 case lltok::kw_optnone:
1198 case lltok::kw_optsize:
1199 case lltok::kw_returns_twice:
1200 case lltok::kw_sanitize_address:
1201 case lltok::kw_sanitize_memory:
1202 case lltok::kw_sanitize_thread:
1204 case lltok::kw_sspreq:
1205 case lltok::kw_sspstrong:
1206 case lltok::kw_uwtable:
1207 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1215 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1216 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1217 bool HaveError = false;
1222 lltok::Kind Token = Lex.getKind();
1224 default: // End of attributes.
1226 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1227 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1228 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1229 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1232 case lltok::kw_align:
1233 case lltok::kw_byval:
1234 case lltok::kw_inalloca:
1235 case lltok::kw_nest:
1236 case lltok::kw_nocapture:
1237 case lltok::kw_returned:
1238 case lltok::kw_sret:
1239 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1242 case lltok::kw_alignstack:
1243 case lltok::kw_alwaysinline:
1244 case lltok::kw_builtin:
1245 case lltok::kw_cold:
1246 case lltok::kw_inlinehint:
1247 case lltok::kw_minsize:
1248 case lltok::kw_naked:
1249 case lltok::kw_nobuiltin:
1250 case lltok::kw_noduplicate:
1251 case lltok::kw_noimplicitfloat:
1252 case lltok::kw_noinline:
1253 case lltok::kw_nonlazybind:
1254 case lltok::kw_noredzone:
1255 case lltok::kw_noreturn:
1256 case lltok::kw_nounwind:
1257 case lltok::kw_optnone:
1258 case lltok::kw_optsize:
1259 case lltok::kw_returns_twice:
1260 case lltok::kw_sanitize_address:
1261 case lltok::kw_sanitize_memory:
1262 case lltok::kw_sanitize_thread:
1264 case lltok::kw_sspreq:
1265 case lltok::kw_sspstrong:
1266 case lltok::kw_uwtable:
1267 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1270 case lltok::kw_readnone:
1271 case lltok::kw_readonly:
1272 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1279 /// ParseOptionalLinkage
1286 /// ::= 'linkonce_odr'
1287 /// ::= 'available_externally'
1290 /// ::= 'extern_weak'
1293 /// Deprecated Values:
1294 /// ::= 'linker_private'
1295 /// ::= 'linker_private_weak'
1296 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1298 switch (Lex.getKind()) {
1299 default: Res=GlobalValue::ExternalLinkage; return false;
1300 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1301 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1302 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1303 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1304 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1305 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1306 case lltok::kw_available_externally:
1307 Res = GlobalValue::AvailableExternallyLinkage;
1309 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1310 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1311 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1312 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1314 case lltok::kw_linker_private:
1315 case lltok::kw_linker_private_weak:
1316 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1319 // treat linker_private and linker_private_weak as PrivateLinkage
1320 Res = GlobalValue::PrivateLinkage;
1328 /// ParseOptionalVisibility
1334 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1335 switch (Lex.getKind()) {
1336 default: Res = GlobalValue::DefaultVisibility; return false;
1337 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1338 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1339 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1345 /// ParseOptionalDLLStorageClass
1350 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1351 switch (Lex.getKind()) {
1352 default: Res = GlobalValue::DefaultStorageClass; return false;
1353 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1354 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1360 /// ParseOptionalCallingConv
1364 /// ::= 'kw_intel_ocl_bicc'
1366 /// ::= 'x86_stdcallcc'
1367 /// ::= 'x86_fastcallcc'
1368 /// ::= 'x86_thiscallcc'
1369 /// ::= 'x86_cdeclmethodcc'
1370 /// ::= 'arm_apcscc'
1371 /// ::= 'arm_aapcscc'
1372 /// ::= 'arm_aapcs_vfpcc'
1373 /// ::= 'msp430_intrcc'
1374 /// ::= 'ptx_kernel'
1375 /// ::= 'ptx_device'
1377 /// ::= 'spir_kernel'
1378 /// ::= 'x86_64_sysvcc'
1379 /// ::= 'x86_64_win64cc'
1380 /// ::= 'webkit_jscc'
1382 /// ::= 'preserve_mostcc'
1383 /// ::= 'preserve_allcc'
1386 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1387 switch (Lex.getKind()) {
1388 default: CC = CallingConv::C; return false;
1389 case lltok::kw_ccc: CC = CallingConv::C; break;
1390 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1391 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1392 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1393 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1394 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1395 case lltok::kw_x86_cdeclmethodcc:CC = CallingConv::X86_CDeclMethod; break;
1396 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1397 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1398 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1399 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1400 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1401 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1402 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1403 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1404 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1405 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1406 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1407 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1408 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1409 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1410 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1411 case lltok::kw_cc: {
1412 unsigned ArbitraryCC;
1414 if (ParseUInt32(ArbitraryCC))
1416 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1425 /// ParseInstructionMetadata
1426 /// ::= !dbg !42 (',' !dbg !57)*
1427 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1428 PerFunctionState *PFS) {
1430 if (Lex.getKind() != lltok::MetadataVar)
1431 return TokError("expected metadata after comma");
1433 std::string Name = Lex.getStrVal();
1434 unsigned MDK = M->getMDKindID(Name);
1438 SMLoc Loc = Lex.getLoc();
1440 if (ParseToken(lltok::exclaim, "expected '!' here"))
1443 // This code is similar to that of ParseMetadataValue, however it needs to
1444 // have special-case code for a forward reference; see the comments on
1445 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1446 // at the top level here.
1447 if (Lex.getKind() == lltok::lbrace) {
1449 if (ParseMetadataListValue(ID, PFS))
1451 assert(ID.Kind == ValID::t_MDNode);
1452 Inst->setMetadata(MDK, ID.MDNodeVal);
1454 unsigned NodeID = 0;
1455 if (ParseMDNodeID(Node, NodeID))
1458 // If we got the node, add it to the instruction.
1459 Inst->setMetadata(MDK, Node);
1461 MDRef R = { Loc, MDK, NodeID };
1462 // Otherwise, remember that this should be resolved later.
1463 ForwardRefInstMetadata[Inst].push_back(R);
1467 if (MDK == LLVMContext::MD_tbaa)
1468 InstsWithTBAATag.push_back(Inst);
1470 // If this is the end of the list, we're done.
1471 } while (EatIfPresent(lltok::comma));
1475 /// ParseOptionalAlignment
1478 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1480 if (!EatIfPresent(lltok::kw_align))
1482 LocTy AlignLoc = Lex.getLoc();
1483 if (ParseUInt32(Alignment)) return true;
1484 if (!isPowerOf2_32(Alignment))
1485 return Error(AlignLoc, "alignment is not a power of two");
1486 if (Alignment > Value::MaximumAlignment)
1487 return Error(AlignLoc, "huge alignments are not supported yet");
1491 /// ParseOptionalCommaAlign
1495 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1497 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1498 bool &AteExtraComma) {
1499 AteExtraComma = false;
1500 while (EatIfPresent(lltok::comma)) {
1501 // Metadata at the end is an early exit.
1502 if (Lex.getKind() == lltok::MetadataVar) {
1503 AteExtraComma = true;
1507 if (Lex.getKind() != lltok::kw_align)
1508 return Error(Lex.getLoc(), "expected metadata or 'align'");
1510 if (ParseOptionalAlignment(Alignment)) return true;
1516 /// ParseScopeAndOrdering
1517 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1520 /// This sets Scope and Ordering to the parsed values.
1521 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1522 AtomicOrdering &Ordering) {
1526 Scope = CrossThread;
1527 if (EatIfPresent(lltok::kw_singlethread))
1528 Scope = SingleThread;
1530 return ParseOrdering(Ordering);
1534 /// ::= AtomicOrdering
1536 /// This sets Ordering to the parsed value.
1537 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1538 switch (Lex.getKind()) {
1539 default: return TokError("Expected ordering on atomic instruction");
1540 case lltok::kw_unordered: Ordering = Unordered; break;
1541 case lltok::kw_monotonic: Ordering = Monotonic; break;
1542 case lltok::kw_acquire: Ordering = Acquire; break;
1543 case lltok::kw_release: Ordering = Release; break;
1544 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1545 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1551 /// ParseOptionalStackAlignment
1553 /// ::= 'alignstack' '(' 4 ')'
1554 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1556 if (!EatIfPresent(lltok::kw_alignstack))
1558 LocTy ParenLoc = Lex.getLoc();
1559 if (!EatIfPresent(lltok::lparen))
1560 return Error(ParenLoc, "expected '('");
1561 LocTy AlignLoc = Lex.getLoc();
1562 if (ParseUInt32(Alignment)) return true;
1563 ParenLoc = Lex.getLoc();
1564 if (!EatIfPresent(lltok::rparen))
1565 return Error(ParenLoc, "expected ')'");
1566 if (!isPowerOf2_32(Alignment))
1567 return Error(AlignLoc, "stack alignment is not a power of two");
1571 /// ParseIndexList - This parses the index list for an insert/extractvalue
1572 /// instruction. This sets AteExtraComma in the case where we eat an extra
1573 /// comma at the end of the line and find that it is followed by metadata.
1574 /// Clients that don't allow metadata can call the version of this function that
1575 /// only takes one argument.
1578 /// ::= (',' uint32)+
1580 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1581 bool &AteExtraComma) {
1582 AteExtraComma = false;
1584 if (Lex.getKind() != lltok::comma)
1585 return TokError("expected ',' as start of index list");
1587 while (EatIfPresent(lltok::comma)) {
1588 if (Lex.getKind() == lltok::MetadataVar) {
1589 AteExtraComma = true;
1593 if (ParseUInt32(Idx)) return true;
1594 Indices.push_back(Idx);
1600 //===----------------------------------------------------------------------===//
1602 //===----------------------------------------------------------------------===//
1604 /// ParseType - Parse a type.
1605 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1606 SMLoc TypeLoc = Lex.getLoc();
1607 switch (Lex.getKind()) {
1609 return TokError("expected type");
1611 // Type ::= 'float' | 'void' (etc)
1612 Result = Lex.getTyVal();
1616 // Type ::= StructType
1617 if (ParseAnonStructType(Result, false))
1620 case lltok::lsquare:
1621 // Type ::= '[' ... ']'
1622 Lex.Lex(); // eat the lsquare.
1623 if (ParseArrayVectorType(Result, false))
1626 case lltok::less: // Either vector or packed struct.
1627 // Type ::= '<' ... '>'
1629 if (Lex.getKind() == lltok::lbrace) {
1630 if (ParseAnonStructType(Result, true) ||
1631 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1633 } else if (ParseArrayVectorType(Result, true))
1636 case lltok::LocalVar: {
1638 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1640 // If the type hasn't been defined yet, create a forward definition and
1641 // remember where that forward def'n was seen (in case it never is defined).
1643 Entry.first = StructType::create(Context, Lex.getStrVal());
1644 Entry.second = Lex.getLoc();
1646 Result = Entry.first;
1651 case lltok::LocalVarID: {
1653 if (Lex.getUIntVal() >= NumberedTypes.size())
1654 NumberedTypes.resize(Lex.getUIntVal()+1);
1655 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1657 // If the type hasn't been defined yet, create a forward definition and
1658 // remember where that forward def'n was seen (in case it never is defined).
1660 Entry.first = StructType::create(Context);
1661 Entry.second = Lex.getLoc();
1663 Result = Entry.first;
1669 // Parse the type suffixes.
1671 switch (Lex.getKind()) {
1674 if (!AllowVoid && Result->isVoidTy())
1675 return Error(TypeLoc, "void type only allowed for function results");
1678 // Type ::= Type '*'
1680 if (Result->isLabelTy())
1681 return TokError("basic block pointers are invalid");
1682 if (Result->isVoidTy())
1683 return TokError("pointers to void are invalid - use i8* instead");
1684 if (!PointerType::isValidElementType(Result))
1685 return TokError("pointer to this type is invalid");
1686 Result = PointerType::getUnqual(Result);
1690 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1691 case lltok::kw_addrspace: {
1692 if (Result->isLabelTy())
1693 return TokError("basic block pointers are invalid");
1694 if (Result->isVoidTy())
1695 return TokError("pointers to void are invalid; use i8* instead");
1696 if (!PointerType::isValidElementType(Result))
1697 return TokError("pointer to this type is invalid");
1699 if (ParseOptionalAddrSpace(AddrSpace) ||
1700 ParseToken(lltok::star, "expected '*' in address space"))
1703 Result = PointerType::get(Result, AddrSpace);
1707 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1709 if (ParseFunctionType(Result))
1716 /// ParseParameterList
1718 /// ::= '(' Arg (',' Arg)* ')'
1720 /// ::= Type OptionalAttributes Value OptionalAttributes
1721 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1722 PerFunctionState &PFS) {
1723 if (ParseToken(lltok::lparen, "expected '(' in call"))
1726 unsigned AttrIndex = 1;
1727 while (Lex.getKind() != lltok::rparen) {
1728 // If this isn't the first argument, we need a comma.
1729 if (!ArgList.empty() &&
1730 ParseToken(lltok::comma, "expected ',' in argument list"))
1733 // Parse the argument.
1735 Type *ArgTy = nullptr;
1736 AttrBuilder ArgAttrs;
1738 if (ParseType(ArgTy, ArgLoc))
1741 // Otherwise, handle normal operands.
1742 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1744 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1749 Lex.Lex(); // Lex the ')'.
1755 /// ParseArgumentList - Parse the argument list for a function type or function
1757 /// ::= '(' ArgTypeListI ')'
1761 /// ::= ArgTypeList ',' '...'
1762 /// ::= ArgType (',' ArgType)*
1764 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1767 assert(Lex.getKind() == lltok::lparen);
1768 Lex.Lex(); // eat the (.
1770 if (Lex.getKind() == lltok::rparen) {
1772 } else if (Lex.getKind() == lltok::dotdotdot) {
1776 LocTy TypeLoc = Lex.getLoc();
1777 Type *ArgTy = nullptr;
1781 if (ParseType(ArgTy) ||
1782 ParseOptionalParamAttrs(Attrs)) return true;
1784 if (ArgTy->isVoidTy())
1785 return Error(TypeLoc, "argument can not have void type");
1787 if (Lex.getKind() == lltok::LocalVar) {
1788 Name = Lex.getStrVal();
1792 if (!FunctionType::isValidArgumentType(ArgTy))
1793 return Error(TypeLoc, "invalid type for function argument");
1795 unsigned AttrIndex = 1;
1796 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1797 AttributeSet::get(ArgTy->getContext(),
1798 AttrIndex++, Attrs), Name));
1800 while (EatIfPresent(lltok::comma)) {
1801 // Handle ... at end of arg list.
1802 if (EatIfPresent(lltok::dotdotdot)) {
1807 // Otherwise must be an argument type.
1808 TypeLoc = Lex.getLoc();
1809 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1811 if (ArgTy->isVoidTy())
1812 return Error(TypeLoc, "argument can not have void type");
1814 if (Lex.getKind() == lltok::LocalVar) {
1815 Name = Lex.getStrVal();
1821 if (!ArgTy->isFirstClassType())
1822 return Error(TypeLoc, "invalid type for function argument");
1824 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1825 AttributeSet::get(ArgTy->getContext(),
1826 AttrIndex++, Attrs),
1831 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1834 /// ParseFunctionType
1835 /// ::= Type ArgumentList OptionalAttrs
1836 bool LLParser::ParseFunctionType(Type *&Result) {
1837 assert(Lex.getKind() == lltok::lparen);
1839 if (!FunctionType::isValidReturnType(Result))
1840 return TokError("invalid function return type");
1842 SmallVector<ArgInfo, 8> ArgList;
1844 if (ParseArgumentList(ArgList, isVarArg))
1847 // Reject names on the arguments lists.
1848 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1849 if (!ArgList[i].Name.empty())
1850 return Error(ArgList[i].Loc, "argument name invalid in function type");
1851 if (ArgList[i].Attrs.hasAttributes(i + 1))
1852 return Error(ArgList[i].Loc,
1853 "argument attributes invalid in function type");
1856 SmallVector<Type*, 16> ArgListTy;
1857 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1858 ArgListTy.push_back(ArgList[i].Ty);
1860 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1864 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1866 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1867 SmallVector<Type*, 8> Elts;
1868 if (ParseStructBody(Elts)) return true;
1870 Result = StructType::get(Context, Elts, Packed);
1874 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1875 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1876 std::pair<Type*, LocTy> &Entry,
1878 // If the type was already defined, diagnose the redefinition.
1879 if (Entry.first && !Entry.second.isValid())
1880 return Error(TypeLoc, "redefinition of type");
1882 // If we have opaque, just return without filling in the definition for the
1883 // struct. This counts as a definition as far as the .ll file goes.
1884 if (EatIfPresent(lltok::kw_opaque)) {
1885 // This type is being defined, so clear the location to indicate this.
1886 Entry.second = SMLoc();
1888 // If this type number has never been uttered, create it.
1890 Entry.first = StructType::create(Context, Name);
1891 ResultTy = Entry.first;
1895 // If the type starts with '<', then it is either a packed struct or a vector.
1896 bool isPacked = EatIfPresent(lltok::less);
1898 // If we don't have a struct, then we have a random type alias, which we
1899 // accept for compatibility with old files. These types are not allowed to be
1900 // forward referenced and not allowed to be recursive.
1901 if (Lex.getKind() != lltok::lbrace) {
1903 return Error(TypeLoc, "forward references to non-struct type");
1907 return ParseArrayVectorType(ResultTy, true);
1908 return ParseType(ResultTy);
1911 // This type is being defined, so clear the location to indicate this.
1912 Entry.second = SMLoc();
1914 // If this type number has never been uttered, create it.
1916 Entry.first = StructType::create(Context, Name);
1918 StructType *STy = cast<StructType>(Entry.first);
1920 SmallVector<Type*, 8> Body;
1921 if (ParseStructBody(Body) ||
1922 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1925 STy->setBody(Body, isPacked);
1931 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1934 /// ::= '{' Type (',' Type)* '}'
1935 /// ::= '<' '{' '}' '>'
1936 /// ::= '<' '{' Type (',' Type)* '}' '>'
1937 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1938 assert(Lex.getKind() == lltok::lbrace);
1939 Lex.Lex(); // Consume the '{'
1941 // Handle the empty struct.
1942 if (EatIfPresent(lltok::rbrace))
1945 LocTy EltTyLoc = Lex.getLoc();
1947 if (ParseType(Ty)) return true;
1950 if (!StructType::isValidElementType(Ty))
1951 return Error(EltTyLoc, "invalid element type for struct");
1953 while (EatIfPresent(lltok::comma)) {
1954 EltTyLoc = Lex.getLoc();
1955 if (ParseType(Ty)) return true;
1957 if (!StructType::isValidElementType(Ty))
1958 return Error(EltTyLoc, "invalid element type for struct");
1963 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1966 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1967 /// token has already been consumed.
1969 /// ::= '[' APSINTVAL 'x' Types ']'
1970 /// ::= '<' APSINTVAL 'x' Types '>'
1971 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1972 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1973 Lex.getAPSIntVal().getBitWidth() > 64)
1974 return TokError("expected number in address space");
1976 LocTy SizeLoc = Lex.getLoc();
1977 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1980 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1983 LocTy TypeLoc = Lex.getLoc();
1984 Type *EltTy = nullptr;
1985 if (ParseType(EltTy)) return true;
1987 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
1988 "expected end of sequential type"))
1993 return Error(SizeLoc, "zero element vector is illegal");
1994 if ((unsigned)Size != Size)
1995 return Error(SizeLoc, "size too large for vector");
1996 if (!VectorType::isValidElementType(EltTy))
1997 return Error(TypeLoc, "invalid vector element type");
1998 Result = VectorType::get(EltTy, unsigned(Size));
2000 if (!ArrayType::isValidElementType(EltTy))
2001 return Error(TypeLoc, "invalid array element type");
2002 Result = ArrayType::get(EltTy, Size);
2007 //===----------------------------------------------------------------------===//
2008 // Function Semantic Analysis.
2009 //===----------------------------------------------------------------------===//
2011 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2013 : P(p), F(f), FunctionNumber(functionNumber) {
2015 // Insert unnamed arguments into the NumberedVals list.
2016 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2019 NumberedVals.push_back(AI);
2022 LLParser::PerFunctionState::~PerFunctionState() {
2023 // If there were any forward referenced non-basicblock values, delete them.
2024 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2025 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2026 if (!isa<BasicBlock>(I->second.first)) {
2027 I->second.first->replaceAllUsesWith(
2028 UndefValue::get(I->second.first->getType()));
2029 delete I->second.first;
2030 I->second.first = nullptr;
2033 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2034 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2035 if (!isa<BasicBlock>(I->second.first)) {
2036 I->second.first->replaceAllUsesWith(
2037 UndefValue::get(I->second.first->getType()));
2038 delete I->second.first;
2039 I->second.first = nullptr;
2043 bool LLParser::PerFunctionState::FinishFunction() {
2044 // Check to see if someone took the address of labels in this block.
2045 if (!P.ForwardRefBlockAddresses.empty()) {
2047 if (!F.getName().empty()) {
2048 FunctionID.Kind = ValID::t_GlobalName;
2049 FunctionID.StrVal = F.getName();
2051 FunctionID.Kind = ValID::t_GlobalID;
2052 FunctionID.UIntVal = FunctionNumber;
2055 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2056 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2057 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2058 // Resolve all these references.
2059 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2062 P.ForwardRefBlockAddresses.erase(FRBAI);
2066 if (!ForwardRefVals.empty())
2067 return P.Error(ForwardRefVals.begin()->second.second,
2068 "use of undefined value '%" + ForwardRefVals.begin()->first +
2070 if (!ForwardRefValIDs.empty())
2071 return P.Error(ForwardRefValIDs.begin()->second.second,
2072 "use of undefined value '%" +
2073 Twine(ForwardRefValIDs.begin()->first) + "'");
2078 /// GetVal - Get a value with the specified name or ID, creating a
2079 /// forward reference record if needed. This can return null if the value
2080 /// exists but does not have the right type.
2081 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2082 Type *Ty, LocTy Loc) {
2083 // Look this name up in the normal function symbol table.
2084 Value *Val = F.getValueSymbolTable().lookup(Name);
2086 // If this is a forward reference for the value, see if we already created a
2087 // forward ref record.
2089 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2090 I = ForwardRefVals.find(Name);
2091 if (I != ForwardRefVals.end())
2092 Val = I->second.first;
2095 // If we have the value in the symbol table or fwd-ref table, return it.
2097 if (Val->getType() == Ty) return Val;
2098 if (Ty->isLabelTy())
2099 P.Error(Loc, "'%" + Name + "' is not a basic block");
2101 P.Error(Loc, "'%" + Name + "' defined with type '" +
2102 getTypeString(Val->getType()) + "'");
2106 // Don't make placeholders with invalid type.
2107 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2108 P.Error(Loc, "invalid use of a non-first-class type");
2112 // Otherwise, create a new forward reference for this value and remember it.
2114 if (Ty->isLabelTy())
2115 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2117 FwdVal = new Argument(Ty, Name);
2119 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2123 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2125 // Look this name up in the normal function symbol table.
2126 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2128 // If this is a forward reference for the value, see if we already created a
2129 // forward ref record.
2131 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2132 I = ForwardRefValIDs.find(ID);
2133 if (I != ForwardRefValIDs.end())
2134 Val = I->second.first;
2137 // If we have the value in the symbol table or fwd-ref table, return it.
2139 if (Val->getType() == Ty) return Val;
2140 if (Ty->isLabelTy())
2141 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2143 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2144 getTypeString(Val->getType()) + "'");
2148 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2149 P.Error(Loc, "invalid use of a non-first-class type");
2153 // Otherwise, create a new forward reference for this value and remember it.
2155 if (Ty->isLabelTy())
2156 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2158 FwdVal = new Argument(Ty);
2160 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2164 /// SetInstName - After an instruction is parsed and inserted into its
2165 /// basic block, this installs its name.
2166 bool LLParser::PerFunctionState::SetInstName(int NameID,
2167 const std::string &NameStr,
2168 LocTy NameLoc, Instruction *Inst) {
2169 // If this instruction has void type, it cannot have a name or ID specified.
2170 if (Inst->getType()->isVoidTy()) {
2171 if (NameID != -1 || !NameStr.empty())
2172 return P.Error(NameLoc, "instructions returning void cannot have a name");
2176 // If this was a numbered instruction, verify that the instruction is the
2177 // expected value and resolve any forward references.
2178 if (NameStr.empty()) {
2179 // If neither a name nor an ID was specified, just use the next ID.
2181 NameID = NumberedVals.size();
2183 if (unsigned(NameID) != NumberedVals.size())
2184 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2185 Twine(NumberedVals.size()) + "'");
2187 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2188 ForwardRefValIDs.find(NameID);
2189 if (FI != ForwardRefValIDs.end()) {
2190 if (FI->second.first->getType() != Inst->getType())
2191 return P.Error(NameLoc, "instruction forward referenced with type '" +
2192 getTypeString(FI->second.first->getType()) + "'");
2193 FI->second.first->replaceAllUsesWith(Inst);
2194 delete FI->second.first;
2195 ForwardRefValIDs.erase(FI);
2198 NumberedVals.push_back(Inst);
2202 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2203 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2204 FI = ForwardRefVals.find(NameStr);
2205 if (FI != ForwardRefVals.end()) {
2206 if (FI->second.first->getType() != Inst->getType())
2207 return P.Error(NameLoc, "instruction forward referenced with type '" +
2208 getTypeString(FI->second.first->getType()) + "'");
2209 FI->second.first->replaceAllUsesWith(Inst);
2210 delete FI->second.first;
2211 ForwardRefVals.erase(FI);
2214 // Set the name on the instruction.
2215 Inst->setName(NameStr);
2217 if (Inst->getName() != NameStr)
2218 return P.Error(NameLoc, "multiple definition of local value named '" +
2223 /// GetBB - Get a basic block with the specified name or ID, creating a
2224 /// forward reference record if needed.
2225 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2227 return cast_or_null<BasicBlock>(GetVal(Name,
2228 Type::getLabelTy(F.getContext()), Loc));
2231 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2232 return cast_or_null<BasicBlock>(GetVal(ID,
2233 Type::getLabelTy(F.getContext()), Loc));
2236 /// DefineBB - Define the specified basic block, which is either named or
2237 /// unnamed. If there is an error, this returns null otherwise it returns
2238 /// the block being defined.
2239 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2243 BB = GetBB(NumberedVals.size(), Loc);
2245 BB = GetBB(Name, Loc);
2246 if (!BB) return nullptr; // Already diagnosed error.
2248 // Move the block to the end of the function. Forward ref'd blocks are
2249 // inserted wherever they happen to be referenced.
2250 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2252 // Remove the block from forward ref sets.
2254 ForwardRefValIDs.erase(NumberedVals.size());
2255 NumberedVals.push_back(BB);
2257 // BB forward references are already in the function symbol table.
2258 ForwardRefVals.erase(Name);
2264 //===----------------------------------------------------------------------===//
2266 //===----------------------------------------------------------------------===//
2268 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2269 /// type implied. For example, if we parse "4" we don't know what integer type
2270 /// it has. The value will later be combined with its type and checked for
2271 /// sanity. PFS is used to convert function-local operands of metadata (since
2272 /// metadata operands are not just parsed here but also converted to values).
2273 /// PFS can be null when we are not parsing metadata values inside a function.
2274 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2275 ID.Loc = Lex.getLoc();
2276 switch (Lex.getKind()) {
2277 default: return TokError("expected value token");
2278 case lltok::GlobalID: // @42
2279 ID.UIntVal = Lex.getUIntVal();
2280 ID.Kind = ValID::t_GlobalID;
2282 case lltok::GlobalVar: // @foo
2283 ID.StrVal = Lex.getStrVal();
2284 ID.Kind = ValID::t_GlobalName;
2286 case lltok::LocalVarID: // %42
2287 ID.UIntVal = Lex.getUIntVal();
2288 ID.Kind = ValID::t_LocalID;
2290 case lltok::LocalVar: // %foo
2291 ID.StrVal = Lex.getStrVal();
2292 ID.Kind = ValID::t_LocalName;
2294 case lltok::exclaim: // !42, !{...}, or !"foo"
2295 return ParseMetadataValue(ID, PFS);
2297 ID.APSIntVal = Lex.getAPSIntVal();
2298 ID.Kind = ValID::t_APSInt;
2300 case lltok::APFloat:
2301 ID.APFloatVal = Lex.getAPFloatVal();
2302 ID.Kind = ValID::t_APFloat;
2304 case lltok::kw_true:
2305 ID.ConstantVal = ConstantInt::getTrue(Context);
2306 ID.Kind = ValID::t_Constant;
2308 case lltok::kw_false:
2309 ID.ConstantVal = ConstantInt::getFalse(Context);
2310 ID.Kind = ValID::t_Constant;
2312 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2313 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2314 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2316 case lltok::lbrace: {
2317 // ValID ::= '{' ConstVector '}'
2319 SmallVector<Constant*, 16> Elts;
2320 if (ParseGlobalValueVector(Elts) ||
2321 ParseToken(lltok::rbrace, "expected end of struct constant"))
2324 ID.ConstantStructElts = new Constant*[Elts.size()];
2325 ID.UIntVal = Elts.size();
2326 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2327 ID.Kind = ValID::t_ConstantStruct;
2331 // ValID ::= '<' ConstVector '>' --> Vector.
2332 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2334 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2336 SmallVector<Constant*, 16> Elts;
2337 LocTy FirstEltLoc = Lex.getLoc();
2338 if (ParseGlobalValueVector(Elts) ||
2340 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2341 ParseToken(lltok::greater, "expected end of constant"))
2344 if (isPackedStruct) {
2345 ID.ConstantStructElts = new Constant*[Elts.size()];
2346 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2347 ID.UIntVal = Elts.size();
2348 ID.Kind = ValID::t_PackedConstantStruct;
2353 return Error(ID.Loc, "constant vector must not be empty");
2355 if (!Elts[0]->getType()->isIntegerTy() &&
2356 !Elts[0]->getType()->isFloatingPointTy() &&
2357 !Elts[0]->getType()->isPointerTy())
2358 return Error(FirstEltLoc,
2359 "vector elements must have integer, pointer or floating point type");
2361 // Verify that all the vector elements have the same type.
2362 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2363 if (Elts[i]->getType() != Elts[0]->getType())
2364 return Error(FirstEltLoc,
2365 "vector element #" + Twine(i) +
2366 " is not of type '" + getTypeString(Elts[0]->getType()));
2368 ID.ConstantVal = ConstantVector::get(Elts);
2369 ID.Kind = ValID::t_Constant;
2372 case lltok::lsquare: { // Array Constant
2374 SmallVector<Constant*, 16> Elts;
2375 LocTy FirstEltLoc = Lex.getLoc();
2376 if (ParseGlobalValueVector(Elts) ||
2377 ParseToken(lltok::rsquare, "expected end of array constant"))
2380 // Handle empty element.
2382 // Use undef instead of an array because it's inconvenient to determine
2383 // the element type at this point, there being no elements to examine.
2384 ID.Kind = ValID::t_EmptyArray;
2388 if (!Elts[0]->getType()->isFirstClassType())
2389 return Error(FirstEltLoc, "invalid array element type: " +
2390 getTypeString(Elts[0]->getType()));
2392 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2394 // Verify all elements are correct type!
2395 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2396 if (Elts[i]->getType() != Elts[0]->getType())
2397 return Error(FirstEltLoc,
2398 "array element #" + Twine(i) +
2399 " is not of type '" + getTypeString(Elts[0]->getType()));
2402 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2403 ID.Kind = ValID::t_Constant;
2406 case lltok::kw_c: // c "foo"
2408 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2410 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2411 ID.Kind = ValID::t_Constant;
2414 case lltok::kw_asm: {
2415 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2417 bool HasSideEffect, AlignStack, AsmDialect;
2419 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2420 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2421 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2422 ParseStringConstant(ID.StrVal) ||
2423 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2424 ParseToken(lltok::StringConstant, "expected constraint string"))
2426 ID.StrVal2 = Lex.getStrVal();
2427 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2428 (unsigned(AsmDialect)<<2);
2429 ID.Kind = ValID::t_InlineAsm;
2433 case lltok::kw_blockaddress: {
2434 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2439 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2441 ParseToken(lltok::comma, "expected comma in block address expression")||
2442 ParseValID(Label) ||
2443 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2446 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2447 return Error(Fn.Loc, "expected function name in blockaddress");
2448 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2449 return Error(Label.Loc, "expected basic block name in blockaddress");
2451 // Make a global variable as a placeholder for this reference.
2452 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2453 false, GlobalValue::InternalLinkage,
2455 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2456 ID.ConstantVal = FwdRef;
2457 ID.Kind = ValID::t_Constant;
2461 case lltok::kw_trunc:
2462 case lltok::kw_zext:
2463 case lltok::kw_sext:
2464 case lltok::kw_fptrunc:
2465 case lltok::kw_fpext:
2466 case lltok::kw_bitcast:
2467 case lltok::kw_addrspacecast:
2468 case lltok::kw_uitofp:
2469 case lltok::kw_sitofp:
2470 case lltok::kw_fptoui:
2471 case lltok::kw_fptosi:
2472 case lltok::kw_inttoptr:
2473 case lltok::kw_ptrtoint: {
2474 unsigned Opc = Lex.getUIntVal();
2475 Type *DestTy = nullptr;
2478 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2479 ParseGlobalTypeAndValue(SrcVal) ||
2480 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2481 ParseType(DestTy) ||
2482 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2484 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2485 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2486 getTypeString(SrcVal->getType()) + "' to '" +
2487 getTypeString(DestTy) + "'");
2488 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2490 ID.Kind = ValID::t_Constant;
2493 case lltok::kw_extractvalue: {
2496 SmallVector<unsigned, 4> Indices;
2497 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2498 ParseGlobalTypeAndValue(Val) ||
2499 ParseIndexList(Indices) ||
2500 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2503 if (!Val->getType()->isAggregateType())
2504 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2505 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2506 return Error(ID.Loc, "invalid indices for extractvalue");
2507 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2508 ID.Kind = ValID::t_Constant;
2511 case lltok::kw_insertvalue: {
2513 Constant *Val0, *Val1;
2514 SmallVector<unsigned, 4> Indices;
2515 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2516 ParseGlobalTypeAndValue(Val0) ||
2517 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2518 ParseGlobalTypeAndValue(Val1) ||
2519 ParseIndexList(Indices) ||
2520 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2522 if (!Val0->getType()->isAggregateType())
2523 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2524 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2525 return Error(ID.Loc, "invalid indices for insertvalue");
2526 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2527 ID.Kind = ValID::t_Constant;
2530 case lltok::kw_icmp:
2531 case lltok::kw_fcmp: {
2532 unsigned PredVal, Opc = Lex.getUIntVal();
2533 Constant *Val0, *Val1;
2535 if (ParseCmpPredicate(PredVal, Opc) ||
2536 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2537 ParseGlobalTypeAndValue(Val0) ||
2538 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2539 ParseGlobalTypeAndValue(Val1) ||
2540 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2543 if (Val0->getType() != Val1->getType())
2544 return Error(ID.Loc, "compare operands must have the same type");
2546 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2548 if (Opc == Instruction::FCmp) {
2549 if (!Val0->getType()->isFPOrFPVectorTy())
2550 return Error(ID.Loc, "fcmp requires floating point operands");
2551 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2553 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2554 if (!Val0->getType()->isIntOrIntVectorTy() &&
2555 !Val0->getType()->getScalarType()->isPointerTy())
2556 return Error(ID.Loc, "icmp requires pointer or integer operands");
2557 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2559 ID.Kind = ValID::t_Constant;
2563 // Binary Operators.
2565 case lltok::kw_fadd:
2567 case lltok::kw_fsub:
2569 case lltok::kw_fmul:
2570 case lltok::kw_udiv:
2571 case lltok::kw_sdiv:
2572 case lltok::kw_fdiv:
2573 case lltok::kw_urem:
2574 case lltok::kw_srem:
2575 case lltok::kw_frem:
2577 case lltok::kw_lshr:
2578 case lltok::kw_ashr: {
2582 unsigned Opc = Lex.getUIntVal();
2583 Constant *Val0, *Val1;
2585 LocTy ModifierLoc = Lex.getLoc();
2586 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2587 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2588 if (EatIfPresent(lltok::kw_nuw))
2590 if (EatIfPresent(lltok::kw_nsw)) {
2592 if (EatIfPresent(lltok::kw_nuw))
2595 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2596 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2597 if (EatIfPresent(lltok::kw_exact))
2600 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2601 ParseGlobalTypeAndValue(Val0) ||
2602 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2603 ParseGlobalTypeAndValue(Val1) ||
2604 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2606 if (Val0->getType() != Val1->getType())
2607 return Error(ID.Loc, "operands of constexpr must have same type");
2608 if (!Val0->getType()->isIntOrIntVectorTy()) {
2610 return Error(ModifierLoc, "nuw only applies to integer operations");
2612 return Error(ModifierLoc, "nsw only applies to integer operations");
2614 // Check that the type is valid for the operator.
2616 case Instruction::Add:
2617 case Instruction::Sub:
2618 case Instruction::Mul:
2619 case Instruction::UDiv:
2620 case Instruction::SDiv:
2621 case Instruction::URem:
2622 case Instruction::SRem:
2623 case Instruction::Shl:
2624 case Instruction::AShr:
2625 case Instruction::LShr:
2626 if (!Val0->getType()->isIntOrIntVectorTy())
2627 return Error(ID.Loc, "constexpr requires integer operands");
2629 case Instruction::FAdd:
2630 case Instruction::FSub:
2631 case Instruction::FMul:
2632 case Instruction::FDiv:
2633 case Instruction::FRem:
2634 if (!Val0->getType()->isFPOrFPVectorTy())
2635 return Error(ID.Loc, "constexpr requires fp operands");
2637 default: llvm_unreachable("Unknown binary operator!");
2640 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2641 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2642 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2643 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2645 ID.Kind = ValID::t_Constant;
2649 // Logical Operations
2652 case lltok::kw_xor: {
2653 unsigned Opc = Lex.getUIntVal();
2654 Constant *Val0, *Val1;
2656 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2657 ParseGlobalTypeAndValue(Val0) ||
2658 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2659 ParseGlobalTypeAndValue(Val1) ||
2660 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2662 if (Val0->getType() != Val1->getType())
2663 return Error(ID.Loc, "operands of constexpr must have same type");
2664 if (!Val0->getType()->isIntOrIntVectorTy())
2665 return Error(ID.Loc,
2666 "constexpr requires integer or integer vector operands");
2667 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2668 ID.Kind = ValID::t_Constant;
2672 case lltok::kw_getelementptr:
2673 case lltok::kw_shufflevector:
2674 case lltok::kw_insertelement:
2675 case lltok::kw_extractelement:
2676 case lltok::kw_select: {
2677 unsigned Opc = Lex.getUIntVal();
2678 SmallVector<Constant*, 16> Elts;
2679 bool InBounds = false;
2681 if (Opc == Instruction::GetElementPtr)
2682 InBounds = EatIfPresent(lltok::kw_inbounds);
2683 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2684 ParseGlobalValueVector(Elts) ||
2685 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2688 if (Opc == Instruction::GetElementPtr) {
2689 if (Elts.size() == 0 ||
2690 !Elts[0]->getType()->getScalarType()->isPointerTy())
2691 return Error(ID.Loc, "getelementptr requires pointer operand");
2693 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2694 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2695 return Error(ID.Loc, "invalid indices for getelementptr");
2696 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2698 } else if (Opc == Instruction::Select) {
2699 if (Elts.size() != 3)
2700 return Error(ID.Loc, "expected three operands to select");
2701 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2703 return Error(ID.Loc, Reason);
2704 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2705 } else if (Opc == Instruction::ShuffleVector) {
2706 if (Elts.size() != 3)
2707 return Error(ID.Loc, "expected three operands to shufflevector");
2708 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2709 return Error(ID.Loc, "invalid operands to shufflevector");
2711 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2712 } else if (Opc == Instruction::ExtractElement) {
2713 if (Elts.size() != 2)
2714 return Error(ID.Loc, "expected two operands to extractelement");
2715 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2716 return Error(ID.Loc, "invalid extractelement operands");
2717 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2719 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2720 if (Elts.size() != 3)
2721 return Error(ID.Loc, "expected three operands to insertelement");
2722 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2723 return Error(ID.Loc, "invalid insertelement operands");
2725 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2728 ID.Kind = ValID::t_Constant;
2737 /// ParseGlobalValue - Parse a global value with the specified type.
2738 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2742 bool Parsed = ParseValID(ID) ||
2743 ConvertValIDToValue(Ty, ID, V, nullptr);
2744 if (V && !(C = dyn_cast<Constant>(V)))
2745 return Error(ID.Loc, "global values must be constants");
2749 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2751 return ParseType(Ty) ||
2752 ParseGlobalValue(Ty, V);
2755 /// ParseGlobalValueVector
2757 /// ::= TypeAndValue (',' TypeAndValue)*
2758 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2760 if (Lex.getKind() == lltok::rbrace ||
2761 Lex.getKind() == lltok::rsquare ||
2762 Lex.getKind() == lltok::greater ||
2763 Lex.getKind() == lltok::rparen)
2767 if (ParseGlobalTypeAndValue(C)) return true;
2770 while (EatIfPresent(lltok::comma)) {
2771 if (ParseGlobalTypeAndValue(C)) return true;
2778 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2779 assert(Lex.getKind() == lltok::lbrace);
2782 SmallVector<Value*, 16> Elts;
2783 if (ParseMDNodeVector(Elts, PFS) ||
2784 ParseToken(lltok::rbrace, "expected end of metadata node"))
2787 ID.MDNodeVal = MDNode::get(Context, Elts);
2788 ID.Kind = ValID::t_MDNode;
2792 /// ParseMetadataValue
2796 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2797 assert(Lex.getKind() == lltok::exclaim);
2802 if (Lex.getKind() == lltok::lbrace)
2803 return ParseMetadataListValue(ID, PFS);
2805 // Standalone metadata reference
2807 if (Lex.getKind() == lltok::APSInt) {
2808 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2809 ID.Kind = ValID::t_MDNode;
2814 // ::= '!' STRINGCONSTANT
2815 if (ParseMDString(ID.MDStringVal)) return true;
2816 ID.Kind = ValID::t_MDString;
2821 //===----------------------------------------------------------------------===//
2822 // Function Parsing.
2823 //===----------------------------------------------------------------------===//
2825 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2826 PerFunctionState *PFS) {
2827 if (Ty->isFunctionTy())
2828 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2831 case ValID::t_LocalID:
2832 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2833 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2834 return V == nullptr;
2835 case ValID::t_LocalName:
2836 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2837 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2838 return V == nullptr;
2839 case ValID::t_InlineAsm: {
2840 PointerType *PTy = dyn_cast<PointerType>(Ty);
2842 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2843 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2844 return Error(ID.Loc, "invalid type for inline asm constraint string");
2845 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2846 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2849 case ValID::t_MDNode:
2850 if (!Ty->isMetadataTy())
2851 return Error(ID.Loc, "metadata value must have metadata type");
2854 case ValID::t_MDString:
2855 if (!Ty->isMetadataTy())
2856 return Error(ID.Loc, "metadata value must have metadata type");
2859 case ValID::t_GlobalName:
2860 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2861 return V == nullptr;
2862 case ValID::t_GlobalID:
2863 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2864 return V == nullptr;
2865 case ValID::t_APSInt:
2866 if (!Ty->isIntegerTy())
2867 return Error(ID.Loc, "integer constant must have integer type");
2868 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2869 V = ConstantInt::get(Context, ID.APSIntVal);
2871 case ValID::t_APFloat:
2872 if (!Ty->isFloatingPointTy() ||
2873 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2874 return Error(ID.Loc, "floating point constant invalid for type");
2876 // The lexer has no type info, so builds all half, float, and double FP
2877 // constants as double. Fix this here. Long double does not need this.
2878 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2881 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2883 else if (Ty->isFloatTy())
2884 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2887 V = ConstantFP::get(Context, ID.APFloatVal);
2889 if (V->getType() != Ty)
2890 return Error(ID.Loc, "floating point constant does not have type '" +
2891 getTypeString(Ty) + "'");
2895 if (!Ty->isPointerTy())
2896 return Error(ID.Loc, "null must be a pointer type");
2897 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2899 case ValID::t_Undef:
2900 // FIXME: LabelTy should not be a first-class type.
2901 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2902 return Error(ID.Loc, "invalid type for undef constant");
2903 V = UndefValue::get(Ty);
2905 case ValID::t_EmptyArray:
2906 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2907 return Error(ID.Loc, "invalid empty array initializer");
2908 V = UndefValue::get(Ty);
2911 // FIXME: LabelTy should not be a first-class type.
2912 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2913 return Error(ID.Loc, "invalid type for null constant");
2914 V = Constant::getNullValue(Ty);
2916 case ValID::t_Constant:
2917 if (ID.ConstantVal->getType() != Ty)
2918 return Error(ID.Loc, "constant expression type mismatch");
2922 case ValID::t_ConstantStruct:
2923 case ValID::t_PackedConstantStruct:
2924 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2925 if (ST->getNumElements() != ID.UIntVal)
2926 return Error(ID.Loc,
2927 "initializer with struct type has wrong # elements");
2928 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2929 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2931 // Verify that the elements are compatible with the structtype.
2932 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2933 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2934 return Error(ID.Loc, "element " + Twine(i) +
2935 " of struct initializer doesn't match struct element type");
2937 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2940 return Error(ID.Loc, "constant expression type mismatch");
2943 llvm_unreachable("Invalid ValID");
2946 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2949 return ParseValID(ID, PFS) ||
2950 ConvertValIDToValue(Ty, ID, V, PFS);
2953 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2955 return ParseType(Ty) ||
2956 ParseValue(Ty, V, PFS);
2959 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2960 PerFunctionState &PFS) {
2963 if (ParseTypeAndValue(V, PFS)) return true;
2964 if (!isa<BasicBlock>(V))
2965 return Error(Loc, "expected a basic block");
2966 BB = cast<BasicBlock>(V);
2972 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2973 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2974 /// OptionalAlign OptGC OptionalPrefix
2975 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2976 // Parse the linkage.
2977 LocTy LinkageLoc = Lex.getLoc();
2980 unsigned Visibility;
2981 unsigned DLLStorageClass;
2982 AttrBuilder RetAttrs;
2984 Type *RetType = nullptr;
2985 LocTy RetTypeLoc = Lex.getLoc();
2986 if (ParseOptionalLinkage(Linkage) ||
2987 ParseOptionalVisibility(Visibility) ||
2988 ParseOptionalDLLStorageClass(DLLStorageClass) ||
2989 ParseOptionalCallingConv(CC) ||
2990 ParseOptionalReturnAttrs(RetAttrs) ||
2991 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
2994 // Verify that the linkage is ok.
2995 switch ((GlobalValue::LinkageTypes)Linkage) {
2996 case GlobalValue::ExternalLinkage:
2997 break; // always ok.
2998 case GlobalValue::ExternalWeakLinkage:
3000 return Error(LinkageLoc, "invalid linkage for function definition");
3002 case GlobalValue::PrivateLinkage:
3003 case GlobalValue::InternalLinkage:
3004 case GlobalValue::AvailableExternallyLinkage:
3005 case GlobalValue::LinkOnceAnyLinkage:
3006 case GlobalValue::LinkOnceODRLinkage:
3007 case GlobalValue::WeakAnyLinkage:
3008 case GlobalValue::WeakODRLinkage:
3010 return Error(LinkageLoc, "invalid linkage for function declaration");
3012 case GlobalValue::AppendingLinkage:
3013 case GlobalValue::CommonLinkage:
3014 return Error(LinkageLoc, "invalid function linkage type");
3017 if (!FunctionType::isValidReturnType(RetType))
3018 return Error(RetTypeLoc, "invalid function return type");
3020 LocTy NameLoc = Lex.getLoc();
3022 std::string FunctionName;
3023 if (Lex.getKind() == lltok::GlobalVar) {
3024 FunctionName = Lex.getStrVal();
3025 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3026 unsigned NameID = Lex.getUIntVal();
3028 if (NameID != NumberedVals.size())
3029 return TokError("function expected to be numbered '%" +
3030 Twine(NumberedVals.size()) + "'");
3032 return TokError("expected function name");
3037 if (Lex.getKind() != lltok::lparen)
3038 return TokError("expected '(' in function argument list");
3040 SmallVector<ArgInfo, 8> ArgList;
3042 AttrBuilder FuncAttrs;
3043 std::vector<unsigned> FwdRefAttrGrps;
3045 std::string Section;
3049 LocTy UnnamedAddrLoc;
3050 Constant *Prefix = nullptr;
3052 if (ParseArgumentList(ArgList, isVarArg) ||
3053 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3055 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3057 (EatIfPresent(lltok::kw_section) &&
3058 ParseStringConstant(Section)) ||
3059 ParseOptionalAlignment(Alignment) ||
3060 (EatIfPresent(lltok::kw_gc) &&
3061 ParseStringConstant(GC)) ||
3062 (EatIfPresent(lltok::kw_prefix) &&
3063 ParseGlobalTypeAndValue(Prefix)))
3066 if (FuncAttrs.contains(Attribute::Builtin))
3067 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3069 // If the alignment was parsed as an attribute, move to the alignment field.
3070 if (FuncAttrs.hasAlignmentAttr()) {
3071 Alignment = FuncAttrs.getAlignment();
3072 FuncAttrs.removeAttribute(Attribute::Alignment);
3075 // Okay, if we got here, the function is syntactically valid. Convert types
3076 // and do semantic checks.
3077 std::vector<Type*> ParamTypeList;
3078 SmallVector<AttributeSet, 8> Attrs;
3080 if (RetAttrs.hasAttributes())
3081 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3082 AttributeSet::ReturnIndex,
3085 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3086 ParamTypeList.push_back(ArgList[i].Ty);
3087 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3088 AttrBuilder B(ArgList[i].Attrs, i + 1);
3089 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3093 if (FuncAttrs.hasAttributes())
3094 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3095 AttributeSet::FunctionIndex,
3098 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3100 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3101 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3104 FunctionType::get(RetType, ParamTypeList, isVarArg);
3105 PointerType *PFT = PointerType::getUnqual(FT);
3108 if (!FunctionName.empty()) {
3109 // If this was a definition of a forward reference, remove the definition
3110 // from the forward reference table and fill in the forward ref.
3111 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3112 ForwardRefVals.find(FunctionName);
3113 if (FRVI != ForwardRefVals.end()) {
3114 Fn = M->getFunction(FunctionName);
3116 return Error(FRVI->second.second, "invalid forward reference to "
3117 "function as global value!");
3118 if (Fn->getType() != PFT)
3119 return Error(FRVI->second.second, "invalid forward reference to "
3120 "function '" + FunctionName + "' with wrong type!");
3122 ForwardRefVals.erase(FRVI);
3123 } else if ((Fn = M->getFunction(FunctionName))) {
3124 // Reject redefinitions.
3125 return Error(NameLoc, "invalid redefinition of function '" +
3126 FunctionName + "'");
3127 } else if (M->getNamedValue(FunctionName)) {
3128 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3132 // If this is a definition of a forward referenced function, make sure the
3134 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3135 = ForwardRefValIDs.find(NumberedVals.size());
3136 if (I != ForwardRefValIDs.end()) {
3137 Fn = cast<Function>(I->second.first);
3138 if (Fn->getType() != PFT)
3139 return Error(NameLoc, "type of definition and forward reference of '@" +
3140 Twine(NumberedVals.size()) + "' disagree");
3141 ForwardRefValIDs.erase(I);
3146 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3147 else // Move the forward-reference to the correct spot in the module.
3148 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3150 if (FunctionName.empty())
3151 NumberedVals.push_back(Fn);
3153 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3154 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3155 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3156 Fn->setCallingConv(CC);
3157 Fn->setAttributes(PAL);
3158 Fn->setUnnamedAddr(UnnamedAddr);
3159 Fn->setAlignment(Alignment);
3160 Fn->setSection(Section);
3161 if (!GC.empty()) Fn->setGC(GC.c_str());
3162 Fn->setPrefixData(Prefix);
3163 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3165 // Add all of the arguments we parsed to the function.
3166 Function::arg_iterator ArgIt = Fn->arg_begin();
3167 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3168 // If the argument has a name, insert it into the argument symbol table.
3169 if (ArgList[i].Name.empty()) continue;
3171 // Set the name, if it conflicted, it will be auto-renamed.
3172 ArgIt->setName(ArgList[i].Name);
3174 if (ArgIt->getName() != ArgList[i].Name)
3175 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3176 ArgList[i].Name + "'");
3183 /// ParseFunctionBody
3184 /// ::= '{' BasicBlock+ '}'
3186 bool LLParser::ParseFunctionBody(Function &Fn) {
3187 if (Lex.getKind() != lltok::lbrace)
3188 return TokError("expected '{' in function body");
3189 Lex.Lex(); // eat the {.
3191 int FunctionNumber = -1;
3192 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3194 PerFunctionState PFS(*this, Fn, FunctionNumber);
3196 // We need at least one basic block.
3197 if (Lex.getKind() == lltok::rbrace)
3198 return TokError("function body requires at least one basic block");
3200 while (Lex.getKind() != lltok::rbrace)
3201 if (ParseBasicBlock(PFS)) return true;
3206 // Verify function is ok.
3207 return PFS.FinishFunction();
3211 /// ::= LabelStr? Instruction*
3212 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3213 // If this basic block starts out with a name, remember it.
3215 LocTy NameLoc = Lex.getLoc();
3216 if (Lex.getKind() == lltok::LabelStr) {
3217 Name = Lex.getStrVal();
3221 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3222 if (!BB) return true;
3224 std::string NameStr;
3226 // Parse the instructions in this block until we get a terminator.
3229 // This instruction may have three possibilities for a name: a) none
3230 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3231 LocTy NameLoc = Lex.getLoc();
3235 if (Lex.getKind() == lltok::LocalVarID) {
3236 NameID = Lex.getUIntVal();
3238 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3240 } else if (Lex.getKind() == lltok::LocalVar) {
3241 NameStr = Lex.getStrVal();
3243 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3247 switch (ParseInstruction(Inst, BB, PFS)) {
3248 default: llvm_unreachable("Unknown ParseInstruction result!");
3249 case InstError: return true;
3251 BB->getInstList().push_back(Inst);
3253 // With a normal result, we check to see if the instruction is followed by
3254 // a comma and metadata.
3255 if (EatIfPresent(lltok::comma))
3256 if (ParseInstructionMetadata(Inst, &PFS))
3259 case InstExtraComma:
3260 BB->getInstList().push_back(Inst);
3262 // If the instruction parser ate an extra comma at the end of it, it
3263 // *must* be followed by metadata.
3264 if (ParseInstructionMetadata(Inst, &PFS))
3269 // Set the name on the instruction.
3270 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3271 } while (!isa<TerminatorInst>(Inst));
3276 //===----------------------------------------------------------------------===//
3277 // Instruction Parsing.
3278 //===----------------------------------------------------------------------===//
3280 /// ParseInstruction - Parse one of the many different instructions.
3282 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3283 PerFunctionState &PFS) {
3284 lltok::Kind Token = Lex.getKind();
3285 if (Token == lltok::Eof)
3286 return TokError("found end of file when expecting more instructions");
3287 LocTy Loc = Lex.getLoc();
3288 unsigned KeywordVal = Lex.getUIntVal();
3289 Lex.Lex(); // Eat the keyword.
3292 default: return Error(Loc, "expected instruction opcode");
3293 // Terminator Instructions.
3294 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3295 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3296 case lltok::kw_br: return ParseBr(Inst, PFS);
3297 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3298 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3299 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3300 case lltok::kw_resume: return ParseResume(Inst, PFS);
3301 // Binary Operators.
3305 case lltok::kw_shl: {
3306 bool NUW = EatIfPresent(lltok::kw_nuw);
3307 bool NSW = EatIfPresent(lltok::kw_nsw);
3308 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3310 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3312 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3313 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3316 case lltok::kw_fadd:
3317 case lltok::kw_fsub:
3318 case lltok::kw_fmul:
3319 case lltok::kw_fdiv:
3320 case lltok::kw_frem: {
3321 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3322 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3326 Inst->setFastMathFlags(FMF);
3330 case lltok::kw_sdiv:
3331 case lltok::kw_udiv:
3332 case lltok::kw_lshr:
3333 case lltok::kw_ashr: {
3334 bool Exact = EatIfPresent(lltok::kw_exact);
3336 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3337 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3341 case lltok::kw_urem:
3342 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3345 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3346 case lltok::kw_icmp:
3347 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3349 case lltok::kw_trunc:
3350 case lltok::kw_zext:
3351 case lltok::kw_sext:
3352 case lltok::kw_fptrunc:
3353 case lltok::kw_fpext:
3354 case lltok::kw_bitcast:
3355 case lltok::kw_addrspacecast:
3356 case lltok::kw_uitofp:
3357 case lltok::kw_sitofp:
3358 case lltok::kw_fptoui:
3359 case lltok::kw_fptosi:
3360 case lltok::kw_inttoptr:
3361 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3363 case lltok::kw_select: return ParseSelect(Inst, PFS);
3364 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3365 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3366 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3367 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3368 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3369 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3371 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3372 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3373 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3375 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3376 case lltok::kw_load: return ParseLoad(Inst, PFS);
3377 case lltok::kw_store: return ParseStore(Inst, PFS);
3378 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3379 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3380 case lltok::kw_fence: return ParseFence(Inst, PFS);
3381 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3382 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3383 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3387 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3388 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3389 if (Opc == Instruction::FCmp) {
3390 switch (Lex.getKind()) {
3391 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3392 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3393 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3394 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3395 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3396 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3397 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3398 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3399 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3400 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3401 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3402 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3403 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3404 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3405 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3406 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3407 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3410 switch (Lex.getKind()) {
3411 default: return TokError("expected icmp predicate (e.g. 'eq')");
3412 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3413 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3414 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3415 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3416 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3417 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3418 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3419 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3420 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3421 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3428 //===----------------------------------------------------------------------===//
3429 // Terminator Instructions.
3430 //===----------------------------------------------------------------------===//
3432 /// ParseRet - Parse a return instruction.
3433 /// ::= 'ret' void (',' !dbg, !1)*
3434 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3435 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3436 PerFunctionState &PFS) {
3437 SMLoc TypeLoc = Lex.getLoc();
3439 if (ParseType(Ty, true /*void allowed*/)) return true;
3441 Type *ResType = PFS.getFunction().getReturnType();
3443 if (Ty->isVoidTy()) {
3444 if (!ResType->isVoidTy())
3445 return Error(TypeLoc, "value doesn't match function result type '" +
3446 getTypeString(ResType) + "'");
3448 Inst = ReturnInst::Create(Context);
3453 if (ParseValue(Ty, RV, PFS)) return true;
3455 if (ResType != RV->getType())
3456 return Error(TypeLoc, "value doesn't match function result type '" +
3457 getTypeString(ResType) + "'");
3459 Inst = ReturnInst::Create(Context, RV);
3465 /// ::= 'br' TypeAndValue
3466 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3467 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3470 BasicBlock *Op1, *Op2;
3471 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3473 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3474 Inst = BranchInst::Create(BB);
3478 if (Op0->getType() != Type::getInt1Ty(Context))
3479 return Error(Loc, "branch condition must have 'i1' type");
3481 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3482 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3483 ParseToken(lltok::comma, "expected ',' after true destination") ||
3484 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3487 Inst = BranchInst::Create(Op1, Op2, Op0);
3493 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3495 /// ::= (TypeAndValue ',' TypeAndValue)*
3496 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3497 LocTy CondLoc, BBLoc;
3499 BasicBlock *DefaultBB;
3500 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3501 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3502 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3503 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3506 if (!Cond->getType()->isIntegerTy())
3507 return Error(CondLoc, "switch condition must have integer type");
3509 // Parse the jump table pairs.
3510 SmallPtrSet<Value*, 32> SeenCases;
3511 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3512 while (Lex.getKind() != lltok::rsquare) {
3516 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3517 ParseToken(lltok::comma, "expected ',' after case value") ||
3518 ParseTypeAndBasicBlock(DestBB, PFS))
3521 if (!SeenCases.insert(Constant))
3522 return Error(CondLoc, "duplicate case value in switch");
3523 if (!isa<ConstantInt>(Constant))
3524 return Error(CondLoc, "case value is not a constant integer");
3526 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3529 Lex.Lex(); // Eat the ']'.
3531 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3532 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3533 SI->addCase(Table[i].first, Table[i].second);
3540 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3541 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3544 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3545 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3546 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3549 if (!Address->getType()->isPointerTy())
3550 return Error(AddrLoc, "indirectbr address must have pointer type");
3552 // Parse the destination list.
3553 SmallVector<BasicBlock*, 16> DestList;
3555 if (Lex.getKind() != lltok::rsquare) {
3557 if (ParseTypeAndBasicBlock(DestBB, PFS))
3559 DestList.push_back(DestBB);
3561 while (EatIfPresent(lltok::comma)) {
3562 if (ParseTypeAndBasicBlock(DestBB, PFS))
3564 DestList.push_back(DestBB);
3568 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3571 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3572 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3573 IBI->addDestination(DestList[i]);
3580 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3581 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3582 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3583 LocTy CallLoc = Lex.getLoc();
3584 AttrBuilder RetAttrs, FnAttrs;
3585 std::vector<unsigned> FwdRefAttrGrps;
3588 Type *RetType = nullptr;
3591 SmallVector<ParamInfo, 16> ArgList;
3593 BasicBlock *NormalBB, *UnwindBB;
3594 if (ParseOptionalCallingConv(CC) ||
3595 ParseOptionalReturnAttrs(RetAttrs) ||
3596 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3597 ParseValID(CalleeID) ||
3598 ParseParameterList(ArgList, PFS) ||
3599 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3601 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3602 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3603 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3604 ParseTypeAndBasicBlock(UnwindBB, PFS))
3607 // If RetType is a non-function pointer type, then this is the short syntax
3608 // for the call, which means that RetType is just the return type. Infer the
3609 // rest of the function argument types from the arguments that are present.
3610 PointerType *PFTy = nullptr;
3611 FunctionType *Ty = nullptr;
3612 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3613 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3614 // Pull out the types of all of the arguments...
3615 std::vector<Type*> ParamTypes;
3616 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3617 ParamTypes.push_back(ArgList[i].V->getType());
3619 if (!FunctionType::isValidReturnType(RetType))
3620 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3622 Ty = FunctionType::get(RetType, ParamTypes, false);
3623 PFTy = PointerType::getUnqual(Ty);
3626 // Look up the callee.
3628 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3630 // Set up the Attribute for the function.
3631 SmallVector<AttributeSet, 8> Attrs;
3632 if (RetAttrs.hasAttributes())
3633 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3634 AttributeSet::ReturnIndex,
3637 SmallVector<Value*, 8> Args;
3639 // Loop through FunctionType's arguments and ensure they are specified
3640 // correctly. Also, gather any parameter attributes.
3641 FunctionType::param_iterator I = Ty->param_begin();
3642 FunctionType::param_iterator E = Ty->param_end();
3643 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3644 Type *ExpectedTy = nullptr;
3647 } else if (!Ty->isVarArg()) {
3648 return Error(ArgList[i].Loc, "too many arguments specified");
3651 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3652 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3653 getTypeString(ExpectedTy) + "'");
3654 Args.push_back(ArgList[i].V);
3655 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3656 AttrBuilder B(ArgList[i].Attrs, i + 1);
3657 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3662 return Error(CallLoc, "not enough parameters specified for call");
3664 if (FnAttrs.hasAttributes())
3665 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3666 AttributeSet::FunctionIndex,
3669 // Finish off the Attribute and check them
3670 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3672 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3673 II->setCallingConv(CC);
3674 II->setAttributes(PAL);
3675 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3681 /// ::= 'resume' TypeAndValue
3682 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3683 Value *Exn; LocTy ExnLoc;
3684 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3687 ResumeInst *RI = ResumeInst::Create(Exn);
3692 //===----------------------------------------------------------------------===//
3693 // Binary Operators.
3694 //===----------------------------------------------------------------------===//
3697 /// ::= ArithmeticOps TypeAndValue ',' Value
3699 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3700 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3701 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3702 unsigned Opc, unsigned OperandType) {
3703 LocTy Loc; Value *LHS, *RHS;
3704 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3705 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3706 ParseValue(LHS->getType(), RHS, PFS))
3710 switch (OperandType) {
3711 default: llvm_unreachable("Unknown operand type!");
3712 case 0: // int or FP.
3713 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3714 LHS->getType()->isFPOrFPVectorTy();
3716 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3717 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3721 return Error(Loc, "invalid operand type for instruction");
3723 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3728 /// ::= ArithmeticOps TypeAndValue ',' Value {
3729 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3731 LocTy Loc; Value *LHS, *RHS;
3732 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3733 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3734 ParseValue(LHS->getType(), RHS, PFS))
3737 if (!LHS->getType()->isIntOrIntVectorTy())
3738 return Error(Loc,"instruction requires integer or integer vector operands");
3740 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3746 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3747 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3748 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3750 // Parse the integer/fp comparison predicate.
3754 if (ParseCmpPredicate(Pred, Opc) ||
3755 ParseTypeAndValue(LHS, Loc, PFS) ||
3756 ParseToken(lltok::comma, "expected ',' after compare value") ||
3757 ParseValue(LHS->getType(), RHS, PFS))
3760 if (Opc == Instruction::FCmp) {
3761 if (!LHS->getType()->isFPOrFPVectorTy())
3762 return Error(Loc, "fcmp requires floating point operands");
3763 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3765 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3766 if (!LHS->getType()->isIntOrIntVectorTy() &&
3767 !LHS->getType()->getScalarType()->isPointerTy())
3768 return Error(Loc, "icmp requires integer operands");
3769 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3774 //===----------------------------------------------------------------------===//
3775 // Other Instructions.
3776 //===----------------------------------------------------------------------===//
3780 /// ::= CastOpc TypeAndValue 'to' Type
3781 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3785 Type *DestTy = nullptr;
3786 if (ParseTypeAndValue(Op, Loc, PFS) ||
3787 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3791 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3792 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3793 return Error(Loc, "invalid cast opcode for cast from '" +
3794 getTypeString(Op->getType()) + "' to '" +
3795 getTypeString(DestTy) + "'");
3797 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3802 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3803 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3805 Value *Op0, *Op1, *Op2;
3806 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3807 ParseToken(lltok::comma, "expected ',' after select condition") ||
3808 ParseTypeAndValue(Op1, PFS) ||
3809 ParseToken(lltok::comma, "expected ',' after select value") ||
3810 ParseTypeAndValue(Op2, PFS))
3813 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3814 return Error(Loc, Reason);
3816 Inst = SelectInst::Create(Op0, Op1, Op2);
3821 /// ::= 'va_arg' TypeAndValue ',' Type
3822 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3824 Type *EltTy = nullptr;
3826 if (ParseTypeAndValue(Op, PFS) ||
3827 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3828 ParseType(EltTy, TypeLoc))
3831 if (!EltTy->isFirstClassType())
3832 return Error(TypeLoc, "va_arg requires operand with first class type");
3834 Inst = new VAArgInst(Op, EltTy);
3838 /// ParseExtractElement
3839 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3840 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3843 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3844 ParseToken(lltok::comma, "expected ',' after extract value") ||
3845 ParseTypeAndValue(Op1, PFS))
3848 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3849 return Error(Loc, "invalid extractelement operands");
3851 Inst = ExtractElementInst::Create(Op0, Op1);
3855 /// ParseInsertElement
3856 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3857 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3859 Value *Op0, *Op1, *Op2;
3860 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3861 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3862 ParseTypeAndValue(Op1, PFS) ||
3863 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3864 ParseTypeAndValue(Op2, PFS))
3867 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3868 return Error(Loc, "invalid insertelement operands");
3870 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3874 /// ParseShuffleVector
3875 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3876 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3878 Value *Op0, *Op1, *Op2;
3879 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3880 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3881 ParseTypeAndValue(Op1, PFS) ||
3882 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3883 ParseTypeAndValue(Op2, PFS))
3886 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3887 return Error(Loc, "invalid shufflevector operands");
3889 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3894 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3895 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3896 Type *Ty = nullptr; LocTy TypeLoc;
3899 if (ParseType(Ty, TypeLoc) ||
3900 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3901 ParseValue(Ty, Op0, PFS) ||
3902 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3903 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3904 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3907 bool AteExtraComma = false;
3908 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3910 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3912 if (!EatIfPresent(lltok::comma))
3915 if (Lex.getKind() == lltok::MetadataVar) {
3916 AteExtraComma = true;
3920 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3921 ParseValue(Ty, Op0, PFS) ||
3922 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3923 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3924 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3928 if (!Ty->isFirstClassType())
3929 return Error(TypeLoc, "phi node must have first class type");
3931 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3932 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3933 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3935 return AteExtraComma ? InstExtraComma : InstNormal;
3939 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3941 /// ::= 'catch' TypeAndValue
3943 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3944 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3945 Type *Ty = nullptr; LocTy TyLoc;
3946 Value *PersFn; LocTy PersFnLoc;
3948 if (ParseType(Ty, TyLoc) ||
3949 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3950 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3953 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3954 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3956 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3957 LandingPadInst::ClauseType CT;
3958 if (EatIfPresent(lltok::kw_catch))
3959 CT = LandingPadInst::Catch;
3960 else if (EatIfPresent(lltok::kw_filter))
3961 CT = LandingPadInst::Filter;
3963 return TokError("expected 'catch' or 'filter' clause type");
3965 Value *V; LocTy VLoc;
3966 if (ParseTypeAndValue(V, VLoc, PFS)) {
3971 // A 'catch' type expects a non-array constant. A filter clause expects an
3973 if (CT == LandingPadInst::Catch) {
3974 if (isa<ArrayType>(V->getType()))
3975 Error(VLoc, "'catch' clause has an invalid type");
3977 if (!isa<ArrayType>(V->getType()))
3978 Error(VLoc, "'filter' clause has an invalid type");
3989 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
3990 /// ParameterList OptionalAttrs
3991 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
3992 /// ParameterList OptionalAttrs
3993 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
3994 /// ParameterList OptionalAttrs
3995 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
3996 CallInst::TailCallKind TCK) {
3997 AttrBuilder RetAttrs, FnAttrs;
3998 std::vector<unsigned> FwdRefAttrGrps;
4001 Type *RetType = nullptr;
4004 SmallVector<ParamInfo, 16> ArgList;
4005 LocTy CallLoc = Lex.getLoc();
4007 if ((TCK != CallInst::TCK_None &&
4008 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4009 ParseOptionalCallingConv(CC) ||
4010 ParseOptionalReturnAttrs(RetAttrs) ||
4011 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4012 ParseValID(CalleeID) ||
4013 ParseParameterList(ArgList, PFS) ||
4014 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4018 // If RetType is a non-function pointer type, then this is the short syntax
4019 // for the call, which means that RetType is just the return type. Infer the
4020 // rest of the function argument types from the arguments that are present.
4021 PointerType *PFTy = nullptr;
4022 FunctionType *Ty = nullptr;
4023 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4024 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4025 // Pull out the types of all of the arguments...
4026 std::vector<Type*> ParamTypes;
4027 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4028 ParamTypes.push_back(ArgList[i].V->getType());
4030 if (!FunctionType::isValidReturnType(RetType))
4031 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4033 Ty = FunctionType::get(RetType, ParamTypes, false);
4034 PFTy = PointerType::getUnqual(Ty);
4037 // Look up the callee.
4039 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4041 // Set up the Attribute for the function.
4042 SmallVector<AttributeSet, 8> Attrs;
4043 if (RetAttrs.hasAttributes())
4044 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4045 AttributeSet::ReturnIndex,
4048 SmallVector<Value*, 8> Args;
4050 // Loop through FunctionType's arguments and ensure they are specified
4051 // correctly. Also, gather any parameter attributes.
4052 FunctionType::param_iterator I = Ty->param_begin();
4053 FunctionType::param_iterator E = Ty->param_end();
4054 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4055 Type *ExpectedTy = nullptr;
4058 } else if (!Ty->isVarArg()) {
4059 return Error(ArgList[i].Loc, "too many arguments specified");
4062 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4063 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4064 getTypeString(ExpectedTy) + "'");
4065 Args.push_back(ArgList[i].V);
4066 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4067 AttrBuilder B(ArgList[i].Attrs, i + 1);
4068 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4073 return Error(CallLoc, "not enough parameters specified for call");
4075 if (FnAttrs.hasAttributes())
4076 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4077 AttributeSet::FunctionIndex,
4080 // Finish off the Attribute and check them
4081 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4083 CallInst *CI = CallInst::Create(Callee, Args);
4084 CI->setTailCallKind(TCK);
4085 CI->setCallingConv(CC);
4086 CI->setAttributes(PAL);
4087 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4092 //===----------------------------------------------------------------------===//
4093 // Memory Instructions.
4094 //===----------------------------------------------------------------------===//
4097 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4098 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4099 Value *Size = nullptr;
4101 unsigned Alignment = 0;
4104 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4106 if (ParseType(Ty)) return true;
4108 bool AteExtraComma = false;
4109 if (EatIfPresent(lltok::comma)) {
4110 if (Lex.getKind() == lltok::kw_align) {
4111 if (ParseOptionalAlignment(Alignment)) return true;
4112 } else if (Lex.getKind() == lltok::MetadataVar) {
4113 AteExtraComma = true;
4115 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4116 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4121 if (Size && !Size->getType()->isIntegerTy())
4122 return Error(SizeLoc, "element count must have integer type");
4124 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4125 AI->setUsedWithInAlloca(IsInAlloca);
4127 return AteExtraComma ? InstExtraComma : InstNormal;
4131 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4132 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4133 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4134 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4135 Value *Val; LocTy Loc;
4136 unsigned Alignment = 0;
4137 bool AteExtraComma = false;
4138 bool isAtomic = false;
4139 AtomicOrdering Ordering = NotAtomic;
4140 SynchronizationScope Scope = CrossThread;
4142 if (Lex.getKind() == lltok::kw_atomic) {
4147 bool isVolatile = false;
4148 if (Lex.getKind() == lltok::kw_volatile) {
4153 if (ParseTypeAndValue(Val, Loc, PFS) ||
4154 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4155 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4158 if (!Val->getType()->isPointerTy() ||
4159 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4160 return Error(Loc, "load operand must be a pointer to a first class type");
4161 if (isAtomic && !Alignment)
4162 return Error(Loc, "atomic load must have explicit non-zero alignment");
4163 if (Ordering == Release || Ordering == AcquireRelease)
4164 return Error(Loc, "atomic load cannot use Release ordering");
4166 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4167 return AteExtraComma ? InstExtraComma : InstNormal;
4172 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4173 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4174 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4175 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4176 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4177 unsigned Alignment = 0;
4178 bool AteExtraComma = false;
4179 bool isAtomic = false;
4180 AtomicOrdering Ordering = NotAtomic;
4181 SynchronizationScope Scope = CrossThread;
4183 if (Lex.getKind() == lltok::kw_atomic) {
4188 bool isVolatile = false;
4189 if (Lex.getKind() == lltok::kw_volatile) {
4194 if (ParseTypeAndValue(Val, Loc, PFS) ||
4195 ParseToken(lltok::comma, "expected ',' after store operand") ||
4196 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4197 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4198 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4201 if (!Ptr->getType()->isPointerTy())
4202 return Error(PtrLoc, "store operand must be a pointer");
4203 if (!Val->getType()->isFirstClassType())
4204 return Error(Loc, "store operand must be a first class value");
4205 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4206 return Error(Loc, "stored value and pointer type do not match");
4207 if (isAtomic && !Alignment)
4208 return Error(Loc, "atomic store must have explicit non-zero alignment");
4209 if (Ordering == Acquire || Ordering == AcquireRelease)
4210 return Error(Loc, "atomic store cannot use Acquire ordering");
4212 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4213 return AteExtraComma ? InstExtraComma : InstNormal;
4217 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4218 /// 'singlethread'? AtomicOrdering AtomicOrdering
4219 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4220 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4221 bool AteExtraComma = false;
4222 AtomicOrdering SuccessOrdering = NotAtomic;
4223 AtomicOrdering FailureOrdering = NotAtomic;
4224 SynchronizationScope Scope = CrossThread;
4225 bool isVolatile = false;
4227 if (EatIfPresent(lltok::kw_volatile))
4230 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4231 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4232 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4233 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4234 ParseTypeAndValue(New, NewLoc, PFS) ||
4235 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4236 ParseOrdering(FailureOrdering))
4239 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4240 return TokError("cmpxchg cannot be unordered");
4241 if (SuccessOrdering < FailureOrdering)
4242 return TokError("cmpxchg must be at least as ordered on success as failure");
4243 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4244 return TokError("cmpxchg failure ordering cannot include release semantics");
4245 if (!Ptr->getType()->isPointerTy())
4246 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4247 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4248 return Error(CmpLoc, "compare value and pointer type do not match");
4249 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4250 return Error(NewLoc, "new value and pointer type do not match");
4251 if (!New->getType()->isIntegerTy())
4252 return Error(NewLoc, "cmpxchg operand must be an integer");
4253 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4254 if (Size < 8 || (Size & (Size - 1)))
4255 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4258 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4259 FailureOrdering, Scope);
4260 CXI->setVolatile(isVolatile);
4262 return AteExtraComma ? InstExtraComma : InstNormal;
4266 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4267 /// 'singlethread'? AtomicOrdering
4268 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4269 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4270 bool AteExtraComma = false;
4271 AtomicOrdering Ordering = NotAtomic;
4272 SynchronizationScope Scope = CrossThread;
4273 bool isVolatile = false;
4274 AtomicRMWInst::BinOp Operation;
4276 if (EatIfPresent(lltok::kw_volatile))
4279 switch (Lex.getKind()) {
4280 default: return TokError("expected binary operation in atomicrmw");
4281 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4282 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4283 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4284 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4285 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4286 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4287 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4288 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4289 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4290 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4291 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4293 Lex.Lex(); // Eat the operation.
4295 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4296 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4297 ParseTypeAndValue(Val, ValLoc, PFS) ||
4298 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4301 if (Ordering == Unordered)
4302 return TokError("atomicrmw cannot be unordered");
4303 if (!Ptr->getType()->isPointerTy())
4304 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4305 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4306 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4307 if (!Val->getType()->isIntegerTy())
4308 return Error(ValLoc, "atomicrmw operand must be an integer");
4309 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4310 if (Size < 8 || (Size & (Size - 1)))
4311 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4314 AtomicRMWInst *RMWI =
4315 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4316 RMWI->setVolatile(isVolatile);
4318 return AteExtraComma ? InstExtraComma : InstNormal;
4322 /// ::= 'fence' 'singlethread'? AtomicOrdering
4323 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4324 AtomicOrdering Ordering = NotAtomic;
4325 SynchronizationScope Scope = CrossThread;
4326 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4329 if (Ordering == Unordered)
4330 return TokError("fence cannot be unordered");
4331 if (Ordering == Monotonic)
4332 return TokError("fence cannot be monotonic");
4334 Inst = new FenceInst(Context, Ordering, Scope);
4338 /// ParseGetElementPtr
4339 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4340 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4341 Value *Ptr = nullptr;
4342 Value *Val = nullptr;
4345 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4347 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4349 Type *BaseType = Ptr->getType();
4350 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4351 if (!BasePointerType)
4352 return Error(Loc, "base of getelementptr must be a pointer");
4354 SmallVector<Value*, 16> Indices;
4355 bool AteExtraComma = false;
4356 while (EatIfPresent(lltok::comma)) {
4357 if (Lex.getKind() == lltok::MetadataVar) {
4358 AteExtraComma = true;
4361 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4362 if (!Val->getType()->getScalarType()->isIntegerTy())
4363 return Error(EltLoc, "getelementptr index must be an integer");
4364 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4365 return Error(EltLoc, "getelementptr index type missmatch");
4366 if (Val->getType()->isVectorTy()) {
4367 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4368 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4369 if (ValNumEl != PtrNumEl)
4370 return Error(EltLoc,
4371 "getelementptr vector index has a wrong number of elements");
4373 Indices.push_back(Val);
4376 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4377 return Error(Loc, "base element of getelementptr must be sized");
4379 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4380 return Error(Loc, "invalid getelementptr indices");
4381 Inst = GetElementPtrInst::Create(Ptr, Indices);
4383 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4384 return AteExtraComma ? InstExtraComma : InstNormal;
4387 /// ParseExtractValue
4388 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4389 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4390 Value *Val; LocTy Loc;
4391 SmallVector<unsigned, 4> Indices;
4393 if (ParseTypeAndValue(Val, Loc, PFS) ||
4394 ParseIndexList(Indices, AteExtraComma))
4397 if (!Val->getType()->isAggregateType())
4398 return Error(Loc, "extractvalue operand must be aggregate type");
4400 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4401 return Error(Loc, "invalid indices for extractvalue");
4402 Inst = ExtractValueInst::Create(Val, Indices);
4403 return AteExtraComma ? InstExtraComma : InstNormal;
4406 /// ParseInsertValue
4407 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4408 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4409 Value *Val0, *Val1; LocTy Loc0, Loc1;
4410 SmallVector<unsigned, 4> Indices;
4412 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4413 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4414 ParseTypeAndValue(Val1, Loc1, PFS) ||
4415 ParseIndexList(Indices, AteExtraComma))
4418 if (!Val0->getType()->isAggregateType())
4419 return Error(Loc0, "insertvalue operand must be aggregate type");
4421 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4422 return Error(Loc0, "invalid indices for insertvalue");
4423 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4424 return AteExtraComma ? InstExtraComma : InstNormal;
4427 //===----------------------------------------------------------------------===//
4428 // Embedded metadata.
4429 //===----------------------------------------------------------------------===//
4431 /// ParseMDNodeVector
4432 /// ::= Element (',' Element)*
4434 /// ::= 'null' | TypeAndValue
4435 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4436 PerFunctionState *PFS) {
4437 // Check for an empty list.
4438 if (Lex.getKind() == lltok::rbrace)
4442 // Null is a special case since it is typeless.
4443 if (EatIfPresent(lltok::kw_null)) {
4444 Elts.push_back(nullptr);
4449 if (ParseTypeAndValue(V, PFS)) return true;
4451 } while (EatIfPresent(lltok::comma));