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 std::unique_ptr<GlobalAlias> GA(new GlobalAlias(
677 Aliasee->getType(), (GlobalValue::LinkageTypes)Linkage, Name, Aliasee));
678 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
679 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
681 // See if this value already exists in the symbol table. If so, it is either
682 // a redefinition or a definition of a forward reference.
683 if (GlobalValue *Val = M->getNamedValue(Name)) {
684 // See if this was a redefinition. If so, there is no entry in
686 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
687 I = ForwardRefVals.find(Name);
688 if (I == ForwardRefVals.end())
689 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
691 // Otherwise, this was a definition of forward ref. Verify that types
693 if (Val->getType() != GA->getType())
694 return Error(NameLoc,
695 "forward reference and definition of alias have different types");
697 // If they agree, just RAUW the old value with the alias and remove the
699 Val->replaceAllUsesWith(GA.get());
700 Val->eraseFromParent();
701 ForwardRefVals.erase(I);
704 // Insert into the module, we know its name won't collide now.
705 M->getAliasList().push_back(GA.get());
706 assert(GA->getName() == Name && "Should not be a name conflict!");
708 // The module owns this now
715 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
716 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
717 /// OptionalExternallyInitialized GlobalType Type Const
718 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
719 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
720 /// OptionalExternallyInitialized GlobalType Type Const
722 /// Everything up to and including OptionalDLLStorageClass has been parsed
725 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
726 unsigned Linkage, bool HasLinkage,
727 unsigned Visibility, unsigned DLLStorageClass) {
728 if (!isValidVisibilityForLinkage(Visibility, Linkage))
729 return Error(NameLoc,
730 "symbol with local linkage must have default visibility");
733 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
734 GlobalVariable::ThreadLocalMode TLM;
735 LocTy UnnamedAddrLoc;
736 LocTy IsExternallyInitializedLoc;
740 if (ParseOptionalThreadLocal(TLM) ||
741 ParseOptionalAddrSpace(AddrSpace) ||
742 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
744 ParseOptionalToken(lltok::kw_externally_initialized,
745 IsExternallyInitialized,
746 &IsExternallyInitializedLoc) ||
747 ParseGlobalType(IsConstant) ||
748 ParseType(Ty, TyLoc))
751 // If the linkage is specified and is external, then no initializer is
753 Constant *Init = nullptr;
754 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
755 Linkage != GlobalValue::ExternalLinkage)) {
756 if (ParseGlobalValue(Ty, Init))
760 if (Ty->isFunctionTy() || Ty->isLabelTy())
761 return Error(TyLoc, "invalid type for global variable");
763 GlobalVariable *GV = nullptr;
765 // See if the global was forward referenced, if so, use the global.
767 if (GlobalValue *GVal = M->getNamedValue(Name)) {
768 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
769 return Error(NameLoc, "redefinition of global '@" + Name + "'");
770 GV = cast<GlobalVariable>(GVal);
773 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
774 I = ForwardRefValIDs.find(NumberedVals.size());
775 if (I != ForwardRefValIDs.end()) {
776 GV = cast<GlobalVariable>(I->second.first);
777 ForwardRefValIDs.erase(I);
782 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
783 Name, nullptr, GlobalVariable::NotThreadLocal,
786 if (GV->getType()->getElementType() != Ty)
788 "forward reference and definition of global have different types");
790 // Move the forward-reference to the correct spot in the module.
791 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
795 NumberedVals.push_back(GV);
797 // Set the parsed properties on the global.
799 GV->setInitializer(Init);
800 GV->setConstant(IsConstant);
801 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
802 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
803 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
804 GV->setExternallyInitialized(IsExternallyInitialized);
805 GV->setThreadLocalMode(TLM);
806 GV->setUnnamedAddr(UnnamedAddr);
808 // Parse attributes on the global.
809 while (Lex.getKind() == lltok::comma) {
812 if (Lex.getKind() == lltok::kw_section) {
814 GV->setSection(Lex.getStrVal());
815 if (ParseToken(lltok::StringConstant, "expected global section string"))
817 } else if (Lex.getKind() == lltok::kw_align) {
819 if (ParseOptionalAlignment(Alignment)) return true;
820 GV->setAlignment(Alignment);
822 TokError("unknown global variable property!");
829 /// ParseUnnamedAttrGrp
830 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
831 bool LLParser::ParseUnnamedAttrGrp() {
832 assert(Lex.getKind() == lltok::kw_attributes);
833 LocTy AttrGrpLoc = Lex.getLoc();
836 assert(Lex.getKind() == lltok::AttrGrpID);
837 unsigned VarID = Lex.getUIntVal();
838 std::vector<unsigned> unused;
842 if (ParseToken(lltok::equal, "expected '=' here") ||
843 ParseToken(lltok::lbrace, "expected '{' here") ||
844 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
846 ParseToken(lltok::rbrace, "expected end of attribute group"))
849 if (!NumberedAttrBuilders[VarID].hasAttributes())
850 return Error(AttrGrpLoc, "attribute group has no attributes");
855 /// ParseFnAttributeValuePairs
856 /// ::= <attr> | <attr> '=' <value>
857 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
858 std::vector<unsigned> &FwdRefAttrGrps,
859 bool inAttrGrp, LocTy &BuiltinLoc) {
860 bool HaveError = false;
865 lltok::Kind Token = Lex.getKind();
866 if (Token == lltok::kw_builtin)
867 BuiltinLoc = Lex.getLoc();
870 if (!inAttrGrp) return HaveError;
871 return Error(Lex.getLoc(), "unterminated attribute group");
876 case lltok::AttrGrpID: {
877 // Allow a function to reference an attribute group:
879 // define void @foo() #1 { ... }
883 "cannot have an attribute group reference in an attribute group");
885 unsigned AttrGrpNum = Lex.getUIntVal();
886 if (inAttrGrp) break;
888 // Save the reference to the attribute group. We'll fill it in later.
889 FwdRefAttrGrps.push_back(AttrGrpNum);
892 // Target-dependent attributes:
893 case lltok::StringConstant: {
894 std::string Attr = Lex.getStrVal();
897 if (EatIfPresent(lltok::equal) &&
898 ParseStringConstant(Val))
901 B.addAttribute(Attr, Val);
905 // Target-independent attributes:
906 case lltok::kw_align: {
907 // As a hack, we allow function alignment to be initially parsed as an
908 // attribute on a function declaration/definition or added to an attribute
909 // group and later moved to the alignment field.
913 if (ParseToken(lltok::equal, "expected '=' here") ||
914 ParseUInt32(Alignment))
917 if (ParseOptionalAlignment(Alignment))
920 B.addAlignmentAttr(Alignment);
923 case lltok::kw_alignstack: {
927 if (ParseToken(lltok::equal, "expected '=' here") ||
928 ParseUInt32(Alignment))
931 if (ParseOptionalStackAlignment(Alignment))
934 B.addStackAlignmentAttr(Alignment);
937 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
938 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
939 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
940 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
941 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
942 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
943 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
944 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
945 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
946 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
947 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
948 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
949 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
950 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
951 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
952 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
953 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
954 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
955 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
956 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
957 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
958 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
959 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
960 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
961 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
962 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
965 case lltok::kw_inreg:
966 case lltok::kw_signext:
967 case lltok::kw_zeroext:
970 "invalid use of attribute on a function");
972 case lltok::kw_byval:
973 case lltok::kw_inalloca:
975 case lltok::kw_noalias:
976 case lltok::kw_nocapture:
977 case lltok::kw_returned:
981 "invalid use of parameter-only attribute on a function");
989 //===----------------------------------------------------------------------===//
990 // GlobalValue Reference/Resolution Routines.
991 //===----------------------------------------------------------------------===//
993 /// GetGlobalVal - Get a value with the specified name or ID, creating a
994 /// forward reference record if needed. This can return null if the value
995 /// exists but does not have the right type.
996 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
998 PointerType *PTy = dyn_cast<PointerType>(Ty);
1000 Error(Loc, "global variable reference must have pointer type");
1004 // Look this name up in the normal function symbol table.
1006 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1008 // If this is a forward reference for the value, see if we already created a
1009 // forward ref record.
1011 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1012 I = ForwardRefVals.find(Name);
1013 if (I != ForwardRefVals.end())
1014 Val = I->second.first;
1017 // If we have the value in the symbol table or fwd-ref table, return it.
1019 if (Val->getType() == Ty) return Val;
1020 Error(Loc, "'@" + Name + "' defined with type '" +
1021 getTypeString(Val->getType()) + "'");
1025 // Otherwise, create a new forward reference for this value and remember it.
1026 GlobalValue *FwdVal;
1027 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1028 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1030 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1031 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1032 nullptr, GlobalVariable::NotThreadLocal,
1033 PTy->getAddressSpace());
1035 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1039 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1040 PointerType *PTy = dyn_cast<PointerType>(Ty);
1042 Error(Loc, "global variable reference must have pointer type");
1046 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1048 // If this is a forward reference for the value, see if we already created a
1049 // forward ref record.
1051 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1052 I = ForwardRefValIDs.find(ID);
1053 if (I != ForwardRefValIDs.end())
1054 Val = I->second.first;
1057 // If we have the value in the symbol table or fwd-ref table, return it.
1059 if (Val->getType() == Ty) return Val;
1060 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1061 getTypeString(Val->getType()) + "'");
1065 // Otherwise, create a new forward reference for this value and remember it.
1066 GlobalValue *FwdVal;
1067 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1068 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1070 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1071 GlobalValue::ExternalWeakLinkage, nullptr, "");
1073 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1078 //===----------------------------------------------------------------------===//
1080 //===----------------------------------------------------------------------===//
1082 /// ParseToken - If the current token has the specified kind, eat it and return
1083 /// success. Otherwise, emit the specified error and return failure.
1084 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1085 if (Lex.getKind() != T)
1086 return TokError(ErrMsg);
1091 /// ParseStringConstant
1092 /// ::= StringConstant
1093 bool LLParser::ParseStringConstant(std::string &Result) {
1094 if (Lex.getKind() != lltok::StringConstant)
1095 return TokError("expected string constant");
1096 Result = Lex.getStrVal();
1103 bool LLParser::ParseUInt32(unsigned &Val) {
1104 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1105 return TokError("expected integer");
1106 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1107 if (Val64 != unsigned(Val64))
1108 return TokError("expected 32-bit integer (too large)");
1115 /// := 'localdynamic'
1116 /// := 'initialexec'
1118 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1119 switch (Lex.getKind()) {
1121 return TokError("expected localdynamic, initialexec or localexec");
1122 case lltok::kw_localdynamic:
1123 TLM = GlobalVariable::LocalDynamicTLSModel;
1125 case lltok::kw_initialexec:
1126 TLM = GlobalVariable::InitialExecTLSModel;
1128 case lltok::kw_localexec:
1129 TLM = GlobalVariable::LocalExecTLSModel;
1137 /// ParseOptionalThreadLocal
1139 /// := 'thread_local'
1140 /// := 'thread_local' '(' tlsmodel ')'
1141 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1142 TLM = GlobalVariable::NotThreadLocal;
1143 if (!EatIfPresent(lltok::kw_thread_local))
1146 TLM = GlobalVariable::GeneralDynamicTLSModel;
1147 if (Lex.getKind() == lltok::lparen) {
1149 return ParseTLSModel(TLM) ||
1150 ParseToken(lltok::rparen, "expected ')' after thread local model");
1155 /// ParseOptionalAddrSpace
1157 /// := 'addrspace' '(' uint32 ')'
1158 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1160 if (!EatIfPresent(lltok::kw_addrspace))
1162 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1163 ParseUInt32(AddrSpace) ||
1164 ParseToken(lltok::rparen, "expected ')' in address space");
1167 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1168 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1169 bool HaveError = false;
1174 lltok::Kind Token = Lex.getKind();
1176 default: // End of attributes.
1178 case lltok::kw_align: {
1180 if (ParseOptionalAlignment(Alignment))
1182 B.addAlignmentAttr(Alignment);
1185 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1186 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1187 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1188 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1189 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1190 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1191 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1192 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1193 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1194 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1195 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1196 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1198 case lltok::kw_alignstack:
1199 case lltok::kw_alwaysinline:
1200 case lltok::kw_builtin:
1201 case lltok::kw_inlinehint:
1202 case lltok::kw_minsize:
1203 case lltok::kw_naked:
1204 case lltok::kw_nobuiltin:
1205 case lltok::kw_noduplicate:
1206 case lltok::kw_noimplicitfloat:
1207 case lltok::kw_noinline:
1208 case lltok::kw_nonlazybind:
1209 case lltok::kw_noredzone:
1210 case lltok::kw_noreturn:
1211 case lltok::kw_nounwind:
1212 case lltok::kw_optnone:
1213 case lltok::kw_optsize:
1214 case lltok::kw_returns_twice:
1215 case lltok::kw_sanitize_address:
1216 case lltok::kw_sanitize_memory:
1217 case lltok::kw_sanitize_thread:
1219 case lltok::kw_sspreq:
1220 case lltok::kw_sspstrong:
1221 case lltok::kw_uwtable:
1222 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1230 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1231 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1232 bool HaveError = false;
1237 lltok::Kind Token = Lex.getKind();
1239 default: // End of attributes.
1241 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1242 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1243 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1244 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1247 case lltok::kw_align:
1248 case lltok::kw_byval:
1249 case lltok::kw_inalloca:
1250 case lltok::kw_nest:
1251 case lltok::kw_nocapture:
1252 case lltok::kw_returned:
1253 case lltok::kw_sret:
1254 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1257 case lltok::kw_alignstack:
1258 case lltok::kw_alwaysinline:
1259 case lltok::kw_builtin:
1260 case lltok::kw_cold:
1261 case lltok::kw_inlinehint:
1262 case lltok::kw_minsize:
1263 case lltok::kw_naked:
1264 case lltok::kw_nobuiltin:
1265 case lltok::kw_noduplicate:
1266 case lltok::kw_noimplicitfloat:
1267 case lltok::kw_noinline:
1268 case lltok::kw_nonlazybind:
1269 case lltok::kw_noredzone:
1270 case lltok::kw_noreturn:
1271 case lltok::kw_nounwind:
1272 case lltok::kw_optnone:
1273 case lltok::kw_optsize:
1274 case lltok::kw_returns_twice:
1275 case lltok::kw_sanitize_address:
1276 case lltok::kw_sanitize_memory:
1277 case lltok::kw_sanitize_thread:
1279 case lltok::kw_sspreq:
1280 case lltok::kw_sspstrong:
1281 case lltok::kw_uwtable:
1282 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1285 case lltok::kw_readnone:
1286 case lltok::kw_readonly:
1287 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1294 /// ParseOptionalLinkage
1301 /// ::= 'linkonce_odr'
1302 /// ::= 'available_externally'
1305 /// ::= 'extern_weak'
1308 /// Deprecated Values:
1309 /// ::= 'linker_private'
1310 /// ::= 'linker_private_weak'
1311 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1313 switch (Lex.getKind()) {
1314 default: Res=GlobalValue::ExternalLinkage; return false;
1315 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1316 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1317 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1318 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1319 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1320 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1321 case lltok::kw_available_externally:
1322 Res = GlobalValue::AvailableExternallyLinkage;
1324 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1325 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1326 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1327 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1329 case lltok::kw_linker_private:
1330 case lltok::kw_linker_private_weak:
1331 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1334 // treat linker_private and linker_private_weak as PrivateLinkage
1335 Res = GlobalValue::PrivateLinkage;
1343 /// ParseOptionalVisibility
1349 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1350 switch (Lex.getKind()) {
1351 default: Res = GlobalValue::DefaultVisibility; return false;
1352 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1353 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1354 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1360 /// ParseOptionalDLLStorageClass
1365 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1366 switch (Lex.getKind()) {
1367 default: Res = GlobalValue::DefaultStorageClass; return false;
1368 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1369 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1375 /// ParseOptionalCallingConv
1379 /// ::= 'kw_intel_ocl_bicc'
1381 /// ::= 'x86_stdcallcc'
1382 /// ::= 'x86_fastcallcc'
1383 /// ::= 'x86_thiscallcc'
1384 /// ::= 'arm_apcscc'
1385 /// ::= 'arm_aapcscc'
1386 /// ::= 'arm_aapcs_vfpcc'
1387 /// ::= 'msp430_intrcc'
1388 /// ::= 'ptx_kernel'
1389 /// ::= 'ptx_device'
1391 /// ::= 'spir_kernel'
1392 /// ::= 'x86_64_sysvcc'
1393 /// ::= 'x86_64_win64cc'
1394 /// ::= 'webkit_jscc'
1396 /// ::= 'preserve_mostcc'
1397 /// ::= 'preserve_allcc'
1400 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1401 switch (Lex.getKind()) {
1402 default: CC = CallingConv::C; return false;
1403 case lltok::kw_ccc: CC = CallingConv::C; break;
1404 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1405 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1406 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1407 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1408 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1409 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1410 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1411 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1412 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1413 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1414 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1415 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1416 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1417 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1418 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1419 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1420 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1421 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1422 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1423 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1424 case lltok::kw_cc: {
1425 unsigned ArbitraryCC;
1427 if (ParseUInt32(ArbitraryCC))
1429 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1438 /// ParseInstructionMetadata
1439 /// ::= !dbg !42 (',' !dbg !57)*
1440 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1441 PerFunctionState *PFS) {
1443 if (Lex.getKind() != lltok::MetadataVar)
1444 return TokError("expected metadata after comma");
1446 std::string Name = Lex.getStrVal();
1447 unsigned MDK = M->getMDKindID(Name);
1451 SMLoc Loc = Lex.getLoc();
1453 if (ParseToken(lltok::exclaim, "expected '!' here"))
1456 // This code is similar to that of ParseMetadataValue, however it needs to
1457 // have special-case code for a forward reference; see the comments on
1458 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1459 // at the top level here.
1460 if (Lex.getKind() == lltok::lbrace) {
1462 if (ParseMetadataListValue(ID, PFS))
1464 assert(ID.Kind == ValID::t_MDNode);
1465 Inst->setMetadata(MDK, ID.MDNodeVal);
1467 unsigned NodeID = 0;
1468 if (ParseMDNodeID(Node, NodeID))
1471 // If we got the node, add it to the instruction.
1472 Inst->setMetadata(MDK, Node);
1474 MDRef R = { Loc, MDK, NodeID };
1475 // Otherwise, remember that this should be resolved later.
1476 ForwardRefInstMetadata[Inst].push_back(R);
1480 if (MDK == LLVMContext::MD_tbaa)
1481 InstsWithTBAATag.push_back(Inst);
1483 // If this is the end of the list, we're done.
1484 } while (EatIfPresent(lltok::comma));
1488 /// ParseOptionalAlignment
1491 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1493 if (!EatIfPresent(lltok::kw_align))
1495 LocTy AlignLoc = Lex.getLoc();
1496 if (ParseUInt32(Alignment)) return true;
1497 if (!isPowerOf2_32(Alignment))
1498 return Error(AlignLoc, "alignment is not a power of two");
1499 if (Alignment > Value::MaximumAlignment)
1500 return Error(AlignLoc, "huge alignments are not supported yet");
1504 /// ParseOptionalCommaAlign
1508 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1510 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1511 bool &AteExtraComma) {
1512 AteExtraComma = false;
1513 while (EatIfPresent(lltok::comma)) {
1514 // Metadata at the end is an early exit.
1515 if (Lex.getKind() == lltok::MetadataVar) {
1516 AteExtraComma = true;
1520 if (Lex.getKind() != lltok::kw_align)
1521 return Error(Lex.getLoc(), "expected metadata or 'align'");
1523 if (ParseOptionalAlignment(Alignment)) return true;
1529 /// ParseScopeAndOrdering
1530 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1533 /// This sets Scope and Ordering to the parsed values.
1534 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1535 AtomicOrdering &Ordering) {
1539 Scope = CrossThread;
1540 if (EatIfPresent(lltok::kw_singlethread))
1541 Scope = SingleThread;
1543 return ParseOrdering(Ordering);
1547 /// ::= AtomicOrdering
1549 /// This sets Ordering to the parsed value.
1550 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1551 switch (Lex.getKind()) {
1552 default: return TokError("Expected ordering on atomic instruction");
1553 case lltok::kw_unordered: Ordering = Unordered; break;
1554 case lltok::kw_monotonic: Ordering = Monotonic; break;
1555 case lltok::kw_acquire: Ordering = Acquire; break;
1556 case lltok::kw_release: Ordering = Release; break;
1557 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1558 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1564 /// ParseOptionalStackAlignment
1566 /// ::= 'alignstack' '(' 4 ')'
1567 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1569 if (!EatIfPresent(lltok::kw_alignstack))
1571 LocTy ParenLoc = Lex.getLoc();
1572 if (!EatIfPresent(lltok::lparen))
1573 return Error(ParenLoc, "expected '('");
1574 LocTy AlignLoc = Lex.getLoc();
1575 if (ParseUInt32(Alignment)) return true;
1576 ParenLoc = Lex.getLoc();
1577 if (!EatIfPresent(lltok::rparen))
1578 return Error(ParenLoc, "expected ')'");
1579 if (!isPowerOf2_32(Alignment))
1580 return Error(AlignLoc, "stack alignment is not a power of two");
1584 /// ParseIndexList - This parses the index list for an insert/extractvalue
1585 /// instruction. This sets AteExtraComma in the case where we eat an extra
1586 /// comma at the end of the line and find that it is followed by metadata.
1587 /// Clients that don't allow metadata can call the version of this function that
1588 /// only takes one argument.
1591 /// ::= (',' uint32)+
1593 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1594 bool &AteExtraComma) {
1595 AteExtraComma = false;
1597 if (Lex.getKind() != lltok::comma)
1598 return TokError("expected ',' as start of index list");
1600 while (EatIfPresent(lltok::comma)) {
1601 if (Lex.getKind() == lltok::MetadataVar) {
1602 AteExtraComma = true;
1606 if (ParseUInt32(Idx)) return true;
1607 Indices.push_back(Idx);
1613 //===----------------------------------------------------------------------===//
1615 //===----------------------------------------------------------------------===//
1617 /// ParseType - Parse a type.
1618 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1619 SMLoc TypeLoc = Lex.getLoc();
1620 switch (Lex.getKind()) {
1622 return TokError("expected type");
1624 // Type ::= 'float' | 'void' (etc)
1625 Result = Lex.getTyVal();
1629 // Type ::= StructType
1630 if (ParseAnonStructType(Result, false))
1633 case lltok::lsquare:
1634 // Type ::= '[' ... ']'
1635 Lex.Lex(); // eat the lsquare.
1636 if (ParseArrayVectorType(Result, false))
1639 case lltok::less: // Either vector or packed struct.
1640 // Type ::= '<' ... '>'
1642 if (Lex.getKind() == lltok::lbrace) {
1643 if (ParseAnonStructType(Result, true) ||
1644 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1646 } else if (ParseArrayVectorType(Result, true))
1649 case lltok::LocalVar: {
1651 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1653 // If the type hasn't been defined yet, create a forward definition and
1654 // remember where that forward def'n was seen (in case it never is defined).
1656 Entry.first = StructType::create(Context, Lex.getStrVal());
1657 Entry.second = Lex.getLoc();
1659 Result = Entry.first;
1664 case lltok::LocalVarID: {
1666 if (Lex.getUIntVal() >= NumberedTypes.size())
1667 NumberedTypes.resize(Lex.getUIntVal()+1);
1668 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1670 // If the type hasn't been defined yet, create a forward definition and
1671 // remember where that forward def'n was seen (in case it never is defined).
1673 Entry.first = StructType::create(Context);
1674 Entry.second = Lex.getLoc();
1676 Result = Entry.first;
1682 // Parse the type suffixes.
1684 switch (Lex.getKind()) {
1687 if (!AllowVoid && Result->isVoidTy())
1688 return Error(TypeLoc, "void type only allowed for function results");
1691 // Type ::= Type '*'
1693 if (Result->isLabelTy())
1694 return TokError("basic block pointers are invalid");
1695 if (Result->isVoidTy())
1696 return TokError("pointers to void are invalid - use i8* instead");
1697 if (!PointerType::isValidElementType(Result))
1698 return TokError("pointer to this type is invalid");
1699 Result = PointerType::getUnqual(Result);
1703 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1704 case lltok::kw_addrspace: {
1705 if (Result->isLabelTy())
1706 return TokError("basic block pointers are invalid");
1707 if (Result->isVoidTy())
1708 return TokError("pointers to void are invalid; use i8* instead");
1709 if (!PointerType::isValidElementType(Result))
1710 return TokError("pointer to this type is invalid");
1712 if (ParseOptionalAddrSpace(AddrSpace) ||
1713 ParseToken(lltok::star, "expected '*' in address space"))
1716 Result = PointerType::get(Result, AddrSpace);
1720 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1722 if (ParseFunctionType(Result))
1729 /// ParseParameterList
1731 /// ::= '(' Arg (',' Arg)* ')'
1733 /// ::= Type OptionalAttributes Value OptionalAttributes
1734 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1735 PerFunctionState &PFS) {
1736 if (ParseToken(lltok::lparen, "expected '(' in call"))
1739 unsigned AttrIndex = 1;
1740 while (Lex.getKind() != lltok::rparen) {
1741 // If this isn't the first argument, we need a comma.
1742 if (!ArgList.empty() &&
1743 ParseToken(lltok::comma, "expected ',' in argument list"))
1746 // Parse the argument.
1748 Type *ArgTy = nullptr;
1749 AttrBuilder ArgAttrs;
1751 if (ParseType(ArgTy, ArgLoc))
1754 // Otherwise, handle normal operands.
1755 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1757 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1762 Lex.Lex(); // Lex the ')'.
1768 /// ParseArgumentList - Parse the argument list for a function type or function
1770 /// ::= '(' ArgTypeListI ')'
1774 /// ::= ArgTypeList ',' '...'
1775 /// ::= ArgType (',' ArgType)*
1777 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1780 assert(Lex.getKind() == lltok::lparen);
1781 Lex.Lex(); // eat the (.
1783 if (Lex.getKind() == lltok::rparen) {
1785 } else if (Lex.getKind() == lltok::dotdotdot) {
1789 LocTy TypeLoc = Lex.getLoc();
1790 Type *ArgTy = nullptr;
1794 if (ParseType(ArgTy) ||
1795 ParseOptionalParamAttrs(Attrs)) return true;
1797 if (ArgTy->isVoidTy())
1798 return Error(TypeLoc, "argument can not have void type");
1800 if (Lex.getKind() == lltok::LocalVar) {
1801 Name = Lex.getStrVal();
1805 if (!FunctionType::isValidArgumentType(ArgTy))
1806 return Error(TypeLoc, "invalid type for function argument");
1808 unsigned AttrIndex = 1;
1809 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1810 AttributeSet::get(ArgTy->getContext(),
1811 AttrIndex++, Attrs), Name));
1813 while (EatIfPresent(lltok::comma)) {
1814 // Handle ... at end of arg list.
1815 if (EatIfPresent(lltok::dotdotdot)) {
1820 // Otherwise must be an argument type.
1821 TypeLoc = Lex.getLoc();
1822 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1824 if (ArgTy->isVoidTy())
1825 return Error(TypeLoc, "argument can not have void type");
1827 if (Lex.getKind() == lltok::LocalVar) {
1828 Name = Lex.getStrVal();
1834 if (!ArgTy->isFirstClassType())
1835 return Error(TypeLoc, "invalid type for function argument");
1837 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1838 AttributeSet::get(ArgTy->getContext(),
1839 AttrIndex++, Attrs),
1844 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1847 /// ParseFunctionType
1848 /// ::= Type ArgumentList OptionalAttrs
1849 bool LLParser::ParseFunctionType(Type *&Result) {
1850 assert(Lex.getKind() == lltok::lparen);
1852 if (!FunctionType::isValidReturnType(Result))
1853 return TokError("invalid function return type");
1855 SmallVector<ArgInfo, 8> ArgList;
1857 if (ParseArgumentList(ArgList, isVarArg))
1860 // Reject names on the arguments lists.
1861 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1862 if (!ArgList[i].Name.empty())
1863 return Error(ArgList[i].Loc, "argument name invalid in function type");
1864 if (ArgList[i].Attrs.hasAttributes(i + 1))
1865 return Error(ArgList[i].Loc,
1866 "argument attributes invalid in function type");
1869 SmallVector<Type*, 16> ArgListTy;
1870 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1871 ArgListTy.push_back(ArgList[i].Ty);
1873 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1877 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1879 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1880 SmallVector<Type*, 8> Elts;
1881 if (ParseStructBody(Elts)) return true;
1883 Result = StructType::get(Context, Elts, Packed);
1887 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1888 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1889 std::pair<Type*, LocTy> &Entry,
1891 // If the type was already defined, diagnose the redefinition.
1892 if (Entry.first && !Entry.second.isValid())
1893 return Error(TypeLoc, "redefinition of type");
1895 // If we have opaque, just return without filling in the definition for the
1896 // struct. This counts as a definition as far as the .ll file goes.
1897 if (EatIfPresent(lltok::kw_opaque)) {
1898 // This type is being defined, so clear the location to indicate this.
1899 Entry.second = SMLoc();
1901 // If this type number has never been uttered, create it.
1903 Entry.first = StructType::create(Context, Name);
1904 ResultTy = Entry.first;
1908 // If the type starts with '<', then it is either a packed struct or a vector.
1909 bool isPacked = EatIfPresent(lltok::less);
1911 // If we don't have a struct, then we have a random type alias, which we
1912 // accept for compatibility with old files. These types are not allowed to be
1913 // forward referenced and not allowed to be recursive.
1914 if (Lex.getKind() != lltok::lbrace) {
1916 return Error(TypeLoc, "forward references to non-struct type");
1920 return ParseArrayVectorType(ResultTy, true);
1921 return ParseType(ResultTy);
1924 // This type is being defined, so clear the location to indicate this.
1925 Entry.second = SMLoc();
1927 // If this type number has never been uttered, create it.
1929 Entry.first = StructType::create(Context, Name);
1931 StructType *STy = cast<StructType>(Entry.first);
1933 SmallVector<Type*, 8> Body;
1934 if (ParseStructBody(Body) ||
1935 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1938 STy->setBody(Body, isPacked);
1944 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1947 /// ::= '{' Type (',' Type)* '}'
1948 /// ::= '<' '{' '}' '>'
1949 /// ::= '<' '{' Type (',' Type)* '}' '>'
1950 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1951 assert(Lex.getKind() == lltok::lbrace);
1952 Lex.Lex(); // Consume the '{'
1954 // Handle the empty struct.
1955 if (EatIfPresent(lltok::rbrace))
1958 LocTy EltTyLoc = Lex.getLoc();
1960 if (ParseType(Ty)) return true;
1963 if (!StructType::isValidElementType(Ty))
1964 return Error(EltTyLoc, "invalid element type for struct");
1966 while (EatIfPresent(lltok::comma)) {
1967 EltTyLoc = Lex.getLoc();
1968 if (ParseType(Ty)) return true;
1970 if (!StructType::isValidElementType(Ty))
1971 return Error(EltTyLoc, "invalid element type for struct");
1976 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1979 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1980 /// token has already been consumed.
1982 /// ::= '[' APSINTVAL 'x' Types ']'
1983 /// ::= '<' APSINTVAL 'x' Types '>'
1984 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1985 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1986 Lex.getAPSIntVal().getBitWidth() > 64)
1987 return TokError("expected number in address space");
1989 LocTy SizeLoc = Lex.getLoc();
1990 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
1993 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
1996 LocTy TypeLoc = Lex.getLoc();
1997 Type *EltTy = nullptr;
1998 if (ParseType(EltTy)) return true;
2000 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2001 "expected end of sequential type"))
2006 return Error(SizeLoc, "zero element vector is illegal");
2007 if ((unsigned)Size != Size)
2008 return Error(SizeLoc, "size too large for vector");
2009 if (!VectorType::isValidElementType(EltTy))
2010 return Error(TypeLoc, "invalid vector element type");
2011 Result = VectorType::get(EltTy, unsigned(Size));
2013 if (!ArrayType::isValidElementType(EltTy))
2014 return Error(TypeLoc, "invalid array element type");
2015 Result = ArrayType::get(EltTy, Size);
2020 //===----------------------------------------------------------------------===//
2021 // Function Semantic Analysis.
2022 //===----------------------------------------------------------------------===//
2024 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2026 : P(p), F(f), FunctionNumber(functionNumber) {
2028 // Insert unnamed arguments into the NumberedVals list.
2029 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2032 NumberedVals.push_back(AI);
2035 LLParser::PerFunctionState::~PerFunctionState() {
2036 // If there were any forward referenced non-basicblock values, delete them.
2037 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2038 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2039 if (!isa<BasicBlock>(I->second.first)) {
2040 I->second.first->replaceAllUsesWith(
2041 UndefValue::get(I->second.first->getType()));
2042 delete I->second.first;
2043 I->second.first = nullptr;
2046 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2047 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2048 if (!isa<BasicBlock>(I->second.first)) {
2049 I->second.first->replaceAllUsesWith(
2050 UndefValue::get(I->second.first->getType()));
2051 delete I->second.first;
2052 I->second.first = nullptr;
2056 bool LLParser::PerFunctionState::FinishFunction() {
2057 // Check to see if someone took the address of labels in this block.
2058 if (!P.ForwardRefBlockAddresses.empty()) {
2060 if (!F.getName().empty()) {
2061 FunctionID.Kind = ValID::t_GlobalName;
2062 FunctionID.StrVal = F.getName();
2064 FunctionID.Kind = ValID::t_GlobalID;
2065 FunctionID.UIntVal = FunctionNumber;
2068 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2069 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2070 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2071 // Resolve all these references.
2072 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2075 P.ForwardRefBlockAddresses.erase(FRBAI);
2079 if (!ForwardRefVals.empty())
2080 return P.Error(ForwardRefVals.begin()->second.second,
2081 "use of undefined value '%" + ForwardRefVals.begin()->first +
2083 if (!ForwardRefValIDs.empty())
2084 return P.Error(ForwardRefValIDs.begin()->second.second,
2085 "use of undefined value '%" +
2086 Twine(ForwardRefValIDs.begin()->first) + "'");
2091 /// GetVal - Get a value with the specified name or ID, creating a
2092 /// forward reference record if needed. This can return null if the value
2093 /// exists but does not have the right type.
2094 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2095 Type *Ty, LocTy Loc) {
2096 // Look this name up in the normal function symbol table.
2097 Value *Val = F.getValueSymbolTable().lookup(Name);
2099 // If this is a forward reference for the value, see if we already created a
2100 // forward ref record.
2102 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2103 I = ForwardRefVals.find(Name);
2104 if (I != ForwardRefVals.end())
2105 Val = I->second.first;
2108 // If we have the value in the symbol table or fwd-ref table, return it.
2110 if (Val->getType() == Ty) return Val;
2111 if (Ty->isLabelTy())
2112 P.Error(Loc, "'%" + Name + "' is not a basic block");
2114 P.Error(Loc, "'%" + Name + "' defined with type '" +
2115 getTypeString(Val->getType()) + "'");
2119 // Don't make placeholders with invalid type.
2120 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2121 P.Error(Loc, "invalid use of a non-first-class type");
2125 // Otherwise, create a new forward reference for this value and remember it.
2127 if (Ty->isLabelTy())
2128 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2130 FwdVal = new Argument(Ty, Name);
2132 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2136 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2138 // Look this name up in the normal function symbol table.
2139 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2141 // If this is a forward reference for the value, see if we already created a
2142 // forward ref record.
2144 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2145 I = ForwardRefValIDs.find(ID);
2146 if (I != ForwardRefValIDs.end())
2147 Val = I->second.first;
2150 // If we have the value in the symbol table or fwd-ref table, return it.
2152 if (Val->getType() == Ty) return Val;
2153 if (Ty->isLabelTy())
2154 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2156 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2157 getTypeString(Val->getType()) + "'");
2161 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2162 P.Error(Loc, "invalid use of a non-first-class type");
2166 // Otherwise, create a new forward reference for this value and remember it.
2168 if (Ty->isLabelTy())
2169 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2171 FwdVal = new Argument(Ty);
2173 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2177 /// SetInstName - After an instruction is parsed and inserted into its
2178 /// basic block, this installs its name.
2179 bool LLParser::PerFunctionState::SetInstName(int NameID,
2180 const std::string &NameStr,
2181 LocTy NameLoc, Instruction *Inst) {
2182 // If this instruction has void type, it cannot have a name or ID specified.
2183 if (Inst->getType()->isVoidTy()) {
2184 if (NameID != -1 || !NameStr.empty())
2185 return P.Error(NameLoc, "instructions returning void cannot have a name");
2189 // If this was a numbered instruction, verify that the instruction is the
2190 // expected value and resolve any forward references.
2191 if (NameStr.empty()) {
2192 // If neither a name nor an ID was specified, just use the next ID.
2194 NameID = NumberedVals.size();
2196 if (unsigned(NameID) != NumberedVals.size())
2197 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2198 Twine(NumberedVals.size()) + "'");
2200 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2201 ForwardRefValIDs.find(NameID);
2202 if (FI != ForwardRefValIDs.end()) {
2203 if (FI->second.first->getType() != Inst->getType())
2204 return P.Error(NameLoc, "instruction forward referenced with type '" +
2205 getTypeString(FI->second.first->getType()) + "'");
2206 FI->second.first->replaceAllUsesWith(Inst);
2207 delete FI->second.first;
2208 ForwardRefValIDs.erase(FI);
2211 NumberedVals.push_back(Inst);
2215 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2216 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2217 FI = ForwardRefVals.find(NameStr);
2218 if (FI != ForwardRefVals.end()) {
2219 if (FI->second.first->getType() != Inst->getType())
2220 return P.Error(NameLoc, "instruction forward referenced with type '" +
2221 getTypeString(FI->second.first->getType()) + "'");
2222 FI->second.first->replaceAllUsesWith(Inst);
2223 delete FI->second.first;
2224 ForwardRefVals.erase(FI);
2227 // Set the name on the instruction.
2228 Inst->setName(NameStr);
2230 if (Inst->getName() != NameStr)
2231 return P.Error(NameLoc, "multiple definition of local value named '" +
2236 /// GetBB - Get a basic block with the specified name or ID, creating a
2237 /// forward reference record if needed.
2238 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2240 return cast_or_null<BasicBlock>(GetVal(Name,
2241 Type::getLabelTy(F.getContext()), Loc));
2244 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2245 return cast_or_null<BasicBlock>(GetVal(ID,
2246 Type::getLabelTy(F.getContext()), Loc));
2249 /// DefineBB - Define the specified basic block, which is either named or
2250 /// unnamed. If there is an error, this returns null otherwise it returns
2251 /// the block being defined.
2252 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2256 BB = GetBB(NumberedVals.size(), Loc);
2258 BB = GetBB(Name, Loc);
2259 if (!BB) return nullptr; // Already diagnosed error.
2261 // Move the block to the end of the function. Forward ref'd blocks are
2262 // inserted wherever they happen to be referenced.
2263 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2265 // Remove the block from forward ref sets.
2267 ForwardRefValIDs.erase(NumberedVals.size());
2268 NumberedVals.push_back(BB);
2270 // BB forward references are already in the function symbol table.
2271 ForwardRefVals.erase(Name);
2277 //===----------------------------------------------------------------------===//
2279 //===----------------------------------------------------------------------===//
2281 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2282 /// type implied. For example, if we parse "4" we don't know what integer type
2283 /// it has. The value will later be combined with its type and checked for
2284 /// sanity. PFS is used to convert function-local operands of metadata (since
2285 /// metadata operands are not just parsed here but also converted to values).
2286 /// PFS can be null when we are not parsing metadata values inside a function.
2287 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2288 ID.Loc = Lex.getLoc();
2289 switch (Lex.getKind()) {
2290 default: return TokError("expected value token");
2291 case lltok::GlobalID: // @42
2292 ID.UIntVal = Lex.getUIntVal();
2293 ID.Kind = ValID::t_GlobalID;
2295 case lltok::GlobalVar: // @foo
2296 ID.StrVal = Lex.getStrVal();
2297 ID.Kind = ValID::t_GlobalName;
2299 case lltok::LocalVarID: // %42
2300 ID.UIntVal = Lex.getUIntVal();
2301 ID.Kind = ValID::t_LocalID;
2303 case lltok::LocalVar: // %foo
2304 ID.StrVal = Lex.getStrVal();
2305 ID.Kind = ValID::t_LocalName;
2307 case lltok::exclaim: // !42, !{...}, or !"foo"
2308 return ParseMetadataValue(ID, PFS);
2310 ID.APSIntVal = Lex.getAPSIntVal();
2311 ID.Kind = ValID::t_APSInt;
2313 case lltok::APFloat:
2314 ID.APFloatVal = Lex.getAPFloatVal();
2315 ID.Kind = ValID::t_APFloat;
2317 case lltok::kw_true:
2318 ID.ConstantVal = ConstantInt::getTrue(Context);
2319 ID.Kind = ValID::t_Constant;
2321 case lltok::kw_false:
2322 ID.ConstantVal = ConstantInt::getFalse(Context);
2323 ID.Kind = ValID::t_Constant;
2325 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2326 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2327 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2329 case lltok::lbrace: {
2330 // ValID ::= '{' ConstVector '}'
2332 SmallVector<Constant*, 16> Elts;
2333 if (ParseGlobalValueVector(Elts) ||
2334 ParseToken(lltok::rbrace, "expected end of struct constant"))
2337 ID.ConstantStructElts = new Constant*[Elts.size()];
2338 ID.UIntVal = Elts.size();
2339 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2340 ID.Kind = ValID::t_ConstantStruct;
2344 // ValID ::= '<' ConstVector '>' --> Vector.
2345 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2347 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2349 SmallVector<Constant*, 16> Elts;
2350 LocTy FirstEltLoc = Lex.getLoc();
2351 if (ParseGlobalValueVector(Elts) ||
2353 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2354 ParseToken(lltok::greater, "expected end of constant"))
2357 if (isPackedStruct) {
2358 ID.ConstantStructElts = new Constant*[Elts.size()];
2359 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2360 ID.UIntVal = Elts.size();
2361 ID.Kind = ValID::t_PackedConstantStruct;
2366 return Error(ID.Loc, "constant vector must not be empty");
2368 if (!Elts[0]->getType()->isIntegerTy() &&
2369 !Elts[0]->getType()->isFloatingPointTy() &&
2370 !Elts[0]->getType()->isPointerTy())
2371 return Error(FirstEltLoc,
2372 "vector elements must have integer, pointer or floating point type");
2374 // Verify that all the vector elements have the same type.
2375 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2376 if (Elts[i]->getType() != Elts[0]->getType())
2377 return Error(FirstEltLoc,
2378 "vector element #" + Twine(i) +
2379 " is not of type '" + getTypeString(Elts[0]->getType()));
2381 ID.ConstantVal = ConstantVector::get(Elts);
2382 ID.Kind = ValID::t_Constant;
2385 case lltok::lsquare: { // Array Constant
2387 SmallVector<Constant*, 16> Elts;
2388 LocTy FirstEltLoc = Lex.getLoc();
2389 if (ParseGlobalValueVector(Elts) ||
2390 ParseToken(lltok::rsquare, "expected end of array constant"))
2393 // Handle empty element.
2395 // Use undef instead of an array because it's inconvenient to determine
2396 // the element type at this point, there being no elements to examine.
2397 ID.Kind = ValID::t_EmptyArray;
2401 if (!Elts[0]->getType()->isFirstClassType())
2402 return Error(FirstEltLoc, "invalid array element type: " +
2403 getTypeString(Elts[0]->getType()));
2405 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2407 // Verify all elements are correct type!
2408 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2409 if (Elts[i]->getType() != Elts[0]->getType())
2410 return Error(FirstEltLoc,
2411 "array element #" + Twine(i) +
2412 " is not of type '" + getTypeString(Elts[0]->getType()));
2415 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2416 ID.Kind = ValID::t_Constant;
2419 case lltok::kw_c: // c "foo"
2421 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2423 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2424 ID.Kind = ValID::t_Constant;
2427 case lltok::kw_asm: {
2428 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2430 bool HasSideEffect, AlignStack, AsmDialect;
2432 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2433 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2434 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2435 ParseStringConstant(ID.StrVal) ||
2436 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2437 ParseToken(lltok::StringConstant, "expected constraint string"))
2439 ID.StrVal2 = Lex.getStrVal();
2440 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2441 (unsigned(AsmDialect)<<2);
2442 ID.Kind = ValID::t_InlineAsm;
2446 case lltok::kw_blockaddress: {
2447 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2452 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2454 ParseToken(lltok::comma, "expected comma in block address expression")||
2455 ParseValID(Label) ||
2456 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2459 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2460 return Error(Fn.Loc, "expected function name in blockaddress");
2461 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2462 return Error(Label.Loc, "expected basic block name in blockaddress");
2464 // Make a global variable as a placeholder for this reference.
2465 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2466 false, GlobalValue::InternalLinkage,
2468 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2469 ID.ConstantVal = FwdRef;
2470 ID.Kind = ValID::t_Constant;
2474 case lltok::kw_trunc:
2475 case lltok::kw_zext:
2476 case lltok::kw_sext:
2477 case lltok::kw_fptrunc:
2478 case lltok::kw_fpext:
2479 case lltok::kw_bitcast:
2480 case lltok::kw_addrspacecast:
2481 case lltok::kw_uitofp:
2482 case lltok::kw_sitofp:
2483 case lltok::kw_fptoui:
2484 case lltok::kw_fptosi:
2485 case lltok::kw_inttoptr:
2486 case lltok::kw_ptrtoint: {
2487 unsigned Opc = Lex.getUIntVal();
2488 Type *DestTy = nullptr;
2491 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2492 ParseGlobalTypeAndValue(SrcVal) ||
2493 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2494 ParseType(DestTy) ||
2495 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2497 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2498 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2499 getTypeString(SrcVal->getType()) + "' to '" +
2500 getTypeString(DestTy) + "'");
2501 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2503 ID.Kind = ValID::t_Constant;
2506 case lltok::kw_extractvalue: {
2509 SmallVector<unsigned, 4> Indices;
2510 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2511 ParseGlobalTypeAndValue(Val) ||
2512 ParseIndexList(Indices) ||
2513 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2516 if (!Val->getType()->isAggregateType())
2517 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2518 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2519 return Error(ID.Loc, "invalid indices for extractvalue");
2520 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2521 ID.Kind = ValID::t_Constant;
2524 case lltok::kw_insertvalue: {
2526 Constant *Val0, *Val1;
2527 SmallVector<unsigned, 4> Indices;
2528 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2529 ParseGlobalTypeAndValue(Val0) ||
2530 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2531 ParseGlobalTypeAndValue(Val1) ||
2532 ParseIndexList(Indices) ||
2533 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2535 if (!Val0->getType()->isAggregateType())
2536 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2537 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2538 return Error(ID.Loc, "invalid indices for insertvalue");
2539 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2540 ID.Kind = ValID::t_Constant;
2543 case lltok::kw_icmp:
2544 case lltok::kw_fcmp: {
2545 unsigned PredVal, Opc = Lex.getUIntVal();
2546 Constant *Val0, *Val1;
2548 if (ParseCmpPredicate(PredVal, Opc) ||
2549 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2550 ParseGlobalTypeAndValue(Val0) ||
2551 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2552 ParseGlobalTypeAndValue(Val1) ||
2553 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2556 if (Val0->getType() != Val1->getType())
2557 return Error(ID.Loc, "compare operands must have the same type");
2559 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2561 if (Opc == Instruction::FCmp) {
2562 if (!Val0->getType()->isFPOrFPVectorTy())
2563 return Error(ID.Loc, "fcmp requires floating point operands");
2564 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2566 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2567 if (!Val0->getType()->isIntOrIntVectorTy() &&
2568 !Val0->getType()->getScalarType()->isPointerTy())
2569 return Error(ID.Loc, "icmp requires pointer or integer operands");
2570 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2572 ID.Kind = ValID::t_Constant;
2576 // Binary Operators.
2578 case lltok::kw_fadd:
2580 case lltok::kw_fsub:
2582 case lltok::kw_fmul:
2583 case lltok::kw_udiv:
2584 case lltok::kw_sdiv:
2585 case lltok::kw_fdiv:
2586 case lltok::kw_urem:
2587 case lltok::kw_srem:
2588 case lltok::kw_frem:
2590 case lltok::kw_lshr:
2591 case lltok::kw_ashr: {
2595 unsigned Opc = Lex.getUIntVal();
2596 Constant *Val0, *Val1;
2598 LocTy ModifierLoc = Lex.getLoc();
2599 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2600 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2601 if (EatIfPresent(lltok::kw_nuw))
2603 if (EatIfPresent(lltok::kw_nsw)) {
2605 if (EatIfPresent(lltok::kw_nuw))
2608 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2609 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2610 if (EatIfPresent(lltok::kw_exact))
2613 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2614 ParseGlobalTypeAndValue(Val0) ||
2615 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2616 ParseGlobalTypeAndValue(Val1) ||
2617 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2619 if (Val0->getType() != Val1->getType())
2620 return Error(ID.Loc, "operands of constexpr must have same type");
2621 if (!Val0->getType()->isIntOrIntVectorTy()) {
2623 return Error(ModifierLoc, "nuw only applies to integer operations");
2625 return Error(ModifierLoc, "nsw only applies to integer operations");
2627 // Check that the type is valid for the operator.
2629 case Instruction::Add:
2630 case Instruction::Sub:
2631 case Instruction::Mul:
2632 case Instruction::UDiv:
2633 case Instruction::SDiv:
2634 case Instruction::URem:
2635 case Instruction::SRem:
2636 case Instruction::Shl:
2637 case Instruction::AShr:
2638 case Instruction::LShr:
2639 if (!Val0->getType()->isIntOrIntVectorTy())
2640 return Error(ID.Loc, "constexpr requires integer operands");
2642 case Instruction::FAdd:
2643 case Instruction::FSub:
2644 case Instruction::FMul:
2645 case Instruction::FDiv:
2646 case Instruction::FRem:
2647 if (!Val0->getType()->isFPOrFPVectorTy())
2648 return Error(ID.Loc, "constexpr requires fp operands");
2650 default: llvm_unreachable("Unknown binary operator!");
2653 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2654 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2655 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2656 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2658 ID.Kind = ValID::t_Constant;
2662 // Logical Operations
2665 case lltok::kw_xor: {
2666 unsigned Opc = Lex.getUIntVal();
2667 Constant *Val0, *Val1;
2669 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2670 ParseGlobalTypeAndValue(Val0) ||
2671 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2672 ParseGlobalTypeAndValue(Val1) ||
2673 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2675 if (Val0->getType() != Val1->getType())
2676 return Error(ID.Loc, "operands of constexpr must have same type");
2677 if (!Val0->getType()->isIntOrIntVectorTy())
2678 return Error(ID.Loc,
2679 "constexpr requires integer or integer vector operands");
2680 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2681 ID.Kind = ValID::t_Constant;
2685 case lltok::kw_getelementptr:
2686 case lltok::kw_shufflevector:
2687 case lltok::kw_insertelement:
2688 case lltok::kw_extractelement:
2689 case lltok::kw_select: {
2690 unsigned Opc = Lex.getUIntVal();
2691 SmallVector<Constant*, 16> Elts;
2692 bool InBounds = false;
2694 if (Opc == Instruction::GetElementPtr)
2695 InBounds = EatIfPresent(lltok::kw_inbounds);
2696 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2697 ParseGlobalValueVector(Elts) ||
2698 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2701 if (Opc == Instruction::GetElementPtr) {
2702 if (Elts.size() == 0 ||
2703 !Elts[0]->getType()->getScalarType()->isPointerTy())
2704 return Error(ID.Loc, "getelementptr requires pointer operand");
2706 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2707 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2708 return Error(ID.Loc, "invalid indices for getelementptr");
2709 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2711 } else if (Opc == Instruction::Select) {
2712 if (Elts.size() != 3)
2713 return Error(ID.Loc, "expected three operands to select");
2714 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2716 return Error(ID.Loc, Reason);
2717 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2718 } else if (Opc == Instruction::ShuffleVector) {
2719 if (Elts.size() != 3)
2720 return Error(ID.Loc, "expected three operands to shufflevector");
2721 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2722 return Error(ID.Loc, "invalid operands to shufflevector");
2724 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2725 } else if (Opc == Instruction::ExtractElement) {
2726 if (Elts.size() != 2)
2727 return Error(ID.Loc, "expected two operands to extractelement");
2728 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2729 return Error(ID.Loc, "invalid extractelement operands");
2730 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2732 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2733 if (Elts.size() != 3)
2734 return Error(ID.Loc, "expected three operands to insertelement");
2735 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2736 return Error(ID.Loc, "invalid insertelement operands");
2738 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2741 ID.Kind = ValID::t_Constant;
2750 /// ParseGlobalValue - Parse a global value with the specified type.
2751 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2755 bool Parsed = ParseValID(ID) ||
2756 ConvertValIDToValue(Ty, ID, V, nullptr);
2757 if (V && !(C = dyn_cast<Constant>(V)))
2758 return Error(ID.Loc, "global values must be constants");
2762 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2764 return ParseType(Ty) ||
2765 ParseGlobalValue(Ty, V);
2768 /// ParseGlobalValueVector
2770 /// ::= TypeAndValue (',' TypeAndValue)*
2771 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2773 if (Lex.getKind() == lltok::rbrace ||
2774 Lex.getKind() == lltok::rsquare ||
2775 Lex.getKind() == lltok::greater ||
2776 Lex.getKind() == lltok::rparen)
2780 if (ParseGlobalTypeAndValue(C)) return true;
2783 while (EatIfPresent(lltok::comma)) {
2784 if (ParseGlobalTypeAndValue(C)) return true;
2791 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2792 assert(Lex.getKind() == lltok::lbrace);
2795 SmallVector<Value*, 16> Elts;
2796 if (ParseMDNodeVector(Elts, PFS) ||
2797 ParseToken(lltok::rbrace, "expected end of metadata node"))
2800 ID.MDNodeVal = MDNode::get(Context, Elts);
2801 ID.Kind = ValID::t_MDNode;
2805 /// ParseMetadataValue
2809 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2810 assert(Lex.getKind() == lltok::exclaim);
2815 if (Lex.getKind() == lltok::lbrace)
2816 return ParseMetadataListValue(ID, PFS);
2818 // Standalone metadata reference
2820 if (Lex.getKind() == lltok::APSInt) {
2821 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2822 ID.Kind = ValID::t_MDNode;
2827 // ::= '!' STRINGCONSTANT
2828 if (ParseMDString(ID.MDStringVal)) return true;
2829 ID.Kind = ValID::t_MDString;
2834 //===----------------------------------------------------------------------===//
2835 // Function Parsing.
2836 //===----------------------------------------------------------------------===//
2838 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2839 PerFunctionState *PFS) {
2840 if (Ty->isFunctionTy())
2841 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2844 case ValID::t_LocalID:
2845 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2846 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2847 return V == nullptr;
2848 case ValID::t_LocalName:
2849 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2850 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2851 return V == nullptr;
2852 case ValID::t_InlineAsm: {
2853 PointerType *PTy = dyn_cast<PointerType>(Ty);
2855 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2856 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2857 return Error(ID.Loc, "invalid type for inline asm constraint string");
2858 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2859 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2862 case ValID::t_MDNode:
2863 if (!Ty->isMetadataTy())
2864 return Error(ID.Loc, "metadata value must have metadata type");
2867 case ValID::t_MDString:
2868 if (!Ty->isMetadataTy())
2869 return Error(ID.Loc, "metadata value must have metadata type");
2872 case ValID::t_GlobalName:
2873 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2874 return V == nullptr;
2875 case ValID::t_GlobalID:
2876 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2877 return V == nullptr;
2878 case ValID::t_APSInt:
2879 if (!Ty->isIntegerTy())
2880 return Error(ID.Loc, "integer constant must have integer type");
2881 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2882 V = ConstantInt::get(Context, ID.APSIntVal);
2884 case ValID::t_APFloat:
2885 if (!Ty->isFloatingPointTy() ||
2886 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2887 return Error(ID.Loc, "floating point constant invalid for type");
2889 // The lexer has no type info, so builds all half, float, and double FP
2890 // constants as double. Fix this here. Long double does not need this.
2891 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2894 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2896 else if (Ty->isFloatTy())
2897 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2900 V = ConstantFP::get(Context, ID.APFloatVal);
2902 if (V->getType() != Ty)
2903 return Error(ID.Loc, "floating point constant does not have type '" +
2904 getTypeString(Ty) + "'");
2908 if (!Ty->isPointerTy())
2909 return Error(ID.Loc, "null must be a pointer type");
2910 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2912 case ValID::t_Undef:
2913 // FIXME: LabelTy should not be a first-class type.
2914 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2915 return Error(ID.Loc, "invalid type for undef constant");
2916 V = UndefValue::get(Ty);
2918 case ValID::t_EmptyArray:
2919 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2920 return Error(ID.Loc, "invalid empty array initializer");
2921 V = UndefValue::get(Ty);
2924 // FIXME: LabelTy should not be a first-class type.
2925 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2926 return Error(ID.Loc, "invalid type for null constant");
2927 V = Constant::getNullValue(Ty);
2929 case ValID::t_Constant:
2930 if (ID.ConstantVal->getType() != Ty)
2931 return Error(ID.Loc, "constant expression type mismatch");
2935 case ValID::t_ConstantStruct:
2936 case ValID::t_PackedConstantStruct:
2937 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2938 if (ST->getNumElements() != ID.UIntVal)
2939 return Error(ID.Loc,
2940 "initializer with struct type has wrong # elements");
2941 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2942 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2944 // Verify that the elements are compatible with the structtype.
2945 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2946 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2947 return Error(ID.Loc, "element " + Twine(i) +
2948 " of struct initializer doesn't match struct element type");
2950 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2953 return Error(ID.Loc, "constant expression type mismatch");
2956 llvm_unreachable("Invalid ValID");
2959 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2962 return ParseValID(ID, PFS) ||
2963 ConvertValIDToValue(Ty, ID, V, PFS);
2966 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2968 return ParseType(Ty) ||
2969 ParseValue(Ty, V, PFS);
2972 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2973 PerFunctionState &PFS) {
2976 if (ParseTypeAndValue(V, PFS)) return true;
2977 if (!isa<BasicBlock>(V))
2978 return Error(Loc, "expected a basic block");
2979 BB = cast<BasicBlock>(V);
2985 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2986 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2987 /// OptionalAlign OptGC OptionalPrefix
2988 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2989 // Parse the linkage.
2990 LocTy LinkageLoc = Lex.getLoc();
2993 unsigned Visibility;
2994 unsigned DLLStorageClass;
2995 AttrBuilder RetAttrs;
2997 Type *RetType = nullptr;
2998 LocTy RetTypeLoc = Lex.getLoc();
2999 if (ParseOptionalLinkage(Linkage) ||
3000 ParseOptionalVisibility(Visibility) ||
3001 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3002 ParseOptionalCallingConv(CC) ||
3003 ParseOptionalReturnAttrs(RetAttrs) ||
3004 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3007 // Verify that the linkage is ok.
3008 switch ((GlobalValue::LinkageTypes)Linkage) {
3009 case GlobalValue::ExternalLinkage:
3010 break; // always ok.
3011 case GlobalValue::ExternalWeakLinkage:
3013 return Error(LinkageLoc, "invalid linkage for function definition");
3015 case GlobalValue::PrivateLinkage:
3016 case GlobalValue::InternalLinkage:
3017 case GlobalValue::AvailableExternallyLinkage:
3018 case GlobalValue::LinkOnceAnyLinkage:
3019 case GlobalValue::LinkOnceODRLinkage:
3020 case GlobalValue::WeakAnyLinkage:
3021 case GlobalValue::WeakODRLinkage:
3023 return Error(LinkageLoc, "invalid linkage for function declaration");
3025 case GlobalValue::AppendingLinkage:
3026 case GlobalValue::CommonLinkage:
3027 return Error(LinkageLoc, "invalid function linkage type");
3030 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3031 return Error(LinkageLoc,
3032 "symbol with local linkage must have default visibility");
3034 if (!FunctionType::isValidReturnType(RetType))
3035 return Error(RetTypeLoc, "invalid function return type");
3037 LocTy NameLoc = Lex.getLoc();
3039 std::string FunctionName;
3040 if (Lex.getKind() == lltok::GlobalVar) {
3041 FunctionName = Lex.getStrVal();
3042 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3043 unsigned NameID = Lex.getUIntVal();
3045 if (NameID != NumberedVals.size())
3046 return TokError("function expected to be numbered '%" +
3047 Twine(NumberedVals.size()) + "'");
3049 return TokError("expected function name");
3054 if (Lex.getKind() != lltok::lparen)
3055 return TokError("expected '(' in function argument list");
3057 SmallVector<ArgInfo, 8> ArgList;
3059 AttrBuilder FuncAttrs;
3060 std::vector<unsigned> FwdRefAttrGrps;
3062 std::string Section;
3066 LocTy UnnamedAddrLoc;
3067 Constant *Prefix = nullptr;
3069 if (ParseArgumentList(ArgList, isVarArg) ||
3070 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3072 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3074 (EatIfPresent(lltok::kw_section) &&
3075 ParseStringConstant(Section)) ||
3076 ParseOptionalAlignment(Alignment) ||
3077 (EatIfPresent(lltok::kw_gc) &&
3078 ParseStringConstant(GC)) ||
3079 (EatIfPresent(lltok::kw_prefix) &&
3080 ParseGlobalTypeAndValue(Prefix)))
3083 if (FuncAttrs.contains(Attribute::Builtin))
3084 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3086 // If the alignment was parsed as an attribute, move to the alignment field.
3087 if (FuncAttrs.hasAlignmentAttr()) {
3088 Alignment = FuncAttrs.getAlignment();
3089 FuncAttrs.removeAttribute(Attribute::Alignment);
3092 // Okay, if we got here, the function is syntactically valid. Convert types
3093 // and do semantic checks.
3094 std::vector<Type*> ParamTypeList;
3095 SmallVector<AttributeSet, 8> Attrs;
3097 if (RetAttrs.hasAttributes())
3098 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3099 AttributeSet::ReturnIndex,
3102 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3103 ParamTypeList.push_back(ArgList[i].Ty);
3104 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3105 AttrBuilder B(ArgList[i].Attrs, i + 1);
3106 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3110 if (FuncAttrs.hasAttributes())
3111 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3112 AttributeSet::FunctionIndex,
3115 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3117 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3118 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3121 FunctionType::get(RetType, ParamTypeList, isVarArg);
3122 PointerType *PFT = PointerType::getUnqual(FT);
3125 if (!FunctionName.empty()) {
3126 // If this was a definition of a forward reference, remove the definition
3127 // from the forward reference table and fill in the forward ref.
3128 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3129 ForwardRefVals.find(FunctionName);
3130 if (FRVI != ForwardRefVals.end()) {
3131 Fn = M->getFunction(FunctionName);
3133 return Error(FRVI->second.second, "invalid forward reference to "
3134 "function as global value!");
3135 if (Fn->getType() != PFT)
3136 return Error(FRVI->second.second, "invalid forward reference to "
3137 "function '" + FunctionName + "' with wrong type!");
3139 ForwardRefVals.erase(FRVI);
3140 } else if ((Fn = M->getFunction(FunctionName))) {
3141 // Reject redefinitions.
3142 return Error(NameLoc, "invalid redefinition of function '" +
3143 FunctionName + "'");
3144 } else if (M->getNamedValue(FunctionName)) {
3145 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3149 // If this is a definition of a forward referenced function, make sure the
3151 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3152 = ForwardRefValIDs.find(NumberedVals.size());
3153 if (I != ForwardRefValIDs.end()) {
3154 Fn = cast<Function>(I->second.first);
3155 if (Fn->getType() != PFT)
3156 return Error(NameLoc, "type of definition and forward reference of '@" +
3157 Twine(NumberedVals.size()) + "' disagree");
3158 ForwardRefValIDs.erase(I);
3163 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3164 else // Move the forward-reference to the correct spot in the module.
3165 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3167 if (FunctionName.empty())
3168 NumberedVals.push_back(Fn);
3170 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3171 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3172 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3173 Fn->setCallingConv(CC);
3174 Fn->setAttributes(PAL);
3175 Fn->setUnnamedAddr(UnnamedAddr);
3176 Fn->setAlignment(Alignment);
3177 Fn->setSection(Section);
3178 if (!GC.empty()) Fn->setGC(GC.c_str());
3179 Fn->setPrefixData(Prefix);
3180 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3182 // Add all of the arguments we parsed to the function.
3183 Function::arg_iterator ArgIt = Fn->arg_begin();
3184 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3185 // If the argument has a name, insert it into the argument symbol table.
3186 if (ArgList[i].Name.empty()) continue;
3188 // Set the name, if it conflicted, it will be auto-renamed.
3189 ArgIt->setName(ArgList[i].Name);
3191 if (ArgIt->getName() != ArgList[i].Name)
3192 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3193 ArgList[i].Name + "'");
3200 /// ParseFunctionBody
3201 /// ::= '{' BasicBlock+ '}'
3203 bool LLParser::ParseFunctionBody(Function &Fn) {
3204 if (Lex.getKind() != lltok::lbrace)
3205 return TokError("expected '{' in function body");
3206 Lex.Lex(); // eat the {.
3208 int FunctionNumber = -1;
3209 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3211 PerFunctionState PFS(*this, Fn, FunctionNumber);
3213 // We need at least one basic block.
3214 if (Lex.getKind() == lltok::rbrace)
3215 return TokError("function body requires at least one basic block");
3217 while (Lex.getKind() != lltok::rbrace)
3218 if (ParseBasicBlock(PFS)) return true;
3223 // Verify function is ok.
3224 return PFS.FinishFunction();
3228 /// ::= LabelStr? Instruction*
3229 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3230 // If this basic block starts out with a name, remember it.
3232 LocTy NameLoc = Lex.getLoc();
3233 if (Lex.getKind() == lltok::LabelStr) {
3234 Name = Lex.getStrVal();
3238 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3239 if (!BB) return true;
3241 std::string NameStr;
3243 // Parse the instructions in this block until we get a terminator.
3246 // This instruction may have three possibilities for a name: a) none
3247 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3248 LocTy NameLoc = Lex.getLoc();
3252 if (Lex.getKind() == lltok::LocalVarID) {
3253 NameID = Lex.getUIntVal();
3255 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3257 } else if (Lex.getKind() == lltok::LocalVar) {
3258 NameStr = Lex.getStrVal();
3260 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3264 switch (ParseInstruction(Inst, BB, PFS)) {
3265 default: llvm_unreachable("Unknown ParseInstruction result!");
3266 case InstError: return true;
3268 BB->getInstList().push_back(Inst);
3270 // With a normal result, we check to see if the instruction is followed by
3271 // a comma and metadata.
3272 if (EatIfPresent(lltok::comma))
3273 if (ParseInstructionMetadata(Inst, &PFS))
3276 case InstExtraComma:
3277 BB->getInstList().push_back(Inst);
3279 // If the instruction parser ate an extra comma at the end of it, it
3280 // *must* be followed by metadata.
3281 if (ParseInstructionMetadata(Inst, &PFS))
3286 // Set the name on the instruction.
3287 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3288 } while (!isa<TerminatorInst>(Inst));
3293 //===----------------------------------------------------------------------===//
3294 // Instruction Parsing.
3295 //===----------------------------------------------------------------------===//
3297 /// ParseInstruction - Parse one of the many different instructions.
3299 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3300 PerFunctionState &PFS) {
3301 lltok::Kind Token = Lex.getKind();
3302 if (Token == lltok::Eof)
3303 return TokError("found end of file when expecting more instructions");
3304 LocTy Loc = Lex.getLoc();
3305 unsigned KeywordVal = Lex.getUIntVal();
3306 Lex.Lex(); // Eat the keyword.
3309 default: return Error(Loc, "expected instruction opcode");
3310 // Terminator Instructions.
3311 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3312 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3313 case lltok::kw_br: return ParseBr(Inst, PFS);
3314 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3315 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3316 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3317 case lltok::kw_resume: return ParseResume(Inst, PFS);
3318 // Binary Operators.
3322 case lltok::kw_shl: {
3323 bool NUW = EatIfPresent(lltok::kw_nuw);
3324 bool NSW = EatIfPresent(lltok::kw_nsw);
3325 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3327 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3329 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3330 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3333 case lltok::kw_fadd:
3334 case lltok::kw_fsub:
3335 case lltok::kw_fmul:
3336 case lltok::kw_fdiv:
3337 case lltok::kw_frem: {
3338 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3339 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3343 Inst->setFastMathFlags(FMF);
3347 case lltok::kw_sdiv:
3348 case lltok::kw_udiv:
3349 case lltok::kw_lshr:
3350 case lltok::kw_ashr: {
3351 bool Exact = EatIfPresent(lltok::kw_exact);
3353 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3354 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3358 case lltok::kw_urem:
3359 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3362 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3363 case lltok::kw_icmp:
3364 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3366 case lltok::kw_trunc:
3367 case lltok::kw_zext:
3368 case lltok::kw_sext:
3369 case lltok::kw_fptrunc:
3370 case lltok::kw_fpext:
3371 case lltok::kw_bitcast:
3372 case lltok::kw_addrspacecast:
3373 case lltok::kw_uitofp:
3374 case lltok::kw_sitofp:
3375 case lltok::kw_fptoui:
3376 case lltok::kw_fptosi:
3377 case lltok::kw_inttoptr:
3378 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3380 case lltok::kw_select: return ParseSelect(Inst, PFS);
3381 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3382 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3383 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3384 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3385 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3386 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3388 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3389 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3390 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3392 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3393 case lltok::kw_load: return ParseLoad(Inst, PFS);
3394 case lltok::kw_store: return ParseStore(Inst, PFS);
3395 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3396 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3397 case lltok::kw_fence: return ParseFence(Inst, PFS);
3398 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3399 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3400 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3404 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3405 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3406 if (Opc == Instruction::FCmp) {
3407 switch (Lex.getKind()) {
3408 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3409 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3410 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3411 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3412 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3413 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3414 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3415 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3416 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3417 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3418 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3419 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3420 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3421 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3422 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3423 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3424 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3427 switch (Lex.getKind()) {
3428 default: return TokError("expected icmp predicate (e.g. 'eq')");
3429 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3430 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3431 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3432 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3433 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3434 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3435 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3436 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3437 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3438 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3445 //===----------------------------------------------------------------------===//
3446 // Terminator Instructions.
3447 //===----------------------------------------------------------------------===//
3449 /// ParseRet - Parse a return instruction.
3450 /// ::= 'ret' void (',' !dbg, !1)*
3451 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3452 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3453 PerFunctionState &PFS) {
3454 SMLoc TypeLoc = Lex.getLoc();
3456 if (ParseType(Ty, true /*void allowed*/)) return true;
3458 Type *ResType = PFS.getFunction().getReturnType();
3460 if (Ty->isVoidTy()) {
3461 if (!ResType->isVoidTy())
3462 return Error(TypeLoc, "value doesn't match function result type '" +
3463 getTypeString(ResType) + "'");
3465 Inst = ReturnInst::Create(Context);
3470 if (ParseValue(Ty, RV, PFS)) return true;
3472 if (ResType != RV->getType())
3473 return Error(TypeLoc, "value doesn't match function result type '" +
3474 getTypeString(ResType) + "'");
3476 Inst = ReturnInst::Create(Context, RV);
3482 /// ::= 'br' TypeAndValue
3483 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3484 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3487 BasicBlock *Op1, *Op2;
3488 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3490 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3491 Inst = BranchInst::Create(BB);
3495 if (Op0->getType() != Type::getInt1Ty(Context))
3496 return Error(Loc, "branch condition must have 'i1' type");
3498 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3499 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3500 ParseToken(lltok::comma, "expected ',' after true destination") ||
3501 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3504 Inst = BranchInst::Create(Op1, Op2, Op0);
3510 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3512 /// ::= (TypeAndValue ',' TypeAndValue)*
3513 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3514 LocTy CondLoc, BBLoc;
3516 BasicBlock *DefaultBB;
3517 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3518 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3519 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3520 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3523 if (!Cond->getType()->isIntegerTy())
3524 return Error(CondLoc, "switch condition must have integer type");
3526 // Parse the jump table pairs.
3527 SmallPtrSet<Value*, 32> SeenCases;
3528 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3529 while (Lex.getKind() != lltok::rsquare) {
3533 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3534 ParseToken(lltok::comma, "expected ',' after case value") ||
3535 ParseTypeAndBasicBlock(DestBB, PFS))
3538 if (!SeenCases.insert(Constant))
3539 return Error(CondLoc, "duplicate case value in switch");
3540 if (!isa<ConstantInt>(Constant))
3541 return Error(CondLoc, "case value is not a constant integer");
3543 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3546 Lex.Lex(); // Eat the ']'.
3548 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3549 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3550 SI->addCase(Table[i].first, Table[i].second);
3557 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3558 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3561 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3562 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3563 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3566 if (!Address->getType()->isPointerTy())
3567 return Error(AddrLoc, "indirectbr address must have pointer type");
3569 // Parse the destination list.
3570 SmallVector<BasicBlock*, 16> DestList;
3572 if (Lex.getKind() != lltok::rsquare) {
3574 if (ParseTypeAndBasicBlock(DestBB, PFS))
3576 DestList.push_back(DestBB);
3578 while (EatIfPresent(lltok::comma)) {
3579 if (ParseTypeAndBasicBlock(DestBB, PFS))
3581 DestList.push_back(DestBB);
3585 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3588 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3589 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3590 IBI->addDestination(DestList[i]);
3597 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3598 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3599 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3600 LocTy CallLoc = Lex.getLoc();
3601 AttrBuilder RetAttrs, FnAttrs;
3602 std::vector<unsigned> FwdRefAttrGrps;
3605 Type *RetType = nullptr;
3608 SmallVector<ParamInfo, 16> ArgList;
3610 BasicBlock *NormalBB, *UnwindBB;
3611 if (ParseOptionalCallingConv(CC) ||
3612 ParseOptionalReturnAttrs(RetAttrs) ||
3613 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3614 ParseValID(CalleeID) ||
3615 ParseParameterList(ArgList, PFS) ||
3616 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3618 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3619 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3620 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3621 ParseTypeAndBasicBlock(UnwindBB, PFS))
3624 // If RetType is a non-function pointer type, then this is the short syntax
3625 // for the call, which means that RetType is just the return type. Infer the
3626 // rest of the function argument types from the arguments that are present.
3627 PointerType *PFTy = nullptr;
3628 FunctionType *Ty = nullptr;
3629 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3630 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3631 // Pull out the types of all of the arguments...
3632 std::vector<Type*> ParamTypes;
3633 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3634 ParamTypes.push_back(ArgList[i].V->getType());
3636 if (!FunctionType::isValidReturnType(RetType))
3637 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3639 Ty = FunctionType::get(RetType, ParamTypes, false);
3640 PFTy = PointerType::getUnqual(Ty);
3643 // Look up the callee.
3645 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3647 // Set up the Attribute for the function.
3648 SmallVector<AttributeSet, 8> Attrs;
3649 if (RetAttrs.hasAttributes())
3650 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3651 AttributeSet::ReturnIndex,
3654 SmallVector<Value*, 8> Args;
3656 // Loop through FunctionType's arguments and ensure they are specified
3657 // correctly. Also, gather any parameter attributes.
3658 FunctionType::param_iterator I = Ty->param_begin();
3659 FunctionType::param_iterator E = Ty->param_end();
3660 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3661 Type *ExpectedTy = nullptr;
3664 } else if (!Ty->isVarArg()) {
3665 return Error(ArgList[i].Loc, "too many arguments specified");
3668 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3669 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3670 getTypeString(ExpectedTy) + "'");
3671 Args.push_back(ArgList[i].V);
3672 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3673 AttrBuilder B(ArgList[i].Attrs, i + 1);
3674 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3679 return Error(CallLoc, "not enough parameters specified for call");
3681 if (FnAttrs.hasAttributes())
3682 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3683 AttributeSet::FunctionIndex,
3686 // Finish off the Attribute and check them
3687 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3689 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3690 II->setCallingConv(CC);
3691 II->setAttributes(PAL);
3692 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3698 /// ::= 'resume' TypeAndValue
3699 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3700 Value *Exn; LocTy ExnLoc;
3701 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3704 ResumeInst *RI = ResumeInst::Create(Exn);
3709 //===----------------------------------------------------------------------===//
3710 // Binary Operators.
3711 //===----------------------------------------------------------------------===//
3714 /// ::= ArithmeticOps TypeAndValue ',' Value
3716 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3717 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3718 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3719 unsigned Opc, unsigned OperandType) {
3720 LocTy Loc; Value *LHS, *RHS;
3721 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3722 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3723 ParseValue(LHS->getType(), RHS, PFS))
3727 switch (OperandType) {
3728 default: llvm_unreachable("Unknown operand type!");
3729 case 0: // int or FP.
3730 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3731 LHS->getType()->isFPOrFPVectorTy();
3733 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3734 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3738 return Error(Loc, "invalid operand type for instruction");
3740 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3745 /// ::= ArithmeticOps TypeAndValue ',' Value {
3746 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3748 LocTy Loc; Value *LHS, *RHS;
3749 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3750 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3751 ParseValue(LHS->getType(), RHS, PFS))
3754 if (!LHS->getType()->isIntOrIntVectorTy())
3755 return Error(Loc,"instruction requires integer or integer vector operands");
3757 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3763 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3764 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3765 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3767 // Parse the integer/fp comparison predicate.
3771 if (ParseCmpPredicate(Pred, Opc) ||
3772 ParseTypeAndValue(LHS, Loc, PFS) ||
3773 ParseToken(lltok::comma, "expected ',' after compare value") ||
3774 ParseValue(LHS->getType(), RHS, PFS))
3777 if (Opc == Instruction::FCmp) {
3778 if (!LHS->getType()->isFPOrFPVectorTy())
3779 return Error(Loc, "fcmp requires floating point operands");
3780 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3782 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3783 if (!LHS->getType()->isIntOrIntVectorTy() &&
3784 !LHS->getType()->getScalarType()->isPointerTy())
3785 return Error(Loc, "icmp requires integer operands");
3786 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3791 //===----------------------------------------------------------------------===//
3792 // Other Instructions.
3793 //===----------------------------------------------------------------------===//
3797 /// ::= CastOpc TypeAndValue 'to' Type
3798 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3802 Type *DestTy = nullptr;
3803 if (ParseTypeAndValue(Op, Loc, PFS) ||
3804 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3808 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3809 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3810 return Error(Loc, "invalid cast opcode for cast from '" +
3811 getTypeString(Op->getType()) + "' to '" +
3812 getTypeString(DestTy) + "'");
3814 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3819 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3820 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3822 Value *Op0, *Op1, *Op2;
3823 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3824 ParseToken(lltok::comma, "expected ',' after select condition") ||
3825 ParseTypeAndValue(Op1, PFS) ||
3826 ParseToken(lltok::comma, "expected ',' after select value") ||
3827 ParseTypeAndValue(Op2, PFS))
3830 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3831 return Error(Loc, Reason);
3833 Inst = SelectInst::Create(Op0, Op1, Op2);
3838 /// ::= 'va_arg' TypeAndValue ',' Type
3839 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3841 Type *EltTy = nullptr;
3843 if (ParseTypeAndValue(Op, PFS) ||
3844 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3845 ParseType(EltTy, TypeLoc))
3848 if (!EltTy->isFirstClassType())
3849 return Error(TypeLoc, "va_arg requires operand with first class type");
3851 Inst = new VAArgInst(Op, EltTy);
3855 /// ParseExtractElement
3856 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3857 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3860 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3861 ParseToken(lltok::comma, "expected ',' after extract value") ||
3862 ParseTypeAndValue(Op1, PFS))
3865 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3866 return Error(Loc, "invalid extractelement operands");
3868 Inst = ExtractElementInst::Create(Op0, Op1);
3872 /// ParseInsertElement
3873 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3874 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3876 Value *Op0, *Op1, *Op2;
3877 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3878 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3879 ParseTypeAndValue(Op1, PFS) ||
3880 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3881 ParseTypeAndValue(Op2, PFS))
3884 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3885 return Error(Loc, "invalid insertelement operands");
3887 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3891 /// ParseShuffleVector
3892 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3893 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3895 Value *Op0, *Op1, *Op2;
3896 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3897 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3898 ParseTypeAndValue(Op1, PFS) ||
3899 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3900 ParseTypeAndValue(Op2, PFS))
3903 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3904 return Error(Loc, "invalid shufflevector operands");
3906 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3911 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3912 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3913 Type *Ty = nullptr; LocTy TypeLoc;
3916 if (ParseType(Ty, TypeLoc) ||
3917 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3918 ParseValue(Ty, Op0, PFS) ||
3919 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3920 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3921 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3924 bool AteExtraComma = false;
3925 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3927 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3929 if (!EatIfPresent(lltok::comma))
3932 if (Lex.getKind() == lltok::MetadataVar) {
3933 AteExtraComma = true;
3937 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3938 ParseValue(Ty, Op0, PFS) ||
3939 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3940 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3941 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3945 if (!Ty->isFirstClassType())
3946 return Error(TypeLoc, "phi node must have first class type");
3948 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3949 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3950 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3952 return AteExtraComma ? InstExtraComma : InstNormal;
3956 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3958 /// ::= 'catch' TypeAndValue
3960 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3961 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3962 Type *Ty = nullptr; LocTy TyLoc;
3963 Value *PersFn; LocTy PersFnLoc;
3965 if (ParseType(Ty, TyLoc) ||
3966 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3967 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3970 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3971 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3973 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3974 LandingPadInst::ClauseType CT;
3975 if (EatIfPresent(lltok::kw_catch))
3976 CT = LandingPadInst::Catch;
3977 else if (EatIfPresent(lltok::kw_filter))
3978 CT = LandingPadInst::Filter;
3980 return TokError("expected 'catch' or 'filter' clause type");
3982 Value *V; LocTy VLoc;
3983 if (ParseTypeAndValue(V, VLoc, PFS)) {
3988 // A 'catch' type expects a non-array constant. A filter clause expects an
3990 if (CT == LandingPadInst::Catch) {
3991 if (isa<ArrayType>(V->getType()))
3992 Error(VLoc, "'catch' clause has an invalid type");
3994 if (!isa<ArrayType>(V->getType()))
3995 Error(VLoc, "'filter' clause has an invalid type");
4006 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4007 /// ParameterList OptionalAttrs
4008 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4009 /// ParameterList OptionalAttrs
4010 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4011 /// ParameterList OptionalAttrs
4012 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4013 CallInst::TailCallKind TCK) {
4014 AttrBuilder RetAttrs, FnAttrs;
4015 std::vector<unsigned> FwdRefAttrGrps;
4018 Type *RetType = nullptr;
4021 SmallVector<ParamInfo, 16> ArgList;
4022 LocTy CallLoc = Lex.getLoc();
4024 if ((TCK != CallInst::TCK_None &&
4025 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4026 ParseOptionalCallingConv(CC) ||
4027 ParseOptionalReturnAttrs(RetAttrs) ||
4028 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4029 ParseValID(CalleeID) ||
4030 ParseParameterList(ArgList, PFS) ||
4031 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4035 // If RetType is a non-function pointer type, then this is the short syntax
4036 // for the call, which means that RetType is just the return type. Infer the
4037 // rest of the function argument types from the arguments that are present.
4038 PointerType *PFTy = nullptr;
4039 FunctionType *Ty = nullptr;
4040 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4041 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4042 // Pull out the types of all of the arguments...
4043 std::vector<Type*> ParamTypes;
4044 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4045 ParamTypes.push_back(ArgList[i].V->getType());
4047 if (!FunctionType::isValidReturnType(RetType))
4048 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4050 Ty = FunctionType::get(RetType, ParamTypes, false);
4051 PFTy = PointerType::getUnqual(Ty);
4054 // Look up the callee.
4056 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4058 // Set up the Attribute for the function.
4059 SmallVector<AttributeSet, 8> Attrs;
4060 if (RetAttrs.hasAttributes())
4061 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4062 AttributeSet::ReturnIndex,
4065 SmallVector<Value*, 8> Args;
4067 // Loop through FunctionType's arguments and ensure they are specified
4068 // correctly. Also, gather any parameter attributes.
4069 FunctionType::param_iterator I = Ty->param_begin();
4070 FunctionType::param_iterator E = Ty->param_end();
4071 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4072 Type *ExpectedTy = nullptr;
4075 } else if (!Ty->isVarArg()) {
4076 return Error(ArgList[i].Loc, "too many arguments specified");
4079 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4080 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4081 getTypeString(ExpectedTy) + "'");
4082 Args.push_back(ArgList[i].V);
4083 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4084 AttrBuilder B(ArgList[i].Attrs, i + 1);
4085 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4090 return Error(CallLoc, "not enough parameters specified for call");
4092 if (FnAttrs.hasAttributes())
4093 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4094 AttributeSet::FunctionIndex,
4097 // Finish off the Attribute and check them
4098 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4100 CallInst *CI = CallInst::Create(Callee, Args);
4101 CI->setTailCallKind(TCK);
4102 CI->setCallingConv(CC);
4103 CI->setAttributes(PAL);
4104 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4109 //===----------------------------------------------------------------------===//
4110 // Memory Instructions.
4111 //===----------------------------------------------------------------------===//
4114 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4115 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4116 Value *Size = nullptr;
4118 unsigned Alignment = 0;
4121 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4123 if (ParseType(Ty)) return true;
4125 bool AteExtraComma = false;
4126 if (EatIfPresent(lltok::comma)) {
4127 if (Lex.getKind() == lltok::kw_align) {
4128 if (ParseOptionalAlignment(Alignment)) return true;
4129 } else if (Lex.getKind() == lltok::MetadataVar) {
4130 AteExtraComma = true;
4132 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4133 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4138 if (Size && !Size->getType()->isIntegerTy())
4139 return Error(SizeLoc, "element count must have integer type");
4141 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4142 AI->setUsedWithInAlloca(IsInAlloca);
4144 return AteExtraComma ? InstExtraComma : InstNormal;
4148 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4149 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4150 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4151 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4152 Value *Val; LocTy Loc;
4153 unsigned Alignment = 0;
4154 bool AteExtraComma = false;
4155 bool isAtomic = false;
4156 AtomicOrdering Ordering = NotAtomic;
4157 SynchronizationScope Scope = CrossThread;
4159 if (Lex.getKind() == lltok::kw_atomic) {
4164 bool isVolatile = false;
4165 if (Lex.getKind() == lltok::kw_volatile) {
4170 if (ParseTypeAndValue(Val, Loc, PFS) ||
4171 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4172 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4175 if (!Val->getType()->isPointerTy() ||
4176 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4177 return Error(Loc, "load operand must be a pointer to a first class type");
4178 if (isAtomic && !Alignment)
4179 return Error(Loc, "atomic load must have explicit non-zero alignment");
4180 if (Ordering == Release || Ordering == AcquireRelease)
4181 return Error(Loc, "atomic load cannot use Release ordering");
4183 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4184 return AteExtraComma ? InstExtraComma : InstNormal;
4189 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4190 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4191 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4192 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4193 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4194 unsigned Alignment = 0;
4195 bool AteExtraComma = false;
4196 bool isAtomic = false;
4197 AtomicOrdering Ordering = NotAtomic;
4198 SynchronizationScope Scope = CrossThread;
4200 if (Lex.getKind() == lltok::kw_atomic) {
4205 bool isVolatile = false;
4206 if (Lex.getKind() == lltok::kw_volatile) {
4211 if (ParseTypeAndValue(Val, Loc, PFS) ||
4212 ParseToken(lltok::comma, "expected ',' after store operand") ||
4213 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4214 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4215 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4218 if (!Ptr->getType()->isPointerTy())
4219 return Error(PtrLoc, "store operand must be a pointer");
4220 if (!Val->getType()->isFirstClassType())
4221 return Error(Loc, "store operand must be a first class value");
4222 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4223 return Error(Loc, "stored value and pointer type do not match");
4224 if (isAtomic && !Alignment)
4225 return Error(Loc, "atomic store must have explicit non-zero alignment");
4226 if (Ordering == Acquire || Ordering == AcquireRelease)
4227 return Error(Loc, "atomic store cannot use Acquire ordering");
4229 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4230 return AteExtraComma ? InstExtraComma : InstNormal;
4234 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4235 /// 'singlethread'? AtomicOrdering AtomicOrdering
4236 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4237 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4238 bool AteExtraComma = false;
4239 AtomicOrdering SuccessOrdering = NotAtomic;
4240 AtomicOrdering FailureOrdering = NotAtomic;
4241 SynchronizationScope Scope = CrossThread;
4242 bool isVolatile = false;
4244 if (EatIfPresent(lltok::kw_volatile))
4247 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4248 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4249 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4250 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4251 ParseTypeAndValue(New, NewLoc, PFS) ||
4252 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4253 ParseOrdering(FailureOrdering))
4256 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4257 return TokError("cmpxchg cannot be unordered");
4258 if (SuccessOrdering < FailureOrdering)
4259 return TokError("cmpxchg must be at least as ordered on success as failure");
4260 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4261 return TokError("cmpxchg failure ordering cannot include release semantics");
4262 if (!Ptr->getType()->isPointerTy())
4263 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4264 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4265 return Error(CmpLoc, "compare value and pointer type do not match");
4266 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4267 return Error(NewLoc, "new value and pointer type do not match");
4268 if (!New->getType()->isIntegerTy())
4269 return Error(NewLoc, "cmpxchg operand must be an integer");
4270 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4271 if (Size < 8 || (Size & (Size - 1)))
4272 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4275 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4276 FailureOrdering, Scope);
4277 CXI->setVolatile(isVolatile);
4279 return AteExtraComma ? InstExtraComma : InstNormal;
4283 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4284 /// 'singlethread'? AtomicOrdering
4285 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4286 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4287 bool AteExtraComma = false;
4288 AtomicOrdering Ordering = NotAtomic;
4289 SynchronizationScope Scope = CrossThread;
4290 bool isVolatile = false;
4291 AtomicRMWInst::BinOp Operation;
4293 if (EatIfPresent(lltok::kw_volatile))
4296 switch (Lex.getKind()) {
4297 default: return TokError("expected binary operation in atomicrmw");
4298 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4299 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4300 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4301 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4302 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4303 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4304 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4305 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4306 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4307 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4308 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4310 Lex.Lex(); // Eat the operation.
4312 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4313 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4314 ParseTypeAndValue(Val, ValLoc, PFS) ||
4315 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4318 if (Ordering == Unordered)
4319 return TokError("atomicrmw cannot be unordered");
4320 if (!Ptr->getType()->isPointerTy())
4321 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4322 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4323 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4324 if (!Val->getType()->isIntegerTy())
4325 return Error(ValLoc, "atomicrmw operand must be an integer");
4326 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4327 if (Size < 8 || (Size & (Size - 1)))
4328 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4331 AtomicRMWInst *RMWI =
4332 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4333 RMWI->setVolatile(isVolatile);
4335 return AteExtraComma ? InstExtraComma : InstNormal;
4339 /// ::= 'fence' 'singlethread'? AtomicOrdering
4340 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4341 AtomicOrdering Ordering = NotAtomic;
4342 SynchronizationScope Scope = CrossThread;
4343 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4346 if (Ordering == Unordered)
4347 return TokError("fence cannot be unordered");
4348 if (Ordering == Monotonic)
4349 return TokError("fence cannot be monotonic");
4351 Inst = new FenceInst(Context, Ordering, Scope);
4355 /// ParseGetElementPtr
4356 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4357 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4358 Value *Ptr = nullptr;
4359 Value *Val = nullptr;
4362 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4364 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4366 Type *BaseType = Ptr->getType();
4367 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4368 if (!BasePointerType)
4369 return Error(Loc, "base of getelementptr must be a pointer");
4371 SmallVector<Value*, 16> Indices;
4372 bool AteExtraComma = false;
4373 while (EatIfPresent(lltok::comma)) {
4374 if (Lex.getKind() == lltok::MetadataVar) {
4375 AteExtraComma = true;
4378 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4379 if (!Val->getType()->getScalarType()->isIntegerTy())
4380 return Error(EltLoc, "getelementptr index must be an integer");
4381 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4382 return Error(EltLoc, "getelementptr index type missmatch");
4383 if (Val->getType()->isVectorTy()) {
4384 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4385 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4386 if (ValNumEl != PtrNumEl)
4387 return Error(EltLoc,
4388 "getelementptr vector index has a wrong number of elements");
4390 Indices.push_back(Val);
4393 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4394 return Error(Loc, "base element of getelementptr must be sized");
4396 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4397 return Error(Loc, "invalid getelementptr indices");
4398 Inst = GetElementPtrInst::Create(Ptr, Indices);
4400 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4401 return AteExtraComma ? InstExtraComma : InstNormal;
4404 /// ParseExtractValue
4405 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4406 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4407 Value *Val; LocTy Loc;
4408 SmallVector<unsigned, 4> Indices;
4410 if (ParseTypeAndValue(Val, Loc, PFS) ||
4411 ParseIndexList(Indices, AteExtraComma))
4414 if (!Val->getType()->isAggregateType())
4415 return Error(Loc, "extractvalue operand must be aggregate type");
4417 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4418 return Error(Loc, "invalid indices for extractvalue");
4419 Inst = ExtractValueInst::Create(Val, Indices);
4420 return AteExtraComma ? InstExtraComma : InstNormal;
4423 /// ParseInsertValue
4424 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4425 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4426 Value *Val0, *Val1; LocTy Loc0, Loc1;
4427 SmallVector<unsigned, 4> Indices;
4429 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4430 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4431 ParseTypeAndValue(Val1, Loc1, PFS) ||
4432 ParseIndexList(Indices, AteExtraComma))
4435 if (!Val0->getType()->isAggregateType())
4436 return Error(Loc0, "insertvalue operand must be aggregate type");
4438 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4439 return Error(Loc0, "invalid indices for insertvalue");
4440 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4441 return AteExtraComma ? InstExtraComma : InstNormal;
4444 //===----------------------------------------------------------------------===//
4445 // Embedded metadata.
4446 //===----------------------------------------------------------------------===//
4448 /// ParseMDNodeVector
4449 /// ::= Element (',' Element)*
4451 /// ::= 'null' | TypeAndValue
4452 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4453 PerFunctionState *PFS) {
4454 // Check for an empty list.
4455 if (Lex.getKind() == lltok::rbrace)
4459 // Null is a special case since it is typeless.
4460 if (EatIfPresent(lltok::kw_null)) {
4461 Elts.push_back(nullptr);
4466 if (ParseTypeAndValue(V, PFS)) return true;
4468 } while (EatIfPresent(lltok::comma));