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;
625 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
626 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
627 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
631 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
632 /// OptionalLinkage Aliasee
635 /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
636 /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
638 /// Everything through DLL storage class has already been parsed.
640 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
641 unsigned Visibility, unsigned DLLStorageClass) {
642 assert(Lex.getKind() == lltok::kw_alias);
644 LocTy LinkageLoc = Lex.getLoc();
646 if (ParseOptionalLinkage(L))
649 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
651 if(!GlobalAlias::isValidLinkage(Linkage))
652 return Error(LinkageLoc, "invalid linkage type for alias");
654 if (!isValidVisibilityForLinkage(Visibility, L))
655 return Error(LinkageLoc,
656 "symbol with local linkage must have default visibility");
659 LocTy AliaseeLoc = Lex.getLoc();
660 if (Lex.getKind() != lltok::kw_bitcast &&
661 Lex.getKind() != lltok::kw_getelementptr) {
662 if (ParseGlobalTypeAndValue(Aliasee)) return true;
664 // The bitcast dest type is not present, it is implied by the dest type.
666 if (ParseValID(ID)) return true;
667 if (ID.Kind != ValID::t_Constant)
668 return Error(AliaseeLoc, "invalid aliasee");
669 Aliasee = ID.ConstantVal;
672 if (!Aliasee->getType()->isPointerTy())
673 return Error(AliaseeLoc, "alias must have pointer type");
675 // Okay, create the alias but do not insert it into the module yet.
676 PointerType *PTy = cast<PointerType>(Aliasee->getType());
677 std::unique_ptr<GlobalAlias> GA(
678 new GlobalAlias(PTy->getElementType(), (GlobalValue::LinkageTypes)Linkage,
679 Name, Aliasee, nullptr, PTy->getAddressSpace()));
680 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
681 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
683 // See if this value already exists in the symbol table. If so, it is either
684 // a redefinition or a definition of a forward reference.
685 if (GlobalValue *Val = M->getNamedValue(Name)) {
686 // See if this was a redefinition. If so, there is no entry in
688 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
689 I = ForwardRefVals.find(Name);
690 if (I == ForwardRefVals.end())
691 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
693 // Otherwise, this was a definition of forward ref. Verify that types
695 if (Val->getType() != GA->getType())
696 return Error(NameLoc,
697 "forward reference and definition of alias have different types");
699 // If they agree, just RAUW the old value with the alias and remove the
701 Val->replaceAllUsesWith(GA.get());
702 Val->eraseFromParent();
703 ForwardRefVals.erase(I);
706 // Insert into the module, we know its name won't collide now.
707 M->getAliasList().push_back(GA.get());
708 assert(GA->getName() == Name && "Should not be a name conflict!");
710 // The module owns this now
717 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
718 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
719 /// OptionalExternallyInitialized GlobalType Type Const
720 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
721 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
722 /// OptionalExternallyInitialized GlobalType Type Const
724 /// Everything up to and including OptionalDLLStorageClass has been parsed
727 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
728 unsigned Linkage, bool HasLinkage,
729 unsigned Visibility, unsigned DLLStorageClass) {
730 if (!isValidVisibilityForLinkage(Visibility, Linkage))
731 return Error(NameLoc,
732 "symbol with local linkage must have default visibility");
735 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
736 GlobalVariable::ThreadLocalMode TLM;
737 LocTy UnnamedAddrLoc;
738 LocTy IsExternallyInitializedLoc;
742 if (ParseOptionalThreadLocal(TLM) ||
743 ParseOptionalAddrSpace(AddrSpace) ||
744 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
746 ParseOptionalToken(lltok::kw_externally_initialized,
747 IsExternallyInitialized,
748 &IsExternallyInitializedLoc) ||
749 ParseGlobalType(IsConstant) ||
750 ParseType(Ty, TyLoc))
753 // If the linkage is specified and is external, then no initializer is
755 Constant *Init = nullptr;
756 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
757 Linkage != GlobalValue::ExternalLinkage)) {
758 if (ParseGlobalValue(Ty, Init))
762 if (Ty->isFunctionTy() || Ty->isLabelTy())
763 return Error(TyLoc, "invalid type for global variable");
765 GlobalVariable *GV = nullptr;
767 // See if the global was forward referenced, if so, use the global.
769 if (GlobalValue *GVal = M->getNamedValue(Name)) {
770 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
771 return Error(NameLoc, "redefinition of global '@" + Name + "'");
772 GV = cast<GlobalVariable>(GVal);
775 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
776 I = ForwardRefValIDs.find(NumberedVals.size());
777 if (I != ForwardRefValIDs.end()) {
778 GV = cast<GlobalVariable>(I->second.first);
779 ForwardRefValIDs.erase(I);
784 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
785 Name, nullptr, GlobalVariable::NotThreadLocal,
788 if (GV->getType()->getElementType() != Ty)
790 "forward reference and definition of global have different types");
792 // Move the forward-reference to the correct spot in the module.
793 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
797 NumberedVals.push_back(GV);
799 // Set the parsed properties on the global.
801 GV->setInitializer(Init);
802 GV->setConstant(IsConstant);
803 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
804 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
805 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
806 GV->setExternallyInitialized(IsExternallyInitialized);
807 GV->setThreadLocalMode(TLM);
808 GV->setUnnamedAddr(UnnamedAddr);
810 // Parse attributes on the global.
811 while (Lex.getKind() == lltok::comma) {
814 if (Lex.getKind() == lltok::kw_section) {
816 GV->setSection(Lex.getStrVal());
817 if (ParseToken(lltok::StringConstant, "expected global section string"))
819 } else if (Lex.getKind() == lltok::kw_align) {
821 if (ParseOptionalAlignment(Alignment)) return true;
822 GV->setAlignment(Alignment);
824 TokError("unknown global variable property!");
831 /// ParseUnnamedAttrGrp
832 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
833 bool LLParser::ParseUnnamedAttrGrp() {
834 assert(Lex.getKind() == lltok::kw_attributes);
835 LocTy AttrGrpLoc = Lex.getLoc();
838 assert(Lex.getKind() == lltok::AttrGrpID);
839 unsigned VarID = Lex.getUIntVal();
840 std::vector<unsigned> unused;
844 if (ParseToken(lltok::equal, "expected '=' here") ||
845 ParseToken(lltok::lbrace, "expected '{' here") ||
846 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
848 ParseToken(lltok::rbrace, "expected end of attribute group"))
851 if (!NumberedAttrBuilders[VarID].hasAttributes())
852 return Error(AttrGrpLoc, "attribute group has no attributes");
857 /// ParseFnAttributeValuePairs
858 /// ::= <attr> | <attr> '=' <value>
859 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
860 std::vector<unsigned> &FwdRefAttrGrps,
861 bool inAttrGrp, LocTy &BuiltinLoc) {
862 bool HaveError = false;
867 lltok::Kind Token = Lex.getKind();
868 if (Token == lltok::kw_builtin)
869 BuiltinLoc = Lex.getLoc();
872 if (!inAttrGrp) return HaveError;
873 return Error(Lex.getLoc(), "unterminated attribute group");
878 case lltok::AttrGrpID: {
879 // Allow a function to reference an attribute group:
881 // define void @foo() #1 { ... }
885 "cannot have an attribute group reference in an attribute group");
887 unsigned AttrGrpNum = Lex.getUIntVal();
888 if (inAttrGrp) break;
890 // Save the reference to the attribute group. We'll fill it in later.
891 FwdRefAttrGrps.push_back(AttrGrpNum);
894 // Target-dependent attributes:
895 case lltok::StringConstant: {
896 std::string Attr = Lex.getStrVal();
899 if (EatIfPresent(lltok::equal) &&
900 ParseStringConstant(Val))
903 B.addAttribute(Attr, Val);
907 // Target-independent attributes:
908 case lltok::kw_align: {
909 // As a hack, we allow function alignment to be initially parsed as an
910 // attribute on a function declaration/definition or added to an attribute
911 // group and later moved to the alignment field.
915 if (ParseToken(lltok::equal, "expected '=' here") ||
916 ParseUInt32(Alignment))
919 if (ParseOptionalAlignment(Alignment))
922 B.addAlignmentAttr(Alignment);
925 case lltok::kw_alignstack: {
929 if (ParseToken(lltok::equal, "expected '=' here") ||
930 ParseUInt32(Alignment))
933 if (ParseOptionalStackAlignment(Alignment))
936 B.addStackAlignmentAttr(Alignment);
939 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
940 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
941 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
942 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
943 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
944 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
945 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
946 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
947 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
948 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
949 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
950 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
951 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
952 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
953 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
954 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
955 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
956 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
957 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
958 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
959 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
960 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
961 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
962 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
963 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
964 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
967 case lltok::kw_inreg:
968 case lltok::kw_signext:
969 case lltok::kw_zeroext:
972 "invalid use of attribute on a function");
974 case lltok::kw_byval:
975 case lltok::kw_inalloca:
977 case lltok::kw_noalias:
978 case lltok::kw_nocapture:
979 case lltok::kw_returned:
983 "invalid use of parameter-only attribute on a function");
991 //===----------------------------------------------------------------------===//
992 // GlobalValue Reference/Resolution Routines.
993 //===----------------------------------------------------------------------===//
995 /// GetGlobalVal - Get a value with the specified name or ID, creating a
996 /// forward reference record if needed. This can return null if the value
997 /// exists but does not have the right type.
998 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1000 PointerType *PTy = dyn_cast<PointerType>(Ty);
1002 Error(Loc, "global variable reference must have pointer type");
1006 // Look this name up in the normal function symbol table.
1008 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1010 // If this is a forward reference for the value, see if we already created a
1011 // forward ref record.
1013 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1014 I = ForwardRefVals.find(Name);
1015 if (I != ForwardRefVals.end())
1016 Val = I->second.first;
1019 // If we have the value in the symbol table or fwd-ref table, return it.
1021 if (Val->getType() == Ty) return Val;
1022 Error(Loc, "'@" + Name + "' defined with type '" +
1023 getTypeString(Val->getType()) + "'");
1027 // Otherwise, create a new forward reference for this value and remember it.
1028 GlobalValue *FwdVal;
1029 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1030 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1032 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1033 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1034 nullptr, GlobalVariable::NotThreadLocal,
1035 PTy->getAddressSpace());
1037 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1041 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1042 PointerType *PTy = dyn_cast<PointerType>(Ty);
1044 Error(Loc, "global variable reference must have pointer type");
1048 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1050 // If this is a forward reference for the value, see if we already created a
1051 // forward ref record.
1053 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1054 I = ForwardRefValIDs.find(ID);
1055 if (I != ForwardRefValIDs.end())
1056 Val = I->second.first;
1059 // If we have the value in the symbol table or fwd-ref table, return it.
1061 if (Val->getType() == Ty) return Val;
1062 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1063 getTypeString(Val->getType()) + "'");
1067 // Otherwise, create a new forward reference for this value and remember it.
1068 GlobalValue *FwdVal;
1069 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1070 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1072 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1073 GlobalValue::ExternalWeakLinkage, nullptr, "");
1075 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1080 //===----------------------------------------------------------------------===//
1082 //===----------------------------------------------------------------------===//
1084 /// ParseToken - If the current token has the specified kind, eat it and return
1085 /// success. Otherwise, emit the specified error and return failure.
1086 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1087 if (Lex.getKind() != T)
1088 return TokError(ErrMsg);
1093 /// ParseStringConstant
1094 /// ::= StringConstant
1095 bool LLParser::ParseStringConstant(std::string &Result) {
1096 if (Lex.getKind() != lltok::StringConstant)
1097 return TokError("expected string constant");
1098 Result = Lex.getStrVal();
1105 bool LLParser::ParseUInt32(unsigned &Val) {
1106 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1107 return TokError("expected integer");
1108 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1109 if (Val64 != unsigned(Val64))
1110 return TokError("expected 32-bit integer (too large)");
1117 /// := 'localdynamic'
1118 /// := 'initialexec'
1120 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1121 switch (Lex.getKind()) {
1123 return TokError("expected localdynamic, initialexec or localexec");
1124 case lltok::kw_localdynamic:
1125 TLM = GlobalVariable::LocalDynamicTLSModel;
1127 case lltok::kw_initialexec:
1128 TLM = GlobalVariable::InitialExecTLSModel;
1130 case lltok::kw_localexec:
1131 TLM = GlobalVariable::LocalExecTLSModel;
1139 /// ParseOptionalThreadLocal
1141 /// := 'thread_local'
1142 /// := 'thread_local' '(' tlsmodel ')'
1143 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1144 TLM = GlobalVariable::NotThreadLocal;
1145 if (!EatIfPresent(lltok::kw_thread_local))
1148 TLM = GlobalVariable::GeneralDynamicTLSModel;
1149 if (Lex.getKind() == lltok::lparen) {
1151 return ParseTLSModel(TLM) ||
1152 ParseToken(lltok::rparen, "expected ')' after thread local model");
1157 /// ParseOptionalAddrSpace
1159 /// := 'addrspace' '(' uint32 ')'
1160 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1162 if (!EatIfPresent(lltok::kw_addrspace))
1164 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1165 ParseUInt32(AddrSpace) ||
1166 ParseToken(lltok::rparen, "expected ')' in address space");
1169 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1170 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1171 bool HaveError = false;
1176 lltok::Kind Token = Lex.getKind();
1178 default: // End of attributes.
1180 case lltok::kw_align: {
1182 if (ParseOptionalAlignment(Alignment))
1184 B.addAlignmentAttr(Alignment);
1187 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1188 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1189 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1190 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1191 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1192 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1193 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1194 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1195 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1196 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1197 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1198 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1200 case lltok::kw_alignstack:
1201 case lltok::kw_alwaysinline:
1202 case lltok::kw_builtin:
1203 case lltok::kw_inlinehint:
1204 case lltok::kw_minsize:
1205 case lltok::kw_naked:
1206 case lltok::kw_nobuiltin:
1207 case lltok::kw_noduplicate:
1208 case lltok::kw_noimplicitfloat:
1209 case lltok::kw_noinline:
1210 case lltok::kw_nonlazybind:
1211 case lltok::kw_noredzone:
1212 case lltok::kw_noreturn:
1213 case lltok::kw_nounwind:
1214 case lltok::kw_optnone:
1215 case lltok::kw_optsize:
1216 case lltok::kw_returns_twice:
1217 case lltok::kw_sanitize_address:
1218 case lltok::kw_sanitize_memory:
1219 case lltok::kw_sanitize_thread:
1221 case lltok::kw_sspreq:
1222 case lltok::kw_sspstrong:
1223 case lltok::kw_uwtable:
1224 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1232 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1233 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1234 bool HaveError = false;
1239 lltok::Kind Token = Lex.getKind();
1241 default: // End of attributes.
1243 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1244 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1245 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1246 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1249 case lltok::kw_align:
1250 case lltok::kw_byval:
1251 case lltok::kw_inalloca:
1252 case lltok::kw_nest:
1253 case lltok::kw_nocapture:
1254 case lltok::kw_returned:
1255 case lltok::kw_sret:
1256 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1259 case lltok::kw_alignstack:
1260 case lltok::kw_alwaysinline:
1261 case lltok::kw_builtin:
1262 case lltok::kw_cold:
1263 case lltok::kw_inlinehint:
1264 case lltok::kw_minsize:
1265 case lltok::kw_naked:
1266 case lltok::kw_nobuiltin:
1267 case lltok::kw_noduplicate:
1268 case lltok::kw_noimplicitfloat:
1269 case lltok::kw_noinline:
1270 case lltok::kw_nonlazybind:
1271 case lltok::kw_noredzone:
1272 case lltok::kw_noreturn:
1273 case lltok::kw_nounwind:
1274 case lltok::kw_optnone:
1275 case lltok::kw_optsize:
1276 case lltok::kw_returns_twice:
1277 case lltok::kw_sanitize_address:
1278 case lltok::kw_sanitize_memory:
1279 case lltok::kw_sanitize_thread:
1281 case lltok::kw_sspreq:
1282 case lltok::kw_sspstrong:
1283 case lltok::kw_uwtable:
1284 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1287 case lltok::kw_readnone:
1288 case lltok::kw_readonly:
1289 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1296 /// ParseOptionalLinkage
1303 /// ::= 'linkonce_odr'
1304 /// ::= 'available_externally'
1307 /// ::= 'extern_weak'
1310 /// Deprecated Values:
1311 /// ::= 'linker_private'
1312 /// ::= 'linker_private_weak'
1313 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1315 switch (Lex.getKind()) {
1316 default: Res=GlobalValue::ExternalLinkage; return false;
1317 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1318 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1319 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1320 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1321 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1322 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1323 case lltok::kw_available_externally:
1324 Res = GlobalValue::AvailableExternallyLinkage;
1326 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1327 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1328 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1329 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1331 case lltok::kw_linker_private:
1332 case lltok::kw_linker_private_weak:
1333 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1336 // treat linker_private and linker_private_weak as PrivateLinkage
1337 Res = GlobalValue::PrivateLinkage;
1345 /// ParseOptionalVisibility
1351 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1352 switch (Lex.getKind()) {
1353 default: Res = GlobalValue::DefaultVisibility; return false;
1354 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1355 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1356 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1362 /// ParseOptionalDLLStorageClass
1367 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1368 switch (Lex.getKind()) {
1369 default: Res = GlobalValue::DefaultStorageClass; return false;
1370 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1371 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1377 /// ParseOptionalCallingConv
1381 /// ::= 'kw_intel_ocl_bicc'
1383 /// ::= 'x86_stdcallcc'
1384 /// ::= 'x86_fastcallcc'
1385 /// ::= 'x86_thiscallcc'
1386 /// ::= 'arm_apcscc'
1387 /// ::= 'arm_aapcscc'
1388 /// ::= 'arm_aapcs_vfpcc'
1389 /// ::= 'msp430_intrcc'
1390 /// ::= 'ptx_kernel'
1391 /// ::= 'ptx_device'
1393 /// ::= 'spir_kernel'
1394 /// ::= 'x86_64_sysvcc'
1395 /// ::= 'x86_64_win64cc'
1396 /// ::= 'webkit_jscc'
1398 /// ::= 'preserve_mostcc'
1399 /// ::= 'preserve_allcc'
1402 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1403 switch (Lex.getKind()) {
1404 default: CC = CallingConv::C; return false;
1405 case lltok::kw_ccc: CC = CallingConv::C; break;
1406 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1407 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1408 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1409 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1410 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1411 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1412 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1413 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1414 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1415 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1416 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1417 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1418 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1419 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1420 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1421 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1422 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1423 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1424 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1425 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1426 case lltok::kw_cc: {
1427 unsigned ArbitraryCC;
1429 if (ParseUInt32(ArbitraryCC))
1431 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1440 /// ParseInstructionMetadata
1441 /// ::= !dbg !42 (',' !dbg !57)*
1442 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1443 PerFunctionState *PFS) {
1445 if (Lex.getKind() != lltok::MetadataVar)
1446 return TokError("expected metadata after comma");
1448 std::string Name = Lex.getStrVal();
1449 unsigned MDK = M->getMDKindID(Name);
1453 SMLoc Loc = Lex.getLoc();
1455 if (ParseToken(lltok::exclaim, "expected '!' here"))
1458 // This code is similar to that of ParseMetadataValue, however it needs to
1459 // have special-case code for a forward reference; see the comments on
1460 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1461 // at the top level here.
1462 if (Lex.getKind() == lltok::lbrace) {
1464 if (ParseMetadataListValue(ID, PFS))
1466 assert(ID.Kind == ValID::t_MDNode);
1467 Inst->setMetadata(MDK, ID.MDNodeVal);
1469 unsigned NodeID = 0;
1470 if (ParseMDNodeID(Node, NodeID))
1473 // If we got the node, add it to the instruction.
1474 Inst->setMetadata(MDK, Node);
1476 MDRef R = { Loc, MDK, NodeID };
1477 // Otherwise, remember that this should be resolved later.
1478 ForwardRefInstMetadata[Inst].push_back(R);
1482 if (MDK == LLVMContext::MD_tbaa)
1483 InstsWithTBAATag.push_back(Inst);
1485 // If this is the end of the list, we're done.
1486 } while (EatIfPresent(lltok::comma));
1490 /// ParseOptionalAlignment
1493 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1495 if (!EatIfPresent(lltok::kw_align))
1497 LocTy AlignLoc = Lex.getLoc();
1498 if (ParseUInt32(Alignment)) return true;
1499 if (!isPowerOf2_32(Alignment))
1500 return Error(AlignLoc, "alignment is not a power of two");
1501 if (Alignment > Value::MaximumAlignment)
1502 return Error(AlignLoc, "huge alignments are not supported yet");
1506 /// ParseOptionalCommaAlign
1510 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1512 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1513 bool &AteExtraComma) {
1514 AteExtraComma = false;
1515 while (EatIfPresent(lltok::comma)) {
1516 // Metadata at the end is an early exit.
1517 if (Lex.getKind() == lltok::MetadataVar) {
1518 AteExtraComma = true;
1522 if (Lex.getKind() != lltok::kw_align)
1523 return Error(Lex.getLoc(), "expected metadata or 'align'");
1525 if (ParseOptionalAlignment(Alignment)) return true;
1531 /// ParseScopeAndOrdering
1532 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1535 /// This sets Scope and Ordering to the parsed values.
1536 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1537 AtomicOrdering &Ordering) {
1541 Scope = CrossThread;
1542 if (EatIfPresent(lltok::kw_singlethread))
1543 Scope = SingleThread;
1545 return ParseOrdering(Ordering);
1549 /// ::= AtomicOrdering
1551 /// This sets Ordering to the parsed value.
1552 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1553 switch (Lex.getKind()) {
1554 default: return TokError("Expected ordering on atomic instruction");
1555 case lltok::kw_unordered: Ordering = Unordered; break;
1556 case lltok::kw_monotonic: Ordering = Monotonic; break;
1557 case lltok::kw_acquire: Ordering = Acquire; break;
1558 case lltok::kw_release: Ordering = Release; break;
1559 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1560 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1566 /// ParseOptionalStackAlignment
1568 /// ::= 'alignstack' '(' 4 ')'
1569 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1571 if (!EatIfPresent(lltok::kw_alignstack))
1573 LocTy ParenLoc = Lex.getLoc();
1574 if (!EatIfPresent(lltok::lparen))
1575 return Error(ParenLoc, "expected '('");
1576 LocTy AlignLoc = Lex.getLoc();
1577 if (ParseUInt32(Alignment)) return true;
1578 ParenLoc = Lex.getLoc();
1579 if (!EatIfPresent(lltok::rparen))
1580 return Error(ParenLoc, "expected ')'");
1581 if (!isPowerOf2_32(Alignment))
1582 return Error(AlignLoc, "stack alignment is not a power of two");
1586 /// ParseIndexList - This parses the index list for an insert/extractvalue
1587 /// instruction. This sets AteExtraComma in the case where we eat an extra
1588 /// comma at the end of the line and find that it is followed by metadata.
1589 /// Clients that don't allow metadata can call the version of this function that
1590 /// only takes one argument.
1593 /// ::= (',' uint32)+
1595 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1596 bool &AteExtraComma) {
1597 AteExtraComma = false;
1599 if (Lex.getKind() != lltok::comma)
1600 return TokError("expected ',' as start of index list");
1602 while (EatIfPresent(lltok::comma)) {
1603 if (Lex.getKind() == lltok::MetadataVar) {
1604 AteExtraComma = true;
1608 if (ParseUInt32(Idx)) return true;
1609 Indices.push_back(Idx);
1615 //===----------------------------------------------------------------------===//
1617 //===----------------------------------------------------------------------===//
1619 /// ParseType - Parse a type.
1620 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1621 SMLoc TypeLoc = Lex.getLoc();
1622 switch (Lex.getKind()) {
1624 return TokError("expected type");
1626 // Type ::= 'float' | 'void' (etc)
1627 Result = Lex.getTyVal();
1631 // Type ::= StructType
1632 if (ParseAnonStructType(Result, false))
1635 case lltok::lsquare:
1636 // Type ::= '[' ... ']'
1637 Lex.Lex(); // eat the lsquare.
1638 if (ParseArrayVectorType(Result, false))
1641 case lltok::less: // Either vector or packed struct.
1642 // Type ::= '<' ... '>'
1644 if (Lex.getKind() == lltok::lbrace) {
1645 if (ParseAnonStructType(Result, true) ||
1646 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1648 } else if (ParseArrayVectorType(Result, true))
1651 case lltok::LocalVar: {
1653 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1655 // If the type hasn't been defined yet, create a forward definition and
1656 // remember where that forward def'n was seen (in case it never is defined).
1658 Entry.first = StructType::create(Context, Lex.getStrVal());
1659 Entry.second = Lex.getLoc();
1661 Result = Entry.first;
1666 case lltok::LocalVarID: {
1668 if (Lex.getUIntVal() >= NumberedTypes.size())
1669 NumberedTypes.resize(Lex.getUIntVal()+1);
1670 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1672 // If the type hasn't been defined yet, create a forward definition and
1673 // remember where that forward def'n was seen (in case it never is defined).
1675 Entry.first = StructType::create(Context);
1676 Entry.second = Lex.getLoc();
1678 Result = Entry.first;
1684 // Parse the type suffixes.
1686 switch (Lex.getKind()) {
1689 if (!AllowVoid && Result->isVoidTy())
1690 return Error(TypeLoc, "void type only allowed for function results");
1693 // Type ::= Type '*'
1695 if (Result->isLabelTy())
1696 return TokError("basic block pointers are invalid");
1697 if (Result->isVoidTy())
1698 return TokError("pointers to void are invalid - use i8* instead");
1699 if (!PointerType::isValidElementType(Result))
1700 return TokError("pointer to this type is invalid");
1701 Result = PointerType::getUnqual(Result);
1705 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1706 case lltok::kw_addrspace: {
1707 if (Result->isLabelTy())
1708 return TokError("basic block pointers are invalid");
1709 if (Result->isVoidTy())
1710 return TokError("pointers to void are invalid; use i8* instead");
1711 if (!PointerType::isValidElementType(Result))
1712 return TokError("pointer to this type is invalid");
1714 if (ParseOptionalAddrSpace(AddrSpace) ||
1715 ParseToken(lltok::star, "expected '*' in address space"))
1718 Result = PointerType::get(Result, AddrSpace);
1722 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1724 if (ParseFunctionType(Result))
1731 /// ParseParameterList
1733 /// ::= '(' Arg (',' Arg)* ')'
1735 /// ::= Type OptionalAttributes Value OptionalAttributes
1736 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1737 PerFunctionState &PFS) {
1738 if (ParseToken(lltok::lparen, "expected '(' in call"))
1741 unsigned AttrIndex = 1;
1742 while (Lex.getKind() != lltok::rparen) {
1743 // If this isn't the first argument, we need a comma.
1744 if (!ArgList.empty() &&
1745 ParseToken(lltok::comma, "expected ',' in argument list"))
1748 // Parse the argument.
1750 Type *ArgTy = nullptr;
1751 AttrBuilder ArgAttrs;
1753 if (ParseType(ArgTy, ArgLoc))
1756 // Otherwise, handle normal operands.
1757 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1759 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1764 Lex.Lex(); // Lex the ')'.
1770 /// ParseArgumentList - Parse the argument list for a function type or function
1772 /// ::= '(' ArgTypeListI ')'
1776 /// ::= ArgTypeList ',' '...'
1777 /// ::= ArgType (',' ArgType)*
1779 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1782 assert(Lex.getKind() == lltok::lparen);
1783 Lex.Lex(); // eat the (.
1785 if (Lex.getKind() == lltok::rparen) {
1787 } else if (Lex.getKind() == lltok::dotdotdot) {
1791 LocTy TypeLoc = Lex.getLoc();
1792 Type *ArgTy = nullptr;
1796 if (ParseType(ArgTy) ||
1797 ParseOptionalParamAttrs(Attrs)) return true;
1799 if (ArgTy->isVoidTy())
1800 return Error(TypeLoc, "argument can not have void type");
1802 if (Lex.getKind() == lltok::LocalVar) {
1803 Name = Lex.getStrVal();
1807 if (!FunctionType::isValidArgumentType(ArgTy))
1808 return Error(TypeLoc, "invalid type for function argument");
1810 unsigned AttrIndex = 1;
1811 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1812 AttributeSet::get(ArgTy->getContext(),
1813 AttrIndex++, Attrs), Name));
1815 while (EatIfPresent(lltok::comma)) {
1816 // Handle ... at end of arg list.
1817 if (EatIfPresent(lltok::dotdotdot)) {
1822 // Otherwise must be an argument type.
1823 TypeLoc = Lex.getLoc();
1824 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1826 if (ArgTy->isVoidTy())
1827 return Error(TypeLoc, "argument can not have void type");
1829 if (Lex.getKind() == lltok::LocalVar) {
1830 Name = Lex.getStrVal();
1836 if (!ArgTy->isFirstClassType())
1837 return Error(TypeLoc, "invalid type for function argument");
1839 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1840 AttributeSet::get(ArgTy->getContext(),
1841 AttrIndex++, Attrs),
1846 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1849 /// ParseFunctionType
1850 /// ::= Type ArgumentList OptionalAttrs
1851 bool LLParser::ParseFunctionType(Type *&Result) {
1852 assert(Lex.getKind() == lltok::lparen);
1854 if (!FunctionType::isValidReturnType(Result))
1855 return TokError("invalid function return type");
1857 SmallVector<ArgInfo, 8> ArgList;
1859 if (ParseArgumentList(ArgList, isVarArg))
1862 // Reject names on the arguments lists.
1863 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1864 if (!ArgList[i].Name.empty())
1865 return Error(ArgList[i].Loc, "argument name invalid in function type");
1866 if (ArgList[i].Attrs.hasAttributes(i + 1))
1867 return Error(ArgList[i].Loc,
1868 "argument attributes invalid in function type");
1871 SmallVector<Type*, 16> ArgListTy;
1872 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1873 ArgListTy.push_back(ArgList[i].Ty);
1875 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1879 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1881 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1882 SmallVector<Type*, 8> Elts;
1883 if (ParseStructBody(Elts)) return true;
1885 Result = StructType::get(Context, Elts, Packed);
1889 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1890 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1891 std::pair<Type*, LocTy> &Entry,
1893 // If the type was already defined, diagnose the redefinition.
1894 if (Entry.first && !Entry.second.isValid())
1895 return Error(TypeLoc, "redefinition of type");
1897 // If we have opaque, just return without filling in the definition for the
1898 // struct. This counts as a definition as far as the .ll file goes.
1899 if (EatIfPresent(lltok::kw_opaque)) {
1900 // This type is being defined, so clear the location to indicate this.
1901 Entry.second = SMLoc();
1903 // If this type number has never been uttered, create it.
1905 Entry.first = StructType::create(Context, Name);
1906 ResultTy = Entry.first;
1910 // If the type starts with '<', then it is either a packed struct or a vector.
1911 bool isPacked = EatIfPresent(lltok::less);
1913 // If we don't have a struct, then we have a random type alias, which we
1914 // accept for compatibility with old files. These types are not allowed to be
1915 // forward referenced and not allowed to be recursive.
1916 if (Lex.getKind() != lltok::lbrace) {
1918 return Error(TypeLoc, "forward references to non-struct type");
1922 return ParseArrayVectorType(ResultTy, true);
1923 return ParseType(ResultTy);
1926 // This type is being defined, so clear the location to indicate this.
1927 Entry.second = SMLoc();
1929 // If this type number has never been uttered, create it.
1931 Entry.first = StructType::create(Context, Name);
1933 StructType *STy = cast<StructType>(Entry.first);
1935 SmallVector<Type*, 8> Body;
1936 if (ParseStructBody(Body) ||
1937 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1940 STy->setBody(Body, isPacked);
1946 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1949 /// ::= '{' Type (',' Type)* '}'
1950 /// ::= '<' '{' '}' '>'
1951 /// ::= '<' '{' Type (',' Type)* '}' '>'
1952 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1953 assert(Lex.getKind() == lltok::lbrace);
1954 Lex.Lex(); // Consume the '{'
1956 // Handle the empty struct.
1957 if (EatIfPresent(lltok::rbrace))
1960 LocTy EltTyLoc = Lex.getLoc();
1962 if (ParseType(Ty)) return true;
1965 if (!StructType::isValidElementType(Ty))
1966 return Error(EltTyLoc, "invalid element type for struct");
1968 while (EatIfPresent(lltok::comma)) {
1969 EltTyLoc = Lex.getLoc();
1970 if (ParseType(Ty)) return true;
1972 if (!StructType::isValidElementType(Ty))
1973 return Error(EltTyLoc, "invalid element type for struct");
1978 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1981 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1982 /// token has already been consumed.
1984 /// ::= '[' APSINTVAL 'x' Types ']'
1985 /// ::= '<' APSINTVAL 'x' Types '>'
1986 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1987 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1988 Lex.getAPSIntVal().getBitWidth() > 64)
1989 return TokError("expected number in address space");
1991 LocTy SizeLoc = Lex.getLoc();
1992 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1995 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1998 LocTy TypeLoc = Lex.getLoc();
1999 Type *EltTy = nullptr;
2000 if (ParseType(EltTy)) return true;
2002 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2003 "expected end of sequential type"))
2008 return Error(SizeLoc, "zero element vector is illegal");
2009 if ((unsigned)Size != Size)
2010 return Error(SizeLoc, "size too large for vector");
2011 if (!VectorType::isValidElementType(EltTy))
2012 return Error(TypeLoc, "invalid vector element type");
2013 Result = VectorType::get(EltTy, unsigned(Size));
2015 if (!ArrayType::isValidElementType(EltTy))
2016 return Error(TypeLoc, "invalid array element type");
2017 Result = ArrayType::get(EltTy, Size);
2022 //===----------------------------------------------------------------------===//
2023 // Function Semantic Analysis.
2024 //===----------------------------------------------------------------------===//
2026 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2028 : P(p), F(f), FunctionNumber(functionNumber) {
2030 // Insert unnamed arguments into the NumberedVals list.
2031 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2034 NumberedVals.push_back(AI);
2037 LLParser::PerFunctionState::~PerFunctionState() {
2038 // If there were any forward referenced non-basicblock values, delete them.
2039 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2040 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2041 if (!isa<BasicBlock>(I->second.first)) {
2042 I->second.first->replaceAllUsesWith(
2043 UndefValue::get(I->second.first->getType()));
2044 delete I->second.first;
2045 I->second.first = nullptr;
2048 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2049 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2050 if (!isa<BasicBlock>(I->second.first)) {
2051 I->second.first->replaceAllUsesWith(
2052 UndefValue::get(I->second.first->getType()));
2053 delete I->second.first;
2054 I->second.first = nullptr;
2058 bool LLParser::PerFunctionState::FinishFunction() {
2059 // Check to see if someone took the address of labels in this block.
2060 if (!P.ForwardRefBlockAddresses.empty()) {
2062 if (!F.getName().empty()) {
2063 FunctionID.Kind = ValID::t_GlobalName;
2064 FunctionID.StrVal = F.getName();
2066 FunctionID.Kind = ValID::t_GlobalID;
2067 FunctionID.UIntVal = FunctionNumber;
2070 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2071 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2072 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2073 // Resolve all these references.
2074 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2077 P.ForwardRefBlockAddresses.erase(FRBAI);
2081 if (!ForwardRefVals.empty())
2082 return P.Error(ForwardRefVals.begin()->second.second,
2083 "use of undefined value '%" + ForwardRefVals.begin()->first +
2085 if (!ForwardRefValIDs.empty())
2086 return P.Error(ForwardRefValIDs.begin()->second.second,
2087 "use of undefined value '%" +
2088 Twine(ForwardRefValIDs.begin()->first) + "'");
2093 /// GetVal - Get a value with the specified name or ID, creating a
2094 /// forward reference record if needed. This can return null if the value
2095 /// exists but does not have the right type.
2096 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2097 Type *Ty, LocTy Loc) {
2098 // Look this name up in the normal function symbol table.
2099 Value *Val = F.getValueSymbolTable().lookup(Name);
2101 // If this is a forward reference for the value, see if we already created a
2102 // forward ref record.
2104 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2105 I = ForwardRefVals.find(Name);
2106 if (I != ForwardRefVals.end())
2107 Val = I->second.first;
2110 // If we have the value in the symbol table or fwd-ref table, return it.
2112 if (Val->getType() == Ty) return Val;
2113 if (Ty->isLabelTy())
2114 P.Error(Loc, "'%" + Name + "' is not a basic block");
2116 P.Error(Loc, "'%" + Name + "' defined with type '" +
2117 getTypeString(Val->getType()) + "'");
2121 // Don't make placeholders with invalid type.
2122 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2123 P.Error(Loc, "invalid use of a non-first-class type");
2127 // Otherwise, create a new forward reference for this value and remember it.
2129 if (Ty->isLabelTy())
2130 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2132 FwdVal = new Argument(Ty, Name);
2134 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2138 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2140 // Look this name up in the normal function symbol table.
2141 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2143 // If this is a forward reference for the value, see if we already created a
2144 // forward ref record.
2146 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2147 I = ForwardRefValIDs.find(ID);
2148 if (I != ForwardRefValIDs.end())
2149 Val = I->second.first;
2152 // If we have the value in the symbol table or fwd-ref table, return it.
2154 if (Val->getType() == Ty) return Val;
2155 if (Ty->isLabelTy())
2156 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2158 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2159 getTypeString(Val->getType()) + "'");
2163 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2164 P.Error(Loc, "invalid use of a non-first-class type");
2168 // Otherwise, create a new forward reference for this value and remember it.
2170 if (Ty->isLabelTy())
2171 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2173 FwdVal = new Argument(Ty);
2175 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2179 /// SetInstName - After an instruction is parsed and inserted into its
2180 /// basic block, this installs its name.
2181 bool LLParser::PerFunctionState::SetInstName(int NameID,
2182 const std::string &NameStr,
2183 LocTy NameLoc, Instruction *Inst) {
2184 // If this instruction has void type, it cannot have a name or ID specified.
2185 if (Inst->getType()->isVoidTy()) {
2186 if (NameID != -1 || !NameStr.empty())
2187 return P.Error(NameLoc, "instructions returning void cannot have a name");
2191 // If this was a numbered instruction, verify that the instruction is the
2192 // expected value and resolve any forward references.
2193 if (NameStr.empty()) {
2194 // If neither a name nor an ID was specified, just use the next ID.
2196 NameID = NumberedVals.size();
2198 if (unsigned(NameID) != NumberedVals.size())
2199 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2200 Twine(NumberedVals.size()) + "'");
2202 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2203 ForwardRefValIDs.find(NameID);
2204 if (FI != ForwardRefValIDs.end()) {
2205 if (FI->second.first->getType() != Inst->getType())
2206 return P.Error(NameLoc, "instruction forward referenced with type '" +
2207 getTypeString(FI->second.first->getType()) + "'");
2208 FI->second.first->replaceAllUsesWith(Inst);
2209 delete FI->second.first;
2210 ForwardRefValIDs.erase(FI);
2213 NumberedVals.push_back(Inst);
2217 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2218 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2219 FI = ForwardRefVals.find(NameStr);
2220 if (FI != ForwardRefVals.end()) {
2221 if (FI->second.first->getType() != Inst->getType())
2222 return P.Error(NameLoc, "instruction forward referenced with type '" +
2223 getTypeString(FI->second.first->getType()) + "'");
2224 FI->second.first->replaceAllUsesWith(Inst);
2225 delete FI->second.first;
2226 ForwardRefVals.erase(FI);
2229 // Set the name on the instruction.
2230 Inst->setName(NameStr);
2232 if (Inst->getName() != NameStr)
2233 return P.Error(NameLoc, "multiple definition of local value named '" +
2238 /// GetBB - Get a basic block with the specified name or ID, creating a
2239 /// forward reference record if needed.
2240 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2242 return cast_or_null<BasicBlock>(GetVal(Name,
2243 Type::getLabelTy(F.getContext()), Loc));
2246 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2247 return cast_or_null<BasicBlock>(GetVal(ID,
2248 Type::getLabelTy(F.getContext()), Loc));
2251 /// DefineBB - Define the specified basic block, which is either named or
2252 /// unnamed. If there is an error, this returns null otherwise it returns
2253 /// the block being defined.
2254 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2258 BB = GetBB(NumberedVals.size(), Loc);
2260 BB = GetBB(Name, Loc);
2261 if (!BB) return nullptr; // Already diagnosed error.
2263 // Move the block to the end of the function. Forward ref'd blocks are
2264 // inserted wherever they happen to be referenced.
2265 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2267 // Remove the block from forward ref sets.
2269 ForwardRefValIDs.erase(NumberedVals.size());
2270 NumberedVals.push_back(BB);
2272 // BB forward references are already in the function symbol table.
2273 ForwardRefVals.erase(Name);
2279 //===----------------------------------------------------------------------===//
2281 //===----------------------------------------------------------------------===//
2283 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2284 /// type implied. For example, if we parse "4" we don't know what integer type
2285 /// it has. The value will later be combined with its type and checked for
2286 /// sanity. PFS is used to convert function-local operands of metadata (since
2287 /// metadata operands are not just parsed here but also converted to values).
2288 /// PFS can be null when we are not parsing metadata values inside a function.
2289 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2290 ID.Loc = Lex.getLoc();
2291 switch (Lex.getKind()) {
2292 default: return TokError("expected value token");
2293 case lltok::GlobalID: // @42
2294 ID.UIntVal = Lex.getUIntVal();
2295 ID.Kind = ValID::t_GlobalID;
2297 case lltok::GlobalVar: // @foo
2298 ID.StrVal = Lex.getStrVal();
2299 ID.Kind = ValID::t_GlobalName;
2301 case lltok::LocalVarID: // %42
2302 ID.UIntVal = Lex.getUIntVal();
2303 ID.Kind = ValID::t_LocalID;
2305 case lltok::LocalVar: // %foo
2306 ID.StrVal = Lex.getStrVal();
2307 ID.Kind = ValID::t_LocalName;
2309 case lltok::exclaim: // !42, !{...}, or !"foo"
2310 return ParseMetadataValue(ID, PFS);
2312 ID.APSIntVal = Lex.getAPSIntVal();
2313 ID.Kind = ValID::t_APSInt;
2315 case lltok::APFloat:
2316 ID.APFloatVal = Lex.getAPFloatVal();
2317 ID.Kind = ValID::t_APFloat;
2319 case lltok::kw_true:
2320 ID.ConstantVal = ConstantInt::getTrue(Context);
2321 ID.Kind = ValID::t_Constant;
2323 case lltok::kw_false:
2324 ID.ConstantVal = ConstantInt::getFalse(Context);
2325 ID.Kind = ValID::t_Constant;
2327 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2328 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2329 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2331 case lltok::lbrace: {
2332 // ValID ::= '{' ConstVector '}'
2334 SmallVector<Constant*, 16> Elts;
2335 if (ParseGlobalValueVector(Elts) ||
2336 ParseToken(lltok::rbrace, "expected end of struct constant"))
2339 ID.ConstantStructElts = new Constant*[Elts.size()];
2340 ID.UIntVal = Elts.size();
2341 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2342 ID.Kind = ValID::t_ConstantStruct;
2346 // ValID ::= '<' ConstVector '>' --> Vector.
2347 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2349 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2351 SmallVector<Constant*, 16> Elts;
2352 LocTy FirstEltLoc = Lex.getLoc();
2353 if (ParseGlobalValueVector(Elts) ||
2355 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2356 ParseToken(lltok::greater, "expected end of constant"))
2359 if (isPackedStruct) {
2360 ID.ConstantStructElts = new Constant*[Elts.size()];
2361 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2362 ID.UIntVal = Elts.size();
2363 ID.Kind = ValID::t_PackedConstantStruct;
2368 return Error(ID.Loc, "constant vector must not be empty");
2370 if (!Elts[0]->getType()->isIntegerTy() &&
2371 !Elts[0]->getType()->isFloatingPointTy() &&
2372 !Elts[0]->getType()->isPointerTy())
2373 return Error(FirstEltLoc,
2374 "vector elements must have integer, pointer or floating point type");
2376 // Verify that all the vector elements have the same type.
2377 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2378 if (Elts[i]->getType() != Elts[0]->getType())
2379 return Error(FirstEltLoc,
2380 "vector element #" + Twine(i) +
2381 " is not of type '" + getTypeString(Elts[0]->getType()));
2383 ID.ConstantVal = ConstantVector::get(Elts);
2384 ID.Kind = ValID::t_Constant;
2387 case lltok::lsquare: { // Array Constant
2389 SmallVector<Constant*, 16> Elts;
2390 LocTy FirstEltLoc = Lex.getLoc();
2391 if (ParseGlobalValueVector(Elts) ||
2392 ParseToken(lltok::rsquare, "expected end of array constant"))
2395 // Handle empty element.
2397 // Use undef instead of an array because it's inconvenient to determine
2398 // the element type at this point, there being no elements to examine.
2399 ID.Kind = ValID::t_EmptyArray;
2403 if (!Elts[0]->getType()->isFirstClassType())
2404 return Error(FirstEltLoc, "invalid array element type: " +
2405 getTypeString(Elts[0]->getType()));
2407 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2409 // Verify all elements are correct type!
2410 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2411 if (Elts[i]->getType() != Elts[0]->getType())
2412 return Error(FirstEltLoc,
2413 "array element #" + Twine(i) +
2414 " is not of type '" + getTypeString(Elts[0]->getType()));
2417 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2418 ID.Kind = ValID::t_Constant;
2421 case lltok::kw_c: // c "foo"
2423 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2425 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2426 ID.Kind = ValID::t_Constant;
2429 case lltok::kw_asm: {
2430 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2432 bool HasSideEffect, AlignStack, AsmDialect;
2434 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2435 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2436 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2437 ParseStringConstant(ID.StrVal) ||
2438 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2439 ParseToken(lltok::StringConstant, "expected constraint string"))
2441 ID.StrVal2 = Lex.getStrVal();
2442 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2443 (unsigned(AsmDialect)<<2);
2444 ID.Kind = ValID::t_InlineAsm;
2448 case lltok::kw_blockaddress: {
2449 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2454 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2456 ParseToken(lltok::comma, "expected comma in block address expression")||
2457 ParseValID(Label) ||
2458 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2461 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2462 return Error(Fn.Loc, "expected function name in blockaddress");
2463 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2464 return Error(Label.Loc, "expected basic block name in blockaddress");
2466 // Make a global variable as a placeholder for this reference.
2467 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2468 false, GlobalValue::InternalLinkage,
2470 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2471 ID.ConstantVal = FwdRef;
2472 ID.Kind = ValID::t_Constant;
2476 case lltok::kw_trunc:
2477 case lltok::kw_zext:
2478 case lltok::kw_sext:
2479 case lltok::kw_fptrunc:
2480 case lltok::kw_fpext:
2481 case lltok::kw_bitcast:
2482 case lltok::kw_addrspacecast:
2483 case lltok::kw_uitofp:
2484 case lltok::kw_sitofp:
2485 case lltok::kw_fptoui:
2486 case lltok::kw_fptosi:
2487 case lltok::kw_inttoptr:
2488 case lltok::kw_ptrtoint: {
2489 unsigned Opc = Lex.getUIntVal();
2490 Type *DestTy = nullptr;
2493 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2494 ParseGlobalTypeAndValue(SrcVal) ||
2495 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2496 ParseType(DestTy) ||
2497 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2499 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2500 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2501 getTypeString(SrcVal->getType()) + "' to '" +
2502 getTypeString(DestTy) + "'");
2503 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2505 ID.Kind = ValID::t_Constant;
2508 case lltok::kw_extractvalue: {
2511 SmallVector<unsigned, 4> Indices;
2512 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2513 ParseGlobalTypeAndValue(Val) ||
2514 ParseIndexList(Indices) ||
2515 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2518 if (!Val->getType()->isAggregateType())
2519 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2520 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2521 return Error(ID.Loc, "invalid indices for extractvalue");
2522 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2523 ID.Kind = ValID::t_Constant;
2526 case lltok::kw_insertvalue: {
2528 Constant *Val0, *Val1;
2529 SmallVector<unsigned, 4> Indices;
2530 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2531 ParseGlobalTypeAndValue(Val0) ||
2532 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2533 ParseGlobalTypeAndValue(Val1) ||
2534 ParseIndexList(Indices) ||
2535 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2537 if (!Val0->getType()->isAggregateType())
2538 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2539 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2540 return Error(ID.Loc, "invalid indices for insertvalue");
2541 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2542 ID.Kind = ValID::t_Constant;
2545 case lltok::kw_icmp:
2546 case lltok::kw_fcmp: {
2547 unsigned PredVal, Opc = Lex.getUIntVal();
2548 Constant *Val0, *Val1;
2550 if (ParseCmpPredicate(PredVal, Opc) ||
2551 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2552 ParseGlobalTypeAndValue(Val0) ||
2553 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2554 ParseGlobalTypeAndValue(Val1) ||
2555 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2558 if (Val0->getType() != Val1->getType())
2559 return Error(ID.Loc, "compare operands must have the same type");
2561 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2563 if (Opc == Instruction::FCmp) {
2564 if (!Val0->getType()->isFPOrFPVectorTy())
2565 return Error(ID.Loc, "fcmp requires floating point operands");
2566 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2568 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2569 if (!Val0->getType()->isIntOrIntVectorTy() &&
2570 !Val0->getType()->getScalarType()->isPointerTy())
2571 return Error(ID.Loc, "icmp requires pointer or integer operands");
2572 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2574 ID.Kind = ValID::t_Constant;
2578 // Binary Operators.
2580 case lltok::kw_fadd:
2582 case lltok::kw_fsub:
2584 case lltok::kw_fmul:
2585 case lltok::kw_udiv:
2586 case lltok::kw_sdiv:
2587 case lltok::kw_fdiv:
2588 case lltok::kw_urem:
2589 case lltok::kw_srem:
2590 case lltok::kw_frem:
2592 case lltok::kw_lshr:
2593 case lltok::kw_ashr: {
2597 unsigned Opc = Lex.getUIntVal();
2598 Constant *Val0, *Val1;
2600 LocTy ModifierLoc = Lex.getLoc();
2601 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2602 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2603 if (EatIfPresent(lltok::kw_nuw))
2605 if (EatIfPresent(lltok::kw_nsw)) {
2607 if (EatIfPresent(lltok::kw_nuw))
2610 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2611 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2612 if (EatIfPresent(lltok::kw_exact))
2615 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2616 ParseGlobalTypeAndValue(Val0) ||
2617 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2618 ParseGlobalTypeAndValue(Val1) ||
2619 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2621 if (Val0->getType() != Val1->getType())
2622 return Error(ID.Loc, "operands of constexpr must have same type");
2623 if (!Val0->getType()->isIntOrIntVectorTy()) {
2625 return Error(ModifierLoc, "nuw only applies to integer operations");
2627 return Error(ModifierLoc, "nsw only applies to integer operations");
2629 // Check that the type is valid for the operator.
2631 case Instruction::Add:
2632 case Instruction::Sub:
2633 case Instruction::Mul:
2634 case Instruction::UDiv:
2635 case Instruction::SDiv:
2636 case Instruction::URem:
2637 case Instruction::SRem:
2638 case Instruction::Shl:
2639 case Instruction::AShr:
2640 case Instruction::LShr:
2641 if (!Val0->getType()->isIntOrIntVectorTy())
2642 return Error(ID.Loc, "constexpr requires integer operands");
2644 case Instruction::FAdd:
2645 case Instruction::FSub:
2646 case Instruction::FMul:
2647 case Instruction::FDiv:
2648 case Instruction::FRem:
2649 if (!Val0->getType()->isFPOrFPVectorTy())
2650 return Error(ID.Loc, "constexpr requires fp operands");
2652 default: llvm_unreachable("Unknown binary operator!");
2655 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2656 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2657 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2658 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2660 ID.Kind = ValID::t_Constant;
2664 // Logical Operations
2667 case lltok::kw_xor: {
2668 unsigned Opc = Lex.getUIntVal();
2669 Constant *Val0, *Val1;
2671 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2672 ParseGlobalTypeAndValue(Val0) ||
2673 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2674 ParseGlobalTypeAndValue(Val1) ||
2675 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2677 if (Val0->getType() != Val1->getType())
2678 return Error(ID.Loc, "operands of constexpr must have same type");
2679 if (!Val0->getType()->isIntOrIntVectorTy())
2680 return Error(ID.Loc,
2681 "constexpr requires integer or integer vector operands");
2682 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2683 ID.Kind = ValID::t_Constant;
2687 case lltok::kw_getelementptr:
2688 case lltok::kw_shufflevector:
2689 case lltok::kw_insertelement:
2690 case lltok::kw_extractelement:
2691 case lltok::kw_select: {
2692 unsigned Opc = Lex.getUIntVal();
2693 SmallVector<Constant*, 16> Elts;
2694 bool InBounds = false;
2696 if (Opc == Instruction::GetElementPtr)
2697 InBounds = EatIfPresent(lltok::kw_inbounds);
2698 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2699 ParseGlobalValueVector(Elts) ||
2700 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2703 if (Opc == Instruction::GetElementPtr) {
2704 if (Elts.size() == 0 ||
2705 !Elts[0]->getType()->getScalarType()->isPointerTy())
2706 return Error(ID.Loc, "getelementptr requires pointer operand");
2708 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2709 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2710 return Error(ID.Loc, "invalid indices for getelementptr");
2711 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2713 } else if (Opc == Instruction::Select) {
2714 if (Elts.size() != 3)
2715 return Error(ID.Loc, "expected three operands to select");
2716 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2718 return Error(ID.Loc, Reason);
2719 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2720 } else if (Opc == Instruction::ShuffleVector) {
2721 if (Elts.size() != 3)
2722 return Error(ID.Loc, "expected three operands to shufflevector");
2723 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2724 return Error(ID.Loc, "invalid operands to shufflevector");
2726 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2727 } else if (Opc == Instruction::ExtractElement) {
2728 if (Elts.size() != 2)
2729 return Error(ID.Loc, "expected two operands to extractelement");
2730 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2731 return Error(ID.Loc, "invalid extractelement operands");
2732 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2734 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2735 if (Elts.size() != 3)
2736 return Error(ID.Loc, "expected three operands to insertelement");
2737 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2738 return Error(ID.Loc, "invalid insertelement operands");
2740 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2743 ID.Kind = ValID::t_Constant;
2752 /// ParseGlobalValue - Parse a global value with the specified type.
2753 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2757 bool Parsed = ParseValID(ID) ||
2758 ConvertValIDToValue(Ty, ID, V, nullptr);
2759 if (V && !(C = dyn_cast<Constant>(V)))
2760 return Error(ID.Loc, "global values must be constants");
2764 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2766 return ParseType(Ty) ||
2767 ParseGlobalValue(Ty, V);
2770 /// ParseGlobalValueVector
2772 /// ::= TypeAndValue (',' TypeAndValue)*
2773 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2775 if (Lex.getKind() == lltok::rbrace ||
2776 Lex.getKind() == lltok::rsquare ||
2777 Lex.getKind() == lltok::greater ||
2778 Lex.getKind() == lltok::rparen)
2782 if (ParseGlobalTypeAndValue(C)) return true;
2785 while (EatIfPresent(lltok::comma)) {
2786 if (ParseGlobalTypeAndValue(C)) return true;
2793 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2794 assert(Lex.getKind() == lltok::lbrace);
2797 SmallVector<Value*, 16> Elts;
2798 if (ParseMDNodeVector(Elts, PFS) ||
2799 ParseToken(lltok::rbrace, "expected end of metadata node"))
2802 ID.MDNodeVal = MDNode::get(Context, Elts);
2803 ID.Kind = ValID::t_MDNode;
2807 /// ParseMetadataValue
2811 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2812 assert(Lex.getKind() == lltok::exclaim);
2817 if (Lex.getKind() == lltok::lbrace)
2818 return ParseMetadataListValue(ID, PFS);
2820 // Standalone metadata reference
2822 if (Lex.getKind() == lltok::APSInt) {
2823 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2824 ID.Kind = ValID::t_MDNode;
2829 // ::= '!' STRINGCONSTANT
2830 if (ParseMDString(ID.MDStringVal)) return true;
2831 ID.Kind = ValID::t_MDString;
2836 //===----------------------------------------------------------------------===//
2837 // Function Parsing.
2838 //===----------------------------------------------------------------------===//
2840 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2841 PerFunctionState *PFS) {
2842 if (Ty->isFunctionTy())
2843 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2846 case ValID::t_LocalID:
2847 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2848 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2849 return V == nullptr;
2850 case ValID::t_LocalName:
2851 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2852 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2853 return V == nullptr;
2854 case ValID::t_InlineAsm: {
2855 PointerType *PTy = dyn_cast<PointerType>(Ty);
2857 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2858 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2859 return Error(ID.Loc, "invalid type for inline asm constraint string");
2860 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2861 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2864 case ValID::t_MDNode:
2865 if (!Ty->isMetadataTy())
2866 return Error(ID.Loc, "metadata value must have metadata type");
2869 case ValID::t_MDString:
2870 if (!Ty->isMetadataTy())
2871 return Error(ID.Loc, "metadata value must have metadata type");
2874 case ValID::t_GlobalName:
2875 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2876 return V == nullptr;
2877 case ValID::t_GlobalID:
2878 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2879 return V == nullptr;
2880 case ValID::t_APSInt:
2881 if (!Ty->isIntegerTy())
2882 return Error(ID.Loc, "integer constant must have integer type");
2883 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2884 V = ConstantInt::get(Context, ID.APSIntVal);
2886 case ValID::t_APFloat:
2887 if (!Ty->isFloatingPointTy() ||
2888 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2889 return Error(ID.Loc, "floating point constant invalid for type");
2891 // The lexer has no type info, so builds all half, float, and double FP
2892 // constants as double. Fix this here. Long double does not need this.
2893 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2896 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2898 else if (Ty->isFloatTy())
2899 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2902 V = ConstantFP::get(Context, ID.APFloatVal);
2904 if (V->getType() != Ty)
2905 return Error(ID.Loc, "floating point constant does not have type '" +
2906 getTypeString(Ty) + "'");
2910 if (!Ty->isPointerTy())
2911 return Error(ID.Loc, "null must be a pointer type");
2912 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2914 case ValID::t_Undef:
2915 // FIXME: LabelTy should not be a first-class type.
2916 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2917 return Error(ID.Loc, "invalid type for undef constant");
2918 V = UndefValue::get(Ty);
2920 case ValID::t_EmptyArray:
2921 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2922 return Error(ID.Loc, "invalid empty array initializer");
2923 V = UndefValue::get(Ty);
2926 // FIXME: LabelTy should not be a first-class type.
2927 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2928 return Error(ID.Loc, "invalid type for null constant");
2929 V = Constant::getNullValue(Ty);
2931 case ValID::t_Constant:
2932 if (ID.ConstantVal->getType() != Ty)
2933 return Error(ID.Loc, "constant expression type mismatch");
2937 case ValID::t_ConstantStruct:
2938 case ValID::t_PackedConstantStruct:
2939 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2940 if (ST->getNumElements() != ID.UIntVal)
2941 return Error(ID.Loc,
2942 "initializer with struct type has wrong # elements");
2943 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2944 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2946 // Verify that the elements are compatible with the structtype.
2947 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2948 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2949 return Error(ID.Loc, "element " + Twine(i) +
2950 " of struct initializer doesn't match struct element type");
2952 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2955 return Error(ID.Loc, "constant expression type mismatch");
2958 llvm_unreachable("Invalid ValID");
2961 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2964 return ParseValID(ID, PFS) ||
2965 ConvertValIDToValue(Ty, ID, V, PFS);
2968 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2970 return ParseType(Ty) ||
2971 ParseValue(Ty, V, PFS);
2974 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2975 PerFunctionState &PFS) {
2978 if (ParseTypeAndValue(V, PFS)) return true;
2979 if (!isa<BasicBlock>(V))
2980 return Error(Loc, "expected a basic block");
2981 BB = cast<BasicBlock>(V);
2987 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2988 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2989 /// OptionalAlign OptGC OptionalPrefix
2990 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2991 // Parse the linkage.
2992 LocTy LinkageLoc = Lex.getLoc();
2995 unsigned Visibility;
2996 unsigned DLLStorageClass;
2997 AttrBuilder RetAttrs;
2999 Type *RetType = nullptr;
3000 LocTy RetTypeLoc = Lex.getLoc();
3001 if (ParseOptionalLinkage(Linkage) ||
3002 ParseOptionalVisibility(Visibility) ||
3003 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3004 ParseOptionalCallingConv(CC) ||
3005 ParseOptionalReturnAttrs(RetAttrs) ||
3006 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3009 // Verify that the linkage is ok.
3010 switch ((GlobalValue::LinkageTypes)Linkage) {
3011 case GlobalValue::ExternalLinkage:
3012 break; // always ok.
3013 case GlobalValue::ExternalWeakLinkage:
3015 return Error(LinkageLoc, "invalid linkage for function definition");
3017 case GlobalValue::PrivateLinkage:
3018 case GlobalValue::InternalLinkage:
3019 case GlobalValue::AvailableExternallyLinkage:
3020 case GlobalValue::LinkOnceAnyLinkage:
3021 case GlobalValue::LinkOnceODRLinkage:
3022 case GlobalValue::WeakAnyLinkage:
3023 case GlobalValue::WeakODRLinkage:
3025 return Error(LinkageLoc, "invalid linkage for function declaration");
3027 case GlobalValue::AppendingLinkage:
3028 case GlobalValue::CommonLinkage:
3029 return Error(LinkageLoc, "invalid function linkage type");
3032 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3033 return Error(LinkageLoc,
3034 "symbol with local linkage must have default visibility");
3036 if (!FunctionType::isValidReturnType(RetType))
3037 return Error(RetTypeLoc, "invalid function return type");
3039 LocTy NameLoc = Lex.getLoc();
3041 std::string FunctionName;
3042 if (Lex.getKind() == lltok::GlobalVar) {
3043 FunctionName = Lex.getStrVal();
3044 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3045 unsigned NameID = Lex.getUIntVal();
3047 if (NameID != NumberedVals.size())
3048 return TokError("function expected to be numbered '%" +
3049 Twine(NumberedVals.size()) + "'");
3051 return TokError("expected function name");
3056 if (Lex.getKind() != lltok::lparen)
3057 return TokError("expected '(' in function argument list");
3059 SmallVector<ArgInfo, 8> ArgList;
3061 AttrBuilder FuncAttrs;
3062 std::vector<unsigned> FwdRefAttrGrps;
3064 std::string Section;
3068 LocTy UnnamedAddrLoc;
3069 Constant *Prefix = nullptr;
3071 if (ParseArgumentList(ArgList, isVarArg) ||
3072 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3074 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3076 (EatIfPresent(lltok::kw_section) &&
3077 ParseStringConstant(Section)) ||
3078 ParseOptionalAlignment(Alignment) ||
3079 (EatIfPresent(lltok::kw_gc) &&
3080 ParseStringConstant(GC)) ||
3081 (EatIfPresent(lltok::kw_prefix) &&
3082 ParseGlobalTypeAndValue(Prefix)))
3085 if (FuncAttrs.contains(Attribute::Builtin))
3086 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3088 // If the alignment was parsed as an attribute, move to the alignment field.
3089 if (FuncAttrs.hasAlignmentAttr()) {
3090 Alignment = FuncAttrs.getAlignment();
3091 FuncAttrs.removeAttribute(Attribute::Alignment);
3094 // Okay, if we got here, the function is syntactically valid. Convert types
3095 // and do semantic checks.
3096 std::vector<Type*> ParamTypeList;
3097 SmallVector<AttributeSet, 8> Attrs;
3099 if (RetAttrs.hasAttributes())
3100 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3101 AttributeSet::ReturnIndex,
3104 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3105 ParamTypeList.push_back(ArgList[i].Ty);
3106 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3107 AttrBuilder B(ArgList[i].Attrs, i + 1);
3108 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3112 if (FuncAttrs.hasAttributes())
3113 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3114 AttributeSet::FunctionIndex,
3117 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3119 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3120 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3123 FunctionType::get(RetType, ParamTypeList, isVarArg);
3124 PointerType *PFT = PointerType::getUnqual(FT);
3127 if (!FunctionName.empty()) {
3128 // If this was a definition of a forward reference, remove the definition
3129 // from the forward reference table and fill in the forward ref.
3130 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3131 ForwardRefVals.find(FunctionName);
3132 if (FRVI != ForwardRefVals.end()) {
3133 Fn = M->getFunction(FunctionName);
3135 return Error(FRVI->second.second, "invalid forward reference to "
3136 "function as global value!");
3137 if (Fn->getType() != PFT)
3138 return Error(FRVI->second.second, "invalid forward reference to "
3139 "function '" + FunctionName + "' with wrong type!");
3141 ForwardRefVals.erase(FRVI);
3142 } else if ((Fn = M->getFunction(FunctionName))) {
3143 // Reject redefinitions.
3144 return Error(NameLoc, "invalid redefinition of function '" +
3145 FunctionName + "'");
3146 } else if (M->getNamedValue(FunctionName)) {
3147 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3151 // If this is a definition of a forward referenced function, make sure the
3153 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3154 = ForwardRefValIDs.find(NumberedVals.size());
3155 if (I != ForwardRefValIDs.end()) {
3156 Fn = cast<Function>(I->second.first);
3157 if (Fn->getType() != PFT)
3158 return Error(NameLoc, "type of definition and forward reference of '@" +
3159 Twine(NumberedVals.size()) + "' disagree");
3160 ForwardRefValIDs.erase(I);
3165 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3166 else // Move the forward-reference to the correct spot in the module.
3167 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3169 if (FunctionName.empty())
3170 NumberedVals.push_back(Fn);
3172 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3173 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3174 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3175 Fn->setCallingConv(CC);
3176 Fn->setAttributes(PAL);
3177 Fn->setUnnamedAddr(UnnamedAddr);
3178 Fn->setAlignment(Alignment);
3179 Fn->setSection(Section);
3180 if (!GC.empty()) Fn->setGC(GC.c_str());
3181 Fn->setPrefixData(Prefix);
3182 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3184 // Add all of the arguments we parsed to the function.
3185 Function::arg_iterator ArgIt = Fn->arg_begin();
3186 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3187 // If the argument has a name, insert it into the argument symbol table.
3188 if (ArgList[i].Name.empty()) continue;
3190 // Set the name, if it conflicted, it will be auto-renamed.
3191 ArgIt->setName(ArgList[i].Name);
3193 if (ArgIt->getName() != ArgList[i].Name)
3194 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3195 ArgList[i].Name + "'");
3202 /// ParseFunctionBody
3203 /// ::= '{' BasicBlock+ '}'
3205 bool LLParser::ParseFunctionBody(Function &Fn) {
3206 if (Lex.getKind() != lltok::lbrace)
3207 return TokError("expected '{' in function body");
3208 Lex.Lex(); // eat the {.
3210 int FunctionNumber = -1;
3211 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3213 PerFunctionState PFS(*this, Fn, FunctionNumber);
3215 // We need at least one basic block.
3216 if (Lex.getKind() == lltok::rbrace)
3217 return TokError("function body requires at least one basic block");
3219 while (Lex.getKind() != lltok::rbrace)
3220 if (ParseBasicBlock(PFS)) return true;
3225 // Verify function is ok.
3226 return PFS.FinishFunction();
3230 /// ::= LabelStr? Instruction*
3231 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3232 // If this basic block starts out with a name, remember it.
3234 LocTy NameLoc = Lex.getLoc();
3235 if (Lex.getKind() == lltok::LabelStr) {
3236 Name = Lex.getStrVal();
3240 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3241 if (!BB) return true;
3243 std::string NameStr;
3245 // Parse the instructions in this block until we get a terminator.
3248 // This instruction may have three possibilities for a name: a) none
3249 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3250 LocTy NameLoc = Lex.getLoc();
3254 if (Lex.getKind() == lltok::LocalVarID) {
3255 NameID = Lex.getUIntVal();
3257 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3259 } else if (Lex.getKind() == lltok::LocalVar) {
3260 NameStr = Lex.getStrVal();
3262 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3266 switch (ParseInstruction(Inst, BB, PFS)) {
3267 default: llvm_unreachable("Unknown ParseInstruction result!");
3268 case InstError: return true;
3270 BB->getInstList().push_back(Inst);
3272 // With a normal result, we check to see if the instruction is followed by
3273 // a comma and metadata.
3274 if (EatIfPresent(lltok::comma))
3275 if (ParseInstructionMetadata(Inst, &PFS))
3278 case InstExtraComma:
3279 BB->getInstList().push_back(Inst);
3281 // If the instruction parser ate an extra comma at the end of it, it
3282 // *must* be followed by metadata.
3283 if (ParseInstructionMetadata(Inst, &PFS))
3288 // Set the name on the instruction.
3289 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3290 } while (!isa<TerminatorInst>(Inst));
3295 //===----------------------------------------------------------------------===//
3296 // Instruction Parsing.
3297 //===----------------------------------------------------------------------===//
3299 /// ParseInstruction - Parse one of the many different instructions.
3301 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3302 PerFunctionState &PFS) {
3303 lltok::Kind Token = Lex.getKind();
3304 if (Token == lltok::Eof)
3305 return TokError("found end of file when expecting more instructions");
3306 LocTy Loc = Lex.getLoc();
3307 unsigned KeywordVal = Lex.getUIntVal();
3308 Lex.Lex(); // Eat the keyword.
3311 default: return Error(Loc, "expected instruction opcode");
3312 // Terminator Instructions.
3313 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3314 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3315 case lltok::kw_br: return ParseBr(Inst, PFS);
3316 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3317 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3318 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3319 case lltok::kw_resume: return ParseResume(Inst, PFS);
3320 // Binary Operators.
3324 case lltok::kw_shl: {
3325 bool NUW = EatIfPresent(lltok::kw_nuw);
3326 bool NSW = EatIfPresent(lltok::kw_nsw);
3327 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3329 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3331 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3332 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3335 case lltok::kw_fadd:
3336 case lltok::kw_fsub:
3337 case lltok::kw_fmul:
3338 case lltok::kw_fdiv:
3339 case lltok::kw_frem: {
3340 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3341 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3345 Inst->setFastMathFlags(FMF);
3349 case lltok::kw_sdiv:
3350 case lltok::kw_udiv:
3351 case lltok::kw_lshr:
3352 case lltok::kw_ashr: {
3353 bool Exact = EatIfPresent(lltok::kw_exact);
3355 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3356 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3360 case lltok::kw_urem:
3361 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3364 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3365 case lltok::kw_icmp:
3366 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3368 case lltok::kw_trunc:
3369 case lltok::kw_zext:
3370 case lltok::kw_sext:
3371 case lltok::kw_fptrunc:
3372 case lltok::kw_fpext:
3373 case lltok::kw_bitcast:
3374 case lltok::kw_addrspacecast:
3375 case lltok::kw_uitofp:
3376 case lltok::kw_sitofp:
3377 case lltok::kw_fptoui:
3378 case lltok::kw_fptosi:
3379 case lltok::kw_inttoptr:
3380 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3382 case lltok::kw_select: return ParseSelect(Inst, PFS);
3383 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3384 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3385 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3386 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3387 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3388 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3390 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3391 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3392 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3394 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3395 case lltok::kw_load: return ParseLoad(Inst, PFS);
3396 case lltok::kw_store: return ParseStore(Inst, PFS);
3397 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3398 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3399 case lltok::kw_fence: return ParseFence(Inst, PFS);
3400 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3401 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3402 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3406 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3407 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3408 if (Opc == Instruction::FCmp) {
3409 switch (Lex.getKind()) {
3410 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3411 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3412 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3413 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3414 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3415 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3416 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3417 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3418 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3419 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3420 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3421 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3422 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3423 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3424 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3425 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3426 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3429 switch (Lex.getKind()) {
3430 default: return TokError("expected icmp predicate (e.g. 'eq')");
3431 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3432 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3433 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3434 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3435 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3436 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3437 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3438 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3439 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3440 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3447 //===----------------------------------------------------------------------===//
3448 // Terminator Instructions.
3449 //===----------------------------------------------------------------------===//
3451 /// ParseRet - Parse a return instruction.
3452 /// ::= 'ret' void (',' !dbg, !1)*
3453 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3454 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3455 PerFunctionState &PFS) {
3456 SMLoc TypeLoc = Lex.getLoc();
3458 if (ParseType(Ty, true /*void allowed*/)) return true;
3460 Type *ResType = PFS.getFunction().getReturnType();
3462 if (Ty->isVoidTy()) {
3463 if (!ResType->isVoidTy())
3464 return Error(TypeLoc, "value doesn't match function result type '" +
3465 getTypeString(ResType) + "'");
3467 Inst = ReturnInst::Create(Context);
3472 if (ParseValue(Ty, RV, PFS)) return true;
3474 if (ResType != RV->getType())
3475 return Error(TypeLoc, "value doesn't match function result type '" +
3476 getTypeString(ResType) + "'");
3478 Inst = ReturnInst::Create(Context, RV);
3484 /// ::= 'br' TypeAndValue
3485 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3486 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3489 BasicBlock *Op1, *Op2;
3490 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3492 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3493 Inst = BranchInst::Create(BB);
3497 if (Op0->getType() != Type::getInt1Ty(Context))
3498 return Error(Loc, "branch condition must have 'i1' type");
3500 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3501 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3502 ParseToken(lltok::comma, "expected ',' after true destination") ||
3503 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3506 Inst = BranchInst::Create(Op1, Op2, Op0);
3512 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3514 /// ::= (TypeAndValue ',' TypeAndValue)*
3515 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3516 LocTy CondLoc, BBLoc;
3518 BasicBlock *DefaultBB;
3519 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3520 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3521 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3522 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3525 if (!Cond->getType()->isIntegerTy())
3526 return Error(CondLoc, "switch condition must have integer type");
3528 // Parse the jump table pairs.
3529 SmallPtrSet<Value*, 32> SeenCases;
3530 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3531 while (Lex.getKind() != lltok::rsquare) {
3535 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3536 ParseToken(lltok::comma, "expected ',' after case value") ||
3537 ParseTypeAndBasicBlock(DestBB, PFS))
3540 if (!SeenCases.insert(Constant))
3541 return Error(CondLoc, "duplicate case value in switch");
3542 if (!isa<ConstantInt>(Constant))
3543 return Error(CondLoc, "case value is not a constant integer");
3545 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3548 Lex.Lex(); // Eat the ']'.
3550 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3551 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3552 SI->addCase(Table[i].first, Table[i].second);
3559 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3560 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3563 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3564 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3565 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3568 if (!Address->getType()->isPointerTy())
3569 return Error(AddrLoc, "indirectbr address must have pointer type");
3571 // Parse the destination list.
3572 SmallVector<BasicBlock*, 16> DestList;
3574 if (Lex.getKind() != lltok::rsquare) {
3576 if (ParseTypeAndBasicBlock(DestBB, PFS))
3578 DestList.push_back(DestBB);
3580 while (EatIfPresent(lltok::comma)) {
3581 if (ParseTypeAndBasicBlock(DestBB, PFS))
3583 DestList.push_back(DestBB);
3587 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3590 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3591 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3592 IBI->addDestination(DestList[i]);
3599 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3600 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3601 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3602 LocTy CallLoc = Lex.getLoc();
3603 AttrBuilder RetAttrs, FnAttrs;
3604 std::vector<unsigned> FwdRefAttrGrps;
3607 Type *RetType = nullptr;
3610 SmallVector<ParamInfo, 16> ArgList;
3612 BasicBlock *NormalBB, *UnwindBB;
3613 if (ParseOptionalCallingConv(CC) ||
3614 ParseOptionalReturnAttrs(RetAttrs) ||
3615 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3616 ParseValID(CalleeID) ||
3617 ParseParameterList(ArgList, PFS) ||
3618 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3620 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3621 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3622 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3623 ParseTypeAndBasicBlock(UnwindBB, PFS))
3626 // If RetType is a non-function pointer type, then this is the short syntax
3627 // for the call, which means that RetType is just the return type. Infer the
3628 // rest of the function argument types from the arguments that are present.
3629 PointerType *PFTy = nullptr;
3630 FunctionType *Ty = nullptr;
3631 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3632 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3633 // Pull out the types of all of the arguments...
3634 std::vector<Type*> ParamTypes;
3635 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3636 ParamTypes.push_back(ArgList[i].V->getType());
3638 if (!FunctionType::isValidReturnType(RetType))
3639 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3641 Ty = FunctionType::get(RetType, ParamTypes, false);
3642 PFTy = PointerType::getUnqual(Ty);
3645 // Look up the callee.
3647 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3649 // Set up the Attribute for the function.
3650 SmallVector<AttributeSet, 8> Attrs;
3651 if (RetAttrs.hasAttributes())
3652 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3653 AttributeSet::ReturnIndex,
3656 SmallVector<Value*, 8> Args;
3658 // Loop through FunctionType's arguments and ensure they are specified
3659 // correctly. Also, gather any parameter attributes.
3660 FunctionType::param_iterator I = Ty->param_begin();
3661 FunctionType::param_iterator E = Ty->param_end();
3662 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3663 Type *ExpectedTy = nullptr;
3666 } else if (!Ty->isVarArg()) {
3667 return Error(ArgList[i].Loc, "too many arguments specified");
3670 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3671 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3672 getTypeString(ExpectedTy) + "'");
3673 Args.push_back(ArgList[i].V);
3674 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3675 AttrBuilder B(ArgList[i].Attrs, i + 1);
3676 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3681 return Error(CallLoc, "not enough parameters specified for call");
3683 if (FnAttrs.hasAttributes())
3684 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3685 AttributeSet::FunctionIndex,
3688 // Finish off the Attribute and check them
3689 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3691 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3692 II->setCallingConv(CC);
3693 II->setAttributes(PAL);
3694 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3700 /// ::= 'resume' TypeAndValue
3701 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3702 Value *Exn; LocTy ExnLoc;
3703 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3706 ResumeInst *RI = ResumeInst::Create(Exn);
3711 //===----------------------------------------------------------------------===//
3712 // Binary Operators.
3713 //===----------------------------------------------------------------------===//
3716 /// ::= ArithmeticOps TypeAndValue ',' Value
3718 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3719 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3720 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3721 unsigned Opc, unsigned OperandType) {
3722 LocTy Loc; Value *LHS, *RHS;
3723 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3724 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3725 ParseValue(LHS->getType(), RHS, PFS))
3729 switch (OperandType) {
3730 default: llvm_unreachable("Unknown operand type!");
3731 case 0: // int or FP.
3732 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3733 LHS->getType()->isFPOrFPVectorTy();
3735 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3736 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3740 return Error(Loc, "invalid operand type for instruction");
3742 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3747 /// ::= ArithmeticOps TypeAndValue ',' Value {
3748 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3750 LocTy Loc; Value *LHS, *RHS;
3751 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3752 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3753 ParseValue(LHS->getType(), RHS, PFS))
3756 if (!LHS->getType()->isIntOrIntVectorTy())
3757 return Error(Loc,"instruction requires integer or integer vector operands");
3759 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3765 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3766 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3767 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3769 // Parse the integer/fp comparison predicate.
3773 if (ParseCmpPredicate(Pred, Opc) ||
3774 ParseTypeAndValue(LHS, Loc, PFS) ||
3775 ParseToken(lltok::comma, "expected ',' after compare value") ||
3776 ParseValue(LHS->getType(), RHS, PFS))
3779 if (Opc == Instruction::FCmp) {
3780 if (!LHS->getType()->isFPOrFPVectorTy())
3781 return Error(Loc, "fcmp requires floating point operands");
3782 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3784 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3785 if (!LHS->getType()->isIntOrIntVectorTy() &&
3786 !LHS->getType()->getScalarType()->isPointerTy())
3787 return Error(Loc, "icmp requires integer operands");
3788 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3793 //===----------------------------------------------------------------------===//
3794 // Other Instructions.
3795 //===----------------------------------------------------------------------===//
3799 /// ::= CastOpc TypeAndValue 'to' Type
3800 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3804 Type *DestTy = nullptr;
3805 if (ParseTypeAndValue(Op, Loc, PFS) ||
3806 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3810 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3811 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3812 return Error(Loc, "invalid cast opcode for cast from '" +
3813 getTypeString(Op->getType()) + "' to '" +
3814 getTypeString(DestTy) + "'");
3816 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3821 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3822 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3824 Value *Op0, *Op1, *Op2;
3825 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3826 ParseToken(lltok::comma, "expected ',' after select condition") ||
3827 ParseTypeAndValue(Op1, PFS) ||
3828 ParseToken(lltok::comma, "expected ',' after select value") ||
3829 ParseTypeAndValue(Op2, PFS))
3832 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3833 return Error(Loc, Reason);
3835 Inst = SelectInst::Create(Op0, Op1, Op2);
3840 /// ::= 'va_arg' TypeAndValue ',' Type
3841 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3843 Type *EltTy = nullptr;
3845 if (ParseTypeAndValue(Op, PFS) ||
3846 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3847 ParseType(EltTy, TypeLoc))
3850 if (!EltTy->isFirstClassType())
3851 return Error(TypeLoc, "va_arg requires operand with first class type");
3853 Inst = new VAArgInst(Op, EltTy);
3857 /// ParseExtractElement
3858 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3859 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3862 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3863 ParseToken(lltok::comma, "expected ',' after extract value") ||
3864 ParseTypeAndValue(Op1, PFS))
3867 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3868 return Error(Loc, "invalid extractelement operands");
3870 Inst = ExtractElementInst::Create(Op0, Op1);
3874 /// ParseInsertElement
3875 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3876 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3878 Value *Op0, *Op1, *Op2;
3879 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3880 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3881 ParseTypeAndValue(Op1, PFS) ||
3882 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3883 ParseTypeAndValue(Op2, PFS))
3886 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3887 return Error(Loc, "invalid insertelement operands");
3889 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3893 /// ParseShuffleVector
3894 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3895 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3897 Value *Op0, *Op1, *Op2;
3898 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3899 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3900 ParseTypeAndValue(Op1, PFS) ||
3901 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3902 ParseTypeAndValue(Op2, PFS))
3905 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3906 return Error(Loc, "invalid shufflevector operands");
3908 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3913 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3914 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3915 Type *Ty = nullptr; LocTy TypeLoc;
3918 if (ParseType(Ty, TypeLoc) ||
3919 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3920 ParseValue(Ty, Op0, PFS) ||
3921 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3922 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3923 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3926 bool AteExtraComma = false;
3927 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3929 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3931 if (!EatIfPresent(lltok::comma))
3934 if (Lex.getKind() == lltok::MetadataVar) {
3935 AteExtraComma = true;
3939 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3940 ParseValue(Ty, Op0, PFS) ||
3941 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3942 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3943 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3947 if (!Ty->isFirstClassType())
3948 return Error(TypeLoc, "phi node must have first class type");
3950 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3951 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3952 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3954 return AteExtraComma ? InstExtraComma : InstNormal;
3958 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3960 /// ::= 'catch' TypeAndValue
3962 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3963 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3964 Type *Ty = nullptr; LocTy TyLoc;
3965 Value *PersFn; LocTy PersFnLoc;
3967 if (ParseType(Ty, TyLoc) ||
3968 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3969 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3972 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3973 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3975 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3976 LandingPadInst::ClauseType CT;
3977 if (EatIfPresent(lltok::kw_catch))
3978 CT = LandingPadInst::Catch;
3979 else if (EatIfPresent(lltok::kw_filter))
3980 CT = LandingPadInst::Filter;
3982 return TokError("expected 'catch' or 'filter' clause type");
3984 Value *V; LocTy VLoc;
3985 if (ParseTypeAndValue(V, VLoc, PFS)) {
3990 // A 'catch' type expects a non-array constant. A filter clause expects an
3992 if (CT == LandingPadInst::Catch) {
3993 if (isa<ArrayType>(V->getType()))
3994 Error(VLoc, "'catch' clause has an invalid type");
3996 if (!isa<ArrayType>(V->getType()))
3997 Error(VLoc, "'filter' clause has an invalid type");
4008 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4009 /// ParameterList OptionalAttrs
4010 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4011 /// ParameterList OptionalAttrs
4012 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4013 /// ParameterList OptionalAttrs
4014 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4015 CallInst::TailCallKind TCK) {
4016 AttrBuilder RetAttrs, FnAttrs;
4017 std::vector<unsigned> FwdRefAttrGrps;
4020 Type *RetType = nullptr;
4023 SmallVector<ParamInfo, 16> ArgList;
4024 LocTy CallLoc = Lex.getLoc();
4026 if ((TCK != CallInst::TCK_None &&
4027 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4028 ParseOptionalCallingConv(CC) ||
4029 ParseOptionalReturnAttrs(RetAttrs) ||
4030 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4031 ParseValID(CalleeID) ||
4032 ParseParameterList(ArgList, PFS) ||
4033 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4037 // If RetType is a non-function pointer type, then this is the short syntax
4038 // for the call, which means that RetType is just the return type. Infer the
4039 // rest of the function argument types from the arguments that are present.
4040 PointerType *PFTy = nullptr;
4041 FunctionType *Ty = nullptr;
4042 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4043 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4044 // Pull out the types of all of the arguments...
4045 std::vector<Type*> ParamTypes;
4046 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4047 ParamTypes.push_back(ArgList[i].V->getType());
4049 if (!FunctionType::isValidReturnType(RetType))
4050 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4052 Ty = FunctionType::get(RetType, ParamTypes, false);
4053 PFTy = PointerType::getUnqual(Ty);
4056 // Look up the callee.
4058 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4060 // Set up the Attribute for the function.
4061 SmallVector<AttributeSet, 8> Attrs;
4062 if (RetAttrs.hasAttributes())
4063 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4064 AttributeSet::ReturnIndex,
4067 SmallVector<Value*, 8> Args;
4069 // Loop through FunctionType's arguments and ensure they are specified
4070 // correctly. Also, gather any parameter attributes.
4071 FunctionType::param_iterator I = Ty->param_begin();
4072 FunctionType::param_iterator E = Ty->param_end();
4073 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4074 Type *ExpectedTy = nullptr;
4077 } else if (!Ty->isVarArg()) {
4078 return Error(ArgList[i].Loc, "too many arguments specified");
4081 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4082 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4083 getTypeString(ExpectedTy) + "'");
4084 Args.push_back(ArgList[i].V);
4085 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4086 AttrBuilder B(ArgList[i].Attrs, i + 1);
4087 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4092 return Error(CallLoc, "not enough parameters specified for call");
4094 if (FnAttrs.hasAttributes())
4095 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4096 AttributeSet::FunctionIndex,
4099 // Finish off the Attribute and check them
4100 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4102 CallInst *CI = CallInst::Create(Callee, Args);
4103 CI->setTailCallKind(TCK);
4104 CI->setCallingConv(CC);
4105 CI->setAttributes(PAL);
4106 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4111 //===----------------------------------------------------------------------===//
4112 // Memory Instructions.
4113 //===----------------------------------------------------------------------===//
4116 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4117 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4118 Value *Size = nullptr;
4120 unsigned Alignment = 0;
4123 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4125 if (ParseType(Ty)) return true;
4127 bool AteExtraComma = false;
4128 if (EatIfPresent(lltok::comma)) {
4129 if (Lex.getKind() == lltok::kw_align) {
4130 if (ParseOptionalAlignment(Alignment)) return true;
4131 } else if (Lex.getKind() == lltok::MetadataVar) {
4132 AteExtraComma = true;
4134 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4135 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4140 if (Size && !Size->getType()->isIntegerTy())
4141 return Error(SizeLoc, "element count must have integer type");
4143 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4144 AI->setUsedWithInAlloca(IsInAlloca);
4146 return AteExtraComma ? InstExtraComma : InstNormal;
4150 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4151 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4152 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4153 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4154 Value *Val; LocTy Loc;
4155 unsigned Alignment = 0;
4156 bool AteExtraComma = false;
4157 bool isAtomic = false;
4158 AtomicOrdering Ordering = NotAtomic;
4159 SynchronizationScope Scope = CrossThread;
4161 if (Lex.getKind() == lltok::kw_atomic) {
4166 bool isVolatile = false;
4167 if (Lex.getKind() == lltok::kw_volatile) {
4172 if (ParseTypeAndValue(Val, Loc, PFS) ||
4173 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4174 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4177 if (!Val->getType()->isPointerTy() ||
4178 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4179 return Error(Loc, "load operand must be a pointer to a first class type");
4180 if (isAtomic && !Alignment)
4181 return Error(Loc, "atomic load must have explicit non-zero alignment");
4182 if (Ordering == Release || Ordering == AcquireRelease)
4183 return Error(Loc, "atomic load cannot use Release ordering");
4185 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4186 return AteExtraComma ? InstExtraComma : InstNormal;
4191 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4192 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4193 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4194 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4195 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4196 unsigned Alignment = 0;
4197 bool AteExtraComma = false;
4198 bool isAtomic = false;
4199 AtomicOrdering Ordering = NotAtomic;
4200 SynchronizationScope Scope = CrossThread;
4202 if (Lex.getKind() == lltok::kw_atomic) {
4207 bool isVolatile = false;
4208 if (Lex.getKind() == lltok::kw_volatile) {
4213 if (ParseTypeAndValue(Val, Loc, PFS) ||
4214 ParseToken(lltok::comma, "expected ',' after store operand") ||
4215 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4216 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4217 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4220 if (!Ptr->getType()->isPointerTy())
4221 return Error(PtrLoc, "store operand must be a pointer");
4222 if (!Val->getType()->isFirstClassType())
4223 return Error(Loc, "store operand must be a first class value");
4224 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4225 return Error(Loc, "stored value and pointer type do not match");
4226 if (isAtomic && !Alignment)
4227 return Error(Loc, "atomic store must have explicit non-zero alignment");
4228 if (Ordering == Acquire || Ordering == AcquireRelease)
4229 return Error(Loc, "atomic store cannot use Acquire ordering");
4231 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4232 return AteExtraComma ? InstExtraComma : InstNormal;
4236 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4237 /// 'singlethread'? AtomicOrdering AtomicOrdering
4238 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4239 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4240 bool AteExtraComma = false;
4241 AtomicOrdering SuccessOrdering = NotAtomic;
4242 AtomicOrdering FailureOrdering = NotAtomic;
4243 SynchronizationScope Scope = CrossThread;
4244 bool isVolatile = false;
4246 if (EatIfPresent(lltok::kw_volatile))
4249 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4250 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4251 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4252 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4253 ParseTypeAndValue(New, NewLoc, PFS) ||
4254 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4255 ParseOrdering(FailureOrdering))
4258 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4259 return TokError("cmpxchg cannot be unordered");
4260 if (SuccessOrdering < FailureOrdering)
4261 return TokError("cmpxchg must be at least as ordered on success as failure");
4262 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4263 return TokError("cmpxchg failure ordering cannot include release semantics");
4264 if (!Ptr->getType()->isPointerTy())
4265 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4266 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4267 return Error(CmpLoc, "compare value and pointer type do not match");
4268 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4269 return Error(NewLoc, "new value and pointer type do not match");
4270 if (!New->getType()->isIntegerTy())
4271 return Error(NewLoc, "cmpxchg operand must be an integer");
4272 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4273 if (Size < 8 || (Size & (Size - 1)))
4274 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4277 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4278 FailureOrdering, Scope);
4279 CXI->setVolatile(isVolatile);
4281 return AteExtraComma ? InstExtraComma : InstNormal;
4285 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4286 /// 'singlethread'? AtomicOrdering
4287 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4288 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4289 bool AteExtraComma = false;
4290 AtomicOrdering Ordering = NotAtomic;
4291 SynchronizationScope Scope = CrossThread;
4292 bool isVolatile = false;
4293 AtomicRMWInst::BinOp Operation;
4295 if (EatIfPresent(lltok::kw_volatile))
4298 switch (Lex.getKind()) {
4299 default: return TokError("expected binary operation in atomicrmw");
4300 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4301 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4302 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4303 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4304 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4305 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4306 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4307 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4308 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4309 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4310 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4312 Lex.Lex(); // Eat the operation.
4314 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4315 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4316 ParseTypeAndValue(Val, ValLoc, PFS) ||
4317 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4320 if (Ordering == Unordered)
4321 return TokError("atomicrmw cannot be unordered");
4322 if (!Ptr->getType()->isPointerTy())
4323 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4324 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4325 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4326 if (!Val->getType()->isIntegerTy())
4327 return Error(ValLoc, "atomicrmw operand must be an integer");
4328 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4329 if (Size < 8 || (Size & (Size - 1)))
4330 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4333 AtomicRMWInst *RMWI =
4334 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4335 RMWI->setVolatile(isVolatile);
4337 return AteExtraComma ? InstExtraComma : InstNormal;
4341 /// ::= 'fence' 'singlethread'? AtomicOrdering
4342 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4343 AtomicOrdering Ordering = NotAtomic;
4344 SynchronizationScope Scope = CrossThread;
4345 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4348 if (Ordering == Unordered)
4349 return TokError("fence cannot be unordered");
4350 if (Ordering == Monotonic)
4351 return TokError("fence cannot be monotonic");
4353 Inst = new FenceInst(Context, Ordering, Scope);
4357 /// ParseGetElementPtr
4358 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4359 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4360 Value *Ptr = nullptr;
4361 Value *Val = nullptr;
4364 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4366 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4368 Type *BaseType = Ptr->getType();
4369 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4370 if (!BasePointerType)
4371 return Error(Loc, "base of getelementptr must be a pointer");
4373 SmallVector<Value*, 16> Indices;
4374 bool AteExtraComma = false;
4375 while (EatIfPresent(lltok::comma)) {
4376 if (Lex.getKind() == lltok::MetadataVar) {
4377 AteExtraComma = true;
4380 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4381 if (!Val->getType()->getScalarType()->isIntegerTy())
4382 return Error(EltLoc, "getelementptr index must be an integer");
4383 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4384 return Error(EltLoc, "getelementptr index type missmatch");
4385 if (Val->getType()->isVectorTy()) {
4386 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4387 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4388 if (ValNumEl != PtrNumEl)
4389 return Error(EltLoc,
4390 "getelementptr vector index has a wrong number of elements");
4392 Indices.push_back(Val);
4395 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4396 return Error(Loc, "base element of getelementptr must be sized");
4398 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4399 return Error(Loc, "invalid getelementptr indices");
4400 Inst = GetElementPtrInst::Create(Ptr, Indices);
4402 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4403 return AteExtraComma ? InstExtraComma : InstNormal;
4406 /// ParseExtractValue
4407 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4408 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4409 Value *Val; LocTy Loc;
4410 SmallVector<unsigned, 4> Indices;
4412 if (ParseTypeAndValue(Val, Loc, PFS) ||
4413 ParseIndexList(Indices, AteExtraComma))
4416 if (!Val->getType()->isAggregateType())
4417 return Error(Loc, "extractvalue operand must be aggregate type");
4419 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4420 return Error(Loc, "invalid indices for extractvalue");
4421 Inst = ExtractValueInst::Create(Val, Indices);
4422 return AteExtraComma ? InstExtraComma : InstNormal;
4425 /// ParseInsertValue
4426 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4427 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4428 Value *Val0, *Val1; LocTy Loc0, Loc1;
4429 SmallVector<unsigned, 4> Indices;
4431 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4432 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4433 ParseTypeAndValue(Val1, Loc1, PFS) ||
4434 ParseIndexList(Indices, AteExtraComma))
4437 if (!Val0->getType()->isAggregateType())
4438 return Error(Loc0, "insertvalue operand must be aggregate type");
4440 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4441 return Error(Loc0, "invalid indices for insertvalue");
4442 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4443 return AteExtraComma ? InstExtraComma : InstNormal;
4446 //===----------------------------------------------------------------------===//
4447 // Embedded metadata.
4448 //===----------------------------------------------------------------------===//
4450 /// ParseMDNodeVector
4451 /// ::= Element (',' Element)*
4453 /// ::= 'null' | TypeAndValue
4454 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4455 PerFunctionState *PFS) {
4456 // Check for an empty list.
4457 if (Lex.getKind() == lltok::rbrace)
4461 // Null is a special case since it is typeless.
4462 if (EatIfPresent(lltok::kw_null)) {
4463 Elts.push_back(nullptr);
4468 if (ParseTypeAndValue(V, PFS)) return true;
4470 } while (EatIfPresent(lltok::comma));