1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
30 static std::string getTypeString(Type *T) {
32 raw_string_ostream Tmp(Result);
37 /// Run: module ::= toplevelentity*
38 bool LLParser::Run() {
42 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
46 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48 bool LLParser::ValidateEndOfModule() {
49 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
57 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
60 if (SlotNo >= NumberedMetadata.size() ||
61 NumberedMetadata[SlotNo] == nullptr)
62 return Error(MDList[i].Loc, "use of undefined metadata '!" +
64 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
67 ForwardRefInstMetadata.clear();
70 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
71 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
73 // Handle any function attribute group forward references.
74 for (std::map<Value*, std::vector<unsigned> >::iterator
75 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
78 std::vector<unsigned> &Vec = I->second;
81 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
83 B.merge(NumberedAttrBuilders[*VI]);
85 if (Function *Fn = dyn_cast<Function>(V)) {
86 AttributeSet AS = Fn->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
93 // If the alignment was parsed as an attribute, move to the alignment
95 if (FnAttrs.hasAlignmentAttr()) {
96 Fn->setAlignment(FnAttrs.getAlignment());
97 FnAttrs.removeAttribute(Attribute::Alignment);
100 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
101 AttributeSet::get(Context,
102 AttributeSet::FunctionIndex,
104 Fn->setAttributes(AS);
105 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
106 AttributeSet AS = CI->getAttributes();
107 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
108 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
109 AS.getFnAttributes());
111 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
112 AttributeSet::get(Context,
113 AttributeSet::FunctionIndex,
115 CI->setAttributes(AS);
116 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
117 AttributeSet AS = II->getAttributes();
118 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120 AS.getFnAttributes());
122 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
123 AttributeSet::get(Context,
124 AttributeSet::FunctionIndex,
126 II->setAttributes(AS);
128 llvm_unreachable("invalid object with forward attribute group reference");
132 // If there are entries in ForwardRefBlockAddresses at this point, they are
133 // references after the function was defined. Resolve those now.
134 while (!ForwardRefBlockAddresses.empty()) {
135 // Okay, we are referencing an already-parsed function, resolve them now.
136 Function *TheFn = nullptr;
137 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
138 if (Fn.Kind == ValID::t_GlobalName)
139 TheFn = M->getFunction(Fn.StrVal);
140 else if (Fn.UIntVal < NumberedVals.size())
141 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
144 return Error(Fn.Loc, "unknown function referenced by blockaddress");
146 // Resolve all these references.
147 if (ResolveForwardRefBlockAddresses(TheFn,
148 ForwardRefBlockAddresses.begin()->second,
152 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
155 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
156 if (NumberedTypes[i].second.isValid())
157 return Error(NumberedTypes[i].second,
158 "use of undefined type '%" + Twine(i) + "'");
160 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
161 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
162 if (I->second.second.isValid())
163 return Error(I->second.second,
164 "use of undefined type named '" + I->getKey() + "'");
166 if (!ForwardRefVals.empty())
167 return Error(ForwardRefVals.begin()->second.second,
168 "use of undefined value '@" + ForwardRefVals.begin()->first +
171 if (!ForwardRefValIDs.empty())
172 return Error(ForwardRefValIDs.begin()->second.second,
173 "use of undefined value '@" +
174 Twine(ForwardRefValIDs.begin()->first) + "'");
176 if (!ForwardRefMDNodes.empty())
177 return Error(ForwardRefMDNodes.begin()->second.second,
178 "use of undefined metadata '!" +
179 Twine(ForwardRefMDNodes.begin()->first) + "'");
182 // Look for intrinsic functions and CallInst that need to be upgraded
183 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
184 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
186 UpgradeDebugInfo(*M);
191 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
192 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
193 PerFunctionState *PFS) {
194 // Loop over all the references, resolving them.
195 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
198 if (Refs[i].first.Kind == ValID::t_LocalName)
199 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
201 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
202 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
203 return Error(Refs[i].first.Loc,
204 "cannot take address of numeric label after the function is defined");
206 Res = dyn_cast_or_null<BasicBlock>(
207 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
211 return Error(Refs[i].first.Loc,
212 "referenced value is not a basic block");
214 // Get the BlockAddress for this and update references to use it.
215 BlockAddress *BA = BlockAddress::get(TheFn, Res);
216 Refs[i].second->replaceAllUsesWith(BA);
217 Refs[i].second->eraseFromParent();
223 //===----------------------------------------------------------------------===//
224 // Top-Level Entities
225 //===----------------------------------------------------------------------===//
227 bool LLParser::ParseTopLevelEntities() {
229 switch (Lex.getKind()) {
230 default: return TokError("expected top-level entity");
231 case lltok::Eof: return false;
232 case lltok::kw_declare: if (ParseDeclare()) return true; break;
233 case lltok::kw_define: if (ParseDefine()) return true; break;
234 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
235 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
236 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
237 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
238 case lltok::LocalVar: if (ParseNamedType()) return true; break;
239 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
240 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
241 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
242 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
244 // The Global variable production with no name can have many different
245 // optional leading prefixes, the production is:
246 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
247 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
248 // ('constant'|'global') ...
249 case lltok::kw_private: // OptionalLinkage
250 case lltok::kw_internal: // OptionalLinkage
251 case lltok::kw_linker_private: // Obsolete OptionalLinkage
252 case lltok::kw_linker_private_weak: // Obsolete OptionalLinkage
253 case lltok::kw_weak: // OptionalLinkage
254 case lltok::kw_weak_odr: // OptionalLinkage
255 case lltok::kw_linkonce: // OptionalLinkage
256 case lltok::kw_linkonce_odr: // OptionalLinkage
257 case lltok::kw_appending: // OptionalLinkage
258 case lltok::kw_common: // OptionalLinkage
259 case lltok::kw_extern_weak: // OptionalLinkage
260 case lltok::kw_external: { // OptionalLinkage
261 unsigned Linkage, Visibility, DLLStorageClass;
262 GlobalVariable::ThreadLocalMode TLM;
263 if (ParseOptionalLinkage(Linkage) ||
264 ParseOptionalVisibility(Visibility) ||
265 ParseOptionalDLLStorageClass(DLLStorageClass) ||
266 ParseOptionalThreadLocal(TLM) ||
267 ParseGlobal("", SMLoc(), Linkage, true, Visibility, DLLStorageClass,
272 case lltok::kw_default: // OptionalVisibility
273 case lltok::kw_hidden: // OptionalVisibility
274 case lltok::kw_protected: { // OptionalVisibility
275 unsigned Visibility, DLLStorageClass;
276 GlobalVariable::ThreadLocalMode TLM;
277 if (ParseOptionalVisibility(Visibility) ||
278 ParseOptionalDLLStorageClass(DLLStorageClass) ||
279 ParseOptionalThreadLocal(TLM) ||
280 ParseGlobal("", SMLoc(), 0, false, Visibility, DLLStorageClass, TLM))
285 case lltok::kw_thread_local: { // OptionalThreadLocal
286 GlobalVariable::ThreadLocalMode TLM;
287 if (ParseOptionalThreadLocal(TLM) ||
288 ParseGlobal("", SMLoc(), 0, false, 0, 0, TLM))
293 case lltok::kw_addrspace: // OptionalAddrSpace
294 case lltok::kw_constant: // GlobalType
295 case lltok::kw_global: // GlobalType
296 if (ParseGlobal("", SMLoc(), 0, false, 0, 0, GlobalValue::NotThreadLocal))
300 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
307 /// ::= 'module' 'asm' STRINGCONSTANT
308 bool LLParser::ParseModuleAsm() {
309 assert(Lex.getKind() == lltok::kw_module);
313 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
314 ParseStringConstant(AsmStr)) return true;
316 M->appendModuleInlineAsm(AsmStr);
321 /// ::= 'target' 'triple' '=' STRINGCONSTANT
322 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
323 bool LLParser::ParseTargetDefinition() {
324 assert(Lex.getKind() == lltok::kw_target);
327 default: return TokError("unknown target property");
328 case lltok::kw_triple:
330 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
331 ParseStringConstant(Str))
333 M->setTargetTriple(Str);
335 case lltok::kw_datalayout:
337 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
338 ParseStringConstant(Str))
340 M->setDataLayout(Str);
346 /// ::= 'deplibs' '=' '[' ']'
347 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
348 /// FIXME: Remove in 4.0. Currently parse, but ignore.
349 bool LLParser::ParseDepLibs() {
350 assert(Lex.getKind() == lltok::kw_deplibs);
352 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
353 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
356 if (EatIfPresent(lltok::rsquare))
361 if (ParseStringConstant(Str)) return true;
362 } while (EatIfPresent(lltok::comma));
364 return ParseToken(lltok::rsquare, "expected ']' at end of list");
367 /// ParseUnnamedType:
368 /// ::= LocalVarID '=' 'type' type
369 bool LLParser::ParseUnnamedType() {
370 LocTy TypeLoc = Lex.getLoc();
371 unsigned TypeID = Lex.getUIntVal();
372 Lex.Lex(); // eat LocalVarID;
374 if (ParseToken(lltok::equal, "expected '=' after name") ||
375 ParseToken(lltok::kw_type, "expected 'type' after '='"))
378 if (TypeID >= NumberedTypes.size())
379 NumberedTypes.resize(TypeID+1);
381 Type *Result = nullptr;
382 if (ParseStructDefinition(TypeLoc, "",
383 NumberedTypes[TypeID], Result)) return true;
385 if (!isa<StructType>(Result)) {
386 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
388 return Error(TypeLoc, "non-struct types may not be recursive");
389 Entry.first = Result;
390 Entry.second = SMLoc();
398 /// ::= LocalVar '=' 'type' type
399 bool LLParser::ParseNamedType() {
400 std::string Name = Lex.getStrVal();
401 LocTy NameLoc = Lex.getLoc();
402 Lex.Lex(); // eat LocalVar.
404 if (ParseToken(lltok::equal, "expected '=' after name") ||
405 ParseToken(lltok::kw_type, "expected 'type' after name"))
408 Type *Result = nullptr;
409 if (ParseStructDefinition(NameLoc, Name,
410 NamedTypes[Name], Result)) return true;
412 if (!isa<StructType>(Result)) {
413 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
415 return Error(NameLoc, "non-struct types may not be recursive");
416 Entry.first = Result;
417 Entry.second = SMLoc();
425 /// ::= 'declare' FunctionHeader
426 bool LLParser::ParseDeclare() {
427 assert(Lex.getKind() == lltok::kw_declare);
431 return ParseFunctionHeader(F, false);
435 /// ::= 'define' FunctionHeader '{' ...
436 bool LLParser::ParseDefine() {
437 assert(Lex.getKind() == lltok::kw_define);
441 return ParseFunctionHeader(F, true) ||
442 ParseFunctionBody(*F);
448 bool LLParser::ParseGlobalType(bool &IsConstant) {
449 if (Lex.getKind() == lltok::kw_constant)
451 else if (Lex.getKind() == lltok::kw_global)
455 return TokError("expected 'global' or 'constant'");
461 /// ParseUnnamedGlobal:
462 /// OptionalVisibility ALIAS ...
463 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
464 /// ... -> global variable
465 /// GlobalID '=' OptionalVisibility ALIAS ...
466 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
467 /// ... -> global variable
468 bool LLParser::ParseUnnamedGlobal() {
469 unsigned VarID = NumberedVals.size();
471 LocTy NameLoc = Lex.getLoc();
473 // Handle the GlobalID form.
474 if (Lex.getKind() == lltok::GlobalID) {
475 if (Lex.getUIntVal() != VarID)
476 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
478 Lex.Lex(); // eat GlobalID;
480 if (ParseToken(lltok::equal, "expected '=' after name"))
485 unsigned Linkage, Visibility, DLLStorageClass;
486 GlobalVariable::ThreadLocalMode TLM;
487 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
488 ParseOptionalVisibility(Visibility) ||
489 ParseOptionalDLLStorageClass(DLLStorageClass) ||
490 ParseOptionalThreadLocal(TLM))
493 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
494 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
495 DLLStorageClass, TLM);
496 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM);
499 /// ParseNamedGlobal:
500 /// GlobalVar '=' OptionalVisibility ALIAS ...
501 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
502 /// ... -> global variable
503 bool LLParser::ParseNamedGlobal() {
504 assert(Lex.getKind() == lltok::GlobalVar);
505 LocTy NameLoc = Lex.getLoc();
506 std::string Name = Lex.getStrVal();
510 unsigned Linkage, Visibility, DLLStorageClass;
511 GlobalVariable::ThreadLocalMode TLM;
512 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
513 ParseOptionalLinkage(Linkage, HasLinkage) ||
514 ParseOptionalVisibility(Visibility) ||
515 ParseOptionalDLLStorageClass(DLLStorageClass) ||
516 ParseOptionalThreadLocal(TLM))
519 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
520 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
521 DLLStorageClass, TLM);
522 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM);
526 // ::= '!' STRINGCONSTANT
527 bool LLParser::ParseMDString(MDString *&Result) {
529 if (ParseStringConstant(Str)) return true;
530 Result = MDString::get(Context, Str);
535 // ::= '!' MDNodeNumber
537 /// This version of ParseMDNodeID returns the slot number and null in the case
538 /// of a forward reference.
539 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
540 // !{ ..., !42, ... }
541 if (ParseUInt32(SlotNo)) return true;
543 // Check existing MDNode.
544 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
545 Result = NumberedMetadata[SlotNo];
551 bool LLParser::ParseMDNodeID(MDNode *&Result) {
552 // !{ ..., !42, ... }
554 if (ParseMDNodeID(Result, MID)) return true;
556 // If not a forward reference, just return it now.
557 if (Result) return false;
559 // Otherwise, create MDNode forward reference.
560 MDNode *FwdNode = MDNode::getTemporary(Context, None);
561 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
563 if (NumberedMetadata.size() <= MID)
564 NumberedMetadata.resize(MID+1);
565 NumberedMetadata[MID] = FwdNode;
570 /// ParseNamedMetadata:
571 /// !foo = !{ !1, !2 }
572 bool LLParser::ParseNamedMetadata() {
573 assert(Lex.getKind() == lltok::MetadataVar);
574 std::string Name = Lex.getStrVal();
577 if (ParseToken(lltok::equal, "expected '=' here") ||
578 ParseToken(lltok::exclaim, "Expected '!' here") ||
579 ParseToken(lltok::lbrace, "Expected '{' here"))
582 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
583 if (Lex.getKind() != lltok::rbrace)
585 if (ParseToken(lltok::exclaim, "Expected '!' here"))
589 if (ParseMDNodeID(N)) return true;
591 } while (EatIfPresent(lltok::comma));
593 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
599 /// ParseStandaloneMetadata:
601 bool LLParser::ParseStandaloneMetadata() {
602 assert(Lex.getKind() == lltok::exclaim);
604 unsigned MetadataID = 0;
608 SmallVector<Value *, 16> Elts;
609 if (ParseUInt32(MetadataID) ||
610 ParseToken(lltok::equal, "expected '=' here") ||
611 ParseType(Ty, TyLoc) ||
612 ParseToken(lltok::exclaim, "Expected '!' here") ||
613 ParseToken(lltok::lbrace, "Expected '{' here") ||
614 ParseMDNodeVector(Elts, nullptr) ||
615 ParseToken(lltok::rbrace, "expected end of metadata node"))
618 MDNode *Init = MDNode::get(Context, Elts);
620 // See if this was forward referenced, if so, handle it.
621 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
622 FI = ForwardRefMDNodes.find(MetadataID);
623 if (FI != ForwardRefMDNodes.end()) {
624 MDNode *Temp = FI->second.first;
625 Temp->replaceAllUsesWith(Init);
626 MDNode::deleteTemporary(Temp);
627 ForwardRefMDNodes.erase(FI);
629 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
631 if (MetadataID >= NumberedMetadata.size())
632 NumberedMetadata.resize(MetadataID+1);
634 if (NumberedMetadata[MetadataID] != nullptr)
635 return TokError("Metadata id is already used");
636 NumberedMetadata[MetadataID] = Init;
642 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
643 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
644 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
648 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
649 /// OptionalLinkage Aliasee
654 /// Everything through DLL storage class has already been parsed.
656 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
657 unsigned Visibility, unsigned DLLStorageClass,
658 GlobalVariable::ThreadLocalMode TLM) {
659 assert(Lex.getKind() == lltok::kw_alias);
661 LocTy LinkageLoc = Lex.getLoc();
663 if (ParseOptionalLinkage(L))
666 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
668 if(!GlobalAlias::isValidLinkage(Linkage))
669 return Error(LinkageLoc, "invalid linkage type for alias");
671 if (!isValidVisibilityForLinkage(Visibility, L))
672 return Error(LinkageLoc,
673 "symbol with local linkage must have default visibility");
676 LocTy AliaseeLoc = Lex.getLoc();
677 if (Lex.getKind() != lltok::kw_bitcast &&
678 Lex.getKind() != lltok::kw_getelementptr &&
679 Lex.getKind() != lltok::kw_addrspacecast &&
680 Lex.getKind() != lltok::kw_inttoptr) {
681 if (ParseGlobalTypeAndValue(Aliasee))
684 // The bitcast dest type is not present, it is implied by the dest type.
688 if (ID.Kind != ValID::t_Constant)
689 return Error(AliaseeLoc, "invalid aliasee");
690 Aliasee = ID.ConstantVal;
693 Type *AliaseeType = Aliasee->getType();
694 auto *PTy = dyn_cast<PointerType>(AliaseeType);
696 return Error(AliaseeLoc, "An alias must have pointer type");
697 Type *Ty = PTy->getElementType();
698 unsigned AddrSpace = PTy->getAddressSpace();
700 // Okay, create the alias but do not insert it into the module yet.
701 std::unique_ptr<GlobalAlias> GA(
702 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
703 Name, Aliasee, /*Parent*/ nullptr));
704 GA->setThreadLocalMode(TLM);
705 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
706 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
708 // See if this value already exists in the symbol table. If so, it is either
709 // a redefinition or a definition of a forward reference.
710 if (GlobalValue *Val = M->getNamedValue(Name)) {
711 // See if this was a redefinition. If so, there is no entry in
713 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
714 I = ForwardRefVals.find(Name);
715 if (I == ForwardRefVals.end())
716 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
718 // Otherwise, this was a definition of forward ref. Verify that types
720 if (Val->getType() != GA->getType())
721 return Error(NameLoc,
722 "forward reference and definition of alias have different types");
724 // If they agree, just RAUW the old value with the alias and remove the
726 Val->replaceAllUsesWith(GA.get());
727 Val->eraseFromParent();
728 ForwardRefVals.erase(I);
731 // Insert into the module, we know its name won't collide now.
732 M->getAliasList().push_back(GA.get());
733 assert(GA->getName() == Name && "Should not be a name conflict!");
735 // The module owns this now
742 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
743 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
744 /// OptionalExternallyInitialized GlobalType Type Const
745 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
746 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
747 /// OptionalExternallyInitialized GlobalType Type Const
749 /// Everything up to and including OptionalDLLStorageClass has been parsed
752 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
753 unsigned Linkage, bool HasLinkage,
754 unsigned Visibility, unsigned DLLStorageClass,
755 GlobalVariable::ThreadLocalMode TLM) {
756 if (!isValidVisibilityForLinkage(Visibility, Linkage))
757 return Error(NameLoc,
758 "symbol with local linkage must have default visibility");
761 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
762 LocTy UnnamedAddrLoc;
763 LocTy IsExternallyInitializedLoc;
767 if (ParseOptionalAddrSpace(AddrSpace) ||
768 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
770 ParseOptionalToken(lltok::kw_externally_initialized,
771 IsExternallyInitialized,
772 &IsExternallyInitializedLoc) ||
773 ParseGlobalType(IsConstant) ||
774 ParseType(Ty, TyLoc))
777 // If the linkage is specified and is external, then no initializer is
779 Constant *Init = nullptr;
780 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
781 Linkage != GlobalValue::ExternalLinkage)) {
782 if (ParseGlobalValue(Ty, Init))
786 if (Ty->isFunctionTy() || Ty->isLabelTy())
787 return Error(TyLoc, "invalid type for global variable");
789 GlobalVariable *GV = nullptr;
791 // See if the global was forward referenced, if so, use the global.
793 if (GlobalValue *GVal = M->getNamedValue(Name)) {
794 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
795 return Error(NameLoc, "redefinition of global '@" + Name + "'");
796 GV = cast<GlobalVariable>(GVal);
799 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
800 I = ForwardRefValIDs.find(NumberedVals.size());
801 if (I != ForwardRefValIDs.end()) {
802 GV = cast<GlobalVariable>(I->second.first);
803 ForwardRefValIDs.erase(I);
808 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
809 Name, nullptr, GlobalVariable::NotThreadLocal,
812 if (GV->getType()->getElementType() != Ty)
814 "forward reference and definition of global have different types");
816 // Move the forward-reference to the correct spot in the module.
817 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
821 NumberedVals.push_back(GV);
823 // Set the parsed properties on the global.
825 GV->setInitializer(Init);
826 GV->setConstant(IsConstant);
827 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
828 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
829 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
830 GV->setExternallyInitialized(IsExternallyInitialized);
831 GV->setThreadLocalMode(TLM);
832 GV->setUnnamedAddr(UnnamedAddr);
834 // Parse attributes on the global.
835 while (Lex.getKind() == lltok::comma) {
838 if (Lex.getKind() == lltok::kw_section) {
840 GV->setSection(Lex.getStrVal());
841 if (ParseToken(lltok::StringConstant, "expected global section string"))
843 } else if (Lex.getKind() == lltok::kw_align) {
845 if (ParseOptionalAlignment(Alignment)) return true;
846 GV->setAlignment(Alignment);
848 TokError("unknown global variable property!");
855 /// ParseUnnamedAttrGrp
856 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
857 bool LLParser::ParseUnnamedAttrGrp() {
858 assert(Lex.getKind() == lltok::kw_attributes);
859 LocTy AttrGrpLoc = Lex.getLoc();
862 assert(Lex.getKind() == lltok::AttrGrpID);
863 unsigned VarID = Lex.getUIntVal();
864 std::vector<unsigned> unused;
868 if (ParseToken(lltok::equal, "expected '=' here") ||
869 ParseToken(lltok::lbrace, "expected '{' here") ||
870 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
872 ParseToken(lltok::rbrace, "expected end of attribute group"))
875 if (!NumberedAttrBuilders[VarID].hasAttributes())
876 return Error(AttrGrpLoc, "attribute group has no attributes");
881 /// ParseFnAttributeValuePairs
882 /// ::= <attr> | <attr> '=' <value>
883 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
884 std::vector<unsigned> &FwdRefAttrGrps,
885 bool inAttrGrp, LocTy &BuiltinLoc) {
886 bool HaveError = false;
891 lltok::Kind Token = Lex.getKind();
892 if (Token == lltok::kw_builtin)
893 BuiltinLoc = Lex.getLoc();
896 if (!inAttrGrp) return HaveError;
897 return Error(Lex.getLoc(), "unterminated attribute group");
902 case lltok::AttrGrpID: {
903 // Allow a function to reference an attribute group:
905 // define void @foo() #1 { ... }
909 "cannot have an attribute group reference in an attribute group");
911 unsigned AttrGrpNum = Lex.getUIntVal();
912 if (inAttrGrp) break;
914 // Save the reference to the attribute group. We'll fill it in later.
915 FwdRefAttrGrps.push_back(AttrGrpNum);
918 // Target-dependent attributes:
919 case lltok::StringConstant: {
920 std::string Attr = Lex.getStrVal();
923 if (EatIfPresent(lltok::equal) &&
924 ParseStringConstant(Val))
927 B.addAttribute(Attr, Val);
931 // Target-independent attributes:
932 case lltok::kw_align: {
933 // As a hack, we allow function alignment to be initially parsed as an
934 // attribute on a function declaration/definition or added to an attribute
935 // group and later moved to the alignment field.
939 if (ParseToken(lltok::equal, "expected '=' here") ||
940 ParseUInt32(Alignment))
943 if (ParseOptionalAlignment(Alignment))
946 B.addAlignmentAttr(Alignment);
949 case lltok::kw_alignstack: {
953 if (ParseToken(lltok::equal, "expected '=' here") ||
954 ParseUInt32(Alignment))
957 if (ParseOptionalStackAlignment(Alignment))
960 B.addStackAlignmentAttr(Alignment);
963 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
964 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
965 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
966 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
967 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
968 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
969 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
970 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
971 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
972 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
973 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
974 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
975 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
976 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
977 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
978 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
979 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
980 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
981 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
982 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
983 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
984 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
985 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
986 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
987 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
988 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
991 case lltok::kw_inreg:
992 case lltok::kw_signext:
993 case lltok::kw_zeroext:
996 "invalid use of attribute on a function");
998 case lltok::kw_byval:
999 case lltok::kw_inalloca:
1000 case lltok::kw_nest:
1001 case lltok::kw_noalias:
1002 case lltok::kw_nocapture:
1003 case lltok::kw_nonnull:
1004 case lltok::kw_returned:
1005 case lltok::kw_sret:
1008 "invalid use of parameter-only attribute on a function");
1016 //===----------------------------------------------------------------------===//
1017 // GlobalValue Reference/Resolution Routines.
1018 //===----------------------------------------------------------------------===//
1020 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1021 /// forward reference record if needed. This can return null if the value
1022 /// exists but does not have the right type.
1023 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1025 PointerType *PTy = dyn_cast<PointerType>(Ty);
1027 Error(Loc, "global variable reference must have pointer type");
1031 // Look this name up in the normal function symbol table.
1033 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1035 // If this is a forward reference for the value, see if we already created a
1036 // forward ref record.
1038 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1039 I = ForwardRefVals.find(Name);
1040 if (I != ForwardRefVals.end())
1041 Val = I->second.first;
1044 // If we have the value in the symbol table or fwd-ref table, return it.
1046 if (Val->getType() == Ty) return Val;
1047 Error(Loc, "'@" + Name + "' defined with type '" +
1048 getTypeString(Val->getType()) + "'");
1052 // Otherwise, create a new forward reference for this value and remember it.
1053 GlobalValue *FwdVal;
1054 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1055 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1057 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1058 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1059 nullptr, GlobalVariable::NotThreadLocal,
1060 PTy->getAddressSpace());
1062 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1066 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1067 PointerType *PTy = dyn_cast<PointerType>(Ty);
1069 Error(Loc, "global variable reference must have pointer type");
1073 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1075 // If this is a forward reference for the value, see if we already created a
1076 // forward ref record.
1078 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1079 I = ForwardRefValIDs.find(ID);
1080 if (I != ForwardRefValIDs.end())
1081 Val = I->second.first;
1084 // If we have the value in the symbol table or fwd-ref table, return it.
1086 if (Val->getType() == Ty) return Val;
1087 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1088 getTypeString(Val->getType()) + "'");
1092 // Otherwise, create a new forward reference for this value and remember it.
1093 GlobalValue *FwdVal;
1094 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1095 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1097 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1098 GlobalValue::ExternalWeakLinkage, nullptr, "");
1100 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1105 //===----------------------------------------------------------------------===//
1107 //===----------------------------------------------------------------------===//
1109 /// ParseToken - If the current token has the specified kind, eat it and return
1110 /// success. Otherwise, emit the specified error and return failure.
1111 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1112 if (Lex.getKind() != T)
1113 return TokError(ErrMsg);
1118 /// ParseStringConstant
1119 /// ::= StringConstant
1120 bool LLParser::ParseStringConstant(std::string &Result) {
1121 if (Lex.getKind() != lltok::StringConstant)
1122 return TokError("expected string constant");
1123 Result = Lex.getStrVal();
1130 bool LLParser::ParseUInt32(unsigned &Val) {
1131 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1132 return TokError("expected integer");
1133 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1134 if (Val64 != unsigned(Val64))
1135 return TokError("expected 32-bit integer (too large)");
1142 /// := 'localdynamic'
1143 /// := 'initialexec'
1145 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1146 switch (Lex.getKind()) {
1148 return TokError("expected localdynamic, initialexec or localexec");
1149 case lltok::kw_localdynamic:
1150 TLM = GlobalVariable::LocalDynamicTLSModel;
1152 case lltok::kw_initialexec:
1153 TLM = GlobalVariable::InitialExecTLSModel;
1155 case lltok::kw_localexec:
1156 TLM = GlobalVariable::LocalExecTLSModel;
1164 /// ParseOptionalThreadLocal
1166 /// := 'thread_local'
1167 /// := 'thread_local' '(' tlsmodel ')'
1168 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1169 TLM = GlobalVariable::NotThreadLocal;
1170 if (!EatIfPresent(lltok::kw_thread_local))
1173 TLM = GlobalVariable::GeneralDynamicTLSModel;
1174 if (Lex.getKind() == lltok::lparen) {
1176 return ParseTLSModel(TLM) ||
1177 ParseToken(lltok::rparen, "expected ')' after thread local model");
1182 /// ParseOptionalAddrSpace
1184 /// := 'addrspace' '(' uint32 ')'
1185 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1187 if (!EatIfPresent(lltok::kw_addrspace))
1189 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1190 ParseUInt32(AddrSpace) ||
1191 ParseToken(lltok::rparen, "expected ')' in address space");
1194 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1195 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1196 bool HaveError = false;
1201 lltok::Kind Token = Lex.getKind();
1203 default: // End of attributes.
1205 case lltok::kw_align: {
1207 if (ParseOptionalAlignment(Alignment))
1209 B.addAlignmentAttr(Alignment);
1212 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1213 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1214 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1215 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1216 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1217 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1218 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1219 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1220 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1221 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1222 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1223 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1224 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1226 case lltok::kw_alignstack:
1227 case lltok::kw_alwaysinline:
1228 case lltok::kw_builtin:
1229 case lltok::kw_inlinehint:
1230 case lltok::kw_minsize:
1231 case lltok::kw_naked:
1232 case lltok::kw_nobuiltin:
1233 case lltok::kw_noduplicate:
1234 case lltok::kw_noimplicitfloat:
1235 case lltok::kw_noinline:
1236 case lltok::kw_nonlazybind:
1237 case lltok::kw_noredzone:
1238 case lltok::kw_noreturn:
1239 case lltok::kw_nounwind:
1240 case lltok::kw_optnone:
1241 case lltok::kw_optsize:
1242 case lltok::kw_returns_twice:
1243 case lltok::kw_sanitize_address:
1244 case lltok::kw_sanitize_memory:
1245 case lltok::kw_sanitize_thread:
1247 case lltok::kw_sspreq:
1248 case lltok::kw_sspstrong:
1249 case lltok::kw_uwtable:
1250 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1258 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1259 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1260 bool HaveError = false;
1265 lltok::Kind Token = Lex.getKind();
1267 default: // End of attributes.
1269 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1270 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1271 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1272 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1273 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1276 case lltok::kw_align:
1277 case lltok::kw_byval:
1278 case lltok::kw_inalloca:
1279 case lltok::kw_nest:
1280 case lltok::kw_nocapture:
1281 case lltok::kw_returned:
1282 case lltok::kw_sret:
1283 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1286 case lltok::kw_alignstack:
1287 case lltok::kw_alwaysinline:
1288 case lltok::kw_builtin:
1289 case lltok::kw_cold:
1290 case lltok::kw_inlinehint:
1291 case lltok::kw_minsize:
1292 case lltok::kw_naked:
1293 case lltok::kw_nobuiltin:
1294 case lltok::kw_noduplicate:
1295 case lltok::kw_noimplicitfloat:
1296 case lltok::kw_noinline:
1297 case lltok::kw_nonlazybind:
1298 case lltok::kw_noredzone:
1299 case lltok::kw_noreturn:
1300 case lltok::kw_nounwind:
1301 case lltok::kw_optnone:
1302 case lltok::kw_optsize:
1303 case lltok::kw_returns_twice:
1304 case lltok::kw_sanitize_address:
1305 case lltok::kw_sanitize_memory:
1306 case lltok::kw_sanitize_thread:
1308 case lltok::kw_sspreq:
1309 case lltok::kw_sspstrong:
1310 case lltok::kw_uwtable:
1311 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1314 case lltok::kw_readnone:
1315 case lltok::kw_readonly:
1316 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1323 /// ParseOptionalLinkage
1330 /// ::= 'linkonce_odr'
1331 /// ::= 'available_externally'
1334 /// ::= 'extern_weak'
1337 /// Deprecated Values:
1338 /// ::= 'linker_private'
1339 /// ::= 'linker_private_weak'
1340 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1342 switch (Lex.getKind()) {
1343 default: Res=GlobalValue::ExternalLinkage; return false;
1344 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1345 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1346 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1347 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1348 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1349 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1350 case lltok::kw_available_externally:
1351 Res = GlobalValue::AvailableExternallyLinkage;
1353 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1354 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1355 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1356 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1358 case lltok::kw_linker_private:
1359 case lltok::kw_linker_private_weak:
1360 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1363 // treat linker_private and linker_private_weak as PrivateLinkage
1364 Res = GlobalValue::PrivateLinkage;
1372 /// ParseOptionalVisibility
1378 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1379 switch (Lex.getKind()) {
1380 default: Res = GlobalValue::DefaultVisibility; return false;
1381 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1382 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1383 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1389 /// ParseOptionalDLLStorageClass
1394 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1395 switch (Lex.getKind()) {
1396 default: Res = GlobalValue::DefaultStorageClass; return false;
1397 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1398 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1404 /// ParseOptionalCallingConv
1408 /// ::= 'kw_intel_ocl_bicc'
1410 /// ::= 'x86_stdcallcc'
1411 /// ::= 'x86_fastcallcc'
1412 /// ::= 'x86_thiscallcc'
1413 /// ::= 'arm_apcscc'
1414 /// ::= 'arm_aapcscc'
1415 /// ::= 'arm_aapcs_vfpcc'
1416 /// ::= 'msp430_intrcc'
1417 /// ::= 'ptx_kernel'
1418 /// ::= 'ptx_device'
1420 /// ::= 'spir_kernel'
1421 /// ::= 'x86_64_sysvcc'
1422 /// ::= 'x86_64_win64cc'
1423 /// ::= 'webkit_jscc'
1425 /// ::= 'preserve_mostcc'
1426 /// ::= 'preserve_allcc'
1429 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1430 switch (Lex.getKind()) {
1431 default: CC = CallingConv::C; return false;
1432 case lltok::kw_ccc: CC = CallingConv::C; break;
1433 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1434 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1435 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1436 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1437 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1438 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1439 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1440 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1441 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1442 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1443 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1444 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1445 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1446 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1447 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1448 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1449 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1450 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1451 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1452 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1453 case lltok::kw_cc: {
1454 unsigned ArbitraryCC;
1456 if (ParseUInt32(ArbitraryCC))
1458 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1467 /// ParseInstructionMetadata
1468 /// ::= !dbg !42 (',' !dbg !57)*
1469 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1470 PerFunctionState *PFS) {
1472 if (Lex.getKind() != lltok::MetadataVar)
1473 return TokError("expected metadata after comma");
1475 std::string Name = Lex.getStrVal();
1476 unsigned MDK = M->getMDKindID(Name);
1480 SMLoc Loc = Lex.getLoc();
1482 if (ParseToken(lltok::exclaim, "expected '!' here"))
1485 // This code is similar to that of ParseMetadataValue, however it needs to
1486 // have special-case code for a forward reference; see the comments on
1487 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1488 // at the top level here.
1489 if (Lex.getKind() == lltok::lbrace) {
1491 if (ParseMetadataListValue(ID, PFS))
1493 assert(ID.Kind == ValID::t_MDNode);
1494 Inst->setMetadata(MDK, ID.MDNodeVal);
1496 unsigned NodeID = 0;
1497 if (ParseMDNodeID(Node, NodeID))
1500 // If we got the node, add it to the instruction.
1501 Inst->setMetadata(MDK, Node);
1503 MDRef R = { Loc, MDK, NodeID };
1504 // Otherwise, remember that this should be resolved later.
1505 ForwardRefInstMetadata[Inst].push_back(R);
1509 if (MDK == LLVMContext::MD_tbaa)
1510 InstsWithTBAATag.push_back(Inst);
1512 // If this is the end of the list, we're done.
1513 } while (EatIfPresent(lltok::comma));
1517 /// ParseOptionalAlignment
1520 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1522 if (!EatIfPresent(lltok::kw_align))
1524 LocTy AlignLoc = Lex.getLoc();
1525 if (ParseUInt32(Alignment)) return true;
1526 if (!isPowerOf2_32(Alignment))
1527 return Error(AlignLoc, "alignment is not a power of two");
1528 if (Alignment > Value::MaximumAlignment)
1529 return Error(AlignLoc, "huge alignments are not supported yet");
1533 /// ParseOptionalCommaAlign
1537 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1539 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1540 bool &AteExtraComma) {
1541 AteExtraComma = false;
1542 while (EatIfPresent(lltok::comma)) {
1543 // Metadata at the end is an early exit.
1544 if (Lex.getKind() == lltok::MetadataVar) {
1545 AteExtraComma = true;
1549 if (Lex.getKind() != lltok::kw_align)
1550 return Error(Lex.getLoc(), "expected metadata or 'align'");
1552 if (ParseOptionalAlignment(Alignment)) return true;
1558 /// ParseScopeAndOrdering
1559 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1562 /// This sets Scope and Ordering to the parsed values.
1563 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1564 AtomicOrdering &Ordering) {
1568 Scope = CrossThread;
1569 if (EatIfPresent(lltok::kw_singlethread))
1570 Scope = SingleThread;
1572 return ParseOrdering(Ordering);
1576 /// ::= AtomicOrdering
1578 /// This sets Ordering to the parsed value.
1579 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1580 switch (Lex.getKind()) {
1581 default: return TokError("Expected ordering on atomic instruction");
1582 case lltok::kw_unordered: Ordering = Unordered; break;
1583 case lltok::kw_monotonic: Ordering = Monotonic; break;
1584 case lltok::kw_acquire: Ordering = Acquire; break;
1585 case lltok::kw_release: Ordering = Release; break;
1586 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1587 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1593 /// ParseOptionalStackAlignment
1595 /// ::= 'alignstack' '(' 4 ')'
1596 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1598 if (!EatIfPresent(lltok::kw_alignstack))
1600 LocTy ParenLoc = Lex.getLoc();
1601 if (!EatIfPresent(lltok::lparen))
1602 return Error(ParenLoc, "expected '('");
1603 LocTy AlignLoc = Lex.getLoc();
1604 if (ParseUInt32(Alignment)) return true;
1605 ParenLoc = Lex.getLoc();
1606 if (!EatIfPresent(lltok::rparen))
1607 return Error(ParenLoc, "expected ')'");
1608 if (!isPowerOf2_32(Alignment))
1609 return Error(AlignLoc, "stack alignment is not a power of two");
1613 /// ParseIndexList - This parses the index list for an insert/extractvalue
1614 /// instruction. This sets AteExtraComma in the case where we eat an extra
1615 /// comma at the end of the line and find that it is followed by metadata.
1616 /// Clients that don't allow metadata can call the version of this function that
1617 /// only takes one argument.
1620 /// ::= (',' uint32)+
1622 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1623 bool &AteExtraComma) {
1624 AteExtraComma = false;
1626 if (Lex.getKind() != lltok::comma)
1627 return TokError("expected ',' as start of index list");
1629 while (EatIfPresent(lltok::comma)) {
1630 if (Lex.getKind() == lltok::MetadataVar) {
1631 AteExtraComma = true;
1635 if (ParseUInt32(Idx)) return true;
1636 Indices.push_back(Idx);
1642 //===----------------------------------------------------------------------===//
1644 //===----------------------------------------------------------------------===//
1646 /// ParseType - Parse a type.
1647 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1648 SMLoc TypeLoc = Lex.getLoc();
1649 switch (Lex.getKind()) {
1651 return TokError("expected type");
1653 // Type ::= 'float' | 'void' (etc)
1654 Result = Lex.getTyVal();
1658 // Type ::= StructType
1659 if (ParseAnonStructType(Result, false))
1662 case lltok::lsquare:
1663 // Type ::= '[' ... ']'
1664 Lex.Lex(); // eat the lsquare.
1665 if (ParseArrayVectorType(Result, false))
1668 case lltok::less: // Either vector or packed struct.
1669 // Type ::= '<' ... '>'
1671 if (Lex.getKind() == lltok::lbrace) {
1672 if (ParseAnonStructType(Result, true) ||
1673 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1675 } else if (ParseArrayVectorType(Result, true))
1678 case lltok::LocalVar: {
1680 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1682 // If the type hasn't been defined yet, create a forward definition and
1683 // remember where that forward def'n was seen (in case it never is defined).
1685 Entry.first = StructType::create(Context, Lex.getStrVal());
1686 Entry.second = Lex.getLoc();
1688 Result = Entry.first;
1693 case lltok::LocalVarID: {
1695 if (Lex.getUIntVal() >= NumberedTypes.size())
1696 NumberedTypes.resize(Lex.getUIntVal()+1);
1697 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1699 // If the type hasn't been defined yet, create a forward definition and
1700 // remember where that forward def'n was seen (in case it never is defined).
1702 Entry.first = StructType::create(Context);
1703 Entry.second = Lex.getLoc();
1705 Result = Entry.first;
1711 // Parse the type suffixes.
1713 switch (Lex.getKind()) {
1716 if (!AllowVoid && Result->isVoidTy())
1717 return Error(TypeLoc, "void type only allowed for function results");
1720 // Type ::= Type '*'
1722 if (Result->isLabelTy())
1723 return TokError("basic block pointers are invalid");
1724 if (Result->isVoidTy())
1725 return TokError("pointers to void are invalid - use i8* instead");
1726 if (!PointerType::isValidElementType(Result))
1727 return TokError("pointer to this type is invalid");
1728 Result = PointerType::getUnqual(Result);
1732 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1733 case lltok::kw_addrspace: {
1734 if (Result->isLabelTy())
1735 return TokError("basic block pointers are invalid");
1736 if (Result->isVoidTy())
1737 return TokError("pointers to void are invalid; use i8* instead");
1738 if (!PointerType::isValidElementType(Result))
1739 return TokError("pointer to this type is invalid");
1741 if (ParseOptionalAddrSpace(AddrSpace) ||
1742 ParseToken(lltok::star, "expected '*' in address space"))
1745 Result = PointerType::get(Result, AddrSpace);
1749 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1751 if (ParseFunctionType(Result))
1758 /// ParseParameterList
1760 /// ::= '(' Arg (',' Arg)* ')'
1762 /// ::= Type OptionalAttributes Value OptionalAttributes
1763 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1764 PerFunctionState &PFS) {
1765 if (ParseToken(lltok::lparen, "expected '(' in call"))
1768 unsigned AttrIndex = 1;
1769 while (Lex.getKind() != lltok::rparen) {
1770 // If this isn't the first argument, we need a comma.
1771 if (!ArgList.empty() &&
1772 ParseToken(lltok::comma, "expected ',' in argument list"))
1775 // Parse the argument.
1777 Type *ArgTy = nullptr;
1778 AttrBuilder ArgAttrs;
1780 if (ParseType(ArgTy, ArgLoc))
1783 // Otherwise, handle normal operands.
1784 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1786 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1791 Lex.Lex(); // Lex the ')'.
1797 /// ParseArgumentList - Parse the argument list for a function type or function
1799 /// ::= '(' ArgTypeListI ')'
1803 /// ::= ArgTypeList ',' '...'
1804 /// ::= ArgType (',' ArgType)*
1806 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1809 assert(Lex.getKind() == lltok::lparen);
1810 Lex.Lex(); // eat the (.
1812 if (Lex.getKind() == lltok::rparen) {
1814 } else if (Lex.getKind() == lltok::dotdotdot) {
1818 LocTy TypeLoc = Lex.getLoc();
1819 Type *ArgTy = nullptr;
1823 if (ParseType(ArgTy) ||
1824 ParseOptionalParamAttrs(Attrs)) return true;
1826 if (ArgTy->isVoidTy())
1827 return Error(TypeLoc, "argument can not have void type");
1829 if (Lex.getKind() == lltok::LocalVar) {
1830 Name = Lex.getStrVal();
1834 if (!FunctionType::isValidArgumentType(ArgTy))
1835 return Error(TypeLoc, "invalid type for function argument");
1837 unsigned AttrIndex = 1;
1838 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1839 AttributeSet::get(ArgTy->getContext(),
1840 AttrIndex++, Attrs), Name));
1842 while (EatIfPresent(lltok::comma)) {
1843 // Handle ... at end of arg list.
1844 if (EatIfPresent(lltok::dotdotdot)) {
1849 // Otherwise must be an argument type.
1850 TypeLoc = Lex.getLoc();
1851 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1853 if (ArgTy->isVoidTy())
1854 return Error(TypeLoc, "argument can not have void type");
1856 if (Lex.getKind() == lltok::LocalVar) {
1857 Name = Lex.getStrVal();
1863 if (!ArgTy->isFirstClassType())
1864 return Error(TypeLoc, "invalid type for function argument");
1866 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1867 AttributeSet::get(ArgTy->getContext(),
1868 AttrIndex++, Attrs),
1873 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1876 /// ParseFunctionType
1877 /// ::= Type ArgumentList OptionalAttrs
1878 bool LLParser::ParseFunctionType(Type *&Result) {
1879 assert(Lex.getKind() == lltok::lparen);
1881 if (!FunctionType::isValidReturnType(Result))
1882 return TokError("invalid function return type");
1884 SmallVector<ArgInfo, 8> ArgList;
1886 if (ParseArgumentList(ArgList, isVarArg))
1889 // Reject names on the arguments lists.
1890 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1891 if (!ArgList[i].Name.empty())
1892 return Error(ArgList[i].Loc, "argument name invalid in function type");
1893 if (ArgList[i].Attrs.hasAttributes(i + 1))
1894 return Error(ArgList[i].Loc,
1895 "argument attributes invalid in function type");
1898 SmallVector<Type*, 16> ArgListTy;
1899 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1900 ArgListTy.push_back(ArgList[i].Ty);
1902 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1906 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1908 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1909 SmallVector<Type*, 8> Elts;
1910 if (ParseStructBody(Elts)) return true;
1912 Result = StructType::get(Context, Elts, Packed);
1916 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1917 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1918 std::pair<Type*, LocTy> &Entry,
1920 // If the type was already defined, diagnose the redefinition.
1921 if (Entry.first && !Entry.second.isValid())
1922 return Error(TypeLoc, "redefinition of type");
1924 // If we have opaque, just return without filling in the definition for the
1925 // struct. This counts as a definition as far as the .ll file goes.
1926 if (EatIfPresent(lltok::kw_opaque)) {
1927 // This type is being defined, so clear the location to indicate this.
1928 Entry.second = SMLoc();
1930 // If this type number has never been uttered, create it.
1932 Entry.first = StructType::create(Context, Name);
1933 ResultTy = Entry.first;
1937 // If the type starts with '<', then it is either a packed struct or a vector.
1938 bool isPacked = EatIfPresent(lltok::less);
1940 // If we don't have a struct, then we have a random type alias, which we
1941 // accept for compatibility with old files. These types are not allowed to be
1942 // forward referenced and not allowed to be recursive.
1943 if (Lex.getKind() != lltok::lbrace) {
1945 return Error(TypeLoc, "forward references to non-struct type");
1949 return ParseArrayVectorType(ResultTy, true);
1950 return ParseType(ResultTy);
1953 // This type is being defined, so clear the location to indicate this.
1954 Entry.second = SMLoc();
1956 // If this type number has never been uttered, create it.
1958 Entry.first = StructType::create(Context, Name);
1960 StructType *STy = cast<StructType>(Entry.first);
1962 SmallVector<Type*, 8> Body;
1963 if (ParseStructBody(Body) ||
1964 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1967 STy->setBody(Body, isPacked);
1973 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1976 /// ::= '{' Type (',' Type)* '}'
1977 /// ::= '<' '{' '}' '>'
1978 /// ::= '<' '{' Type (',' Type)* '}' '>'
1979 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1980 assert(Lex.getKind() == lltok::lbrace);
1981 Lex.Lex(); // Consume the '{'
1983 // Handle the empty struct.
1984 if (EatIfPresent(lltok::rbrace))
1987 LocTy EltTyLoc = Lex.getLoc();
1989 if (ParseType(Ty)) return true;
1992 if (!StructType::isValidElementType(Ty))
1993 return Error(EltTyLoc, "invalid element type for struct");
1995 while (EatIfPresent(lltok::comma)) {
1996 EltTyLoc = Lex.getLoc();
1997 if (ParseType(Ty)) return true;
1999 if (!StructType::isValidElementType(Ty))
2000 return Error(EltTyLoc, "invalid element type for struct");
2005 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
2008 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
2009 /// token has already been consumed.
2011 /// ::= '[' APSINTVAL 'x' Types ']'
2012 /// ::= '<' APSINTVAL 'x' Types '>'
2013 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
2014 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
2015 Lex.getAPSIntVal().getBitWidth() > 64)
2016 return TokError("expected number in address space");
2018 LocTy SizeLoc = Lex.getLoc();
2019 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2022 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2025 LocTy TypeLoc = Lex.getLoc();
2026 Type *EltTy = nullptr;
2027 if (ParseType(EltTy)) return true;
2029 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2030 "expected end of sequential type"))
2035 return Error(SizeLoc, "zero element vector is illegal");
2036 if ((unsigned)Size != Size)
2037 return Error(SizeLoc, "size too large for vector");
2038 if (!VectorType::isValidElementType(EltTy))
2039 return Error(TypeLoc, "invalid vector element type");
2040 Result = VectorType::get(EltTy, unsigned(Size));
2042 if (!ArrayType::isValidElementType(EltTy))
2043 return Error(TypeLoc, "invalid array element type");
2044 Result = ArrayType::get(EltTy, Size);
2049 //===----------------------------------------------------------------------===//
2050 // Function Semantic Analysis.
2051 //===----------------------------------------------------------------------===//
2053 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2055 : P(p), F(f), FunctionNumber(functionNumber) {
2057 // Insert unnamed arguments into the NumberedVals list.
2058 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2061 NumberedVals.push_back(AI);
2064 LLParser::PerFunctionState::~PerFunctionState() {
2065 // If there were any forward referenced non-basicblock values, delete them.
2066 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2067 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2068 if (!isa<BasicBlock>(I->second.first)) {
2069 I->second.first->replaceAllUsesWith(
2070 UndefValue::get(I->second.first->getType()));
2071 delete I->second.first;
2072 I->second.first = nullptr;
2075 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2076 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2077 if (!isa<BasicBlock>(I->second.first)) {
2078 I->second.first->replaceAllUsesWith(
2079 UndefValue::get(I->second.first->getType()));
2080 delete I->second.first;
2081 I->second.first = nullptr;
2085 bool LLParser::PerFunctionState::FinishFunction() {
2086 // Check to see if someone took the address of labels in this block.
2087 if (!P.ForwardRefBlockAddresses.empty()) {
2089 if (!F.getName().empty()) {
2090 FunctionID.Kind = ValID::t_GlobalName;
2091 FunctionID.StrVal = F.getName();
2093 FunctionID.Kind = ValID::t_GlobalID;
2094 FunctionID.UIntVal = FunctionNumber;
2097 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2098 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2099 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2100 // Resolve all these references.
2101 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2104 P.ForwardRefBlockAddresses.erase(FRBAI);
2108 if (!ForwardRefVals.empty())
2109 return P.Error(ForwardRefVals.begin()->second.second,
2110 "use of undefined value '%" + ForwardRefVals.begin()->first +
2112 if (!ForwardRefValIDs.empty())
2113 return P.Error(ForwardRefValIDs.begin()->second.second,
2114 "use of undefined value '%" +
2115 Twine(ForwardRefValIDs.begin()->first) + "'");
2120 /// GetVal - Get a value with the specified name or ID, creating a
2121 /// forward reference record if needed. This can return null if the value
2122 /// exists but does not have the right type.
2123 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2124 Type *Ty, LocTy Loc) {
2125 // Look this name up in the normal function symbol table.
2126 Value *Val = F.getValueSymbolTable().lookup(Name);
2128 // If this is a forward reference for the value, see if we already created a
2129 // forward ref record.
2131 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2132 I = ForwardRefVals.find(Name);
2133 if (I != ForwardRefVals.end())
2134 Val = I->second.first;
2137 // If we have the value in the symbol table or fwd-ref table, return it.
2139 if (Val->getType() == Ty) return Val;
2140 if (Ty->isLabelTy())
2141 P.Error(Loc, "'%" + Name + "' is not a basic block");
2143 P.Error(Loc, "'%" + Name + "' defined with type '" +
2144 getTypeString(Val->getType()) + "'");
2148 // Don't make placeholders with invalid type.
2149 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2150 P.Error(Loc, "invalid use of a non-first-class type");
2154 // Otherwise, create a new forward reference for this value and remember it.
2156 if (Ty->isLabelTy())
2157 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2159 FwdVal = new Argument(Ty, Name);
2161 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2165 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2167 // Look this name up in the normal function symbol table.
2168 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2170 // If this is a forward reference for the value, see if we already created a
2171 // forward ref record.
2173 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2174 I = ForwardRefValIDs.find(ID);
2175 if (I != ForwardRefValIDs.end())
2176 Val = I->second.first;
2179 // If we have the value in the symbol table or fwd-ref table, return it.
2181 if (Val->getType() == Ty) return Val;
2182 if (Ty->isLabelTy())
2183 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2185 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2186 getTypeString(Val->getType()) + "'");
2190 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2191 P.Error(Loc, "invalid use of a non-first-class type");
2195 // Otherwise, create a new forward reference for this value and remember it.
2197 if (Ty->isLabelTy())
2198 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2200 FwdVal = new Argument(Ty);
2202 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2206 /// SetInstName - After an instruction is parsed and inserted into its
2207 /// basic block, this installs its name.
2208 bool LLParser::PerFunctionState::SetInstName(int NameID,
2209 const std::string &NameStr,
2210 LocTy NameLoc, Instruction *Inst) {
2211 // If this instruction has void type, it cannot have a name or ID specified.
2212 if (Inst->getType()->isVoidTy()) {
2213 if (NameID != -1 || !NameStr.empty())
2214 return P.Error(NameLoc, "instructions returning void cannot have a name");
2218 // If this was a numbered instruction, verify that the instruction is the
2219 // expected value and resolve any forward references.
2220 if (NameStr.empty()) {
2221 // If neither a name nor an ID was specified, just use the next ID.
2223 NameID = NumberedVals.size();
2225 if (unsigned(NameID) != NumberedVals.size())
2226 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2227 Twine(NumberedVals.size()) + "'");
2229 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2230 ForwardRefValIDs.find(NameID);
2231 if (FI != ForwardRefValIDs.end()) {
2232 if (FI->second.first->getType() != Inst->getType())
2233 return P.Error(NameLoc, "instruction forward referenced with type '" +
2234 getTypeString(FI->second.first->getType()) + "'");
2235 FI->second.first->replaceAllUsesWith(Inst);
2236 delete FI->second.first;
2237 ForwardRefValIDs.erase(FI);
2240 NumberedVals.push_back(Inst);
2244 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2245 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2246 FI = ForwardRefVals.find(NameStr);
2247 if (FI != ForwardRefVals.end()) {
2248 if (FI->second.first->getType() != Inst->getType())
2249 return P.Error(NameLoc, "instruction forward referenced with type '" +
2250 getTypeString(FI->second.first->getType()) + "'");
2251 FI->second.first->replaceAllUsesWith(Inst);
2252 delete FI->second.first;
2253 ForwardRefVals.erase(FI);
2256 // Set the name on the instruction.
2257 Inst->setName(NameStr);
2259 if (Inst->getName() != NameStr)
2260 return P.Error(NameLoc, "multiple definition of local value named '" +
2265 /// GetBB - Get a basic block with the specified name or ID, creating a
2266 /// forward reference record if needed.
2267 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2269 return cast_or_null<BasicBlock>(GetVal(Name,
2270 Type::getLabelTy(F.getContext()), Loc));
2273 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2274 return cast_or_null<BasicBlock>(GetVal(ID,
2275 Type::getLabelTy(F.getContext()), Loc));
2278 /// DefineBB - Define the specified basic block, which is either named or
2279 /// unnamed. If there is an error, this returns null otherwise it returns
2280 /// the block being defined.
2281 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2285 BB = GetBB(NumberedVals.size(), Loc);
2287 BB = GetBB(Name, Loc);
2288 if (!BB) return nullptr; // Already diagnosed error.
2290 // Move the block to the end of the function. Forward ref'd blocks are
2291 // inserted wherever they happen to be referenced.
2292 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2294 // Remove the block from forward ref sets.
2296 ForwardRefValIDs.erase(NumberedVals.size());
2297 NumberedVals.push_back(BB);
2299 // BB forward references are already in the function symbol table.
2300 ForwardRefVals.erase(Name);
2306 //===----------------------------------------------------------------------===//
2308 //===----------------------------------------------------------------------===//
2310 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2311 /// type implied. For example, if we parse "4" we don't know what integer type
2312 /// it has. The value will later be combined with its type and checked for
2313 /// sanity. PFS is used to convert function-local operands of metadata (since
2314 /// metadata operands are not just parsed here but also converted to values).
2315 /// PFS can be null when we are not parsing metadata values inside a function.
2316 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2317 ID.Loc = Lex.getLoc();
2318 switch (Lex.getKind()) {
2319 default: return TokError("expected value token");
2320 case lltok::GlobalID: // @42
2321 ID.UIntVal = Lex.getUIntVal();
2322 ID.Kind = ValID::t_GlobalID;
2324 case lltok::GlobalVar: // @foo
2325 ID.StrVal = Lex.getStrVal();
2326 ID.Kind = ValID::t_GlobalName;
2328 case lltok::LocalVarID: // %42
2329 ID.UIntVal = Lex.getUIntVal();
2330 ID.Kind = ValID::t_LocalID;
2332 case lltok::LocalVar: // %foo
2333 ID.StrVal = Lex.getStrVal();
2334 ID.Kind = ValID::t_LocalName;
2336 case lltok::exclaim: // !42, !{...}, or !"foo"
2337 return ParseMetadataValue(ID, PFS);
2339 ID.APSIntVal = Lex.getAPSIntVal();
2340 ID.Kind = ValID::t_APSInt;
2342 case lltok::APFloat:
2343 ID.APFloatVal = Lex.getAPFloatVal();
2344 ID.Kind = ValID::t_APFloat;
2346 case lltok::kw_true:
2347 ID.ConstantVal = ConstantInt::getTrue(Context);
2348 ID.Kind = ValID::t_Constant;
2350 case lltok::kw_false:
2351 ID.ConstantVal = ConstantInt::getFalse(Context);
2352 ID.Kind = ValID::t_Constant;
2354 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2355 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2356 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2358 case lltok::lbrace: {
2359 // ValID ::= '{' ConstVector '}'
2361 SmallVector<Constant*, 16> Elts;
2362 if (ParseGlobalValueVector(Elts) ||
2363 ParseToken(lltok::rbrace, "expected end of struct constant"))
2366 ID.ConstantStructElts = new Constant*[Elts.size()];
2367 ID.UIntVal = Elts.size();
2368 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2369 ID.Kind = ValID::t_ConstantStruct;
2373 // ValID ::= '<' ConstVector '>' --> Vector.
2374 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2376 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2378 SmallVector<Constant*, 16> Elts;
2379 LocTy FirstEltLoc = Lex.getLoc();
2380 if (ParseGlobalValueVector(Elts) ||
2382 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2383 ParseToken(lltok::greater, "expected end of constant"))
2386 if (isPackedStruct) {
2387 ID.ConstantStructElts = new Constant*[Elts.size()];
2388 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2389 ID.UIntVal = Elts.size();
2390 ID.Kind = ValID::t_PackedConstantStruct;
2395 return Error(ID.Loc, "constant vector must not be empty");
2397 if (!Elts[0]->getType()->isIntegerTy() &&
2398 !Elts[0]->getType()->isFloatingPointTy() &&
2399 !Elts[0]->getType()->isPointerTy())
2400 return Error(FirstEltLoc,
2401 "vector elements must have integer, pointer or floating point type");
2403 // Verify that all the vector elements have the same type.
2404 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2405 if (Elts[i]->getType() != Elts[0]->getType())
2406 return Error(FirstEltLoc,
2407 "vector element #" + Twine(i) +
2408 " is not of type '" + getTypeString(Elts[0]->getType()));
2410 ID.ConstantVal = ConstantVector::get(Elts);
2411 ID.Kind = ValID::t_Constant;
2414 case lltok::lsquare: { // Array Constant
2416 SmallVector<Constant*, 16> Elts;
2417 LocTy FirstEltLoc = Lex.getLoc();
2418 if (ParseGlobalValueVector(Elts) ||
2419 ParseToken(lltok::rsquare, "expected end of array constant"))
2422 // Handle empty element.
2424 // Use undef instead of an array because it's inconvenient to determine
2425 // the element type at this point, there being no elements to examine.
2426 ID.Kind = ValID::t_EmptyArray;
2430 if (!Elts[0]->getType()->isFirstClassType())
2431 return Error(FirstEltLoc, "invalid array element type: " +
2432 getTypeString(Elts[0]->getType()));
2434 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2436 // Verify all elements are correct type!
2437 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2438 if (Elts[i]->getType() != Elts[0]->getType())
2439 return Error(FirstEltLoc,
2440 "array element #" + Twine(i) +
2441 " is not of type '" + getTypeString(Elts[0]->getType()));
2444 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2445 ID.Kind = ValID::t_Constant;
2448 case lltok::kw_c: // c "foo"
2450 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2452 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2453 ID.Kind = ValID::t_Constant;
2456 case lltok::kw_asm: {
2457 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2459 bool HasSideEffect, AlignStack, AsmDialect;
2461 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2462 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2463 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2464 ParseStringConstant(ID.StrVal) ||
2465 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2466 ParseToken(lltok::StringConstant, "expected constraint string"))
2468 ID.StrVal2 = Lex.getStrVal();
2469 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2470 (unsigned(AsmDialect)<<2);
2471 ID.Kind = ValID::t_InlineAsm;
2475 case lltok::kw_blockaddress: {
2476 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2481 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2483 ParseToken(lltok::comma, "expected comma in block address expression")||
2484 ParseValID(Label) ||
2485 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2488 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2489 return Error(Fn.Loc, "expected function name in blockaddress");
2490 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2491 return Error(Label.Loc, "expected basic block name in blockaddress");
2493 // Make a global variable as a placeholder for this reference.
2494 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2495 false, GlobalValue::InternalLinkage,
2497 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2498 ID.ConstantVal = FwdRef;
2499 ID.Kind = ValID::t_Constant;
2503 case lltok::kw_trunc:
2504 case lltok::kw_zext:
2505 case lltok::kw_sext:
2506 case lltok::kw_fptrunc:
2507 case lltok::kw_fpext:
2508 case lltok::kw_bitcast:
2509 case lltok::kw_addrspacecast:
2510 case lltok::kw_uitofp:
2511 case lltok::kw_sitofp:
2512 case lltok::kw_fptoui:
2513 case lltok::kw_fptosi:
2514 case lltok::kw_inttoptr:
2515 case lltok::kw_ptrtoint: {
2516 unsigned Opc = Lex.getUIntVal();
2517 Type *DestTy = nullptr;
2520 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2521 ParseGlobalTypeAndValue(SrcVal) ||
2522 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2523 ParseType(DestTy) ||
2524 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2526 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2527 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2528 getTypeString(SrcVal->getType()) + "' to '" +
2529 getTypeString(DestTy) + "'");
2530 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2532 ID.Kind = ValID::t_Constant;
2535 case lltok::kw_extractvalue: {
2538 SmallVector<unsigned, 4> Indices;
2539 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2540 ParseGlobalTypeAndValue(Val) ||
2541 ParseIndexList(Indices) ||
2542 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2545 if (!Val->getType()->isAggregateType())
2546 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2547 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2548 return Error(ID.Loc, "invalid indices for extractvalue");
2549 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2550 ID.Kind = ValID::t_Constant;
2553 case lltok::kw_insertvalue: {
2555 Constant *Val0, *Val1;
2556 SmallVector<unsigned, 4> Indices;
2557 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2558 ParseGlobalTypeAndValue(Val0) ||
2559 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2560 ParseGlobalTypeAndValue(Val1) ||
2561 ParseIndexList(Indices) ||
2562 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2564 if (!Val0->getType()->isAggregateType())
2565 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2566 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2567 return Error(ID.Loc, "invalid indices for insertvalue");
2568 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2569 ID.Kind = ValID::t_Constant;
2572 case lltok::kw_icmp:
2573 case lltok::kw_fcmp: {
2574 unsigned PredVal, Opc = Lex.getUIntVal();
2575 Constant *Val0, *Val1;
2577 if (ParseCmpPredicate(PredVal, Opc) ||
2578 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2579 ParseGlobalTypeAndValue(Val0) ||
2580 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2581 ParseGlobalTypeAndValue(Val1) ||
2582 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2585 if (Val0->getType() != Val1->getType())
2586 return Error(ID.Loc, "compare operands must have the same type");
2588 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2590 if (Opc == Instruction::FCmp) {
2591 if (!Val0->getType()->isFPOrFPVectorTy())
2592 return Error(ID.Loc, "fcmp requires floating point operands");
2593 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2595 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2596 if (!Val0->getType()->isIntOrIntVectorTy() &&
2597 !Val0->getType()->getScalarType()->isPointerTy())
2598 return Error(ID.Loc, "icmp requires pointer or integer operands");
2599 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2601 ID.Kind = ValID::t_Constant;
2605 // Binary Operators.
2607 case lltok::kw_fadd:
2609 case lltok::kw_fsub:
2611 case lltok::kw_fmul:
2612 case lltok::kw_udiv:
2613 case lltok::kw_sdiv:
2614 case lltok::kw_fdiv:
2615 case lltok::kw_urem:
2616 case lltok::kw_srem:
2617 case lltok::kw_frem:
2619 case lltok::kw_lshr:
2620 case lltok::kw_ashr: {
2624 unsigned Opc = Lex.getUIntVal();
2625 Constant *Val0, *Val1;
2627 LocTy ModifierLoc = Lex.getLoc();
2628 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2629 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2630 if (EatIfPresent(lltok::kw_nuw))
2632 if (EatIfPresent(lltok::kw_nsw)) {
2634 if (EatIfPresent(lltok::kw_nuw))
2637 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2638 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2639 if (EatIfPresent(lltok::kw_exact))
2642 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2643 ParseGlobalTypeAndValue(Val0) ||
2644 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2645 ParseGlobalTypeAndValue(Val1) ||
2646 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2648 if (Val0->getType() != Val1->getType())
2649 return Error(ID.Loc, "operands of constexpr must have same type");
2650 if (!Val0->getType()->isIntOrIntVectorTy()) {
2652 return Error(ModifierLoc, "nuw only applies to integer operations");
2654 return Error(ModifierLoc, "nsw only applies to integer operations");
2656 // Check that the type is valid for the operator.
2658 case Instruction::Add:
2659 case Instruction::Sub:
2660 case Instruction::Mul:
2661 case Instruction::UDiv:
2662 case Instruction::SDiv:
2663 case Instruction::URem:
2664 case Instruction::SRem:
2665 case Instruction::Shl:
2666 case Instruction::AShr:
2667 case Instruction::LShr:
2668 if (!Val0->getType()->isIntOrIntVectorTy())
2669 return Error(ID.Loc, "constexpr requires integer operands");
2671 case Instruction::FAdd:
2672 case Instruction::FSub:
2673 case Instruction::FMul:
2674 case Instruction::FDiv:
2675 case Instruction::FRem:
2676 if (!Val0->getType()->isFPOrFPVectorTy())
2677 return Error(ID.Loc, "constexpr requires fp operands");
2679 default: llvm_unreachable("Unknown binary operator!");
2682 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2683 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2684 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2685 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2687 ID.Kind = ValID::t_Constant;
2691 // Logical Operations
2694 case lltok::kw_xor: {
2695 unsigned Opc = Lex.getUIntVal();
2696 Constant *Val0, *Val1;
2698 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2699 ParseGlobalTypeAndValue(Val0) ||
2700 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2701 ParseGlobalTypeAndValue(Val1) ||
2702 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2704 if (Val0->getType() != Val1->getType())
2705 return Error(ID.Loc, "operands of constexpr must have same type");
2706 if (!Val0->getType()->isIntOrIntVectorTy())
2707 return Error(ID.Loc,
2708 "constexpr requires integer or integer vector operands");
2709 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2710 ID.Kind = ValID::t_Constant;
2714 case lltok::kw_getelementptr:
2715 case lltok::kw_shufflevector:
2716 case lltok::kw_insertelement:
2717 case lltok::kw_extractelement:
2718 case lltok::kw_select: {
2719 unsigned Opc = Lex.getUIntVal();
2720 SmallVector<Constant*, 16> Elts;
2721 bool InBounds = false;
2723 if (Opc == Instruction::GetElementPtr)
2724 InBounds = EatIfPresent(lltok::kw_inbounds);
2725 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2726 ParseGlobalValueVector(Elts) ||
2727 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2730 if (Opc == Instruction::GetElementPtr) {
2731 if (Elts.size() == 0 ||
2732 !Elts[0]->getType()->getScalarType()->isPointerTy())
2733 return Error(ID.Loc, "getelementptr requires pointer operand");
2735 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2736 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2737 return Error(ID.Loc, "invalid indices for getelementptr");
2738 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2740 } else if (Opc == Instruction::Select) {
2741 if (Elts.size() != 3)
2742 return Error(ID.Loc, "expected three operands to select");
2743 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2745 return Error(ID.Loc, Reason);
2746 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2747 } else if (Opc == Instruction::ShuffleVector) {
2748 if (Elts.size() != 3)
2749 return Error(ID.Loc, "expected three operands to shufflevector");
2750 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2751 return Error(ID.Loc, "invalid operands to shufflevector");
2753 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2754 } else if (Opc == Instruction::ExtractElement) {
2755 if (Elts.size() != 2)
2756 return Error(ID.Loc, "expected two operands to extractelement");
2757 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2758 return Error(ID.Loc, "invalid extractelement operands");
2759 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2761 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2762 if (Elts.size() != 3)
2763 return Error(ID.Loc, "expected three operands to insertelement");
2764 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2765 return Error(ID.Loc, "invalid insertelement operands");
2767 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2770 ID.Kind = ValID::t_Constant;
2779 /// ParseGlobalValue - Parse a global value with the specified type.
2780 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2784 bool Parsed = ParseValID(ID) ||
2785 ConvertValIDToValue(Ty, ID, V, nullptr);
2786 if (V && !(C = dyn_cast<Constant>(V)))
2787 return Error(ID.Loc, "global values must be constants");
2791 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2793 return ParseType(Ty) ||
2794 ParseGlobalValue(Ty, V);
2797 /// ParseGlobalValueVector
2799 /// ::= TypeAndValue (',' TypeAndValue)*
2800 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2802 if (Lex.getKind() == lltok::rbrace ||
2803 Lex.getKind() == lltok::rsquare ||
2804 Lex.getKind() == lltok::greater ||
2805 Lex.getKind() == lltok::rparen)
2809 if (ParseGlobalTypeAndValue(C)) return true;
2812 while (EatIfPresent(lltok::comma)) {
2813 if (ParseGlobalTypeAndValue(C)) return true;
2820 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2821 assert(Lex.getKind() == lltok::lbrace);
2824 SmallVector<Value*, 16> Elts;
2825 if (ParseMDNodeVector(Elts, PFS) ||
2826 ParseToken(lltok::rbrace, "expected end of metadata node"))
2829 ID.MDNodeVal = MDNode::get(Context, Elts);
2830 ID.Kind = ValID::t_MDNode;
2834 /// ParseMetadataValue
2838 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2839 assert(Lex.getKind() == lltok::exclaim);
2844 if (Lex.getKind() == lltok::lbrace)
2845 return ParseMetadataListValue(ID, PFS);
2847 // Standalone metadata reference
2849 if (Lex.getKind() == lltok::APSInt) {
2850 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2851 ID.Kind = ValID::t_MDNode;
2856 // ::= '!' STRINGCONSTANT
2857 if (ParseMDString(ID.MDStringVal)) return true;
2858 ID.Kind = ValID::t_MDString;
2863 //===----------------------------------------------------------------------===//
2864 // Function Parsing.
2865 //===----------------------------------------------------------------------===//
2867 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2868 PerFunctionState *PFS) {
2869 if (Ty->isFunctionTy())
2870 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2873 case ValID::t_LocalID:
2874 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2875 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2876 return V == nullptr;
2877 case ValID::t_LocalName:
2878 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2879 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2880 return V == nullptr;
2881 case ValID::t_InlineAsm: {
2882 PointerType *PTy = dyn_cast<PointerType>(Ty);
2884 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2885 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2886 return Error(ID.Loc, "invalid type for inline asm constraint string");
2887 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2888 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2891 case ValID::t_MDNode:
2892 if (!Ty->isMetadataTy())
2893 return Error(ID.Loc, "metadata value must have metadata type");
2896 case ValID::t_MDString:
2897 if (!Ty->isMetadataTy())
2898 return Error(ID.Loc, "metadata value must have metadata type");
2901 case ValID::t_GlobalName:
2902 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2903 return V == nullptr;
2904 case ValID::t_GlobalID:
2905 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2906 return V == nullptr;
2907 case ValID::t_APSInt:
2908 if (!Ty->isIntegerTy())
2909 return Error(ID.Loc, "integer constant must have integer type");
2910 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2911 V = ConstantInt::get(Context, ID.APSIntVal);
2913 case ValID::t_APFloat:
2914 if (!Ty->isFloatingPointTy() ||
2915 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2916 return Error(ID.Loc, "floating point constant invalid for type");
2918 // The lexer has no type info, so builds all half, float, and double FP
2919 // constants as double. Fix this here. Long double does not need this.
2920 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2923 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2925 else if (Ty->isFloatTy())
2926 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2929 V = ConstantFP::get(Context, ID.APFloatVal);
2931 if (V->getType() != Ty)
2932 return Error(ID.Loc, "floating point constant does not have type '" +
2933 getTypeString(Ty) + "'");
2937 if (!Ty->isPointerTy())
2938 return Error(ID.Loc, "null must be a pointer type");
2939 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2941 case ValID::t_Undef:
2942 // FIXME: LabelTy should not be a first-class type.
2943 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2944 return Error(ID.Loc, "invalid type for undef constant");
2945 V = UndefValue::get(Ty);
2947 case ValID::t_EmptyArray:
2948 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2949 return Error(ID.Loc, "invalid empty array initializer");
2950 V = UndefValue::get(Ty);
2953 // FIXME: LabelTy should not be a first-class type.
2954 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2955 return Error(ID.Loc, "invalid type for null constant");
2956 V = Constant::getNullValue(Ty);
2958 case ValID::t_Constant:
2959 if (ID.ConstantVal->getType() != Ty)
2960 return Error(ID.Loc, "constant expression type mismatch");
2964 case ValID::t_ConstantStruct:
2965 case ValID::t_PackedConstantStruct:
2966 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2967 if (ST->getNumElements() != ID.UIntVal)
2968 return Error(ID.Loc,
2969 "initializer with struct type has wrong # elements");
2970 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2971 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2973 // Verify that the elements are compatible with the structtype.
2974 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2975 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2976 return Error(ID.Loc, "element " + Twine(i) +
2977 " of struct initializer doesn't match struct element type");
2979 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2982 return Error(ID.Loc, "constant expression type mismatch");
2985 llvm_unreachable("Invalid ValID");
2988 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2991 return ParseValID(ID, PFS) ||
2992 ConvertValIDToValue(Ty, ID, V, PFS);
2995 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2997 return ParseType(Ty) ||
2998 ParseValue(Ty, V, PFS);
3001 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
3002 PerFunctionState &PFS) {
3005 if (ParseTypeAndValue(V, PFS)) return true;
3006 if (!isa<BasicBlock>(V))
3007 return Error(Loc, "expected a basic block");
3008 BB = cast<BasicBlock>(V);
3014 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
3015 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
3016 /// OptionalAlign OptGC OptionalPrefix
3017 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
3018 // Parse the linkage.
3019 LocTy LinkageLoc = Lex.getLoc();
3022 unsigned Visibility;
3023 unsigned DLLStorageClass;
3024 AttrBuilder RetAttrs;
3026 Type *RetType = nullptr;
3027 LocTy RetTypeLoc = Lex.getLoc();
3028 if (ParseOptionalLinkage(Linkage) ||
3029 ParseOptionalVisibility(Visibility) ||
3030 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3031 ParseOptionalCallingConv(CC) ||
3032 ParseOptionalReturnAttrs(RetAttrs) ||
3033 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3036 // Verify that the linkage is ok.
3037 switch ((GlobalValue::LinkageTypes)Linkage) {
3038 case GlobalValue::ExternalLinkage:
3039 break; // always ok.
3040 case GlobalValue::ExternalWeakLinkage:
3042 return Error(LinkageLoc, "invalid linkage for function definition");
3044 case GlobalValue::PrivateLinkage:
3045 case GlobalValue::InternalLinkage:
3046 case GlobalValue::AvailableExternallyLinkage:
3047 case GlobalValue::LinkOnceAnyLinkage:
3048 case GlobalValue::LinkOnceODRLinkage:
3049 case GlobalValue::WeakAnyLinkage:
3050 case GlobalValue::WeakODRLinkage:
3052 return Error(LinkageLoc, "invalid linkage for function declaration");
3054 case GlobalValue::AppendingLinkage:
3055 case GlobalValue::CommonLinkage:
3056 return Error(LinkageLoc, "invalid function linkage type");
3059 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3060 return Error(LinkageLoc,
3061 "symbol with local linkage must have default visibility");
3063 if (!FunctionType::isValidReturnType(RetType))
3064 return Error(RetTypeLoc, "invalid function return type");
3066 LocTy NameLoc = Lex.getLoc();
3068 std::string FunctionName;
3069 if (Lex.getKind() == lltok::GlobalVar) {
3070 FunctionName = Lex.getStrVal();
3071 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3072 unsigned NameID = Lex.getUIntVal();
3074 if (NameID != NumberedVals.size())
3075 return TokError("function expected to be numbered '%" +
3076 Twine(NumberedVals.size()) + "'");
3078 return TokError("expected function name");
3083 if (Lex.getKind() != lltok::lparen)
3084 return TokError("expected '(' in function argument list");
3086 SmallVector<ArgInfo, 8> ArgList;
3088 AttrBuilder FuncAttrs;
3089 std::vector<unsigned> FwdRefAttrGrps;
3091 std::string Section;
3095 LocTy UnnamedAddrLoc;
3096 Constant *Prefix = nullptr;
3098 if (ParseArgumentList(ArgList, isVarArg) ||
3099 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3101 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3103 (EatIfPresent(lltok::kw_section) &&
3104 ParseStringConstant(Section)) ||
3105 ParseOptionalAlignment(Alignment) ||
3106 (EatIfPresent(lltok::kw_gc) &&
3107 ParseStringConstant(GC)) ||
3108 (EatIfPresent(lltok::kw_prefix) &&
3109 ParseGlobalTypeAndValue(Prefix)))
3112 if (FuncAttrs.contains(Attribute::Builtin))
3113 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3115 // If the alignment was parsed as an attribute, move to the alignment field.
3116 if (FuncAttrs.hasAlignmentAttr()) {
3117 Alignment = FuncAttrs.getAlignment();
3118 FuncAttrs.removeAttribute(Attribute::Alignment);
3121 // Okay, if we got here, the function is syntactically valid. Convert types
3122 // and do semantic checks.
3123 std::vector<Type*> ParamTypeList;
3124 SmallVector<AttributeSet, 8> Attrs;
3126 if (RetAttrs.hasAttributes())
3127 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3128 AttributeSet::ReturnIndex,
3131 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3132 ParamTypeList.push_back(ArgList[i].Ty);
3133 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3134 AttrBuilder B(ArgList[i].Attrs, i + 1);
3135 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3139 if (FuncAttrs.hasAttributes())
3140 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3141 AttributeSet::FunctionIndex,
3144 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3146 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3147 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3150 FunctionType::get(RetType, ParamTypeList, isVarArg);
3151 PointerType *PFT = PointerType::getUnqual(FT);
3154 if (!FunctionName.empty()) {
3155 // If this was a definition of a forward reference, remove the definition
3156 // from the forward reference table and fill in the forward ref.
3157 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3158 ForwardRefVals.find(FunctionName);
3159 if (FRVI != ForwardRefVals.end()) {
3160 Fn = M->getFunction(FunctionName);
3162 return Error(FRVI->second.second, "invalid forward reference to "
3163 "function as global value!");
3164 if (Fn->getType() != PFT)
3165 return Error(FRVI->second.second, "invalid forward reference to "
3166 "function '" + FunctionName + "' with wrong type!");
3168 ForwardRefVals.erase(FRVI);
3169 } else if ((Fn = M->getFunction(FunctionName))) {
3170 // Reject redefinitions.
3171 return Error(NameLoc, "invalid redefinition of function '" +
3172 FunctionName + "'");
3173 } else if (M->getNamedValue(FunctionName)) {
3174 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3178 // If this is a definition of a forward referenced function, make sure the
3180 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3181 = ForwardRefValIDs.find(NumberedVals.size());
3182 if (I != ForwardRefValIDs.end()) {
3183 Fn = cast<Function>(I->second.first);
3184 if (Fn->getType() != PFT)
3185 return Error(NameLoc, "type of definition and forward reference of '@" +
3186 Twine(NumberedVals.size()) + "' disagree");
3187 ForwardRefValIDs.erase(I);
3192 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3193 else // Move the forward-reference to the correct spot in the module.
3194 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3196 if (FunctionName.empty())
3197 NumberedVals.push_back(Fn);
3199 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3200 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3201 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3202 Fn->setCallingConv(CC);
3203 Fn->setAttributes(PAL);
3204 Fn->setUnnamedAddr(UnnamedAddr);
3205 Fn->setAlignment(Alignment);
3206 Fn->setSection(Section);
3207 if (!GC.empty()) Fn->setGC(GC.c_str());
3208 Fn->setPrefixData(Prefix);
3209 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3211 // Add all of the arguments we parsed to the function.
3212 Function::arg_iterator ArgIt = Fn->arg_begin();
3213 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3214 // If the argument has a name, insert it into the argument symbol table.
3215 if (ArgList[i].Name.empty()) continue;
3217 // Set the name, if it conflicted, it will be auto-renamed.
3218 ArgIt->setName(ArgList[i].Name);
3220 if (ArgIt->getName() != ArgList[i].Name)
3221 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3222 ArgList[i].Name + "'");
3229 /// ParseFunctionBody
3230 /// ::= '{' BasicBlock+ '}'
3232 bool LLParser::ParseFunctionBody(Function &Fn) {
3233 if (Lex.getKind() != lltok::lbrace)
3234 return TokError("expected '{' in function body");
3235 Lex.Lex(); // eat the {.
3237 int FunctionNumber = -1;
3238 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3240 PerFunctionState PFS(*this, Fn, FunctionNumber);
3242 // We need at least one basic block.
3243 if (Lex.getKind() == lltok::rbrace)
3244 return TokError("function body requires at least one basic block");
3246 while (Lex.getKind() != lltok::rbrace)
3247 if (ParseBasicBlock(PFS)) return true;
3252 // Verify function is ok.
3253 return PFS.FinishFunction();
3257 /// ::= LabelStr? Instruction*
3258 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3259 // If this basic block starts out with a name, remember it.
3261 LocTy NameLoc = Lex.getLoc();
3262 if (Lex.getKind() == lltok::LabelStr) {
3263 Name = Lex.getStrVal();
3267 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3268 if (!BB) return true;
3270 std::string NameStr;
3272 // Parse the instructions in this block until we get a terminator.
3275 // This instruction may have three possibilities for a name: a) none
3276 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3277 LocTy NameLoc = Lex.getLoc();
3281 if (Lex.getKind() == lltok::LocalVarID) {
3282 NameID = Lex.getUIntVal();
3284 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3286 } else if (Lex.getKind() == lltok::LocalVar) {
3287 NameStr = Lex.getStrVal();
3289 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3293 switch (ParseInstruction(Inst, BB, PFS)) {
3294 default: llvm_unreachable("Unknown ParseInstruction result!");
3295 case InstError: return true;
3297 BB->getInstList().push_back(Inst);
3299 // With a normal result, we check to see if the instruction is followed by
3300 // a comma and metadata.
3301 if (EatIfPresent(lltok::comma))
3302 if (ParseInstructionMetadata(Inst, &PFS))
3305 case InstExtraComma:
3306 BB->getInstList().push_back(Inst);
3308 // If the instruction parser ate an extra comma at the end of it, it
3309 // *must* be followed by metadata.
3310 if (ParseInstructionMetadata(Inst, &PFS))
3315 // Set the name on the instruction.
3316 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3317 } while (!isa<TerminatorInst>(Inst));
3322 //===----------------------------------------------------------------------===//
3323 // Instruction Parsing.
3324 //===----------------------------------------------------------------------===//
3326 /// ParseInstruction - Parse one of the many different instructions.
3328 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3329 PerFunctionState &PFS) {
3330 lltok::Kind Token = Lex.getKind();
3331 if (Token == lltok::Eof)
3332 return TokError("found end of file when expecting more instructions");
3333 LocTy Loc = Lex.getLoc();
3334 unsigned KeywordVal = Lex.getUIntVal();
3335 Lex.Lex(); // Eat the keyword.
3338 default: return Error(Loc, "expected instruction opcode");
3339 // Terminator Instructions.
3340 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3341 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3342 case lltok::kw_br: return ParseBr(Inst, PFS);
3343 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3344 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3345 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3346 case lltok::kw_resume: return ParseResume(Inst, PFS);
3347 // Binary Operators.
3351 case lltok::kw_shl: {
3352 bool NUW = EatIfPresent(lltok::kw_nuw);
3353 bool NSW = EatIfPresent(lltok::kw_nsw);
3354 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3356 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3358 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3359 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3362 case lltok::kw_fadd:
3363 case lltok::kw_fsub:
3364 case lltok::kw_fmul:
3365 case lltok::kw_fdiv:
3366 case lltok::kw_frem: {
3367 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3368 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3372 Inst->setFastMathFlags(FMF);
3376 case lltok::kw_sdiv:
3377 case lltok::kw_udiv:
3378 case lltok::kw_lshr:
3379 case lltok::kw_ashr: {
3380 bool Exact = EatIfPresent(lltok::kw_exact);
3382 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3383 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3387 case lltok::kw_urem:
3388 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3391 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3392 case lltok::kw_icmp:
3393 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3395 case lltok::kw_trunc:
3396 case lltok::kw_zext:
3397 case lltok::kw_sext:
3398 case lltok::kw_fptrunc:
3399 case lltok::kw_fpext:
3400 case lltok::kw_bitcast:
3401 case lltok::kw_addrspacecast:
3402 case lltok::kw_uitofp:
3403 case lltok::kw_sitofp:
3404 case lltok::kw_fptoui:
3405 case lltok::kw_fptosi:
3406 case lltok::kw_inttoptr:
3407 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3409 case lltok::kw_select: return ParseSelect(Inst, PFS);
3410 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3411 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3412 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3413 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3414 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3415 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3417 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3418 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3419 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3421 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3422 case lltok::kw_load: return ParseLoad(Inst, PFS);
3423 case lltok::kw_store: return ParseStore(Inst, PFS);
3424 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3425 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3426 case lltok::kw_fence: return ParseFence(Inst, PFS);
3427 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3428 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3429 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3433 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3434 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3435 if (Opc == Instruction::FCmp) {
3436 switch (Lex.getKind()) {
3437 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3438 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3439 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3440 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3441 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3442 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3443 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3444 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3445 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3446 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3447 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3448 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3449 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3450 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3451 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3452 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3453 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3456 switch (Lex.getKind()) {
3457 default: return TokError("expected icmp predicate (e.g. 'eq')");
3458 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3459 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3460 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3461 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3462 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3463 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3464 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3465 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3466 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3467 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3474 //===----------------------------------------------------------------------===//
3475 // Terminator Instructions.
3476 //===----------------------------------------------------------------------===//
3478 /// ParseRet - Parse a return instruction.
3479 /// ::= 'ret' void (',' !dbg, !1)*
3480 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3481 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3482 PerFunctionState &PFS) {
3483 SMLoc TypeLoc = Lex.getLoc();
3485 if (ParseType(Ty, true /*void allowed*/)) return true;
3487 Type *ResType = PFS.getFunction().getReturnType();
3489 if (Ty->isVoidTy()) {
3490 if (!ResType->isVoidTy())
3491 return Error(TypeLoc, "value doesn't match function result type '" +
3492 getTypeString(ResType) + "'");
3494 Inst = ReturnInst::Create(Context);
3499 if (ParseValue(Ty, RV, PFS)) return true;
3501 if (ResType != RV->getType())
3502 return Error(TypeLoc, "value doesn't match function result type '" +
3503 getTypeString(ResType) + "'");
3505 Inst = ReturnInst::Create(Context, RV);
3511 /// ::= 'br' TypeAndValue
3512 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3513 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3516 BasicBlock *Op1, *Op2;
3517 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3519 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3520 Inst = BranchInst::Create(BB);
3524 if (Op0->getType() != Type::getInt1Ty(Context))
3525 return Error(Loc, "branch condition must have 'i1' type");
3527 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3528 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3529 ParseToken(lltok::comma, "expected ',' after true destination") ||
3530 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3533 Inst = BranchInst::Create(Op1, Op2, Op0);
3539 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3541 /// ::= (TypeAndValue ',' TypeAndValue)*
3542 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3543 LocTy CondLoc, BBLoc;
3545 BasicBlock *DefaultBB;
3546 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3547 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3548 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3549 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3552 if (!Cond->getType()->isIntegerTy())
3553 return Error(CondLoc, "switch condition must have integer type");
3555 // Parse the jump table pairs.
3556 SmallPtrSet<Value*, 32> SeenCases;
3557 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3558 while (Lex.getKind() != lltok::rsquare) {
3562 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3563 ParseToken(lltok::comma, "expected ',' after case value") ||
3564 ParseTypeAndBasicBlock(DestBB, PFS))
3567 if (!SeenCases.insert(Constant))
3568 return Error(CondLoc, "duplicate case value in switch");
3569 if (!isa<ConstantInt>(Constant))
3570 return Error(CondLoc, "case value is not a constant integer");
3572 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3575 Lex.Lex(); // Eat the ']'.
3577 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3578 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3579 SI->addCase(Table[i].first, Table[i].second);
3586 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3587 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3590 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3591 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3592 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3595 if (!Address->getType()->isPointerTy())
3596 return Error(AddrLoc, "indirectbr address must have pointer type");
3598 // Parse the destination list.
3599 SmallVector<BasicBlock*, 16> DestList;
3601 if (Lex.getKind() != lltok::rsquare) {
3603 if (ParseTypeAndBasicBlock(DestBB, PFS))
3605 DestList.push_back(DestBB);
3607 while (EatIfPresent(lltok::comma)) {
3608 if (ParseTypeAndBasicBlock(DestBB, PFS))
3610 DestList.push_back(DestBB);
3614 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3617 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3618 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3619 IBI->addDestination(DestList[i]);
3626 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3627 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3628 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3629 LocTy CallLoc = Lex.getLoc();
3630 AttrBuilder RetAttrs, FnAttrs;
3631 std::vector<unsigned> FwdRefAttrGrps;
3634 Type *RetType = nullptr;
3637 SmallVector<ParamInfo, 16> ArgList;
3639 BasicBlock *NormalBB, *UnwindBB;
3640 if (ParseOptionalCallingConv(CC) ||
3641 ParseOptionalReturnAttrs(RetAttrs) ||
3642 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3643 ParseValID(CalleeID) ||
3644 ParseParameterList(ArgList, PFS) ||
3645 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3647 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3648 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3649 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3650 ParseTypeAndBasicBlock(UnwindBB, PFS))
3653 // If RetType is a non-function pointer type, then this is the short syntax
3654 // for the call, which means that RetType is just the return type. Infer the
3655 // rest of the function argument types from the arguments that are present.
3656 PointerType *PFTy = nullptr;
3657 FunctionType *Ty = nullptr;
3658 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3659 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3660 // Pull out the types of all of the arguments...
3661 std::vector<Type*> ParamTypes;
3662 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3663 ParamTypes.push_back(ArgList[i].V->getType());
3665 if (!FunctionType::isValidReturnType(RetType))
3666 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3668 Ty = FunctionType::get(RetType, ParamTypes, false);
3669 PFTy = PointerType::getUnqual(Ty);
3672 // Look up the callee.
3674 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3676 // Set up the Attribute for the function.
3677 SmallVector<AttributeSet, 8> Attrs;
3678 if (RetAttrs.hasAttributes())
3679 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3680 AttributeSet::ReturnIndex,
3683 SmallVector<Value*, 8> Args;
3685 // Loop through FunctionType's arguments and ensure they are specified
3686 // correctly. Also, gather any parameter attributes.
3687 FunctionType::param_iterator I = Ty->param_begin();
3688 FunctionType::param_iterator E = Ty->param_end();
3689 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3690 Type *ExpectedTy = nullptr;
3693 } else if (!Ty->isVarArg()) {
3694 return Error(ArgList[i].Loc, "too many arguments specified");
3697 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3698 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3699 getTypeString(ExpectedTy) + "'");
3700 Args.push_back(ArgList[i].V);
3701 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3702 AttrBuilder B(ArgList[i].Attrs, i + 1);
3703 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3708 return Error(CallLoc, "not enough parameters specified for call");
3710 if (FnAttrs.hasAttributes())
3711 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3712 AttributeSet::FunctionIndex,
3715 // Finish off the Attribute and check them
3716 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3718 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3719 II->setCallingConv(CC);
3720 II->setAttributes(PAL);
3721 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3727 /// ::= 'resume' TypeAndValue
3728 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3729 Value *Exn; LocTy ExnLoc;
3730 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3733 ResumeInst *RI = ResumeInst::Create(Exn);
3738 //===----------------------------------------------------------------------===//
3739 // Binary Operators.
3740 //===----------------------------------------------------------------------===//
3743 /// ::= ArithmeticOps TypeAndValue ',' Value
3745 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3746 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3747 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3748 unsigned Opc, unsigned OperandType) {
3749 LocTy Loc; Value *LHS, *RHS;
3750 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3751 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3752 ParseValue(LHS->getType(), RHS, PFS))
3756 switch (OperandType) {
3757 default: llvm_unreachable("Unknown operand type!");
3758 case 0: // int or FP.
3759 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3760 LHS->getType()->isFPOrFPVectorTy();
3762 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3763 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3767 return Error(Loc, "invalid operand type for instruction");
3769 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3774 /// ::= ArithmeticOps TypeAndValue ',' Value {
3775 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3777 LocTy Loc; Value *LHS, *RHS;
3778 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3779 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3780 ParseValue(LHS->getType(), RHS, PFS))
3783 if (!LHS->getType()->isIntOrIntVectorTy())
3784 return Error(Loc,"instruction requires integer or integer vector operands");
3786 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3792 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3793 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3794 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3796 // Parse the integer/fp comparison predicate.
3800 if (ParseCmpPredicate(Pred, Opc) ||
3801 ParseTypeAndValue(LHS, Loc, PFS) ||
3802 ParseToken(lltok::comma, "expected ',' after compare value") ||
3803 ParseValue(LHS->getType(), RHS, PFS))
3806 if (Opc == Instruction::FCmp) {
3807 if (!LHS->getType()->isFPOrFPVectorTy())
3808 return Error(Loc, "fcmp requires floating point operands");
3809 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3811 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3812 if (!LHS->getType()->isIntOrIntVectorTy() &&
3813 !LHS->getType()->getScalarType()->isPointerTy())
3814 return Error(Loc, "icmp requires integer operands");
3815 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3820 //===----------------------------------------------------------------------===//
3821 // Other Instructions.
3822 //===----------------------------------------------------------------------===//
3826 /// ::= CastOpc TypeAndValue 'to' Type
3827 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3831 Type *DestTy = nullptr;
3832 if (ParseTypeAndValue(Op, Loc, PFS) ||
3833 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3837 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3838 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3839 return Error(Loc, "invalid cast opcode for cast from '" +
3840 getTypeString(Op->getType()) + "' to '" +
3841 getTypeString(DestTy) + "'");
3843 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3848 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3849 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3851 Value *Op0, *Op1, *Op2;
3852 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3853 ParseToken(lltok::comma, "expected ',' after select condition") ||
3854 ParseTypeAndValue(Op1, PFS) ||
3855 ParseToken(lltok::comma, "expected ',' after select value") ||
3856 ParseTypeAndValue(Op2, PFS))
3859 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3860 return Error(Loc, Reason);
3862 Inst = SelectInst::Create(Op0, Op1, Op2);
3867 /// ::= 'va_arg' TypeAndValue ',' Type
3868 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3870 Type *EltTy = nullptr;
3872 if (ParseTypeAndValue(Op, PFS) ||
3873 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3874 ParseType(EltTy, TypeLoc))
3877 if (!EltTy->isFirstClassType())
3878 return Error(TypeLoc, "va_arg requires operand with first class type");
3880 Inst = new VAArgInst(Op, EltTy);
3884 /// ParseExtractElement
3885 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3886 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3889 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3890 ParseToken(lltok::comma, "expected ',' after extract value") ||
3891 ParseTypeAndValue(Op1, PFS))
3894 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3895 return Error(Loc, "invalid extractelement operands");
3897 Inst = ExtractElementInst::Create(Op0, Op1);
3901 /// ParseInsertElement
3902 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3903 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3905 Value *Op0, *Op1, *Op2;
3906 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3907 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3908 ParseTypeAndValue(Op1, PFS) ||
3909 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3910 ParseTypeAndValue(Op2, PFS))
3913 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3914 return Error(Loc, "invalid insertelement operands");
3916 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3920 /// ParseShuffleVector
3921 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3922 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3924 Value *Op0, *Op1, *Op2;
3925 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3926 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3927 ParseTypeAndValue(Op1, PFS) ||
3928 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3929 ParseTypeAndValue(Op2, PFS))
3932 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3933 return Error(Loc, "invalid shufflevector operands");
3935 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3940 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3941 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3942 Type *Ty = nullptr; LocTy TypeLoc;
3945 if (ParseType(Ty, TypeLoc) ||
3946 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3947 ParseValue(Ty, Op0, PFS) ||
3948 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3949 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3950 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3953 bool AteExtraComma = false;
3954 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3956 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3958 if (!EatIfPresent(lltok::comma))
3961 if (Lex.getKind() == lltok::MetadataVar) {
3962 AteExtraComma = true;
3966 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3967 ParseValue(Ty, Op0, PFS) ||
3968 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3969 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3970 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3974 if (!Ty->isFirstClassType())
3975 return Error(TypeLoc, "phi node must have first class type");
3977 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3978 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3979 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3981 return AteExtraComma ? InstExtraComma : InstNormal;
3985 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3987 /// ::= 'catch' TypeAndValue
3989 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3990 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3991 Type *Ty = nullptr; LocTy TyLoc;
3992 Value *PersFn; LocTy PersFnLoc;
3994 if (ParseType(Ty, TyLoc) ||
3995 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3996 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3999 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
4000 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
4002 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
4003 LandingPadInst::ClauseType CT;
4004 if (EatIfPresent(lltok::kw_catch))
4005 CT = LandingPadInst::Catch;
4006 else if (EatIfPresent(lltok::kw_filter))
4007 CT = LandingPadInst::Filter;
4009 return TokError("expected 'catch' or 'filter' clause type");
4011 Value *V; LocTy VLoc;
4012 if (ParseTypeAndValue(V, VLoc, PFS)) {
4017 // A 'catch' type expects a non-array constant. A filter clause expects an
4019 if (CT == LandingPadInst::Catch) {
4020 if (isa<ArrayType>(V->getType()))
4021 Error(VLoc, "'catch' clause has an invalid type");
4023 if (!isa<ArrayType>(V->getType()))
4024 Error(VLoc, "'filter' clause has an invalid type");
4035 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4036 /// ParameterList OptionalAttrs
4037 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4038 /// ParameterList OptionalAttrs
4039 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4040 /// ParameterList OptionalAttrs
4041 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4042 CallInst::TailCallKind TCK) {
4043 AttrBuilder RetAttrs, FnAttrs;
4044 std::vector<unsigned> FwdRefAttrGrps;
4047 Type *RetType = nullptr;
4050 SmallVector<ParamInfo, 16> ArgList;
4051 LocTy CallLoc = Lex.getLoc();
4053 if ((TCK != CallInst::TCK_None &&
4054 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4055 ParseOptionalCallingConv(CC) ||
4056 ParseOptionalReturnAttrs(RetAttrs) ||
4057 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4058 ParseValID(CalleeID) ||
4059 ParseParameterList(ArgList, PFS) ||
4060 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4064 // If RetType is a non-function pointer type, then this is the short syntax
4065 // for the call, which means that RetType is just the return type. Infer the
4066 // rest of the function argument types from the arguments that are present.
4067 PointerType *PFTy = nullptr;
4068 FunctionType *Ty = nullptr;
4069 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4070 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4071 // Pull out the types of all of the arguments...
4072 std::vector<Type*> ParamTypes;
4073 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4074 ParamTypes.push_back(ArgList[i].V->getType());
4076 if (!FunctionType::isValidReturnType(RetType))
4077 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4079 Ty = FunctionType::get(RetType, ParamTypes, false);
4080 PFTy = PointerType::getUnqual(Ty);
4083 // Look up the callee.
4085 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4087 // Set up the Attribute for the function.
4088 SmallVector<AttributeSet, 8> Attrs;
4089 if (RetAttrs.hasAttributes())
4090 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4091 AttributeSet::ReturnIndex,
4094 SmallVector<Value*, 8> Args;
4096 // Loop through FunctionType's arguments and ensure they are specified
4097 // correctly. Also, gather any parameter attributes.
4098 FunctionType::param_iterator I = Ty->param_begin();
4099 FunctionType::param_iterator E = Ty->param_end();
4100 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4101 Type *ExpectedTy = nullptr;
4104 } else if (!Ty->isVarArg()) {
4105 return Error(ArgList[i].Loc, "too many arguments specified");
4108 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4109 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4110 getTypeString(ExpectedTy) + "'");
4111 Args.push_back(ArgList[i].V);
4112 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4113 AttrBuilder B(ArgList[i].Attrs, i + 1);
4114 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4119 return Error(CallLoc, "not enough parameters specified for call");
4121 if (FnAttrs.hasAttributes())
4122 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4123 AttributeSet::FunctionIndex,
4126 // Finish off the Attribute and check them
4127 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4129 CallInst *CI = CallInst::Create(Callee, Args);
4130 CI->setTailCallKind(TCK);
4131 CI->setCallingConv(CC);
4132 CI->setAttributes(PAL);
4133 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4138 //===----------------------------------------------------------------------===//
4139 // Memory Instructions.
4140 //===----------------------------------------------------------------------===//
4143 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4144 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4145 Value *Size = nullptr;
4147 unsigned Alignment = 0;
4150 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4152 if (ParseType(Ty)) return true;
4154 bool AteExtraComma = false;
4155 if (EatIfPresent(lltok::comma)) {
4156 if (Lex.getKind() == lltok::kw_align) {
4157 if (ParseOptionalAlignment(Alignment)) return true;
4158 } else if (Lex.getKind() == lltok::MetadataVar) {
4159 AteExtraComma = true;
4161 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4162 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4167 if (Size && !Size->getType()->isIntegerTy())
4168 return Error(SizeLoc, "element count must have integer type");
4170 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4171 AI->setUsedWithInAlloca(IsInAlloca);
4173 return AteExtraComma ? InstExtraComma : InstNormal;
4177 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4178 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4179 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4180 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4181 Value *Val; LocTy Loc;
4182 unsigned Alignment = 0;
4183 bool AteExtraComma = false;
4184 bool isAtomic = false;
4185 AtomicOrdering Ordering = NotAtomic;
4186 SynchronizationScope Scope = CrossThread;
4188 if (Lex.getKind() == lltok::kw_atomic) {
4193 bool isVolatile = false;
4194 if (Lex.getKind() == lltok::kw_volatile) {
4199 if (ParseTypeAndValue(Val, Loc, PFS) ||
4200 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4201 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4204 if (!Val->getType()->isPointerTy() ||
4205 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4206 return Error(Loc, "load operand must be a pointer to a first class type");
4207 if (isAtomic && !Alignment)
4208 return Error(Loc, "atomic load must have explicit non-zero alignment");
4209 if (Ordering == Release || Ordering == AcquireRelease)
4210 return Error(Loc, "atomic load cannot use Release ordering");
4212 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4213 return AteExtraComma ? InstExtraComma : InstNormal;
4218 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4219 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4220 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4221 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4222 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4223 unsigned Alignment = 0;
4224 bool AteExtraComma = false;
4225 bool isAtomic = false;
4226 AtomicOrdering Ordering = NotAtomic;
4227 SynchronizationScope Scope = CrossThread;
4229 if (Lex.getKind() == lltok::kw_atomic) {
4234 bool isVolatile = false;
4235 if (Lex.getKind() == lltok::kw_volatile) {
4240 if (ParseTypeAndValue(Val, Loc, PFS) ||
4241 ParseToken(lltok::comma, "expected ',' after store operand") ||
4242 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4243 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4244 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4247 if (!Ptr->getType()->isPointerTy())
4248 return Error(PtrLoc, "store operand must be a pointer");
4249 if (!Val->getType()->isFirstClassType())
4250 return Error(Loc, "store operand must be a first class value");
4251 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4252 return Error(Loc, "stored value and pointer type do not match");
4253 if (isAtomic && !Alignment)
4254 return Error(Loc, "atomic store must have explicit non-zero alignment");
4255 if (Ordering == Acquire || Ordering == AcquireRelease)
4256 return Error(Loc, "atomic store cannot use Acquire ordering");
4258 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4259 return AteExtraComma ? InstExtraComma : InstNormal;
4263 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4264 /// 'singlethread'? AtomicOrdering AtomicOrdering
4265 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4266 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4267 bool AteExtraComma = false;
4268 AtomicOrdering SuccessOrdering = NotAtomic;
4269 AtomicOrdering FailureOrdering = NotAtomic;
4270 SynchronizationScope Scope = CrossThread;
4271 bool isVolatile = false;
4273 if (EatIfPresent(lltok::kw_volatile))
4276 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4277 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4278 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4279 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4280 ParseTypeAndValue(New, NewLoc, PFS) ||
4281 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4282 ParseOrdering(FailureOrdering))
4285 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4286 return TokError("cmpxchg cannot be unordered");
4287 if (SuccessOrdering < FailureOrdering)
4288 return TokError("cmpxchg must be at least as ordered on success as failure");
4289 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4290 return TokError("cmpxchg failure ordering cannot include release semantics");
4291 if (!Ptr->getType()->isPointerTy())
4292 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4293 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4294 return Error(CmpLoc, "compare value and pointer type do not match");
4295 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4296 return Error(NewLoc, "new value and pointer type do not match");
4297 if (!New->getType()->isIntegerTy())
4298 return Error(NewLoc, "cmpxchg operand must be an integer");
4299 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4300 if (Size < 8 || (Size & (Size - 1)))
4301 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4304 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4305 FailureOrdering, Scope);
4306 CXI->setVolatile(isVolatile);
4308 return AteExtraComma ? InstExtraComma : InstNormal;
4312 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4313 /// 'singlethread'? AtomicOrdering
4314 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4315 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4316 bool AteExtraComma = false;
4317 AtomicOrdering Ordering = NotAtomic;
4318 SynchronizationScope Scope = CrossThread;
4319 bool isVolatile = false;
4320 AtomicRMWInst::BinOp Operation;
4322 if (EatIfPresent(lltok::kw_volatile))
4325 switch (Lex.getKind()) {
4326 default: return TokError("expected binary operation in atomicrmw");
4327 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4328 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4329 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4330 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4331 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4332 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4333 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4334 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4335 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4336 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4337 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4339 Lex.Lex(); // Eat the operation.
4341 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4342 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4343 ParseTypeAndValue(Val, ValLoc, PFS) ||
4344 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4347 if (Ordering == Unordered)
4348 return TokError("atomicrmw cannot be unordered");
4349 if (!Ptr->getType()->isPointerTy())
4350 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4351 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4352 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4353 if (!Val->getType()->isIntegerTy())
4354 return Error(ValLoc, "atomicrmw operand must be an integer");
4355 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4356 if (Size < 8 || (Size & (Size - 1)))
4357 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4360 AtomicRMWInst *RMWI =
4361 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4362 RMWI->setVolatile(isVolatile);
4364 return AteExtraComma ? InstExtraComma : InstNormal;
4368 /// ::= 'fence' 'singlethread'? AtomicOrdering
4369 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4370 AtomicOrdering Ordering = NotAtomic;
4371 SynchronizationScope Scope = CrossThread;
4372 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4375 if (Ordering == Unordered)
4376 return TokError("fence cannot be unordered");
4377 if (Ordering == Monotonic)
4378 return TokError("fence cannot be monotonic");
4380 Inst = new FenceInst(Context, Ordering, Scope);
4384 /// ParseGetElementPtr
4385 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4386 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4387 Value *Ptr = nullptr;
4388 Value *Val = nullptr;
4391 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4393 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4395 Type *BaseType = Ptr->getType();
4396 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4397 if (!BasePointerType)
4398 return Error(Loc, "base of getelementptr must be a pointer");
4400 SmallVector<Value*, 16> Indices;
4401 bool AteExtraComma = false;
4402 while (EatIfPresent(lltok::comma)) {
4403 if (Lex.getKind() == lltok::MetadataVar) {
4404 AteExtraComma = true;
4407 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4408 if (!Val->getType()->getScalarType()->isIntegerTy())
4409 return Error(EltLoc, "getelementptr index must be an integer");
4410 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4411 return Error(EltLoc, "getelementptr index type missmatch");
4412 if (Val->getType()->isVectorTy()) {
4413 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4414 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4415 if (ValNumEl != PtrNumEl)
4416 return Error(EltLoc,
4417 "getelementptr vector index has a wrong number of elements");
4419 Indices.push_back(Val);
4422 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4423 return Error(Loc, "base element of getelementptr must be sized");
4425 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4426 return Error(Loc, "invalid getelementptr indices");
4427 Inst = GetElementPtrInst::Create(Ptr, Indices);
4429 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4430 return AteExtraComma ? InstExtraComma : InstNormal;
4433 /// ParseExtractValue
4434 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4435 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4436 Value *Val; LocTy Loc;
4437 SmallVector<unsigned, 4> Indices;
4439 if (ParseTypeAndValue(Val, Loc, PFS) ||
4440 ParseIndexList(Indices, AteExtraComma))
4443 if (!Val->getType()->isAggregateType())
4444 return Error(Loc, "extractvalue operand must be aggregate type");
4446 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4447 return Error(Loc, "invalid indices for extractvalue");
4448 Inst = ExtractValueInst::Create(Val, Indices);
4449 return AteExtraComma ? InstExtraComma : InstNormal;
4452 /// ParseInsertValue
4453 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4454 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4455 Value *Val0, *Val1; LocTy Loc0, Loc1;
4456 SmallVector<unsigned, 4> Indices;
4458 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4459 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4460 ParseTypeAndValue(Val1, Loc1, PFS) ||
4461 ParseIndexList(Indices, AteExtraComma))
4464 if (!Val0->getType()->isAggregateType())
4465 return Error(Loc0, "insertvalue operand must be aggregate type");
4467 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4468 return Error(Loc0, "invalid indices for insertvalue");
4469 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4470 return AteExtraComma ? InstExtraComma : InstNormal;
4473 //===----------------------------------------------------------------------===//
4474 // Embedded metadata.
4475 //===----------------------------------------------------------------------===//
4477 /// ParseMDNodeVector
4478 /// ::= Element (',' Element)*
4480 /// ::= 'null' | TypeAndValue
4481 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4482 PerFunctionState *PFS) {
4483 // Check for an empty list.
4484 if (Lex.getKind() == lltok::rbrace)
4488 // Null is a special case since it is typeless.
4489 if (EatIfPresent(lltok::kw_null)) {
4490 Elts.push_back(nullptr);
4495 if (ParseTypeAndValue(V, PFS)) return true;
4497 } while (EatIfPresent(lltok::comma));