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 case lltok::kw_default: // OptionalVisibility
262 case lltok::kw_hidden: // OptionalVisibility
263 case lltok::kw_protected: // OptionalVisibility
264 case lltok::kw_dllimport: // OptionalDLLStorageClass
265 case lltok::kw_dllexport: // OptionalDLLStorageClass
266 case lltok::kw_thread_local: // OptionalThreadLocal
267 case lltok::kw_addrspace: // OptionalAddrSpace
268 case lltok::kw_constant: // GlobalType
269 case lltok::kw_global: { // GlobalType
270 unsigned Linkage, Visibility, DLLStorageClass;
272 GlobalVariable::ThreadLocalMode TLM;
274 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
275 ParseOptionalVisibility(Visibility) ||
276 ParseOptionalDLLStorageClass(DLLStorageClass) ||
277 ParseOptionalThreadLocal(TLM) ||
278 parseOptionalUnnamedAddr(UnnamedAddr) ||
279 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
280 DLLStorageClass, TLM, UnnamedAddr))
285 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
292 /// ::= 'module' 'asm' STRINGCONSTANT
293 bool LLParser::ParseModuleAsm() {
294 assert(Lex.getKind() == lltok::kw_module);
298 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
299 ParseStringConstant(AsmStr)) return true;
301 M->appendModuleInlineAsm(AsmStr);
306 /// ::= 'target' 'triple' '=' STRINGCONSTANT
307 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
308 bool LLParser::ParseTargetDefinition() {
309 assert(Lex.getKind() == lltok::kw_target);
312 default: return TokError("unknown target property");
313 case lltok::kw_triple:
315 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
316 ParseStringConstant(Str))
318 M->setTargetTriple(Str);
320 case lltok::kw_datalayout:
322 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
323 ParseStringConstant(Str))
325 M->setDataLayout(Str);
331 /// ::= 'deplibs' '=' '[' ']'
332 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
333 /// FIXME: Remove in 4.0. Currently parse, but ignore.
334 bool LLParser::ParseDepLibs() {
335 assert(Lex.getKind() == lltok::kw_deplibs);
337 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
338 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
341 if (EatIfPresent(lltok::rsquare))
346 if (ParseStringConstant(Str)) return true;
347 } while (EatIfPresent(lltok::comma));
349 return ParseToken(lltok::rsquare, "expected ']' at end of list");
352 /// ParseUnnamedType:
353 /// ::= LocalVarID '=' 'type' type
354 bool LLParser::ParseUnnamedType() {
355 LocTy TypeLoc = Lex.getLoc();
356 unsigned TypeID = Lex.getUIntVal();
357 Lex.Lex(); // eat LocalVarID;
359 if (ParseToken(lltok::equal, "expected '=' after name") ||
360 ParseToken(lltok::kw_type, "expected 'type' after '='"))
363 if (TypeID >= NumberedTypes.size())
364 NumberedTypes.resize(TypeID+1);
366 Type *Result = nullptr;
367 if (ParseStructDefinition(TypeLoc, "",
368 NumberedTypes[TypeID], Result)) return true;
370 if (!isa<StructType>(Result)) {
371 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
373 return Error(TypeLoc, "non-struct types may not be recursive");
374 Entry.first = Result;
375 Entry.second = SMLoc();
383 /// ::= LocalVar '=' 'type' type
384 bool LLParser::ParseNamedType() {
385 std::string Name = Lex.getStrVal();
386 LocTy NameLoc = Lex.getLoc();
387 Lex.Lex(); // eat LocalVar.
389 if (ParseToken(lltok::equal, "expected '=' after name") ||
390 ParseToken(lltok::kw_type, "expected 'type' after name"))
393 Type *Result = nullptr;
394 if (ParseStructDefinition(NameLoc, Name,
395 NamedTypes[Name], Result)) return true;
397 if (!isa<StructType>(Result)) {
398 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
400 return Error(NameLoc, "non-struct types may not be recursive");
401 Entry.first = Result;
402 Entry.second = SMLoc();
410 /// ::= 'declare' FunctionHeader
411 bool LLParser::ParseDeclare() {
412 assert(Lex.getKind() == lltok::kw_declare);
416 return ParseFunctionHeader(F, false);
420 /// ::= 'define' FunctionHeader '{' ...
421 bool LLParser::ParseDefine() {
422 assert(Lex.getKind() == lltok::kw_define);
426 return ParseFunctionHeader(F, true) ||
427 ParseFunctionBody(*F);
433 bool LLParser::ParseGlobalType(bool &IsConstant) {
434 if (Lex.getKind() == lltok::kw_constant)
436 else if (Lex.getKind() == lltok::kw_global)
440 return TokError("expected 'global' or 'constant'");
446 /// ParseUnnamedGlobal:
447 /// OptionalVisibility ALIAS ...
448 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
449 /// ... -> global variable
450 /// GlobalID '=' OptionalVisibility ALIAS ...
451 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
452 /// ... -> global variable
453 bool LLParser::ParseUnnamedGlobal() {
454 unsigned VarID = NumberedVals.size();
456 LocTy NameLoc = Lex.getLoc();
458 // Handle the GlobalID form.
459 if (Lex.getKind() == lltok::GlobalID) {
460 if (Lex.getUIntVal() != VarID)
461 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
463 Lex.Lex(); // eat GlobalID;
465 if (ParseToken(lltok::equal, "expected '=' after name"))
470 unsigned Linkage, Visibility, DLLStorageClass;
471 GlobalVariable::ThreadLocalMode TLM;
473 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
474 ParseOptionalVisibility(Visibility) ||
475 ParseOptionalDLLStorageClass(DLLStorageClass) ||
476 ParseOptionalThreadLocal(TLM) ||
477 parseOptionalUnnamedAddr(UnnamedAddr))
480 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
481 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
482 DLLStorageClass, TLM, UnnamedAddr);
483 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM,
487 /// ParseNamedGlobal:
488 /// GlobalVar '=' OptionalVisibility ALIAS ...
489 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
490 /// ... -> global variable
491 bool LLParser::ParseNamedGlobal() {
492 assert(Lex.getKind() == lltok::GlobalVar);
493 LocTy NameLoc = Lex.getLoc();
494 std::string Name = Lex.getStrVal();
498 unsigned Linkage, Visibility, DLLStorageClass;
499 GlobalVariable::ThreadLocalMode TLM;
501 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
502 ParseOptionalLinkage(Linkage, HasLinkage) ||
503 ParseOptionalVisibility(Visibility) ||
504 ParseOptionalDLLStorageClass(DLLStorageClass) ||
505 ParseOptionalThreadLocal(TLM) ||
506 parseOptionalUnnamedAddr(UnnamedAddr))
509 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
510 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
511 DLLStorageClass, TLM, UnnamedAddr);
512 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM,
517 // ::= '!' STRINGCONSTANT
518 bool LLParser::ParseMDString(MDString *&Result) {
520 if (ParseStringConstant(Str)) return true;
521 Result = MDString::get(Context, Str);
526 // ::= '!' MDNodeNumber
528 /// This version of ParseMDNodeID returns the slot number and null in the case
529 /// of a forward reference.
530 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
531 // !{ ..., !42, ... }
532 if (ParseUInt32(SlotNo)) return true;
534 // Check existing MDNode.
535 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
536 Result = NumberedMetadata[SlotNo];
542 bool LLParser::ParseMDNodeID(MDNode *&Result) {
543 // !{ ..., !42, ... }
545 if (ParseMDNodeID(Result, MID)) return true;
547 // If not a forward reference, just return it now.
548 if (Result) return false;
550 // Otherwise, create MDNode forward reference.
551 MDNode *FwdNode = MDNode::getTemporary(Context, None);
552 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
554 if (NumberedMetadata.size() <= MID)
555 NumberedMetadata.resize(MID+1);
556 NumberedMetadata[MID] = FwdNode;
561 /// ParseNamedMetadata:
562 /// !foo = !{ !1, !2 }
563 bool LLParser::ParseNamedMetadata() {
564 assert(Lex.getKind() == lltok::MetadataVar);
565 std::string Name = Lex.getStrVal();
568 if (ParseToken(lltok::equal, "expected '=' here") ||
569 ParseToken(lltok::exclaim, "Expected '!' here") ||
570 ParseToken(lltok::lbrace, "Expected '{' here"))
573 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
574 if (Lex.getKind() != lltok::rbrace)
576 if (ParseToken(lltok::exclaim, "Expected '!' here"))
580 if (ParseMDNodeID(N)) return true;
582 } while (EatIfPresent(lltok::comma));
584 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
590 /// ParseStandaloneMetadata:
592 bool LLParser::ParseStandaloneMetadata() {
593 assert(Lex.getKind() == lltok::exclaim);
595 unsigned MetadataID = 0;
599 SmallVector<Value *, 16> Elts;
600 if (ParseUInt32(MetadataID) ||
601 ParseToken(lltok::equal, "expected '=' here") ||
602 ParseType(Ty, TyLoc) ||
603 ParseToken(lltok::exclaim, "Expected '!' here") ||
604 ParseToken(lltok::lbrace, "Expected '{' here") ||
605 ParseMDNodeVector(Elts, nullptr) ||
606 ParseToken(lltok::rbrace, "expected end of metadata node"))
609 MDNode *Init = MDNode::get(Context, Elts);
611 // See if this was forward referenced, if so, handle it.
612 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
613 FI = ForwardRefMDNodes.find(MetadataID);
614 if (FI != ForwardRefMDNodes.end()) {
615 MDNode *Temp = FI->second.first;
616 Temp->replaceAllUsesWith(Init);
617 MDNode::deleteTemporary(Temp);
618 ForwardRefMDNodes.erase(FI);
620 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
622 if (MetadataID >= NumberedMetadata.size())
623 NumberedMetadata.resize(MetadataID+1);
625 if (NumberedMetadata[MetadataID] != nullptr)
626 return TokError("Metadata id is already used");
627 NumberedMetadata[MetadataID] = Init;
633 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
634 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
635 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
639 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass
640 /// OptionalThreadLocal OptionalUnNammedAddr 'alias'
641 /// OptionalLinkage Aliasee
646 /// Everything through OptionalUnNammedAddr has already been parsed.
648 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
649 unsigned Visibility, unsigned DLLStorageClass,
650 GlobalVariable::ThreadLocalMode TLM,
652 assert(Lex.getKind() == lltok::kw_alias);
654 LocTy LinkageLoc = Lex.getLoc();
656 if (ParseOptionalLinkage(L))
659 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
661 if(!GlobalAlias::isValidLinkage(Linkage))
662 return Error(LinkageLoc, "invalid linkage type for alias");
664 if (!isValidVisibilityForLinkage(Visibility, L))
665 return Error(LinkageLoc,
666 "symbol with local linkage must have default visibility");
669 LocTy AliaseeLoc = Lex.getLoc();
670 if (Lex.getKind() != lltok::kw_bitcast &&
671 Lex.getKind() != lltok::kw_getelementptr &&
672 Lex.getKind() != lltok::kw_addrspacecast &&
673 Lex.getKind() != lltok::kw_inttoptr) {
674 if (ParseGlobalTypeAndValue(Aliasee))
677 // The bitcast dest type is not present, it is implied by the dest type.
681 if (ID.Kind != ValID::t_Constant)
682 return Error(AliaseeLoc, "invalid aliasee");
683 Aliasee = ID.ConstantVal;
686 Type *AliaseeType = Aliasee->getType();
687 auto *PTy = dyn_cast<PointerType>(AliaseeType);
689 return Error(AliaseeLoc, "An alias must have pointer type");
690 Type *Ty = PTy->getElementType();
691 unsigned AddrSpace = PTy->getAddressSpace();
693 // Okay, create the alias but do not insert it into the module yet.
694 std::unique_ptr<GlobalAlias> GA(
695 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
696 Name, Aliasee, /*Parent*/ nullptr));
697 GA->setThreadLocalMode(TLM);
698 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
699 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
700 GA->setUnnamedAddr(UnnamedAddr);
702 // See if this value already exists in the symbol table. If so, it is either
703 // a redefinition or a definition of a forward reference.
704 if (GlobalValue *Val = M->getNamedValue(Name)) {
705 // See if this was a redefinition. If so, there is no entry in
707 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
708 I = ForwardRefVals.find(Name);
709 if (I == ForwardRefVals.end())
710 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
712 // Otherwise, this was a definition of forward ref. Verify that types
714 if (Val->getType() != GA->getType())
715 return Error(NameLoc,
716 "forward reference and definition of alias have different types");
718 // If they agree, just RAUW the old value with the alias and remove the
720 Val->replaceAllUsesWith(GA.get());
721 Val->eraseFromParent();
722 ForwardRefVals.erase(I);
725 // Insert into the module, we know its name won't collide now.
726 M->getAliasList().push_back(GA.get());
727 assert(GA->getName() == Name && "Should not be a name conflict!");
729 // The module owns this now
736 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
737 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
738 /// OptionalExternallyInitialized GlobalType Type Const
739 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
740 /// OptionalThreadLocal OptionalUnNammedAddr OptionalAddrSpace
741 /// OptionalExternallyInitialized GlobalType Type Const
743 /// Everything up to and including OptionalUnNammedAddr has been parsed
746 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
747 unsigned Linkage, bool HasLinkage,
748 unsigned Visibility, unsigned DLLStorageClass,
749 GlobalVariable::ThreadLocalMode TLM,
751 if (!isValidVisibilityForLinkage(Visibility, Linkage))
752 return Error(NameLoc,
753 "symbol with local linkage must have default visibility");
756 bool IsConstant, IsExternallyInitialized;
757 LocTy IsExternallyInitializedLoc;
761 if (ParseOptionalAddrSpace(AddrSpace) ||
762 ParseOptionalToken(lltok::kw_externally_initialized,
763 IsExternallyInitialized,
764 &IsExternallyInitializedLoc) ||
765 ParseGlobalType(IsConstant) ||
766 ParseType(Ty, TyLoc))
769 // If the linkage is specified and is external, then no initializer is
771 Constant *Init = nullptr;
772 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
773 Linkage != GlobalValue::ExternalLinkage)) {
774 if (ParseGlobalValue(Ty, Init))
778 if (Ty->isFunctionTy() || Ty->isLabelTy())
779 return Error(TyLoc, "invalid type for global variable");
781 GlobalVariable *GV = nullptr;
783 // See if the global was forward referenced, if so, use the global.
785 if (GlobalValue *GVal = M->getNamedValue(Name)) {
786 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
787 return Error(NameLoc, "redefinition of global '@" + Name + "'");
788 GV = cast<GlobalVariable>(GVal);
791 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
792 I = ForwardRefValIDs.find(NumberedVals.size());
793 if (I != ForwardRefValIDs.end()) {
794 GV = cast<GlobalVariable>(I->second.first);
795 ForwardRefValIDs.erase(I);
800 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
801 Name, nullptr, GlobalVariable::NotThreadLocal,
804 if (GV->getType()->getElementType() != Ty)
806 "forward reference and definition of global have different types");
808 // Move the forward-reference to the correct spot in the module.
809 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
813 NumberedVals.push_back(GV);
815 // Set the parsed properties on the global.
817 GV->setInitializer(Init);
818 GV->setConstant(IsConstant);
819 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
820 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
821 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
822 GV->setExternallyInitialized(IsExternallyInitialized);
823 GV->setThreadLocalMode(TLM);
824 GV->setUnnamedAddr(UnnamedAddr);
826 // Parse attributes on the global.
827 while (Lex.getKind() == lltok::comma) {
830 if (Lex.getKind() == lltok::kw_section) {
832 GV->setSection(Lex.getStrVal());
833 if (ParseToken(lltok::StringConstant, "expected global section string"))
835 } else if (Lex.getKind() == lltok::kw_align) {
837 if (ParseOptionalAlignment(Alignment)) return true;
838 GV->setAlignment(Alignment);
840 TokError("unknown global variable property!");
847 /// ParseUnnamedAttrGrp
848 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
849 bool LLParser::ParseUnnamedAttrGrp() {
850 assert(Lex.getKind() == lltok::kw_attributes);
851 LocTy AttrGrpLoc = Lex.getLoc();
854 assert(Lex.getKind() == lltok::AttrGrpID);
855 unsigned VarID = Lex.getUIntVal();
856 std::vector<unsigned> unused;
860 if (ParseToken(lltok::equal, "expected '=' here") ||
861 ParseToken(lltok::lbrace, "expected '{' here") ||
862 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
864 ParseToken(lltok::rbrace, "expected end of attribute group"))
867 if (!NumberedAttrBuilders[VarID].hasAttributes())
868 return Error(AttrGrpLoc, "attribute group has no attributes");
873 /// ParseFnAttributeValuePairs
874 /// ::= <attr> | <attr> '=' <value>
875 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
876 std::vector<unsigned> &FwdRefAttrGrps,
877 bool inAttrGrp, LocTy &BuiltinLoc) {
878 bool HaveError = false;
883 lltok::Kind Token = Lex.getKind();
884 if (Token == lltok::kw_builtin)
885 BuiltinLoc = Lex.getLoc();
888 if (!inAttrGrp) return HaveError;
889 return Error(Lex.getLoc(), "unterminated attribute group");
894 case lltok::AttrGrpID: {
895 // Allow a function to reference an attribute group:
897 // define void @foo() #1 { ... }
901 "cannot have an attribute group reference in an attribute group");
903 unsigned AttrGrpNum = Lex.getUIntVal();
904 if (inAttrGrp) break;
906 // Save the reference to the attribute group. We'll fill it in later.
907 FwdRefAttrGrps.push_back(AttrGrpNum);
910 // Target-dependent attributes:
911 case lltok::StringConstant: {
912 std::string Attr = Lex.getStrVal();
915 if (EatIfPresent(lltok::equal) &&
916 ParseStringConstant(Val))
919 B.addAttribute(Attr, Val);
923 // Target-independent attributes:
924 case lltok::kw_align: {
925 // As a hack, we allow function alignment to be initially parsed as an
926 // attribute on a function declaration/definition or added to an attribute
927 // group and later moved to the alignment field.
931 if (ParseToken(lltok::equal, "expected '=' here") ||
932 ParseUInt32(Alignment))
935 if (ParseOptionalAlignment(Alignment))
938 B.addAlignmentAttr(Alignment);
941 case lltok::kw_alignstack: {
945 if (ParseToken(lltok::equal, "expected '=' here") ||
946 ParseUInt32(Alignment))
949 if (ParseOptionalStackAlignment(Alignment))
952 B.addStackAlignmentAttr(Alignment);
955 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
956 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
957 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
958 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
959 case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
960 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
961 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
962 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
963 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
964 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
965 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
966 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
967 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
968 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
969 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
970 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
971 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
972 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
973 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
974 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
975 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
976 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
977 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
978 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
979 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
980 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
981 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
984 case lltok::kw_inreg:
985 case lltok::kw_signext:
986 case lltok::kw_zeroext:
989 "invalid use of attribute on a function");
991 case lltok::kw_byval:
992 case lltok::kw_inalloca:
994 case lltok::kw_noalias:
995 case lltok::kw_nocapture:
996 case lltok::kw_nonnull:
997 case lltok::kw_returned:
1001 "invalid use of parameter-only attribute on a function");
1009 //===----------------------------------------------------------------------===//
1010 // GlobalValue Reference/Resolution Routines.
1011 //===----------------------------------------------------------------------===//
1013 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1014 /// forward reference record if needed. This can return null if the value
1015 /// exists but does not have the right type.
1016 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1018 PointerType *PTy = dyn_cast<PointerType>(Ty);
1020 Error(Loc, "global variable reference must have pointer type");
1024 // Look this name up in the normal function symbol table.
1026 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1028 // If this is a forward reference for the value, see if we already created a
1029 // forward ref record.
1031 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1032 I = ForwardRefVals.find(Name);
1033 if (I != ForwardRefVals.end())
1034 Val = I->second.first;
1037 // If we have the value in the symbol table or fwd-ref table, return it.
1039 if (Val->getType() == Ty) return Val;
1040 Error(Loc, "'@" + Name + "' defined with type '" +
1041 getTypeString(Val->getType()) + "'");
1045 // Otherwise, create a new forward reference for this value and remember it.
1046 GlobalValue *FwdVal;
1047 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1048 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1050 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1051 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1052 nullptr, GlobalVariable::NotThreadLocal,
1053 PTy->getAddressSpace());
1055 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1059 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1060 PointerType *PTy = dyn_cast<PointerType>(Ty);
1062 Error(Loc, "global variable reference must have pointer type");
1066 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1068 // If this is a forward reference for the value, see if we already created a
1069 // forward ref record.
1071 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1072 I = ForwardRefValIDs.find(ID);
1073 if (I != ForwardRefValIDs.end())
1074 Val = I->second.first;
1077 // If we have the value in the symbol table or fwd-ref table, return it.
1079 if (Val->getType() == Ty) return Val;
1080 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1081 getTypeString(Val->getType()) + "'");
1085 // Otherwise, create a new forward reference for this value and remember it.
1086 GlobalValue *FwdVal;
1087 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1088 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1090 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1091 GlobalValue::ExternalWeakLinkage, nullptr, "");
1093 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1098 //===----------------------------------------------------------------------===//
1100 //===----------------------------------------------------------------------===//
1102 /// ParseToken - If the current token has the specified kind, eat it and return
1103 /// success. Otherwise, emit the specified error and return failure.
1104 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1105 if (Lex.getKind() != T)
1106 return TokError(ErrMsg);
1111 /// ParseStringConstant
1112 /// ::= StringConstant
1113 bool LLParser::ParseStringConstant(std::string &Result) {
1114 if (Lex.getKind() != lltok::StringConstant)
1115 return TokError("expected string constant");
1116 Result = Lex.getStrVal();
1123 bool LLParser::ParseUInt32(unsigned &Val) {
1124 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1125 return TokError("expected integer");
1126 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1127 if (Val64 != unsigned(Val64))
1128 return TokError("expected 32-bit integer (too large)");
1135 /// := 'localdynamic'
1136 /// := 'initialexec'
1138 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1139 switch (Lex.getKind()) {
1141 return TokError("expected localdynamic, initialexec or localexec");
1142 case lltok::kw_localdynamic:
1143 TLM = GlobalVariable::LocalDynamicTLSModel;
1145 case lltok::kw_initialexec:
1146 TLM = GlobalVariable::InitialExecTLSModel;
1148 case lltok::kw_localexec:
1149 TLM = GlobalVariable::LocalExecTLSModel;
1157 /// ParseOptionalThreadLocal
1159 /// := 'thread_local'
1160 /// := 'thread_local' '(' tlsmodel ')'
1161 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1162 TLM = GlobalVariable::NotThreadLocal;
1163 if (!EatIfPresent(lltok::kw_thread_local))
1166 TLM = GlobalVariable::GeneralDynamicTLSModel;
1167 if (Lex.getKind() == lltok::lparen) {
1169 return ParseTLSModel(TLM) ||
1170 ParseToken(lltok::rparen, "expected ')' after thread local model");
1175 /// ParseOptionalAddrSpace
1177 /// := 'addrspace' '(' uint32 ')'
1178 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1180 if (!EatIfPresent(lltok::kw_addrspace))
1182 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1183 ParseUInt32(AddrSpace) ||
1184 ParseToken(lltok::rparen, "expected ')' in address space");
1187 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1188 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1189 bool HaveError = false;
1194 lltok::Kind Token = Lex.getKind();
1196 default: // End of attributes.
1198 case lltok::kw_align: {
1200 if (ParseOptionalAlignment(Alignment))
1202 B.addAlignmentAttr(Alignment);
1205 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1206 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1207 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1208 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1209 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1210 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1211 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1212 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1213 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1214 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1215 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1216 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1217 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1219 case lltok::kw_alignstack:
1220 case lltok::kw_alwaysinline:
1221 case lltok::kw_builtin:
1222 case lltok::kw_inlinehint:
1223 case lltok::kw_jumptable:
1224 case lltok::kw_minsize:
1225 case lltok::kw_naked:
1226 case lltok::kw_nobuiltin:
1227 case lltok::kw_noduplicate:
1228 case lltok::kw_noimplicitfloat:
1229 case lltok::kw_noinline:
1230 case lltok::kw_nonlazybind:
1231 case lltok::kw_noredzone:
1232 case lltok::kw_noreturn:
1233 case lltok::kw_nounwind:
1234 case lltok::kw_optnone:
1235 case lltok::kw_optsize:
1236 case lltok::kw_returns_twice:
1237 case lltok::kw_sanitize_address:
1238 case lltok::kw_sanitize_memory:
1239 case lltok::kw_sanitize_thread:
1241 case lltok::kw_sspreq:
1242 case lltok::kw_sspstrong:
1243 case lltok::kw_uwtable:
1244 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1252 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1253 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1254 bool HaveError = false;
1259 lltok::Kind Token = Lex.getKind();
1261 default: // End of attributes.
1263 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1264 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1265 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1266 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1267 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1270 case lltok::kw_align:
1271 case lltok::kw_byval:
1272 case lltok::kw_inalloca:
1273 case lltok::kw_nest:
1274 case lltok::kw_nocapture:
1275 case lltok::kw_returned:
1276 case lltok::kw_sret:
1277 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1280 case lltok::kw_alignstack:
1281 case lltok::kw_alwaysinline:
1282 case lltok::kw_builtin:
1283 case lltok::kw_cold:
1284 case lltok::kw_inlinehint:
1285 case lltok::kw_jumptable:
1286 case lltok::kw_minsize:
1287 case lltok::kw_naked:
1288 case lltok::kw_nobuiltin:
1289 case lltok::kw_noduplicate:
1290 case lltok::kw_noimplicitfloat:
1291 case lltok::kw_noinline:
1292 case lltok::kw_nonlazybind:
1293 case lltok::kw_noredzone:
1294 case lltok::kw_noreturn:
1295 case lltok::kw_nounwind:
1296 case lltok::kw_optnone:
1297 case lltok::kw_optsize:
1298 case lltok::kw_returns_twice:
1299 case lltok::kw_sanitize_address:
1300 case lltok::kw_sanitize_memory:
1301 case lltok::kw_sanitize_thread:
1303 case lltok::kw_sspreq:
1304 case lltok::kw_sspstrong:
1305 case lltok::kw_uwtable:
1306 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1309 case lltok::kw_readnone:
1310 case lltok::kw_readonly:
1311 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1318 /// ParseOptionalLinkage
1325 /// ::= 'linkonce_odr'
1326 /// ::= 'available_externally'
1329 /// ::= 'extern_weak'
1332 /// Deprecated Values:
1333 /// ::= 'linker_private'
1334 /// ::= 'linker_private_weak'
1335 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1337 switch (Lex.getKind()) {
1338 default: Res=GlobalValue::ExternalLinkage; return false;
1339 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1340 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1341 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1342 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1343 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1344 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1345 case lltok::kw_available_externally:
1346 Res = GlobalValue::AvailableExternallyLinkage;
1348 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1349 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1350 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1351 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1353 case lltok::kw_linker_private:
1354 case lltok::kw_linker_private_weak:
1355 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1358 // treat linker_private and linker_private_weak as PrivateLinkage
1359 Res = GlobalValue::PrivateLinkage;
1367 /// ParseOptionalVisibility
1373 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1374 switch (Lex.getKind()) {
1375 default: Res = GlobalValue::DefaultVisibility; return false;
1376 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1377 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1378 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1384 /// ParseOptionalDLLStorageClass
1389 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1390 switch (Lex.getKind()) {
1391 default: Res = GlobalValue::DefaultStorageClass; return false;
1392 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1393 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1399 /// ParseOptionalCallingConv
1403 /// ::= 'kw_intel_ocl_bicc'
1405 /// ::= 'x86_stdcallcc'
1406 /// ::= 'x86_fastcallcc'
1407 /// ::= 'x86_thiscallcc'
1408 /// ::= 'arm_apcscc'
1409 /// ::= 'arm_aapcscc'
1410 /// ::= 'arm_aapcs_vfpcc'
1411 /// ::= 'msp430_intrcc'
1412 /// ::= 'ptx_kernel'
1413 /// ::= 'ptx_device'
1415 /// ::= 'spir_kernel'
1416 /// ::= 'x86_64_sysvcc'
1417 /// ::= 'x86_64_win64cc'
1418 /// ::= 'webkit_jscc'
1420 /// ::= 'preserve_mostcc'
1421 /// ::= 'preserve_allcc'
1424 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1425 switch (Lex.getKind()) {
1426 default: CC = CallingConv::C; return false;
1427 case lltok::kw_ccc: CC = CallingConv::C; break;
1428 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1429 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1430 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1431 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1432 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1433 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1434 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1435 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1436 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1437 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1438 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1439 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1440 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1441 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1442 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1443 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1444 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1445 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1446 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1447 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1448 case lltok::kw_cc: {
1449 unsigned ArbitraryCC;
1451 if (ParseUInt32(ArbitraryCC))
1453 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1462 /// ParseInstructionMetadata
1463 /// ::= !dbg !42 (',' !dbg !57)*
1464 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1465 PerFunctionState *PFS) {
1467 if (Lex.getKind() != lltok::MetadataVar)
1468 return TokError("expected metadata after comma");
1470 std::string Name = Lex.getStrVal();
1471 unsigned MDK = M->getMDKindID(Name);
1475 SMLoc Loc = Lex.getLoc();
1477 if (ParseToken(lltok::exclaim, "expected '!' here"))
1480 // This code is similar to that of ParseMetadataValue, however it needs to
1481 // have special-case code for a forward reference; see the comments on
1482 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1483 // at the top level here.
1484 if (Lex.getKind() == lltok::lbrace) {
1486 if (ParseMetadataListValue(ID, PFS))
1488 assert(ID.Kind == ValID::t_MDNode);
1489 Inst->setMetadata(MDK, ID.MDNodeVal);
1491 unsigned NodeID = 0;
1492 if (ParseMDNodeID(Node, NodeID))
1495 // If we got the node, add it to the instruction.
1496 Inst->setMetadata(MDK, Node);
1498 MDRef R = { Loc, MDK, NodeID };
1499 // Otherwise, remember that this should be resolved later.
1500 ForwardRefInstMetadata[Inst].push_back(R);
1504 if (MDK == LLVMContext::MD_tbaa)
1505 InstsWithTBAATag.push_back(Inst);
1507 // If this is the end of the list, we're done.
1508 } while (EatIfPresent(lltok::comma));
1512 /// ParseOptionalAlignment
1515 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1517 if (!EatIfPresent(lltok::kw_align))
1519 LocTy AlignLoc = Lex.getLoc();
1520 if (ParseUInt32(Alignment)) return true;
1521 if (!isPowerOf2_32(Alignment))
1522 return Error(AlignLoc, "alignment is not a power of two");
1523 if (Alignment > Value::MaximumAlignment)
1524 return Error(AlignLoc, "huge alignments are not supported yet");
1528 /// ParseOptionalCommaAlign
1532 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1534 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1535 bool &AteExtraComma) {
1536 AteExtraComma = false;
1537 while (EatIfPresent(lltok::comma)) {
1538 // Metadata at the end is an early exit.
1539 if (Lex.getKind() == lltok::MetadataVar) {
1540 AteExtraComma = true;
1544 if (Lex.getKind() != lltok::kw_align)
1545 return Error(Lex.getLoc(), "expected metadata or 'align'");
1547 if (ParseOptionalAlignment(Alignment)) return true;
1553 /// ParseScopeAndOrdering
1554 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1557 /// This sets Scope and Ordering to the parsed values.
1558 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1559 AtomicOrdering &Ordering) {
1563 Scope = CrossThread;
1564 if (EatIfPresent(lltok::kw_singlethread))
1565 Scope = SingleThread;
1567 return ParseOrdering(Ordering);
1571 /// ::= AtomicOrdering
1573 /// This sets Ordering to the parsed value.
1574 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1575 switch (Lex.getKind()) {
1576 default: return TokError("Expected ordering on atomic instruction");
1577 case lltok::kw_unordered: Ordering = Unordered; break;
1578 case lltok::kw_monotonic: Ordering = Monotonic; break;
1579 case lltok::kw_acquire: Ordering = Acquire; break;
1580 case lltok::kw_release: Ordering = Release; break;
1581 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1582 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1588 /// ParseOptionalStackAlignment
1590 /// ::= 'alignstack' '(' 4 ')'
1591 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1593 if (!EatIfPresent(lltok::kw_alignstack))
1595 LocTy ParenLoc = Lex.getLoc();
1596 if (!EatIfPresent(lltok::lparen))
1597 return Error(ParenLoc, "expected '('");
1598 LocTy AlignLoc = Lex.getLoc();
1599 if (ParseUInt32(Alignment)) return true;
1600 ParenLoc = Lex.getLoc();
1601 if (!EatIfPresent(lltok::rparen))
1602 return Error(ParenLoc, "expected ')'");
1603 if (!isPowerOf2_32(Alignment))
1604 return Error(AlignLoc, "stack alignment is not a power of two");
1608 /// ParseIndexList - This parses the index list for an insert/extractvalue
1609 /// instruction. This sets AteExtraComma in the case where we eat an extra
1610 /// comma at the end of the line and find that it is followed by metadata.
1611 /// Clients that don't allow metadata can call the version of this function that
1612 /// only takes one argument.
1615 /// ::= (',' uint32)+
1617 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1618 bool &AteExtraComma) {
1619 AteExtraComma = false;
1621 if (Lex.getKind() != lltok::comma)
1622 return TokError("expected ',' as start of index list");
1624 while (EatIfPresent(lltok::comma)) {
1625 if (Lex.getKind() == lltok::MetadataVar) {
1626 AteExtraComma = true;
1630 if (ParseUInt32(Idx)) return true;
1631 Indices.push_back(Idx);
1637 //===----------------------------------------------------------------------===//
1639 //===----------------------------------------------------------------------===//
1641 /// ParseType - Parse a type.
1642 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1643 SMLoc TypeLoc = Lex.getLoc();
1644 switch (Lex.getKind()) {
1646 return TokError("expected type");
1648 // Type ::= 'float' | 'void' (etc)
1649 Result = Lex.getTyVal();
1653 // Type ::= StructType
1654 if (ParseAnonStructType(Result, false))
1657 case lltok::lsquare:
1658 // Type ::= '[' ... ']'
1659 Lex.Lex(); // eat the lsquare.
1660 if (ParseArrayVectorType(Result, false))
1663 case lltok::less: // Either vector or packed struct.
1664 // Type ::= '<' ... '>'
1666 if (Lex.getKind() == lltok::lbrace) {
1667 if (ParseAnonStructType(Result, true) ||
1668 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1670 } else if (ParseArrayVectorType(Result, true))
1673 case lltok::LocalVar: {
1675 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1677 // If the type hasn't been defined yet, create a forward definition and
1678 // remember where that forward def'n was seen (in case it never is defined).
1680 Entry.first = StructType::create(Context, Lex.getStrVal());
1681 Entry.second = Lex.getLoc();
1683 Result = Entry.first;
1688 case lltok::LocalVarID: {
1690 if (Lex.getUIntVal() >= NumberedTypes.size())
1691 NumberedTypes.resize(Lex.getUIntVal()+1);
1692 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1694 // If the type hasn't been defined yet, create a forward definition and
1695 // remember where that forward def'n was seen (in case it never is defined).
1697 Entry.first = StructType::create(Context);
1698 Entry.second = Lex.getLoc();
1700 Result = Entry.first;
1706 // Parse the type suffixes.
1708 switch (Lex.getKind()) {
1711 if (!AllowVoid && Result->isVoidTy())
1712 return Error(TypeLoc, "void type only allowed for function results");
1715 // Type ::= Type '*'
1717 if (Result->isLabelTy())
1718 return TokError("basic block pointers are invalid");
1719 if (Result->isVoidTy())
1720 return TokError("pointers to void are invalid - use i8* instead");
1721 if (!PointerType::isValidElementType(Result))
1722 return TokError("pointer to this type is invalid");
1723 Result = PointerType::getUnqual(Result);
1727 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1728 case lltok::kw_addrspace: {
1729 if (Result->isLabelTy())
1730 return TokError("basic block pointers are invalid");
1731 if (Result->isVoidTy())
1732 return TokError("pointers to void are invalid; use i8* instead");
1733 if (!PointerType::isValidElementType(Result))
1734 return TokError("pointer to this type is invalid");
1736 if (ParseOptionalAddrSpace(AddrSpace) ||
1737 ParseToken(lltok::star, "expected '*' in address space"))
1740 Result = PointerType::get(Result, AddrSpace);
1744 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1746 if (ParseFunctionType(Result))
1753 /// ParseParameterList
1755 /// ::= '(' Arg (',' Arg)* ')'
1757 /// ::= Type OptionalAttributes Value OptionalAttributes
1758 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1759 PerFunctionState &PFS) {
1760 if (ParseToken(lltok::lparen, "expected '(' in call"))
1763 unsigned AttrIndex = 1;
1764 while (Lex.getKind() != lltok::rparen) {
1765 // If this isn't the first argument, we need a comma.
1766 if (!ArgList.empty() &&
1767 ParseToken(lltok::comma, "expected ',' in argument list"))
1770 // Parse the argument.
1772 Type *ArgTy = nullptr;
1773 AttrBuilder ArgAttrs;
1775 if (ParseType(ArgTy, ArgLoc))
1778 // Otherwise, handle normal operands.
1779 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1781 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1786 Lex.Lex(); // Lex the ')'.
1792 /// ParseArgumentList - Parse the argument list for a function type or function
1794 /// ::= '(' ArgTypeListI ')'
1798 /// ::= ArgTypeList ',' '...'
1799 /// ::= ArgType (',' ArgType)*
1801 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1804 assert(Lex.getKind() == lltok::lparen);
1805 Lex.Lex(); // eat the (.
1807 if (Lex.getKind() == lltok::rparen) {
1809 } else if (Lex.getKind() == lltok::dotdotdot) {
1813 LocTy TypeLoc = Lex.getLoc();
1814 Type *ArgTy = nullptr;
1818 if (ParseType(ArgTy) ||
1819 ParseOptionalParamAttrs(Attrs)) return true;
1821 if (ArgTy->isVoidTy())
1822 return Error(TypeLoc, "argument can not have void type");
1824 if (Lex.getKind() == lltok::LocalVar) {
1825 Name = Lex.getStrVal();
1829 if (!FunctionType::isValidArgumentType(ArgTy))
1830 return Error(TypeLoc, "invalid type for function argument");
1832 unsigned AttrIndex = 1;
1833 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1834 AttributeSet::get(ArgTy->getContext(),
1835 AttrIndex++, Attrs), Name));
1837 while (EatIfPresent(lltok::comma)) {
1838 // Handle ... at end of arg list.
1839 if (EatIfPresent(lltok::dotdotdot)) {
1844 // Otherwise must be an argument type.
1845 TypeLoc = Lex.getLoc();
1846 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1848 if (ArgTy->isVoidTy())
1849 return Error(TypeLoc, "argument can not have void type");
1851 if (Lex.getKind() == lltok::LocalVar) {
1852 Name = Lex.getStrVal();
1858 if (!ArgTy->isFirstClassType())
1859 return Error(TypeLoc, "invalid type for function argument");
1861 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1862 AttributeSet::get(ArgTy->getContext(),
1863 AttrIndex++, Attrs),
1868 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1871 /// ParseFunctionType
1872 /// ::= Type ArgumentList OptionalAttrs
1873 bool LLParser::ParseFunctionType(Type *&Result) {
1874 assert(Lex.getKind() == lltok::lparen);
1876 if (!FunctionType::isValidReturnType(Result))
1877 return TokError("invalid function return type");
1879 SmallVector<ArgInfo, 8> ArgList;
1881 if (ParseArgumentList(ArgList, isVarArg))
1884 // Reject names on the arguments lists.
1885 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1886 if (!ArgList[i].Name.empty())
1887 return Error(ArgList[i].Loc, "argument name invalid in function type");
1888 if (ArgList[i].Attrs.hasAttributes(i + 1))
1889 return Error(ArgList[i].Loc,
1890 "argument attributes invalid in function type");
1893 SmallVector<Type*, 16> ArgListTy;
1894 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1895 ArgListTy.push_back(ArgList[i].Ty);
1897 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1901 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1903 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1904 SmallVector<Type*, 8> Elts;
1905 if (ParseStructBody(Elts)) return true;
1907 Result = StructType::get(Context, Elts, Packed);
1911 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1912 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1913 std::pair<Type*, LocTy> &Entry,
1915 // If the type was already defined, diagnose the redefinition.
1916 if (Entry.first && !Entry.second.isValid())
1917 return Error(TypeLoc, "redefinition of type");
1919 // If we have opaque, just return without filling in the definition for the
1920 // struct. This counts as a definition as far as the .ll file goes.
1921 if (EatIfPresent(lltok::kw_opaque)) {
1922 // This type is being defined, so clear the location to indicate this.
1923 Entry.second = SMLoc();
1925 // If this type number has never been uttered, create it.
1927 Entry.first = StructType::create(Context, Name);
1928 ResultTy = Entry.first;
1932 // If the type starts with '<', then it is either a packed struct or a vector.
1933 bool isPacked = EatIfPresent(lltok::less);
1935 // If we don't have a struct, then we have a random type alias, which we
1936 // accept for compatibility with old files. These types are not allowed to be
1937 // forward referenced and not allowed to be recursive.
1938 if (Lex.getKind() != lltok::lbrace) {
1940 return Error(TypeLoc, "forward references to non-struct type");
1944 return ParseArrayVectorType(ResultTy, true);
1945 return ParseType(ResultTy);
1948 // This type is being defined, so clear the location to indicate this.
1949 Entry.second = SMLoc();
1951 // If this type number has never been uttered, create it.
1953 Entry.first = StructType::create(Context, Name);
1955 StructType *STy = cast<StructType>(Entry.first);
1957 SmallVector<Type*, 8> Body;
1958 if (ParseStructBody(Body) ||
1959 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1962 STy->setBody(Body, isPacked);
1968 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1971 /// ::= '{' Type (',' Type)* '}'
1972 /// ::= '<' '{' '}' '>'
1973 /// ::= '<' '{' Type (',' Type)* '}' '>'
1974 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1975 assert(Lex.getKind() == lltok::lbrace);
1976 Lex.Lex(); // Consume the '{'
1978 // Handle the empty struct.
1979 if (EatIfPresent(lltok::rbrace))
1982 LocTy EltTyLoc = Lex.getLoc();
1984 if (ParseType(Ty)) return true;
1987 if (!StructType::isValidElementType(Ty))
1988 return Error(EltTyLoc, "invalid element type for struct");
1990 while (EatIfPresent(lltok::comma)) {
1991 EltTyLoc = Lex.getLoc();
1992 if (ParseType(Ty)) return true;
1994 if (!StructType::isValidElementType(Ty))
1995 return Error(EltTyLoc, "invalid element type for struct");
2000 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2003 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2004 /// token has already been consumed.
2006 /// ::= '[' APSINTVAL 'x' Types ']'
2007 /// ::= '<' APSINTVAL 'x' Types '>'
2008 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2009 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2010 Lex.getAPSIntVal().getBitWidth() > 64)
2011 return TokError("expected number in address space");
2013 LocTy SizeLoc = Lex.getLoc();
2014 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2017 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2020 LocTy TypeLoc = Lex.getLoc();
2021 Type *EltTy = nullptr;
2022 if (ParseType(EltTy)) return true;
2024 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2025 "expected end of sequential type"))
2030 return Error(SizeLoc, "zero element vector is illegal");
2031 if ((unsigned)Size != Size)
2032 return Error(SizeLoc, "size too large for vector");
2033 if (!VectorType::isValidElementType(EltTy))
2034 return Error(TypeLoc, "invalid vector element type");
2035 Result = VectorType::get(EltTy, unsigned(Size));
2037 if (!ArrayType::isValidElementType(EltTy))
2038 return Error(TypeLoc, "invalid array element type");
2039 Result = ArrayType::get(EltTy, Size);
2044 //===----------------------------------------------------------------------===//
2045 // Function Semantic Analysis.
2046 //===----------------------------------------------------------------------===//
2048 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2050 : P(p), F(f), FunctionNumber(functionNumber) {
2052 // Insert unnamed arguments into the NumberedVals list.
2053 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2056 NumberedVals.push_back(AI);
2059 LLParser::PerFunctionState::~PerFunctionState() {
2060 // If there were any forward referenced non-basicblock values, delete them.
2061 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2062 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2063 if (!isa<BasicBlock>(I->second.first)) {
2064 I->second.first->replaceAllUsesWith(
2065 UndefValue::get(I->second.first->getType()));
2066 delete I->second.first;
2067 I->second.first = nullptr;
2070 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2071 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2072 if (!isa<BasicBlock>(I->second.first)) {
2073 I->second.first->replaceAllUsesWith(
2074 UndefValue::get(I->second.first->getType()));
2075 delete I->second.first;
2076 I->second.first = nullptr;
2080 bool LLParser::PerFunctionState::FinishFunction() {
2081 // Check to see if someone took the address of labels in this block.
2082 if (!P.ForwardRefBlockAddresses.empty()) {
2084 if (!F.getName().empty()) {
2085 FunctionID.Kind = ValID::t_GlobalName;
2086 FunctionID.StrVal = F.getName();
2088 FunctionID.Kind = ValID::t_GlobalID;
2089 FunctionID.UIntVal = FunctionNumber;
2092 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2093 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2094 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2095 // Resolve all these references.
2096 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2099 P.ForwardRefBlockAddresses.erase(FRBAI);
2103 if (!ForwardRefVals.empty())
2104 return P.Error(ForwardRefVals.begin()->second.second,
2105 "use of undefined value '%" + ForwardRefVals.begin()->first +
2107 if (!ForwardRefValIDs.empty())
2108 return P.Error(ForwardRefValIDs.begin()->second.second,
2109 "use of undefined value '%" +
2110 Twine(ForwardRefValIDs.begin()->first) + "'");
2115 /// GetVal - Get a value with the specified name or ID, creating a
2116 /// forward reference record if needed. This can return null if the value
2117 /// exists but does not have the right type.
2118 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2119 Type *Ty, LocTy Loc) {
2120 // Look this name up in the normal function symbol table.
2121 Value *Val = F.getValueSymbolTable().lookup(Name);
2123 // If this is a forward reference for the value, see if we already created a
2124 // forward ref record.
2126 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2127 I = ForwardRefVals.find(Name);
2128 if (I != ForwardRefVals.end())
2129 Val = I->second.first;
2132 // If we have the value in the symbol table or fwd-ref table, return it.
2134 if (Val->getType() == Ty) return Val;
2135 if (Ty->isLabelTy())
2136 P.Error(Loc, "'%" + Name + "' is not a basic block");
2138 P.Error(Loc, "'%" + Name + "' defined with type '" +
2139 getTypeString(Val->getType()) + "'");
2143 // Don't make placeholders with invalid type.
2144 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2145 P.Error(Loc, "invalid use of a non-first-class type");
2149 // Otherwise, create a new forward reference for this value and remember it.
2151 if (Ty->isLabelTy())
2152 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2154 FwdVal = new Argument(Ty, Name);
2156 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2160 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2162 // Look this name up in the normal function symbol table.
2163 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2165 // If this is a forward reference for the value, see if we already created a
2166 // forward ref record.
2168 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2169 I = ForwardRefValIDs.find(ID);
2170 if (I != ForwardRefValIDs.end())
2171 Val = I->second.first;
2174 // If we have the value in the symbol table or fwd-ref table, return it.
2176 if (Val->getType() == Ty) return Val;
2177 if (Ty->isLabelTy())
2178 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2180 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2181 getTypeString(Val->getType()) + "'");
2185 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2186 P.Error(Loc, "invalid use of a non-first-class type");
2190 // Otherwise, create a new forward reference for this value and remember it.
2192 if (Ty->isLabelTy())
2193 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2195 FwdVal = new Argument(Ty);
2197 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2201 /// SetInstName - After an instruction is parsed and inserted into its
2202 /// basic block, this installs its name.
2203 bool LLParser::PerFunctionState::SetInstName(int NameID,
2204 const std::string &NameStr,
2205 LocTy NameLoc, Instruction *Inst) {
2206 // If this instruction has void type, it cannot have a name or ID specified.
2207 if (Inst->getType()->isVoidTy()) {
2208 if (NameID != -1 || !NameStr.empty())
2209 return P.Error(NameLoc, "instructions returning void cannot have a name");
2213 // If this was a numbered instruction, verify that the instruction is the
2214 // expected value and resolve any forward references.
2215 if (NameStr.empty()) {
2216 // If neither a name nor an ID was specified, just use the next ID.
2218 NameID = NumberedVals.size();
2220 if (unsigned(NameID) != NumberedVals.size())
2221 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2222 Twine(NumberedVals.size()) + "'");
2224 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2225 ForwardRefValIDs.find(NameID);
2226 if (FI != ForwardRefValIDs.end()) {
2227 if (FI->second.first->getType() != Inst->getType())
2228 return P.Error(NameLoc, "instruction forward referenced with type '" +
2229 getTypeString(FI->second.first->getType()) + "'");
2230 FI->second.first->replaceAllUsesWith(Inst);
2231 delete FI->second.first;
2232 ForwardRefValIDs.erase(FI);
2235 NumberedVals.push_back(Inst);
2239 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2240 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2241 FI = ForwardRefVals.find(NameStr);
2242 if (FI != ForwardRefVals.end()) {
2243 if (FI->second.first->getType() != Inst->getType())
2244 return P.Error(NameLoc, "instruction forward referenced with type '" +
2245 getTypeString(FI->second.first->getType()) + "'");
2246 FI->second.first->replaceAllUsesWith(Inst);
2247 delete FI->second.first;
2248 ForwardRefVals.erase(FI);
2251 // Set the name on the instruction.
2252 Inst->setName(NameStr);
2254 if (Inst->getName() != NameStr)
2255 return P.Error(NameLoc, "multiple definition of local value named '" +
2260 /// GetBB - Get a basic block with the specified name or ID, creating a
2261 /// forward reference record if needed.
2262 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2264 return cast_or_null<BasicBlock>(GetVal(Name,
2265 Type::getLabelTy(F.getContext()), Loc));
2268 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2269 return cast_or_null<BasicBlock>(GetVal(ID,
2270 Type::getLabelTy(F.getContext()), Loc));
2273 /// DefineBB - Define the specified basic block, which is either named or
2274 /// unnamed. If there is an error, this returns null otherwise it returns
2275 /// the block being defined.
2276 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2280 BB = GetBB(NumberedVals.size(), Loc);
2282 BB = GetBB(Name, Loc);
2283 if (!BB) return nullptr; // Already diagnosed error.
2285 // Move the block to the end of the function. Forward ref'd blocks are
2286 // inserted wherever they happen to be referenced.
2287 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2289 // Remove the block from forward ref sets.
2291 ForwardRefValIDs.erase(NumberedVals.size());
2292 NumberedVals.push_back(BB);
2294 // BB forward references are already in the function symbol table.
2295 ForwardRefVals.erase(Name);
2301 //===----------------------------------------------------------------------===//
2303 //===----------------------------------------------------------------------===//
2305 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2306 /// type implied. For example, if we parse "4" we don't know what integer type
2307 /// it has. The value will later be combined with its type and checked for
2308 /// sanity. PFS is used to convert function-local operands of metadata (since
2309 /// metadata operands are not just parsed here but also converted to values).
2310 /// PFS can be null when we are not parsing metadata values inside a function.
2311 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2312 ID.Loc = Lex.getLoc();
2313 switch (Lex.getKind()) {
2314 default: return TokError("expected value token");
2315 case lltok::GlobalID: // @42
2316 ID.UIntVal = Lex.getUIntVal();
2317 ID.Kind = ValID::t_GlobalID;
2319 case lltok::GlobalVar: // @foo
2320 ID.StrVal = Lex.getStrVal();
2321 ID.Kind = ValID::t_GlobalName;
2323 case lltok::LocalVarID: // %42
2324 ID.UIntVal = Lex.getUIntVal();
2325 ID.Kind = ValID::t_LocalID;
2327 case lltok::LocalVar: // %foo
2328 ID.StrVal = Lex.getStrVal();
2329 ID.Kind = ValID::t_LocalName;
2331 case lltok::exclaim: // !42, !{...}, or !"foo"
2332 return ParseMetadataValue(ID, PFS);
2334 ID.APSIntVal = Lex.getAPSIntVal();
2335 ID.Kind = ValID::t_APSInt;
2337 case lltok::APFloat:
2338 ID.APFloatVal = Lex.getAPFloatVal();
2339 ID.Kind = ValID::t_APFloat;
2341 case lltok::kw_true:
2342 ID.ConstantVal = ConstantInt::getTrue(Context);
2343 ID.Kind = ValID::t_Constant;
2345 case lltok::kw_false:
2346 ID.ConstantVal = ConstantInt::getFalse(Context);
2347 ID.Kind = ValID::t_Constant;
2349 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2350 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2351 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2353 case lltok::lbrace: {
2354 // ValID ::= '{' ConstVector '}'
2356 SmallVector<Constant*, 16> Elts;
2357 if (ParseGlobalValueVector(Elts) ||
2358 ParseToken(lltok::rbrace, "expected end of struct constant"))
2361 ID.ConstantStructElts = new Constant*[Elts.size()];
2362 ID.UIntVal = Elts.size();
2363 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2364 ID.Kind = ValID::t_ConstantStruct;
2368 // ValID ::= '<' ConstVector '>' --> Vector.
2369 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2371 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2373 SmallVector<Constant*, 16> Elts;
2374 LocTy FirstEltLoc = Lex.getLoc();
2375 if (ParseGlobalValueVector(Elts) ||
2377 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2378 ParseToken(lltok::greater, "expected end of constant"))
2381 if (isPackedStruct) {
2382 ID.ConstantStructElts = new Constant*[Elts.size()];
2383 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2384 ID.UIntVal = Elts.size();
2385 ID.Kind = ValID::t_PackedConstantStruct;
2390 return Error(ID.Loc, "constant vector must not be empty");
2392 if (!Elts[0]->getType()->isIntegerTy() &&
2393 !Elts[0]->getType()->isFloatingPointTy() &&
2394 !Elts[0]->getType()->isPointerTy())
2395 return Error(FirstEltLoc,
2396 "vector elements must have integer, pointer or floating point type");
2398 // Verify that all the vector elements have the same type.
2399 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2400 if (Elts[i]->getType() != Elts[0]->getType())
2401 return Error(FirstEltLoc,
2402 "vector element #" + Twine(i) +
2403 " is not of type '" + getTypeString(Elts[0]->getType()));
2405 ID.ConstantVal = ConstantVector::get(Elts);
2406 ID.Kind = ValID::t_Constant;
2409 case lltok::lsquare: { // Array Constant
2411 SmallVector<Constant*, 16> Elts;
2412 LocTy FirstEltLoc = Lex.getLoc();
2413 if (ParseGlobalValueVector(Elts) ||
2414 ParseToken(lltok::rsquare, "expected end of array constant"))
2417 // Handle empty element.
2419 // Use undef instead of an array because it's inconvenient to determine
2420 // the element type at this point, there being no elements to examine.
2421 ID.Kind = ValID::t_EmptyArray;
2425 if (!Elts[0]->getType()->isFirstClassType())
2426 return Error(FirstEltLoc, "invalid array element type: " +
2427 getTypeString(Elts[0]->getType()));
2429 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2431 // Verify all elements are correct type!
2432 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2433 if (Elts[i]->getType() != Elts[0]->getType())
2434 return Error(FirstEltLoc,
2435 "array element #" + Twine(i) +
2436 " is not of type '" + getTypeString(Elts[0]->getType()));
2439 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2440 ID.Kind = ValID::t_Constant;
2443 case lltok::kw_c: // c "foo"
2445 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2447 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2448 ID.Kind = ValID::t_Constant;
2451 case lltok::kw_asm: {
2452 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2454 bool HasSideEffect, AlignStack, AsmDialect;
2456 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2457 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2458 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2459 ParseStringConstant(ID.StrVal) ||
2460 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2461 ParseToken(lltok::StringConstant, "expected constraint string"))
2463 ID.StrVal2 = Lex.getStrVal();
2464 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2465 (unsigned(AsmDialect)<<2);
2466 ID.Kind = ValID::t_InlineAsm;
2470 case lltok::kw_blockaddress: {
2471 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2476 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2478 ParseToken(lltok::comma, "expected comma in block address expression")||
2479 ParseValID(Label) ||
2480 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2483 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2484 return Error(Fn.Loc, "expected function name in blockaddress");
2485 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2486 return Error(Label.Loc, "expected basic block name in blockaddress");
2488 // Make a global variable as a placeholder for this reference.
2489 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2490 false, GlobalValue::InternalLinkage,
2492 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2493 ID.ConstantVal = FwdRef;
2494 ID.Kind = ValID::t_Constant;
2498 case lltok::kw_trunc:
2499 case lltok::kw_zext:
2500 case lltok::kw_sext:
2501 case lltok::kw_fptrunc:
2502 case lltok::kw_fpext:
2503 case lltok::kw_bitcast:
2504 case lltok::kw_addrspacecast:
2505 case lltok::kw_uitofp:
2506 case lltok::kw_sitofp:
2507 case lltok::kw_fptoui:
2508 case lltok::kw_fptosi:
2509 case lltok::kw_inttoptr:
2510 case lltok::kw_ptrtoint: {
2511 unsigned Opc = Lex.getUIntVal();
2512 Type *DestTy = nullptr;
2515 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2516 ParseGlobalTypeAndValue(SrcVal) ||
2517 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2518 ParseType(DestTy) ||
2519 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2521 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2522 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2523 getTypeString(SrcVal->getType()) + "' to '" +
2524 getTypeString(DestTy) + "'");
2525 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2527 ID.Kind = ValID::t_Constant;
2530 case lltok::kw_extractvalue: {
2533 SmallVector<unsigned, 4> Indices;
2534 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2535 ParseGlobalTypeAndValue(Val) ||
2536 ParseIndexList(Indices) ||
2537 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2540 if (!Val->getType()->isAggregateType())
2541 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2542 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2543 return Error(ID.Loc, "invalid indices for extractvalue");
2544 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2545 ID.Kind = ValID::t_Constant;
2548 case lltok::kw_insertvalue: {
2550 Constant *Val0, *Val1;
2551 SmallVector<unsigned, 4> Indices;
2552 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2553 ParseGlobalTypeAndValue(Val0) ||
2554 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2555 ParseGlobalTypeAndValue(Val1) ||
2556 ParseIndexList(Indices) ||
2557 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2559 if (!Val0->getType()->isAggregateType())
2560 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2561 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2562 return Error(ID.Loc, "invalid indices for insertvalue");
2563 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2564 ID.Kind = ValID::t_Constant;
2567 case lltok::kw_icmp:
2568 case lltok::kw_fcmp: {
2569 unsigned PredVal, Opc = Lex.getUIntVal();
2570 Constant *Val0, *Val1;
2572 if (ParseCmpPredicate(PredVal, Opc) ||
2573 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2574 ParseGlobalTypeAndValue(Val0) ||
2575 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2576 ParseGlobalTypeAndValue(Val1) ||
2577 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2580 if (Val0->getType() != Val1->getType())
2581 return Error(ID.Loc, "compare operands must have the same type");
2583 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2585 if (Opc == Instruction::FCmp) {
2586 if (!Val0->getType()->isFPOrFPVectorTy())
2587 return Error(ID.Loc, "fcmp requires floating point operands");
2588 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2590 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2591 if (!Val0->getType()->isIntOrIntVectorTy() &&
2592 !Val0->getType()->getScalarType()->isPointerTy())
2593 return Error(ID.Loc, "icmp requires pointer or integer operands");
2594 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2596 ID.Kind = ValID::t_Constant;
2600 // Binary Operators.
2602 case lltok::kw_fadd:
2604 case lltok::kw_fsub:
2606 case lltok::kw_fmul:
2607 case lltok::kw_udiv:
2608 case lltok::kw_sdiv:
2609 case lltok::kw_fdiv:
2610 case lltok::kw_urem:
2611 case lltok::kw_srem:
2612 case lltok::kw_frem:
2614 case lltok::kw_lshr:
2615 case lltok::kw_ashr: {
2619 unsigned Opc = Lex.getUIntVal();
2620 Constant *Val0, *Val1;
2622 LocTy ModifierLoc = Lex.getLoc();
2623 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2624 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2625 if (EatIfPresent(lltok::kw_nuw))
2627 if (EatIfPresent(lltok::kw_nsw)) {
2629 if (EatIfPresent(lltok::kw_nuw))
2632 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2633 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2634 if (EatIfPresent(lltok::kw_exact))
2637 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2638 ParseGlobalTypeAndValue(Val0) ||
2639 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2640 ParseGlobalTypeAndValue(Val1) ||
2641 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2643 if (Val0->getType() != Val1->getType())
2644 return Error(ID.Loc, "operands of constexpr must have same type");
2645 if (!Val0->getType()->isIntOrIntVectorTy()) {
2647 return Error(ModifierLoc, "nuw only applies to integer operations");
2649 return Error(ModifierLoc, "nsw only applies to integer operations");
2651 // Check that the type is valid for the operator.
2653 case Instruction::Add:
2654 case Instruction::Sub:
2655 case Instruction::Mul:
2656 case Instruction::UDiv:
2657 case Instruction::SDiv:
2658 case Instruction::URem:
2659 case Instruction::SRem:
2660 case Instruction::Shl:
2661 case Instruction::AShr:
2662 case Instruction::LShr:
2663 if (!Val0->getType()->isIntOrIntVectorTy())
2664 return Error(ID.Loc, "constexpr requires integer operands");
2666 case Instruction::FAdd:
2667 case Instruction::FSub:
2668 case Instruction::FMul:
2669 case Instruction::FDiv:
2670 case Instruction::FRem:
2671 if (!Val0->getType()->isFPOrFPVectorTy())
2672 return Error(ID.Loc, "constexpr requires fp operands");
2674 default: llvm_unreachable("Unknown binary operator!");
2677 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2678 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2679 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2680 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2682 ID.Kind = ValID::t_Constant;
2686 // Logical Operations
2689 case lltok::kw_xor: {
2690 unsigned Opc = Lex.getUIntVal();
2691 Constant *Val0, *Val1;
2693 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2694 ParseGlobalTypeAndValue(Val0) ||
2695 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2696 ParseGlobalTypeAndValue(Val1) ||
2697 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2699 if (Val0->getType() != Val1->getType())
2700 return Error(ID.Loc, "operands of constexpr must have same type");
2701 if (!Val0->getType()->isIntOrIntVectorTy())
2702 return Error(ID.Loc,
2703 "constexpr requires integer or integer vector operands");
2704 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2705 ID.Kind = ValID::t_Constant;
2709 case lltok::kw_getelementptr:
2710 case lltok::kw_shufflevector:
2711 case lltok::kw_insertelement:
2712 case lltok::kw_extractelement:
2713 case lltok::kw_select: {
2714 unsigned Opc = Lex.getUIntVal();
2715 SmallVector<Constant*, 16> Elts;
2716 bool InBounds = false;
2718 if (Opc == Instruction::GetElementPtr)
2719 InBounds = EatIfPresent(lltok::kw_inbounds);
2720 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2721 ParseGlobalValueVector(Elts) ||
2722 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2725 if (Opc == Instruction::GetElementPtr) {
2726 if (Elts.size() == 0 ||
2727 !Elts[0]->getType()->getScalarType()->isPointerTy())
2728 return Error(ID.Loc, "getelementptr requires pointer operand");
2730 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2731 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2732 return Error(ID.Loc, "invalid indices for getelementptr");
2733 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2735 } else if (Opc == Instruction::Select) {
2736 if (Elts.size() != 3)
2737 return Error(ID.Loc, "expected three operands to select");
2738 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2740 return Error(ID.Loc, Reason);
2741 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2742 } else if (Opc == Instruction::ShuffleVector) {
2743 if (Elts.size() != 3)
2744 return Error(ID.Loc, "expected three operands to shufflevector");
2745 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2746 return Error(ID.Loc, "invalid operands to shufflevector");
2748 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2749 } else if (Opc == Instruction::ExtractElement) {
2750 if (Elts.size() != 2)
2751 return Error(ID.Loc, "expected two operands to extractelement");
2752 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2753 return Error(ID.Loc, "invalid extractelement operands");
2754 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2756 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2757 if (Elts.size() != 3)
2758 return Error(ID.Loc, "expected three operands to insertelement");
2759 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2760 return Error(ID.Loc, "invalid insertelement operands");
2762 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2765 ID.Kind = ValID::t_Constant;
2774 /// ParseGlobalValue - Parse a global value with the specified type.
2775 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2779 bool Parsed = ParseValID(ID) ||
2780 ConvertValIDToValue(Ty, ID, V, nullptr);
2781 if (V && !(C = dyn_cast<Constant>(V)))
2782 return Error(ID.Loc, "global values must be constants");
2786 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2788 return ParseType(Ty) ||
2789 ParseGlobalValue(Ty, V);
2792 /// ParseGlobalValueVector
2794 /// ::= TypeAndValue (',' TypeAndValue)*
2795 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2797 if (Lex.getKind() == lltok::rbrace ||
2798 Lex.getKind() == lltok::rsquare ||
2799 Lex.getKind() == lltok::greater ||
2800 Lex.getKind() == lltok::rparen)
2804 if (ParseGlobalTypeAndValue(C)) return true;
2807 while (EatIfPresent(lltok::comma)) {
2808 if (ParseGlobalTypeAndValue(C)) return true;
2815 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2816 assert(Lex.getKind() == lltok::lbrace);
2819 SmallVector<Value*, 16> Elts;
2820 if (ParseMDNodeVector(Elts, PFS) ||
2821 ParseToken(lltok::rbrace, "expected end of metadata node"))
2824 ID.MDNodeVal = MDNode::get(Context, Elts);
2825 ID.Kind = ValID::t_MDNode;
2829 /// ParseMetadataValue
2833 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2834 assert(Lex.getKind() == lltok::exclaim);
2839 if (Lex.getKind() == lltok::lbrace)
2840 return ParseMetadataListValue(ID, PFS);
2842 // Standalone metadata reference
2844 if (Lex.getKind() == lltok::APSInt) {
2845 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2846 ID.Kind = ValID::t_MDNode;
2851 // ::= '!' STRINGCONSTANT
2852 if (ParseMDString(ID.MDStringVal)) return true;
2853 ID.Kind = ValID::t_MDString;
2858 //===----------------------------------------------------------------------===//
2859 // Function Parsing.
2860 //===----------------------------------------------------------------------===//
2862 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2863 PerFunctionState *PFS) {
2864 if (Ty->isFunctionTy())
2865 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2868 case ValID::t_LocalID:
2869 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2870 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2871 return V == nullptr;
2872 case ValID::t_LocalName:
2873 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2874 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2875 return V == nullptr;
2876 case ValID::t_InlineAsm: {
2877 PointerType *PTy = dyn_cast<PointerType>(Ty);
2879 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2880 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2881 return Error(ID.Loc, "invalid type for inline asm constraint string");
2882 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2883 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2886 case ValID::t_MDNode:
2887 if (!Ty->isMetadataTy())
2888 return Error(ID.Loc, "metadata value must have metadata type");
2891 case ValID::t_MDString:
2892 if (!Ty->isMetadataTy())
2893 return Error(ID.Loc, "metadata value must have metadata type");
2896 case ValID::t_GlobalName:
2897 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2898 return V == nullptr;
2899 case ValID::t_GlobalID:
2900 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2901 return V == nullptr;
2902 case ValID::t_APSInt:
2903 if (!Ty->isIntegerTy())
2904 return Error(ID.Loc, "integer constant must have integer type");
2905 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2906 V = ConstantInt::get(Context, ID.APSIntVal);
2908 case ValID::t_APFloat:
2909 if (!Ty->isFloatingPointTy() ||
2910 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2911 return Error(ID.Loc, "floating point constant invalid for type");
2913 // The lexer has no type info, so builds all half, float, and double FP
2914 // constants as double. Fix this here. Long double does not need this.
2915 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2918 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2920 else if (Ty->isFloatTy())
2921 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2924 V = ConstantFP::get(Context, ID.APFloatVal);
2926 if (V->getType() != Ty)
2927 return Error(ID.Loc, "floating point constant does not have type '" +
2928 getTypeString(Ty) + "'");
2932 if (!Ty->isPointerTy())
2933 return Error(ID.Loc, "null must be a pointer type");
2934 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2936 case ValID::t_Undef:
2937 // FIXME: LabelTy should not be a first-class type.
2938 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2939 return Error(ID.Loc, "invalid type for undef constant");
2940 V = UndefValue::get(Ty);
2942 case ValID::t_EmptyArray:
2943 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2944 return Error(ID.Loc, "invalid empty array initializer");
2945 V = UndefValue::get(Ty);
2948 // FIXME: LabelTy should not be a first-class type.
2949 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2950 return Error(ID.Loc, "invalid type for null constant");
2951 V = Constant::getNullValue(Ty);
2953 case ValID::t_Constant:
2954 if (ID.ConstantVal->getType() != Ty)
2955 return Error(ID.Loc, "constant expression type mismatch");
2959 case ValID::t_ConstantStruct:
2960 case ValID::t_PackedConstantStruct:
2961 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2962 if (ST->getNumElements() != ID.UIntVal)
2963 return Error(ID.Loc,
2964 "initializer with struct type has wrong # elements");
2965 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2966 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2968 // Verify that the elements are compatible with the structtype.
2969 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2970 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2971 return Error(ID.Loc, "element " + Twine(i) +
2972 " of struct initializer doesn't match struct element type");
2974 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2977 return Error(ID.Loc, "constant expression type mismatch");
2980 llvm_unreachable("Invalid ValID");
2983 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2986 return ParseValID(ID, PFS) ||
2987 ConvertValIDToValue(Ty, ID, V, PFS);
2990 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2992 return ParseType(Ty) ||
2993 ParseValue(Ty, V, PFS);
2996 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2997 PerFunctionState &PFS) {
3000 if (ParseTypeAndValue(V, PFS)) return true;
3001 if (!isa<BasicBlock>(V))
3002 return Error(Loc, "expected a basic block");
3003 BB = cast<BasicBlock>(V);
3009 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3010 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3011 /// OptionalAlign OptGC OptionalPrefix
3012 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3013 // Parse the linkage.
3014 LocTy LinkageLoc = Lex.getLoc();
3017 unsigned Visibility;
3018 unsigned DLLStorageClass;
3019 AttrBuilder RetAttrs;
3021 Type *RetType = nullptr;
3022 LocTy RetTypeLoc = Lex.getLoc();
3023 if (ParseOptionalLinkage(Linkage) ||
3024 ParseOptionalVisibility(Visibility) ||
3025 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3026 ParseOptionalCallingConv(CC) ||
3027 ParseOptionalReturnAttrs(RetAttrs) ||
3028 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3031 // Verify that the linkage is ok.
3032 switch ((GlobalValue::LinkageTypes)Linkage) {
3033 case GlobalValue::ExternalLinkage:
3034 break; // always ok.
3035 case GlobalValue::ExternalWeakLinkage:
3037 return Error(LinkageLoc, "invalid linkage for function definition");
3039 case GlobalValue::PrivateLinkage:
3040 case GlobalValue::InternalLinkage:
3041 case GlobalValue::AvailableExternallyLinkage:
3042 case GlobalValue::LinkOnceAnyLinkage:
3043 case GlobalValue::LinkOnceODRLinkage:
3044 case GlobalValue::WeakAnyLinkage:
3045 case GlobalValue::WeakODRLinkage:
3047 return Error(LinkageLoc, "invalid linkage for function declaration");
3049 case GlobalValue::AppendingLinkage:
3050 case GlobalValue::CommonLinkage:
3051 return Error(LinkageLoc, "invalid function linkage type");
3054 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3055 return Error(LinkageLoc,
3056 "symbol with local linkage must have default visibility");
3058 if (!FunctionType::isValidReturnType(RetType))
3059 return Error(RetTypeLoc, "invalid function return type");
3061 LocTy NameLoc = Lex.getLoc();
3063 std::string FunctionName;
3064 if (Lex.getKind() == lltok::GlobalVar) {
3065 FunctionName = Lex.getStrVal();
3066 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3067 unsigned NameID = Lex.getUIntVal();
3069 if (NameID != NumberedVals.size())
3070 return TokError("function expected to be numbered '%" +
3071 Twine(NumberedVals.size()) + "'");
3073 return TokError("expected function name");
3078 if (Lex.getKind() != lltok::lparen)
3079 return TokError("expected '(' in function argument list");
3081 SmallVector<ArgInfo, 8> ArgList;
3083 AttrBuilder FuncAttrs;
3084 std::vector<unsigned> FwdRefAttrGrps;
3086 std::string Section;
3090 LocTy UnnamedAddrLoc;
3091 Constant *Prefix = nullptr;
3093 if (ParseArgumentList(ArgList, isVarArg) ||
3094 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3096 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3098 (EatIfPresent(lltok::kw_section) &&
3099 ParseStringConstant(Section)) ||
3100 ParseOptionalAlignment(Alignment) ||
3101 (EatIfPresent(lltok::kw_gc) &&
3102 ParseStringConstant(GC)) ||
3103 (EatIfPresent(lltok::kw_prefix) &&
3104 ParseGlobalTypeAndValue(Prefix)))
3107 if (FuncAttrs.contains(Attribute::Builtin))
3108 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3110 // If the alignment was parsed as an attribute, move to the alignment field.
3111 if (FuncAttrs.hasAlignmentAttr()) {
3112 Alignment = FuncAttrs.getAlignment();
3113 FuncAttrs.removeAttribute(Attribute::Alignment);
3116 // Okay, if we got here, the function is syntactically valid. Convert types
3117 // and do semantic checks.
3118 std::vector<Type*> ParamTypeList;
3119 SmallVector<AttributeSet, 8> Attrs;
3121 if (RetAttrs.hasAttributes())
3122 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3123 AttributeSet::ReturnIndex,
3126 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3127 ParamTypeList.push_back(ArgList[i].Ty);
3128 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3129 AttrBuilder B(ArgList[i].Attrs, i + 1);
3130 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3134 if (FuncAttrs.hasAttributes())
3135 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3136 AttributeSet::FunctionIndex,
3139 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3141 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3142 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3145 FunctionType::get(RetType, ParamTypeList, isVarArg);
3146 PointerType *PFT = PointerType::getUnqual(FT);
3149 if (!FunctionName.empty()) {
3150 // If this was a definition of a forward reference, remove the definition
3151 // from the forward reference table and fill in the forward ref.
3152 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3153 ForwardRefVals.find(FunctionName);
3154 if (FRVI != ForwardRefVals.end()) {
3155 Fn = M->getFunction(FunctionName);
3157 return Error(FRVI->second.second, "invalid forward reference to "
3158 "function as global value!");
3159 if (Fn->getType() != PFT)
3160 return Error(FRVI->second.second, "invalid forward reference to "
3161 "function '" + FunctionName + "' with wrong type!");
3163 ForwardRefVals.erase(FRVI);
3164 } else if ((Fn = M->getFunction(FunctionName))) {
3165 // Reject redefinitions.
3166 return Error(NameLoc, "invalid redefinition of function '" +
3167 FunctionName + "'");
3168 } else if (M->getNamedValue(FunctionName)) {
3169 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3173 // If this is a definition of a forward referenced function, make sure the
3175 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3176 = ForwardRefValIDs.find(NumberedVals.size());
3177 if (I != ForwardRefValIDs.end()) {
3178 Fn = cast<Function>(I->second.first);
3179 if (Fn->getType() != PFT)
3180 return Error(NameLoc, "type of definition and forward reference of '@" +
3181 Twine(NumberedVals.size()) + "' disagree");
3182 ForwardRefValIDs.erase(I);
3187 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3188 else // Move the forward-reference to the correct spot in the module.
3189 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3191 if (FunctionName.empty())
3192 NumberedVals.push_back(Fn);
3194 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3195 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3196 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3197 Fn->setCallingConv(CC);
3198 Fn->setAttributes(PAL);
3199 Fn->setUnnamedAddr(UnnamedAddr);
3200 Fn->setAlignment(Alignment);
3201 Fn->setSection(Section);
3202 if (!GC.empty()) Fn->setGC(GC.c_str());
3203 Fn->setPrefixData(Prefix);
3204 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3206 // Add all of the arguments we parsed to the function.
3207 Function::arg_iterator ArgIt = Fn->arg_begin();
3208 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3209 // If the argument has a name, insert it into the argument symbol table.
3210 if (ArgList[i].Name.empty()) continue;
3212 // Set the name, if it conflicted, it will be auto-renamed.
3213 ArgIt->setName(ArgList[i].Name);
3215 if (ArgIt->getName() != ArgList[i].Name)
3216 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3217 ArgList[i].Name + "'");
3224 /// ParseFunctionBody
3225 /// ::= '{' BasicBlock+ '}'
3227 bool LLParser::ParseFunctionBody(Function &Fn) {
3228 if (Lex.getKind() != lltok::lbrace)
3229 return TokError("expected '{' in function body");
3230 Lex.Lex(); // eat the {.
3232 int FunctionNumber = -1;
3233 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3235 PerFunctionState PFS(*this, Fn, FunctionNumber);
3237 // We need at least one basic block.
3238 if (Lex.getKind() == lltok::rbrace)
3239 return TokError("function body requires at least one basic block");
3241 while (Lex.getKind() != lltok::rbrace)
3242 if (ParseBasicBlock(PFS)) return true;
3247 // Verify function is ok.
3248 return PFS.FinishFunction();
3252 /// ::= LabelStr? Instruction*
3253 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3254 // If this basic block starts out with a name, remember it.
3256 LocTy NameLoc = Lex.getLoc();
3257 if (Lex.getKind() == lltok::LabelStr) {
3258 Name = Lex.getStrVal();
3262 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3263 if (!BB) return true;
3265 std::string NameStr;
3267 // Parse the instructions in this block until we get a terminator.
3270 // This instruction may have three possibilities for a name: a) none
3271 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3272 LocTy NameLoc = Lex.getLoc();
3276 if (Lex.getKind() == lltok::LocalVarID) {
3277 NameID = Lex.getUIntVal();
3279 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3281 } else if (Lex.getKind() == lltok::LocalVar) {
3282 NameStr = Lex.getStrVal();
3284 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3288 switch (ParseInstruction(Inst, BB, PFS)) {
3289 default: llvm_unreachable("Unknown ParseInstruction result!");
3290 case InstError: return true;
3292 BB->getInstList().push_back(Inst);
3294 // With a normal result, we check to see if the instruction is followed by
3295 // a comma and metadata.
3296 if (EatIfPresent(lltok::comma))
3297 if (ParseInstructionMetadata(Inst, &PFS))
3300 case InstExtraComma:
3301 BB->getInstList().push_back(Inst);
3303 // If the instruction parser ate an extra comma at the end of it, it
3304 // *must* be followed by metadata.
3305 if (ParseInstructionMetadata(Inst, &PFS))
3310 // Set the name on the instruction.
3311 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3312 } while (!isa<TerminatorInst>(Inst));
3317 //===----------------------------------------------------------------------===//
3318 // Instruction Parsing.
3319 //===----------------------------------------------------------------------===//
3321 /// ParseInstruction - Parse one of the many different instructions.
3323 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3324 PerFunctionState &PFS) {
3325 lltok::Kind Token = Lex.getKind();
3326 if (Token == lltok::Eof)
3327 return TokError("found end of file when expecting more instructions");
3328 LocTy Loc = Lex.getLoc();
3329 unsigned KeywordVal = Lex.getUIntVal();
3330 Lex.Lex(); // Eat the keyword.
3333 default: return Error(Loc, "expected instruction opcode");
3334 // Terminator Instructions.
3335 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3336 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3337 case lltok::kw_br: return ParseBr(Inst, PFS);
3338 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3339 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3340 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3341 case lltok::kw_resume: return ParseResume(Inst, PFS);
3342 // Binary Operators.
3346 case lltok::kw_shl: {
3347 bool NUW = EatIfPresent(lltok::kw_nuw);
3348 bool NSW = EatIfPresent(lltok::kw_nsw);
3349 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3351 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3353 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3354 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3357 case lltok::kw_fadd:
3358 case lltok::kw_fsub:
3359 case lltok::kw_fmul:
3360 case lltok::kw_fdiv:
3361 case lltok::kw_frem: {
3362 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3363 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3367 Inst->setFastMathFlags(FMF);
3371 case lltok::kw_sdiv:
3372 case lltok::kw_udiv:
3373 case lltok::kw_lshr:
3374 case lltok::kw_ashr: {
3375 bool Exact = EatIfPresent(lltok::kw_exact);
3377 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3378 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3382 case lltok::kw_urem:
3383 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3386 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3387 case lltok::kw_icmp:
3388 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3390 case lltok::kw_trunc:
3391 case lltok::kw_zext:
3392 case lltok::kw_sext:
3393 case lltok::kw_fptrunc:
3394 case lltok::kw_fpext:
3395 case lltok::kw_bitcast:
3396 case lltok::kw_addrspacecast:
3397 case lltok::kw_uitofp:
3398 case lltok::kw_sitofp:
3399 case lltok::kw_fptoui:
3400 case lltok::kw_fptosi:
3401 case lltok::kw_inttoptr:
3402 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3404 case lltok::kw_select: return ParseSelect(Inst, PFS);
3405 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3406 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3407 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3408 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3409 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3410 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3412 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3413 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3414 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3416 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3417 case lltok::kw_load: return ParseLoad(Inst, PFS);
3418 case lltok::kw_store: return ParseStore(Inst, PFS);
3419 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3420 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3421 case lltok::kw_fence: return ParseFence(Inst, PFS);
3422 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3423 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3424 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3428 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3429 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3430 if (Opc == Instruction::FCmp) {
3431 switch (Lex.getKind()) {
3432 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3433 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3434 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3435 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3436 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3437 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3438 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3439 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3440 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3441 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3442 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3443 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3444 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3445 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3446 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3447 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3448 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3451 switch (Lex.getKind()) {
3452 default: return TokError("expected icmp predicate (e.g. 'eq')");
3453 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3454 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3455 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3456 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3457 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3458 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3459 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3460 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3461 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3462 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3469 //===----------------------------------------------------------------------===//
3470 // Terminator Instructions.
3471 //===----------------------------------------------------------------------===//
3473 /// ParseRet - Parse a return instruction.
3474 /// ::= 'ret' void (',' !dbg, !1)*
3475 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3476 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3477 PerFunctionState &PFS) {
3478 SMLoc TypeLoc = Lex.getLoc();
3480 if (ParseType(Ty, true /*void allowed*/)) return true;
3482 Type *ResType = PFS.getFunction().getReturnType();
3484 if (Ty->isVoidTy()) {
3485 if (!ResType->isVoidTy())
3486 return Error(TypeLoc, "value doesn't match function result type '" +
3487 getTypeString(ResType) + "'");
3489 Inst = ReturnInst::Create(Context);
3494 if (ParseValue(Ty, RV, PFS)) return true;
3496 if (ResType != RV->getType())
3497 return Error(TypeLoc, "value doesn't match function result type '" +
3498 getTypeString(ResType) + "'");
3500 Inst = ReturnInst::Create(Context, RV);
3506 /// ::= 'br' TypeAndValue
3507 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3508 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3511 BasicBlock *Op1, *Op2;
3512 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3514 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3515 Inst = BranchInst::Create(BB);
3519 if (Op0->getType() != Type::getInt1Ty(Context))
3520 return Error(Loc, "branch condition must have 'i1' type");
3522 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3523 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3524 ParseToken(lltok::comma, "expected ',' after true destination") ||
3525 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3528 Inst = BranchInst::Create(Op1, Op2, Op0);
3534 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3536 /// ::= (TypeAndValue ',' TypeAndValue)*
3537 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3538 LocTy CondLoc, BBLoc;
3540 BasicBlock *DefaultBB;
3541 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3542 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3543 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3544 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3547 if (!Cond->getType()->isIntegerTy())
3548 return Error(CondLoc, "switch condition must have integer type");
3550 // Parse the jump table pairs.
3551 SmallPtrSet<Value*, 32> SeenCases;
3552 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3553 while (Lex.getKind() != lltok::rsquare) {
3557 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3558 ParseToken(lltok::comma, "expected ',' after case value") ||
3559 ParseTypeAndBasicBlock(DestBB, PFS))
3562 if (!SeenCases.insert(Constant))
3563 return Error(CondLoc, "duplicate case value in switch");
3564 if (!isa<ConstantInt>(Constant))
3565 return Error(CondLoc, "case value is not a constant integer");
3567 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3570 Lex.Lex(); // Eat the ']'.
3572 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3573 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3574 SI->addCase(Table[i].first, Table[i].second);
3581 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3582 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3585 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3586 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3587 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3590 if (!Address->getType()->isPointerTy())
3591 return Error(AddrLoc, "indirectbr address must have pointer type");
3593 // Parse the destination list.
3594 SmallVector<BasicBlock*, 16> DestList;
3596 if (Lex.getKind() != lltok::rsquare) {
3598 if (ParseTypeAndBasicBlock(DestBB, PFS))
3600 DestList.push_back(DestBB);
3602 while (EatIfPresent(lltok::comma)) {
3603 if (ParseTypeAndBasicBlock(DestBB, PFS))
3605 DestList.push_back(DestBB);
3609 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3612 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3613 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3614 IBI->addDestination(DestList[i]);
3621 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3622 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3623 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3624 LocTy CallLoc = Lex.getLoc();
3625 AttrBuilder RetAttrs, FnAttrs;
3626 std::vector<unsigned> FwdRefAttrGrps;
3629 Type *RetType = nullptr;
3632 SmallVector<ParamInfo, 16> ArgList;
3634 BasicBlock *NormalBB, *UnwindBB;
3635 if (ParseOptionalCallingConv(CC) ||
3636 ParseOptionalReturnAttrs(RetAttrs) ||
3637 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3638 ParseValID(CalleeID) ||
3639 ParseParameterList(ArgList, PFS) ||
3640 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3642 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3643 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3644 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3645 ParseTypeAndBasicBlock(UnwindBB, PFS))
3648 // If RetType is a non-function pointer type, then this is the short syntax
3649 // for the call, which means that RetType is just the return type. Infer the
3650 // rest of the function argument types from the arguments that are present.
3651 PointerType *PFTy = nullptr;
3652 FunctionType *Ty = nullptr;
3653 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3654 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3655 // Pull out the types of all of the arguments...
3656 std::vector<Type*> ParamTypes;
3657 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3658 ParamTypes.push_back(ArgList[i].V->getType());
3660 if (!FunctionType::isValidReturnType(RetType))
3661 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3663 Ty = FunctionType::get(RetType, ParamTypes, false);
3664 PFTy = PointerType::getUnqual(Ty);
3667 // Look up the callee.
3669 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3671 // Set up the Attribute for the function.
3672 SmallVector<AttributeSet, 8> Attrs;
3673 if (RetAttrs.hasAttributes())
3674 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3675 AttributeSet::ReturnIndex,
3678 SmallVector<Value*, 8> Args;
3680 // Loop through FunctionType's arguments and ensure they are specified
3681 // correctly. Also, gather any parameter attributes.
3682 FunctionType::param_iterator I = Ty->param_begin();
3683 FunctionType::param_iterator E = Ty->param_end();
3684 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3685 Type *ExpectedTy = nullptr;
3688 } else if (!Ty->isVarArg()) {
3689 return Error(ArgList[i].Loc, "too many arguments specified");
3692 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3693 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3694 getTypeString(ExpectedTy) + "'");
3695 Args.push_back(ArgList[i].V);
3696 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3697 AttrBuilder B(ArgList[i].Attrs, i + 1);
3698 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3703 return Error(CallLoc, "not enough parameters specified for call");
3705 if (FnAttrs.hasAttributes())
3706 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3707 AttributeSet::FunctionIndex,
3710 // Finish off the Attribute and check them
3711 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3713 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3714 II->setCallingConv(CC);
3715 II->setAttributes(PAL);
3716 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3722 /// ::= 'resume' TypeAndValue
3723 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3724 Value *Exn; LocTy ExnLoc;
3725 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3728 ResumeInst *RI = ResumeInst::Create(Exn);
3733 //===----------------------------------------------------------------------===//
3734 // Binary Operators.
3735 //===----------------------------------------------------------------------===//
3738 /// ::= ArithmeticOps TypeAndValue ',' Value
3740 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3741 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3742 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3743 unsigned Opc, unsigned OperandType) {
3744 LocTy Loc; Value *LHS, *RHS;
3745 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3746 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3747 ParseValue(LHS->getType(), RHS, PFS))
3751 switch (OperandType) {
3752 default: llvm_unreachable("Unknown operand type!");
3753 case 0: // int or FP.
3754 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3755 LHS->getType()->isFPOrFPVectorTy();
3757 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3758 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3762 return Error(Loc, "invalid operand type for instruction");
3764 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3769 /// ::= ArithmeticOps TypeAndValue ',' Value {
3770 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3772 LocTy Loc; Value *LHS, *RHS;
3773 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3774 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3775 ParseValue(LHS->getType(), RHS, PFS))
3778 if (!LHS->getType()->isIntOrIntVectorTy())
3779 return Error(Loc,"instruction requires integer or integer vector operands");
3781 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3787 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3788 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3789 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3791 // Parse the integer/fp comparison predicate.
3795 if (ParseCmpPredicate(Pred, Opc) ||
3796 ParseTypeAndValue(LHS, Loc, PFS) ||
3797 ParseToken(lltok::comma, "expected ',' after compare value") ||
3798 ParseValue(LHS->getType(), RHS, PFS))
3801 if (Opc == Instruction::FCmp) {
3802 if (!LHS->getType()->isFPOrFPVectorTy())
3803 return Error(Loc, "fcmp requires floating point operands");
3804 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3806 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3807 if (!LHS->getType()->isIntOrIntVectorTy() &&
3808 !LHS->getType()->getScalarType()->isPointerTy())
3809 return Error(Loc, "icmp requires integer operands");
3810 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3815 //===----------------------------------------------------------------------===//
3816 // Other Instructions.
3817 //===----------------------------------------------------------------------===//
3821 /// ::= CastOpc TypeAndValue 'to' Type
3822 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3826 Type *DestTy = nullptr;
3827 if (ParseTypeAndValue(Op, Loc, PFS) ||
3828 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3832 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3833 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3834 return Error(Loc, "invalid cast opcode for cast from '" +
3835 getTypeString(Op->getType()) + "' to '" +
3836 getTypeString(DestTy) + "'");
3838 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3843 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3844 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3846 Value *Op0, *Op1, *Op2;
3847 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3848 ParseToken(lltok::comma, "expected ',' after select condition") ||
3849 ParseTypeAndValue(Op1, PFS) ||
3850 ParseToken(lltok::comma, "expected ',' after select value") ||
3851 ParseTypeAndValue(Op2, PFS))
3854 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3855 return Error(Loc, Reason);
3857 Inst = SelectInst::Create(Op0, Op1, Op2);
3862 /// ::= 'va_arg' TypeAndValue ',' Type
3863 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3865 Type *EltTy = nullptr;
3867 if (ParseTypeAndValue(Op, PFS) ||
3868 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3869 ParseType(EltTy, TypeLoc))
3872 if (!EltTy->isFirstClassType())
3873 return Error(TypeLoc, "va_arg requires operand with first class type");
3875 Inst = new VAArgInst(Op, EltTy);
3879 /// ParseExtractElement
3880 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3881 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3884 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3885 ParseToken(lltok::comma, "expected ',' after extract value") ||
3886 ParseTypeAndValue(Op1, PFS))
3889 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3890 return Error(Loc, "invalid extractelement operands");
3892 Inst = ExtractElementInst::Create(Op0, Op1);
3896 /// ParseInsertElement
3897 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3898 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3900 Value *Op0, *Op1, *Op2;
3901 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3902 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3903 ParseTypeAndValue(Op1, PFS) ||
3904 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3905 ParseTypeAndValue(Op2, PFS))
3908 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3909 return Error(Loc, "invalid insertelement operands");
3911 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3915 /// ParseShuffleVector
3916 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3917 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3919 Value *Op0, *Op1, *Op2;
3920 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3921 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3922 ParseTypeAndValue(Op1, PFS) ||
3923 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3924 ParseTypeAndValue(Op2, PFS))
3927 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3928 return Error(Loc, "invalid shufflevector operands");
3930 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3935 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3936 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3937 Type *Ty = nullptr; LocTy TypeLoc;
3940 if (ParseType(Ty, TypeLoc) ||
3941 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3942 ParseValue(Ty, Op0, PFS) ||
3943 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3944 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3945 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3948 bool AteExtraComma = false;
3949 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3951 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3953 if (!EatIfPresent(lltok::comma))
3956 if (Lex.getKind() == lltok::MetadataVar) {
3957 AteExtraComma = true;
3961 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3962 ParseValue(Ty, Op0, PFS) ||
3963 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3964 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3965 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3969 if (!Ty->isFirstClassType())
3970 return Error(TypeLoc, "phi node must have first class type");
3972 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3973 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3974 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3976 return AteExtraComma ? InstExtraComma : InstNormal;
3980 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3982 /// ::= 'catch' TypeAndValue
3984 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3985 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3986 Type *Ty = nullptr; LocTy TyLoc;
3987 Value *PersFn; LocTy PersFnLoc;
3989 if (ParseType(Ty, TyLoc) ||
3990 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3991 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3994 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3995 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3997 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3998 LandingPadInst::ClauseType CT;
3999 if (EatIfPresent(lltok::kw_catch))
4000 CT = LandingPadInst::Catch;
4001 else if (EatIfPresent(lltok::kw_filter))
4002 CT = LandingPadInst::Filter;
4004 return TokError("expected 'catch' or 'filter' clause type");
4008 if (ParseTypeAndValue(V, VLoc, PFS)) {
4013 // A 'catch' type expects a non-array constant. A filter clause expects an
4015 if (CT == LandingPadInst::Catch) {
4016 if (isa<ArrayType>(V->getType()))
4017 Error(VLoc, "'catch' clause has an invalid type");
4019 if (!isa<ArrayType>(V->getType()))
4020 Error(VLoc, "'filter' clause has an invalid type");
4023 LP->addClause(cast<Constant>(V));
4031 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4032 /// ParameterList OptionalAttrs
4033 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4034 /// ParameterList OptionalAttrs
4035 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4036 /// ParameterList OptionalAttrs
4037 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4038 CallInst::TailCallKind TCK) {
4039 AttrBuilder RetAttrs, FnAttrs;
4040 std::vector<unsigned> FwdRefAttrGrps;
4043 Type *RetType = nullptr;
4046 SmallVector<ParamInfo, 16> ArgList;
4047 LocTy CallLoc = Lex.getLoc();
4049 if ((TCK != CallInst::TCK_None &&
4050 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4051 ParseOptionalCallingConv(CC) ||
4052 ParseOptionalReturnAttrs(RetAttrs) ||
4053 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4054 ParseValID(CalleeID) ||
4055 ParseParameterList(ArgList, PFS) ||
4056 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4060 // If RetType is a non-function pointer type, then this is the short syntax
4061 // for the call, which means that RetType is just the return type. Infer the
4062 // rest of the function argument types from the arguments that are present.
4063 PointerType *PFTy = nullptr;
4064 FunctionType *Ty = nullptr;
4065 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4066 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4067 // Pull out the types of all of the arguments...
4068 std::vector<Type*> ParamTypes;
4069 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4070 ParamTypes.push_back(ArgList[i].V->getType());
4072 if (!FunctionType::isValidReturnType(RetType))
4073 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4075 Ty = FunctionType::get(RetType, ParamTypes, false);
4076 PFTy = PointerType::getUnqual(Ty);
4079 // Look up the callee.
4081 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4083 // Set up the Attribute for the function.
4084 SmallVector<AttributeSet, 8> Attrs;
4085 if (RetAttrs.hasAttributes())
4086 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4087 AttributeSet::ReturnIndex,
4090 SmallVector<Value*, 8> Args;
4092 // Loop through FunctionType's arguments and ensure they are specified
4093 // correctly. Also, gather any parameter attributes.
4094 FunctionType::param_iterator I = Ty->param_begin();
4095 FunctionType::param_iterator E = Ty->param_end();
4096 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4097 Type *ExpectedTy = nullptr;
4100 } else if (!Ty->isVarArg()) {
4101 return Error(ArgList[i].Loc, "too many arguments specified");
4104 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4105 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4106 getTypeString(ExpectedTy) + "'");
4107 Args.push_back(ArgList[i].V);
4108 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4109 AttrBuilder B(ArgList[i].Attrs, i + 1);
4110 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4115 return Error(CallLoc, "not enough parameters specified for call");
4117 if (FnAttrs.hasAttributes())
4118 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4119 AttributeSet::FunctionIndex,
4122 // Finish off the Attribute and check them
4123 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4125 CallInst *CI = CallInst::Create(Callee, Args);
4126 CI->setTailCallKind(TCK);
4127 CI->setCallingConv(CC);
4128 CI->setAttributes(PAL);
4129 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4134 //===----------------------------------------------------------------------===//
4135 // Memory Instructions.
4136 //===----------------------------------------------------------------------===//
4139 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4140 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4141 Value *Size = nullptr;
4143 unsigned Alignment = 0;
4146 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4148 if (ParseType(Ty)) return true;
4150 bool AteExtraComma = false;
4151 if (EatIfPresent(lltok::comma)) {
4152 if (Lex.getKind() == lltok::kw_align) {
4153 if (ParseOptionalAlignment(Alignment)) return true;
4154 } else if (Lex.getKind() == lltok::MetadataVar) {
4155 AteExtraComma = true;
4157 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4158 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4163 if (Size && !Size->getType()->isIntegerTy())
4164 return Error(SizeLoc, "element count must have integer type");
4166 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4167 AI->setUsedWithInAlloca(IsInAlloca);
4169 return AteExtraComma ? InstExtraComma : InstNormal;
4173 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4174 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4175 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4176 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4177 Value *Val; LocTy Loc;
4178 unsigned Alignment = 0;
4179 bool AteExtraComma = false;
4180 bool isAtomic = false;
4181 AtomicOrdering Ordering = NotAtomic;
4182 SynchronizationScope Scope = CrossThread;
4184 if (Lex.getKind() == lltok::kw_atomic) {
4189 bool isVolatile = false;
4190 if (Lex.getKind() == lltok::kw_volatile) {
4195 if (ParseTypeAndValue(Val, Loc, PFS) ||
4196 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4197 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4200 if (!Val->getType()->isPointerTy() ||
4201 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4202 return Error(Loc, "load operand must be a pointer to a first class type");
4203 if (isAtomic && !Alignment)
4204 return Error(Loc, "atomic load must have explicit non-zero alignment");
4205 if (Ordering == Release || Ordering == AcquireRelease)
4206 return Error(Loc, "atomic load cannot use Release ordering");
4208 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4209 return AteExtraComma ? InstExtraComma : InstNormal;
4214 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4215 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4216 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4217 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4218 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4219 unsigned Alignment = 0;
4220 bool AteExtraComma = false;
4221 bool isAtomic = false;
4222 AtomicOrdering Ordering = NotAtomic;
4223 SynchronizationScope Scope = CrossThread;
4225 if (Lex.getKind() == lltok::kw_atomic) {
4230 bool isVolatile = false;
4231 if (Lex.getKind() == lltok::kw_volatile) {
4236 if (ParseTypeAndValue(Val, Loc, PFS) ||
4237 ParseToken(lltok::comma, "expected ',' after store operand") ||
4238 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4239 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4240 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4243 if (!Ptr->getType()->isPointerTy())
4244 return Error(PtrLoc, "store operand must be a pointer");
4245 if (!Val->getType()->isFirstClassType())
4246 return Error(Loc, "store operand must be a first class value");
4247 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4248 return Error(Loc, "stored value and pointer type do not match");
4249 if (isAtomic && !Alignment)
4250 return Error(Loc, "atomic store must have explicit non-zero alignment");
4251 if (Ordering == Acquire || Ordering == AcquireRelease)
4252 return Error(Loc, "atomic store cannot use Acquire ordering");
4254 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4255 return AteExtraComma ? InstExtraComma : InstNormal;
4259 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4260 /// 'singlethread'? AtomicOrdering AtomicOrdering
4261 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4262 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4263 bool AteExtraComma = false;
4264 AtomicOrdering SuccessOrdering = NotAtomic;
4265 AtomicOrdering FailureOrdering = NotAtomic;
4266 SynchronizationScope Scope = CrossThread;
4267 bool isVolatile = false;
4269 if (EatIfPresent(lltok::kw_volatile))
4272 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4273 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4274 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4275 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4276 ParseTypeAndValue(New, NewLoc, PFS) ||
4277 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4278 ParseOrdering(FailureOrdering))
4281 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4282 return TokError("cmpxchg cannot be unordered");
4283 if (SuccessOrdering < FailureOrdering)
4284 return TokError("cmpxchg must be at least as ordered on success as failure");
4285 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4286 return TokError("cmpxchg failure ordering cannot include release semantics");
4287 if (!Ptr->getType()->isPointerTy())
4288 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4289 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4290 return Error(CmpLoc, "compare value and pointer type do not match");
4291 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4292 return Error(NewLoc, "new value and pointer type do not match");
4293 if (!New->getType()->isIntegerTy())
4294 return Error(NewLoc, "cmpxchg operand must be an integer");
4295 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4296 if (Size < 8 || (Size & (Size - 1)))
4297 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4300 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4301 FailureOrdering, Scope);
4302 CXI->setVolatile(isVolatile);
4304 return AteExtraComma ? InstExtraComma : InstNormal;
4308 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4309 /// 'singlethread'? AtomicOrdering
4310 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4311 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4312 bool AteExtraComma = false;
4313 AtomicOrdering Ordering = NotAtomic;
4314 SynchronizationScope Scope = CrossThread;
4315 bool isVolatile = false;
4316 AtomicRMWInst::BinOp Operation;
4318 if (EatIfPresent(lltok::kw_volatile))
4321 switch (Lex.getKind()) {
4322 default: return TokError("expected binary operation in atomicrmw");
4323 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4324 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4325 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4326 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4327 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4328 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4329 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4330 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4331 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4332 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4333 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4335 Lex.Lex(); // Eat the operation.
4337 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4338 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4339 ParseTypeAndValue(Val, ValLoc, PFS) ||
4340 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4343 if (Ordering == Unordered)
4344 return TokError("atomicrmw cannot be unordered");
4345 if (!Ptr->getType()->isPointerTy())
4346 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4347 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4348 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4349 if (!Val->getType()->isIntegerTy())
4350 return Error(ValLoc, "atomicrmw operand must be an integer");
4351 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4352 if (Size < 8 || (Size & (Size - 1)))
4353 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4356 AtomicRMWInst *RMWI =
4357 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4358 RMWI->setVolatile(isVolatile);
4360 return AteExtraComma ? InstExtraComma : InstNormal;
4364 /// ::= 'fence' 'singlethread'? AtomicOrdering
4365 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4366 AtomicOrdering Ordering = NotAtomic;
4367 SynchronizationScope Scope = CrossThread;
4368 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4371 if (Ordering == Unordered)
4372 return TokError("fence cannot be unordered");
4373 if (Ordering == Monotonic)
4374 return TokError("fence cannot be monotonic");
4376 Inst = new FenceInst(Context, Ordering, Scope);
4380 /// ParseGetElementPtr
4381 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4382 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4383 Value *Ptr = nullptr;
4384 Value *Val = nullptr;
4387 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4389 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4391 Type *BaseType = Ptr->getType();
4392 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4393 if (!BasePointerType)
4394 return Error(Loc, "base of getelementptr must be a pointer");
4396 SmallVector<Value*, 16> Indices;
4397 bool AteExtraComma = false;
4398 while (EatIfPresent(lltok::comma)) {
4399 if (Lex.getKind() == lltok::MetadataVar) {
4400 AteExtraComma = true;
4403 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4404 if (!Val->getType()->getScalarType()->isIntegerTy())
4405 return Error(EltLoc, "getelementptr index must be an integer");
4406 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4407 return Error(EltLoc, "getelementptr index type missmatch");
4408 if (Val->getType()->isVectorTy()) {
4409 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4410 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4411 if (ValNumEl != PtrNumEl)
4412 return Error(EltLoc,
4413 "getelementptr vector index has a wrong number of elements");
4415 Indices.push_back(Val);
4418 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4419 return Error(Loc, "base element of getelementptr must be sized");
4421 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4422 return Error(Loc, "invalid getelementptr indices");
4423 Inst = GetElementPtrInst::Create(Ptr, Indices);
4425 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4426 return AteExtraComma ? InstExtraComma : InstNormal;
4429 /// ParseExtractValue
4430 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4431 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4432 Value *Val; LocTy Loc;
4433 SmallVector<unsigned, 4> Indices;
4435 if (ParseTypeAndValue(Val, Loc, PFS) ||
4436 ParseIndexList(Indices, AteExtraComma))
4439 if (!Val->getType()->isAggregateType())
4440 return Error(Loc, "extractvalue operand must be aggregate type");
4442 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4443 return Error(Loc, "invalid indices for extractvalue");
4444 Inst = ExtractValueInst::Create(Val, Indices);
4445 return AteExtraComma ? InstExtraComma : InstNormal;
4448 /// ParseInsertValue
4449 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4450 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4451 Value *Val0, *Val1; LocTy Loc0, Loc1;
4452 SmallVector<unsigned, 4> Indices;
4454 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4455 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4456 ParseTypeAndValue(Val1, Loc1, PFS) ||
4457 ParseIndexList(Indices, AteExtraComma))
4460 if (!Val0->getType()->isAggregateType())
4461 return Error(Loc0, "insertvalue operand must be aggregate type");
4463 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4464 return Error(Loc0, "invalid indices for insertvalue");
4465 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4466 return AteExtraComma ? InstExtraComma : InstNormal;
4469 //===----------------------------------------------------------------------===//
4470 // Embedded metadata.
4471 //===----------------------------------------------------------------------===//
4473 /// ParseMDNodeVector
4474 /// ::= Element (',' Element)*
4476 /// ::= 'null' | TypeAndValue
4477 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4478 PerFunctionState *PFS) {
4479 // Check for an empty list.
4480 if (Lex.getKind() == lltok::rbrace)
4484 // Null is a special case since it is typeless.
4485 if (EatIfPresent(lltok::kw_null)) {
4486 Elts.push_back(nullptr);
4491 if (ParseTypeAndValue(V, PFS)) return true;
4493 } while (EatIfPresent(lltok::comma));