1 //===-- LLParser.cpp - Parser Class ---------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the parser class for .ll files.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/IR/CallingConv.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/InlineAsm.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/IR/ValueSymbolTable.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
30 static std::string getTypeString(Type *T) {
32 raw_string_ostream Tmp(Result);
37 /// Run: module ::= toplevelentity*
38 bool LLParser::Run() {
42 return ParseTopLevelEntities() ||
43 ValidateEndOfModule();
46 /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
48 bool LLParser::ValidateEndOfModule() {
49 // Handle any instruction metadata forward references.
50 if (!ForwardRefInstMetadata.empty()) {
51 for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
52 I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
54 Instruction *Inst = I->first;
55 const std::vector<MDRef> &MDList = I->second;
57 for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
58 unsigned SlotNo = MDList[i].MDSlot;
60 if (SlotNo >= NumberedMetadata.size() ||
61 NumberedMetadata[SlotNo] == nullptr)
62 return Error(MDList[i].Loc, "use of undefined metadata '!" +
64 Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
67 ForwardRefInstMetadata.clear();
70 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
71 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
73 // Handle any function attribute group forward references.
74 for (std::map<Value*, std::vector<unsigned> >::iterator
75 I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
78 std::vector<unsigned> &Vec = I->second;
81 for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
83 B.merge(NumberedAttrBuilders[*VI]);
85 if (Function *Fn = dyn_cast<Function>(V)) {
86 AttributeSet AS = Fn->getAttributes();
87 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
88 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
89 AS.getFnAttributes());
93 // If the alignment was parsed as an attribute, move to the alignment
95 if (FnAttrs.hasAlignmentAttr()) {
96 Fn->setAlignment(FnAttrs.getAlignment());
97 FnAttrs.removeAttribute(Attribute::Alignment);
100 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
101 AttributeSet::get(Context,
102 AttributeSet::FunctionIndex,
104 Fn->setAttributes(AS);
105 } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
106 AttributeSet AS = CI->getAttributes();
107 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
108 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
109 AS.getFnAttributes());
111 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
112 AttributeSet::get(Context,
113 AttributeSet::FunctionIndex,
115 CI->setAttributes(AS);
116 } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
117 AttributeSet AS = II->getAttributes();
118 AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
119 AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
120 AS.getFnAttributes());
122 AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
123 AttributeSet::get(Context,
124 AttributeSet::FunctionIndex,
126 II->setAttributes(AS);
128 llvm_unreachable("invalid object with forward attribute group reference");
132 // If there are entries in ForwardRefBlockAddresses at this point, they are
133 // references after the function was defined. Resolve those now.
134 while (!ForwardRefBlockAddresses.empty()) {
135 // Okay, we are referencing an already-parsed function, resolve them now.
136 Function *TheFn = nullptr;
137 const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
138 if (Fn.Kind == ValID::t_GlobalName)
139 TheFn = M->getFunction(Fn.StrVal);
140 else if (Fn.UIntVal < NumberedVals.size())
141 TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
144 return Error(Fn.Loc, "unknown function referenced by blockaddress");
146 // Resolve all these references.
147 if (ResolveForwardRefBlockAddresses(TheFn,
148 ForwardRefBlockAddresses.begin()->second,
152 ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
155 for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
156 if (NumberedTypes[i].second.isValid())
157 return Error(NumberedTypes[i].second,
158 "use of undefined type '%" + Twine(i) + "'");
160 for (StringMap<std::pair<Type*, LocTy> >::iterator I =
161 NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
162 if (I->second.second.isValid())
163 return Error(I->second.second,
164 "use of undefined type named '" + I->getKey() + "'");
166 if (!ForwardRefVals.empty())
167 return Error(ForwardRefVals.begin()->second.second,
168 "use of undefined value '@" + ForwardRefVals.begin()->first +
171 if (!ForwardRefValIDs.empty())
172 return Error(ForwardRefValIDs.begin()->second.second,
173 "use of undefined value '@" +
174 Twine(ForwardRefValIDs.begin()->first) + "'");
176 if (!ForwardRefMDNodes.empty())
177 return Error(ForwardRefMDNodes.begin()->second.second,
178 "use of undefined metadata '!" +
179 Twine(ForwardRefMDNodes.begin()->first) + "'");
182 // Look for intrinsic functions and CallInst that need to be upgraded
183 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
184 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
186 UpgradeDebugInfo(*M);
191 bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
192 std::vector<std::pair<ValID, GlobalValue*> > &Refs,
193 PerFunctionState *PFS) {
194 // Loop over all the references, resolving them.
195 for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
198 if (Refs[i].first.Kind == ValID::t_LocalName)
199 Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
201 Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
202 } else if (Refs[i].first.Kind == ValID::t_LocalID) {
203 return Error(Refs[i].first.Loc,
204 "cannot take address of numeric label after the function is defined");
206 Res = dyn_cast_or_null<BasicBlock>(
207 TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
211 return Error(Refs[i].first.Loc,
212 "referenced value is not a basic block");
214 // Get the BlockAddress for this and update references to use it.
215 BlockAddress *BA = BlockAddress::get(TheFn, Res);
216 Refs[i].second->replaceAllUsesWith(BA);
217 Refs[i].second->eraseFromParent();
223 //===----------------------------------------------------------------------===//
224 // Top-Level Entities
225 //===----------------------------------------------------------------------===//
227 bool LLParser::ParseTopLevelEntities() {
229 switch (Lex.getKind()) {
230 default: return TokError("expected top-level entity");
231 case lltok::Eof: return false;
232 case lltok::kw_declare: if (ParseDeclare()) return true; break;
233 case lltok::kw_define: if (ParseDefine()) return true; break;
234 case lltok::kw_module: if (ParseModuleAsm()) return true; break;
235 case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
236 case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
237 case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
238 case lltok::LocalVar: if (ParseNamedType()) return true; break;
239 case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
240 case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
241 case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
242 case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
244 // The Global variable production with no name can have many different
245 // optional leading prefixes, the production is:
246 // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
247 // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
248 // ('constant'|'global') ...
249 case lltok::kw_private: // OptionalLinkage
250 case lltok::kw_internal: // OptionalLinkage
251 case lltok::kw_linker_private: // Obsolete OptionalLinkage
252 case lltok::kw_linker_private_weak: // Obsolete OptionalLinkage
253 case lltok::kw_weak: // OptionalLinkage
254 case lltok::kw_weak_odr: // OptionalLinkage
255 case lltok::kw_linkonce: // OptionalLinkage
256 case lltok::kw_linkonce_odr: // OptionalLinkage
257 case lltok::kw_appending: // OptionalLinkage
258 case lltok::kw_common: // OptionalLinkage
259 case lltok::kw_extern_weak: // OptionalLinkage
260 case lltok::kw_external: // OptionalLinkage
261 case lltok::kw_default: // OptionalVisibility
262 case lltok::kw_hidden: // OptionalVisibility
263 case lltok::kw_protected: // OptionalVisibility
264 case lltok::kw_thread_local: // OptionalThreadLocal
265 case lltok::kw_addrspace: // OptionalAddrSpace
266 case lltok::kw_constant: // GlobalType
267 case lltok::kw_global: { // GlobalType
268 unsigned Linkage, Visibility, DLLStorageClass;
269 GlobalVariable::ThreadLocalMode TLM;
271 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
272 ParseOptionalVisibility(Visibility) ||
273 ParseOptionalDLLStorageClass(DLLStorageClass) ||
274 ParseOptionalThreadLocal(TLM) ||
275 ParseGlobal("", SMLoc(), Linkage, HasLinkage, Visibility,
276 DLLStorageClass, TLM))
281 case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
288 /// ::= 'module' 'asm' STRINGCONSTANT
289 bool LLParser::ParseModuleAsm() {
290 assert(Lex.getKind() == lltok::kw_module);
294 if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
295 ParseStringConstant(AsmStr)) return true;
297 M->appendModuleInlineAsm(AsmStr);
302 /// ::= 'target' 'triple' '=' STRINGCONSTANT
303 /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
304 bool LLParser::ParseTargetDefinition() {
305 assert(Lex.getKind() == lltok::kw_target);
308 default: return TokError("unknown target property");
309 case lltok::kw_triple:
311 if (ParseToken(lltok::equal, "expected '=' after target triple") ||
312 ParseStringConstant(Str))
314 M->setTargetTriple(Str);
316 case lltok::kw_datalayout:
318 if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
319 ParseStringConstant(Str))
321 M->setDataLayout(Str);
327 /// ::= 'deplibs' '=' '[' ']'
328 /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
329 /// FIXME: Remove in 4.0. Currently parse, but ignore.
330 bool LLParser::ParseDepLibs() {
331 assert(Lex.getKind() == lltok::kw_deplibs);
333 if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
334 ParseToken(lltok::lsquare, "expected '=' after deplibs"))
337 if (EatIfPresent(lltok::rsquare))
342 if (ParseStringConstant(Str)) return true;
343 } while (EatIfPresent(lltok::comma));
345 return ParseToken(lltok::rsquare, "expected ']' at end of list");
348 /// ParseUnnamedType:
349 /// ::= LocalVarID '=' 'type' type
350 bool LLParser::ParseUnnamedType() {
351 LocTy TypeLoc = Lex.getLoc();
352 unsigned TypeID = Lex.getUIntVal();
353 Lex.Lex(); // eat LocalVarID;
355 if (ParseToken(lltok::equal, "expected '=' after name") ||
356 ParseToken(lltok::kw_type, "expected 'type' after '='"))
359 if (TypeID >= NumberedTypes.size())
360 NumberedTypes.resize(TypeID+1);
362 Type *Result = nullptr;
363 if (ParseStructDefinition(TypeLoc, "",
364 NumberedTypes[TypeID], Result)) return true;
366 if (!isa<StructType>(Result)) {
367 std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
369 return Error(TypeLoc, "non-struct types may not be recursive");
370 Entry.first = Result;
371 Entry.second = SMLoc();
379 /// ::= LocalVar '=' 'type' type
380 bool LLParser::ParseNamedType() {
381 std::string Name = Lex.getStrVal();
382 LocTy NameLoc = Lex.getLoc();
383 Lex.Lex(); // eat LocalVar.
385 if (ParseToken(lltok::equal, "expected '=' after name") ||
386 ParseToken(lltok::kw_type, "expected 'type' after name"))
389 Type *Result = nullptr;
390 if (ParseStructDefinition(NameLoc, Name,
391 NamedTypes[Name], Result)) return true;
393 if (!isa<StructType>(Result)) {
394 std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
396 return Error(NameLoc, "non-struct types may not be recursive");
397 Entry.first = Result;
398 Entry.second = SMLoc();
406 /// ::= 'declare' FunctionHeader
407 bool LLParser::ParseDeclare() {
408 assert(Lex.getKind() == lltok::kw_declare);
412 return ParseFunctionHeader(F, false);
416 /// ::= 'define' FunctionHeader '{' ...
417 bool LLParser::ParseDefine() {
418 assert(Lex.getKind() == lltok::kw_define);
422 return ParseFunctionHeader(F, true) ||
423 ParseFunctionBody(*F);
429 bool LLParser::ParseGlobalType(bool &IsConstant) {
430 if (Lex.getKind() == lltok::kw_constant)
432 else if (Lex.getKind() == lltok::kw_global)
436 return TokError("expected 'global' or 'constant'");
442 /// ParseUnnamedGlobal:
443 /// OptionalVisibility ALIAS ...
444 /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
445 /// ... -> global variable
446 /// GlobalID '=' OptionalVisibility ALIAS ...
447 /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
448 /// ... -> global variable
449 bool LLParser::ParseUnnamedGlobal() {
450 unsigned VarID = NumberedVals.size();
452 LocTy NameLoc = Lex.getLoc();
454 // Handle the GlobalID form.
455 if (Lex.getKind() == lltok::GlobalID) {
456 if (Lex.getUIntVal() != VarID)
457 return Error(Lex.getLoc(), "variable expected to be numbered '%" +
459 Lex.Lex(); // eat GlobalID;
461 if (ParseToken(lltok::equal, "expected '=' after name"))
466 unsigned Linkage, Visibility, DLLStorageClass;
467 GlobalVariable::ThreadLocalMode TLM;
468 if (ParseOptionalLinkage(Linkage, HasLinkage) ||
469 ParseOptionalVisibility(Visibility) ||
470 ParseOptionalDLLStorageClass(DLLStorageClass) ||
471 ParseOptionalThreadLocal(TLM))
474 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
475 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
476 DLLStorageClass, TLM);
477 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM);
480 /// ParseNamedGlobal:
481 /// GlobalVar '=' OptionalVisibility ALIAS ...
482 /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
483 /// ... -> global variable
484 bool LLParser::ParseNamedGlobal() {
485 assert(Lex.getKind() == lltok::GlobalVar);
486 LocTy NameLoc = Lex.getLoc();
487 std::string Name = Lex.getStrVal();
491 unsigned Linkage, Visibility, DLLStorageClass;
492 GlobalVariable::ThreadLocalMode TLM;
493 if (ParseToken(lltok::equal, "expected '=' in global variable") ||
494 ParseOptionalLinkage(Linkage, HasLinkage) ||
495 ParseOptionalVisibility(Visibility) ||
496 ParseOptionalDLLStorageClass(DLLStorageClass) ||
497 ParseOptionalThreadLocal(TLM))
500 if (HasLinkage || Lex.getKind() != lltok::kw_alias)
501 return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
502 DLLStorageClass, TLM);
503 return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass, TLM);
507 // ::= '!' STRINGCONSTANT
508 bool LLParser::ParseMDString(MDString *&Result) {
510 if (ParseStringConstant(Str)) return true;
511 Result = MDString::get(Context, Str);
516 // ::= '!' MDNodeNumber
518 /// This version of ParseMDNodeID returns the slot number and null in the case
519 /// of a forward reference.
520 bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
521 // !{ ..., !42, ... }
522 if (ParseUInt32(SlotNo)) return true;
524 // Check existing MDNode.
525 if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != nullptr)
526 Result = NumberedMetadata[SlotNo];
532 bool LLParser::ParseMDNodeID(MDNode *&Result) {
533 // !{ ..., !42, ... }
535 if (ParseMDNodeID(Result, MID)) return true;
537 // If not a forward reference, just return it now.
538 if (Result) return false;
540 // Otherwise, create MDNode forward reference.
541 MDNode *FwdNode = MDNode::getTemporary(Context, None);
542 ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
544 if (NumberedMetadata.size() <= MID)
545 NumberedMetadata.resize(MID+1);
546 NumberedMetadata[MID] = FwdNode;
551 /// ParseNamedMetadata:
552 /// !foo = !{ !1, !2 }
553 bool LLParser::ParseNamedMetadata() {
554 assert(Lex.getKind() == lltok::MetadataVar);
555 std::string Name = Lex.getStrVal();
558 if (ParseToken(lltok::equal, "expected '=' here") ||
559 ParseToken(lltok::exclaim, "Expected '!' here") ||
560 ParseToken(lltok::lbrace, "Expected '{' here"))
563 NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
564 if (Lex.getKind() != lltok::rbrace)
566 if (ParseToken(lltok::exclaim, "Expected '!' here"))
570 if (ParseMDNodeID(N)) return true;
572 } while (EatIfPresent(lltok::comma));
574 if (ParseToken(lltok::rbrace, "expected end of metadata node"))
580 /// ParseStandaloneMetadata:
582 bool LLParser::ParseStandaloneMetadata() {
583 assert(Lex.getKind() == lltok::exclaim);
585 unsigned MetadataID = 0;
589 SmallVector<Value *, 16> Elts;
590 if (ParseUInt32(MetadataID) ||
591 ParseToken(lltok::equal, "expected '=' here") ||
592 ParseType(Ty, TyLoc) ||
593 ParseToken(lltok::exclaim, "Expected '!' here") ||
594 ParseToken(lltok::lbrace, "Expected '{' here") ||
595 ParseMDNodeVector(Elts, nullptr) ||
596 ParseToken(lltok::rbrace, "expected end of metadata node"))
599 MDNode *Init = MDNode::get(Context, Elts);
601 // See if this was forward referenced, if so, handle it.
602 std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
603 FI = ForwardRefMDNodes.find(MetadataID);
604 if (FI != ForwardRefMDNodes.end()) {
605 MDNode *Temp = FI->second.first;
606 Temp->replaceAllUsesWith(Init);
607 MDNode::deleteTemporary(Temp);
608 ForwardRefMDNodes.erase(FI);
610 assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
612 if (MetadataID >= NumberedMetadata.size())
613 NumberedMetadata.resize(MetadataID+1);
615 if (NumberedMetadata[MetadataID] != nullptr)
616 return TokError("Metadata id is already used");
617 NumberedMetadata[MetadataID] = Init;
623 static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
624 return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
625 (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
629 /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
630 /// OptionalLinkage Aliasee
635 /// Everything through DLL storage class has already been parsed.
637 bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
638 unsigned Visibility, unsigned DLLStorageClass,
639 GlobalVariable::ThreadLocalMode TLM) {
640 assert(Lex.getKind() == lltok::kw_alias);
642 LocTy LinkageLoc = Lex.getLoc();
644 if (ParseOptionalLinkage(L))
647 GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
649 if(!GlobalAlias::isValidLinkage(Linkage))
650 return Error(LinkageLoc, "invalid linkage type for alias");
652 if (!isValidVisibilityForLinkage(Visibility, L))
653 return Error(LinkageLoc,
654 "symbol with local linkage must have default visibility");
657 LocTy AliaseeLoc = Lex.getLoc();
658 if (Lex.getKind() != lltok::kw_bitcast &&
659 Lex.getKind() != lltok::kw_getelementptr &&
660 Lex.getKind() != lltok::kw_addrspacecast &&
661 Lex.getKind() != lltok::kw_inttoptr) {
662 if (ParseGlobalTypeAndValue(Aliasee))
665 // The bitcast dest type is not present, it is implied by the dest type.
669 if (ID.Kind != ValID::t_Constant)
670 return Error(AliaseeLoc, "invalid aliasee");
671 Aliasee = ID.ConstantVal;
674 Type *AliaseeType = Aliasee->getType();
675 auto *PTy = dyn_cast<PointerType>(AliaseeType);
677 return Error(AliaseeLoc, "An alias must have pointer type");
678 Type *Ty = PTy->getElementType();
679 unsigned AddrSpace = PTy->getAddressSpace();
681 // Okay, create the alias but do not insert it into the module yet.
682 std::unique_ptr<GlobalAlias> GA(
683 GlobalAlias::create(Ty, AddrSpace, (GlobalValue::LinkageTypes)Linkage,
684 Name, Aliasee, /*Parent*/ nullptr));
685 GA->setThreadLocalMode(TLM);
686 GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
687 GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
689 // See if this value already exists in the symbol table. If so, it is either
690 // a redefinition or a definition of a forward reference.
691 if (GlobalValue *Val = M->getNamedValue(Name)) {
692 // See if this was a redefinition. If so, there is no entry in
694 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
695 I = ForwardRefVals.find(Name);
696 if (I == ForwardRefVals.end())
697 return Error(NameLoc, "redefinition of global named '@" + Name + "'");
699 // Otherwise, this was a definition of forward ref. Verify that types
701 if (Val->getType() != GA->getType())
702 return Error(NameLoc,
703 "forward reference and definition of alias have different types");
705 // If they agree, just RAUW the old value with the alias and remove the
707 Val->replaceAllUsesWith(GA.get());
708 Val->eraseFromParent();
709 ForwardRefVals.erase(I);
712 // Insert into the module, we know its name won't collide now.
713 M->getAliasList().push_back(GA.get());
714 assert(GA->getName() == Name && "Should not be a name conflict!");
716 // The module owns this now
723 /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
724 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
725 /// OptionalExternallyInitialized GlobalType Type Const
726 /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
727 /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
728 /// OptionalExternallyInitialized GlobalType Type Const
730 /// Everything up to and including OptionalDLLStorageClass has been parsed
733 bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
734 unsigned Linkage, bool HasLinkage,
735 unsigned Visibility, unsigned DLLStorageClass,
736 GlobalVariable::ThreadLocalMode TLM) {
737 if (!isValidVisibilityForLinkage(Visibility, Linkage))
738 return Error(NameLoc,
739 "symbol with local linkage must have default visibility");
742 bool IsConstant, UnnamedAddr, IsExternallyInitialized;
743 LocTy UnnamedAddrLoc;
744 LocTy IsExternallyInitializedLoc;
748 if (ParseOptionalAddrSpace(AddrSpace) ||
749 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
751 ParseOptionalToken(lltok::kw_externally_initialized,
752 IsExternallyInitialized,
753 &IsExternallyInitializedLoc) ||
754 ParseGlobalType(IsConstant) ||
755 ParseType(Ty, TyLoc))
758 // If the linkage is specified and is external, then no initializer is
760 Constant *Init = nullptr;
761 if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
762 Linkage != GlobalValue::ExternalLinkage)) {
763 if (ParseGlobalValue(Ty, Init))
767 if (Ty->isFunctionTy() || Ty->isLabelTy())
768 return Error(TyLoc, "invalid type for global variable");
770 GlobalVariable *GV = nullptr;
772 // See if the global was forward referenced, if so, use the global.
774 if (GlobalValue *GVal = M->getNamedValue(Name)) {
775 if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
776 return Error(NameLoc, "redefinition of global '@" + Name + "'");
777 GV = cast<GlobalVariable>(GVal);
780 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
781 I = ForwardRefValIDs.find(NumberedVals.size());
782 if (I != ForwardRefValIDs.end()) {
783 GV = cast<GlobalVariable>(I->second.first);
784 ForwardRefValIDs.erase(I);
789 GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
790 Name, nullptr, GlobalVariable::NotThreadLocal,
793 if (GV->getType()->getElementType() != Ty)
795 "forward reference and definition of global have different types");
797 // Move the forward-reference to the correct spot in the module.
798 M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
802 NumberedVals.push_back(GV);
804 // Set the parsed properties on the global.
806 GV->setInitializer(Init);
807 GV->setConstant(IsConstant);
808 GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
809 GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
810 GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
811 GV->setExternallyInitialized(IsExternallyInitialized);
812 GV->setThreadLocalMode(TLM);
813 GV->setUnnamedAddr(UnnamedAddr);
815 // Parse attributes on the global.
816 while (Lex.getKind() == lltok::comma) {
819 if (Lex.getKind() == lltok::kw_section) {
821 GV->setSection(Lex.getStrVal());
822 if (ParseToken(lltok::StringConstant, "expected global section string"))
824 } else if (Lex.getKind() == lltok::kw_align) {
826 if (ParseOptionalAlignment(Alignment)) return true;
827 GV->setAlignment(Alignment);
829 TokError("unknown global variable property!");
836 /// ParseUnnamedAttrGrp
837 /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
838 bool LLParser::ParseUnnamedAttrGrp() {
839 assert(Lex.getKind() == lltok::kw_attributes);
840 LocTy AttrGrpLoc = Lex.getLoc();
843 assert(Lex.getKind() == lltok::AttrGrpID);
844 unsigned VarID = Lex.getUIntVal();
845 std::vector<unsigned> unused;
849 if (ParseToken(lltok::equal, "expected '=' here") ||
850 ParseToken(lltok::lbrace, "expected '{' here") ||
851 ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
853 ParseToken(lltok::rbrace, "expected end of attribute group"))
856 if (!NumberedAttrBuilders[VarID].hasAttributes())
857 return Error(AttrGrpLoc, "attribute group has no attributes");
862 /// ParseFnAttributeValuePairs
863 /// ::= <attr> | <attr> '=' <value>
864 bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
865 std::vector<unsigned> &FwdRefAttrGrps,
866 bool inAttrGrp, LocTy &BuiltinLoc) {
867 bool HaveError = false;
872 lltok::Kind Token = Lex.getKind();
873 if (Token == lltok::kw_builtin)
874 BuiltinLoc = Lex.getLoc();
877 if (!inAttrGrp) return HaveError;
878 return Error(Lex.getLoc(), "unterminated attribute group");
883 case lltok::AttrGrpID: {
884 // Allow a function to reference an attribute group:
886 // define void @foo() #1 { ... }
890 "cannot have an attribute group reference in an attribute group");
892 unsigned AttrGrpNum = Lex.getUIntVal();
893 if (inAttrGrp) break;
895 // Save the reference to the attribute group. We'll fill it in later.
896 FwdRefAttrGrps.push_back(AttrGrpNum);
899 // Target-dependent attributes:
900 case lltok::StringConstant: {
901 std::string Attr = Lex.getStrVal();
904 if (EatIfPresent(lltok::equal) &&
905 ParseStringConstant(Val))
908 B.addAttribute(Attr, Val);
912 // Target-independent attributes:
913 case lltok::kw_align: {
914 // As a hack, we allow function alignment to be initially parsed as an
915 // attribute on a function declaration/definition or added to an attribute
916 // group and later moved to the alignment field.
920 if (ParseToken(lltok::equal, "expected '=' here") ||
921 ParseUInt32(Alignment))
924 if (ParseOptionalAlignment(Alignment))
927 B.addAlignmentAttr(Alignment);
930 case lltok::kw_alignstack: {
934 if (ParseToken(lltok::equal, "expected '=' here") ||
935 ParseUInt32(Alignment))
938 if (ParseOptionalStackAlignment(Alignment))
941 B.addStackAlignmentAttr(Alignment);
944 case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
945 case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
946 case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
947 case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
948 case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
949 case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
950 case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
951 case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
952 case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
953 case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
954 case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
955 case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
956 case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
957 case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
958 case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
959 case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
960 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
961 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
962 case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
963 case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
964 case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
965 case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
966 case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
967 case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
968 case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
969 case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
972 case lltok::kw_inreg:
973 case lltok::kw_signext:
974 case lltok::kw_zeroext:
977 "invalid use of attribute on a function");
979 case lltok::kw_byval:
980 case lltok::kw_inalloca:
982 case lltok::kw_noalias:
983 case lltok::kw_nocapture:
984 case lltok::kw_nonnull:
985 case lltok::kw_returned:
989 "invalid use of parameter-only attribute on a function");
997 //===----------------------------------------------------------------------===//
998 // GlobalValue Reference/Resolution Routines.
999 //===----------------------------------------------------------------------===//
1001 /// GetGlobalVal - Get a value with the specified name or ID, creating a
1002 /// forward reference record if needed. This can return null if the value
1003 /// exists but does not have the right type.
1004 GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
1006 PointerType *PTy = dyn_cast<PointerType>(Ty);
1008 Error(Loc, "global variable reference must have pointer type");
1012 // Look this name up in the normal function symbol table.
1014 cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
1016 // If this is a forward reference for the value, see if we already created a
1017 // forward ref record.
1019 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
1020 I = ForwardRefVals.find(Name);
1021 if (I != ForwardRefVals.end())
1022 Val = I->second.first;
1025 // If we have the value in the symbol table or fwd-ref table, return it.
1027 if (Val->getType() == Ty) return Val;
1028 Error(Loc, "'@" + Name + "' defined with type '" +
1029 getTypeString(Val->getType()) + "'");
1033 // Otherwise, create a new forward reference for this value and remember it.
1034 GlobalValue *FwdVal;
1035 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1036 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
1038 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1039 GlobalValue::ExternalWeakLinkage, nullptr, Name,
1040 nullptr, GlobalVariable::NotThreadLocal,
1041 PTy->getAddressSpace());
1043 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
1047 GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
1048 PointerType *PTy = dyn_cast<PointerType>(Ty);
1050 Error(Loc, "global variable reference must have pointer type");
1054 GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
1056 // If this is a forward reference for the value, see if we already created a
1057 // forward ref record.
1059 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
1060 I = ForwardRefValIDs.find(ID);
1061 if (I != ForwardRefValIDs.end())
1062 Val = I->second.first;
1065 // If we have the value in the symbol table or fwd-ref table, return it.
1067 if (Val->getType() == Ty) return Val;
1068 Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
1069 getTypeString(Val->getType()) + "'");
1073 // Otherwise, create a new forward reference for this value and remember it.
1074 GlobalValue *FwdVal;
1075 if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
1076 FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
1078 FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
1079 GlobalValue::ExternalWeakLinkage, nullptr, "");
1081 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
1086 //===----------------------------------------------------------------------===//
1088 //===----------------------------------------------------------------------===//
1090 /// ParseToken - If the current token has the specified kind, eat it and return
1091 /// success. Otherwise, emit the specified error and return failure.
1092 bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
1093 if (Lex.getKind() != T)
1094 return TokError(ErrMsg);
1099 /// ParseStringConstant
1100 /// ::= StringConstant
1101 bool LLParser::ParseStringConstant(std::string &Result) {
1102 if (Lex.getKind() != lltok::StringConstant)
1103 return TokError("expected string constant");
1104 Result = Lex.getStrVal();
1111 bool LLParser::ParseUInt32(unsigned &Val) {
1112 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
1113 return TokError("expected integer");
1114 uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
1115 if (Val64 != unsigned(Val64))
1116 return TokError("expected 32-bit integer (too large)");
1123 /// := 'localdynamic'
1124 /// := 'initialexec'
1126 bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
1127 switch (Lex.getKind()) {
1129 return TokError("expected localdynamic, initialexec or localexec");
1130 case lltok::kw_localdynamic:
1131 TLM = GlobalVariable::LocalDynamicTLSModel;
1133 case lltok::kw_initialexec:
1134 TLM = GlobalVariable::InitialExecTLSModel;
1136 case lltok::kw_localexec:
1137 TLM = GlobalVariable::LocalExecTLSModel;
1145 /// ParseOptionalThreadLocal
1147 /// := 'thread_local'
1148 /// := 'thread_local' '(' tlsmodel ')'
1149 bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
1150 TLM = GlobalVariable::NotThreadLocal;
1151 if (!EatIfPresent(lltok::kw_thread_local))
1154 TLM = GlobalVariable::GeneralDynamicTLSModel;
1155 if (Lex.getKind() == lltok::lparen) {
1157 return ParseTLSModel(TLM) ||
1158 ParseToken(lltok::rparen, "expected ')' after thread local model");
1163 /// ParseOptionalAddrSpace
1165 /// := 'addrspace' '(' uint32 ')'
1166 bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
1168 if (!EatIfPresent(lltok::kw_addrspace))
1170 return ParseToken(lltok::lparen, "expected '(' in address space") ||
1171 ParseUInt32(AddrSpace) ||
1172 ParseToken(lltok::rparen, "expected ')' in address space");
1175 /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
1176 bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
1177 bool HaveError = false;
1182 lltok::Kind Token = Lex.getKind();
1184 default: // End of attributes.
1186 case lltok::kw_align: {
1188 if (ParseOptionalAlignment(Alignment))
1190 B.addAlignmentAttr(Alignment);
1193 case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
1194 case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
1195 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1196 case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
1197 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1198 case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
1199 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1200 case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
1201 case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
1202 case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
1203 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1204 case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
1205 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1207 case lltok::kw_alignstack:
1208 case lltok::kw_alwaysinline:
1209 case lltok::kw_builtin:
1210 case lltok::kw_inlinehint:
1211 case lltok::kw_minsize:
1212 case lltok::kw_naked:
1213 case lltok::kw_nobuiltin:
1214 case lltok::kw_noduplicate:
1215 case lltok::kw_noimplicitfloat:
1216 case lltok::kw_noinline:
1217 case lltok::kw_nonlazybind:
1218 case lltok::kw_noredzone:
1219 case lltok::kw_noreturn:
1220 case lltok::kw_nounwind:
1221 case lltok::kw_optnone:
1222 case lltok::kw_optsize:
1223 case lltok::kw_returns_twice:
1224 case lltok::kw_sanitize_address:
1225 case lltok::kw_sanitize_memory:
1226 case lltok::kw_sanitize_thread:
1228 case lltok::kw_sspreq:
1229 case lltok::kw_sspstrong:
1230 case lltok::kw_uwtable:
1231 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1239 /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
1240 bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
1241 bool HaveError = false;
1246 lltok::Kind Token = Lex.getKind();
1248 default: // End of attributes.
1250 case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
1251 case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
1252 case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
1253 case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
1254 case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
1257 case lltok::kw_align:
1258 case lltok::kw_byval:
1259 case lltok::kw_inalloca:
1260 case lltok::kw_nest:
1261 case lltok::kw_nocapture:
1262 case lltok::kw_returned:
1263 case lltok::kw_sret:
1264 HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
1267 case lltok::kw_alignstack:
1268 case lltok::kw_alwaysinline:
1269 case lltok::kw_builtin:
1270 case lltok::kw_cold:
1271 case lltok::kw_inlinehint:
1272 case lltok::kw_minsize:
1273 case lltok::kw_naked:
1274 case lltok::kw_nobuiltin:
1275 case lltok::kw_noduplicate:
1276 case lltok::kw_noimplicitfloat:
1277 case lltok::kw_noinline:
1278 case lltok::kw_nonlazybind:
1279 case lltok::kw_noredzone:
1280 case lltok::kw_noreturn:
1281 case lltok::kw_nounwind:
1282 case lltok::kw_optnone:
1283 case lltok::kw_optsize:
1284 case lltok::kw_returns_twice:
1285 case lltok::kw_sanitize_address:
1286 case lltok::kw_sanitize_memory:
1287 case lltok::kw_sanitize_thread:
1289 case lltok::kw_sspreq:
1290 case lltok::kw_sspstrong:
1291 case lltok::kw_uwtable:
1292 HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
1295 case lltok::kw_readnone:
1296 case lltok::kw_readonly:
1297 HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
1304 /// ParseOptionalLinkage
1311 /// ::= 'linkonce_odr'
1312 /// ::= 'available_externally'
1315 /// ::= 'extern_weak'
1318 /// Deprecated Values:
1319 /// ::= 'linker_private'
1320 /// ::= 'linker_private_weak'
1321 bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
1323 switch (Lex.getKind()) {
1324 default: Res=GlobalValue::ExternalLinkage; return false;
1325 case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
1326 case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
1327 case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
1328 case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
1329 case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
1330 case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
1331 case lltok::kw_available_externally:
1332 Res = GlobalValue::AvailableExternallyLinkage;
1334 case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
1335 case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
1336 case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
1337 case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
1339 case lltok::kw_linker_private:
1340 case lltok::kw_linker_private_weak:
1341 Lex.Warning("'" + Lex.getStrVal() + "' is deprecated, treating as"
1344 // treat linker_private and linker_private_weak as PrivateLinkage
1345 Res = GlobalValue::PrivateLinkage;
1353 /// ParseOptionalVisibility
1359 bool LLParser::ParseOptionalVisibility(unsigned &Res) {
1360 switch (Lex.getKind()) {
1361 default: Res = GlobalValue::DefaultVisibility; return false;
1362 case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
1363 case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
1364 case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
1370 /// ParseOptionalDLLStorageClass
1375 bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
1376 switch (Lex.getKind()) {
1377 default: Res = GlobalValue::DefaultStorageClass; return false;
1378 case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
1379 case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
1385 /// ParseOptionalCallingConv
1389 /// ::= 'kw_intel_ocl_bicc'
1391 /// ::= 'x86_stdcallcc'
1392 /// ::= 'x86_fastcallcc'
1393 /// ::= 'x86_thiscallcc'
1394 /// ::= 'arm_apcscc'
1395 /// ::= 'arm_aapcscc'
1396 /// ::= 'arm_aapcs_vfpcc'
1397 /// ::= 'msp430_intrcc'
1398 /// ::= 'ptx_kernel'
1399 /// ::= 'ptx_device'
1401 /// ::= 'spir_kernel'
1402 /// ::= 'x86_64_sysvcc'
1403 /// ::= 'x86_64_win64cc'
1404 /// ::= 'webkit_jscc'
1406 /// ::= 'preserve_mostcc'
1407 /// ::= 'preserve_allcc'
1410 bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
1411 switch (Lex.getKind()) {
1412 default: CC = CallingConv::C; return false;
1413 case lltok::kw_ccc: CC = CallingConv::C; break;
1414 case lltok::kw_fastcc: CC = CallingConv::Fast; break;
1415 case lltok::kw_coldcc: CC = CallingConv::Cold; break;
1416 case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
1417 case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
1418 case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
1419 case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
1420 case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
1421 case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
1422 case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
1423 case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
1424 case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
1425 case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
1426 case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
1427 case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
1428 case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
1429 case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
1430 case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
1431 case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
1432 case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
1433 case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
1434 case lltok::kw_cc: {
1435 unsigned ArbitraryCC;
1437 if (ParseUInt32(ArbitraryCC))
1439 CC = static_cast<CallingConv::ID>(ArbitraryCC);
1448 /// ParseInstructionMetadata
1449 /// ::= !dbg !42 (',' !dbg !57)*
1450 bool LLParser::ParseInstructionMetadata(Instruction *Inst,
1451 PerFunctionState *PFS) {
1453 if (Lex.getKind() != lltok::MetadataVar)
1454 return TokError("expected metadata after comma");
1456 std::string Name = Lex.getStrVal();
1457 unsigned MDK = M->getMDKindID(Name);
1461 SMLoc Loc = Lex.getLoc();
1463 if (ParseToken(lltok::exclaim, "expected '!' here"))
1466 // This code is similar to that of ParseMetadataValue, however it needs to
1467 // have special-case code for a forward reference; see the comments on
1468 // ForwardRefInstMetadata for details. Also, MDStrings are not supported
1469 // at the top level here.
1470 if (Lex.getKind() == lltok::lbrace) {
1472 if (ParseMetadataListValue(ID, PFS))
1474 assert(ID.Kind == ValID::t_MDNode);
1475 Inst->setMetadata(MDK, ID.MDNodeVal);
1477 unsigned NodeID = 0;
1478 if (ParseMDNodeID(Node, NodeID))
1481 // If we got the node, add it to the instruction.
1482 Inst->setMetadata(MDK, Node);
1484 MDRef R = { Loc, MDK, NodeID };
1485 // Otherwise, remember that this should be resolved later.
1486 ForwardRefInstMetadata[Inst].push_back(R);
1490 if (MDK == LLVMContext::MD_tbaa)
1491 InstsWithTBAATag.push_back(Inst);
1493 // If this is the end of the list, we're done.
1494 } while (EatIfPresent(lltok::comma));
1498 /// ParseOptionalAlignment
1501 bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
1503 if (!EatIfPresent(lltok::kw_align))
1505 LocTy AlignLoc = Lex.getLoc();
1506 if (ParseUInt32(Alignment)) return true;
1507 if (!isPowerOf2_32(Alignment))
1508 return Error(AlignLoc, "alignment is not a power of two");
1509 if (Alignment > Value::MaximumAlignment)
1510 return Error(AlignLoc, "huge alignments are not supported yet");
1514 /// ParseOptionalCommaAlign
1518 /// This returns with AteExtraComma set to true if it ate an excess comma at the
1520 bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
1521 bool &AteExtraComma) {
1522 AteExtraComma = false;
1523 while (EatIfPresent(lltok::comma)) {
1524 // Metadata at the end is an early exit.
1525 if (Lex.getKind() == lltok::MetadataVar) {
1526 AteExtraComma = true;
1530 if (Lex.getKind() != lltok::kw_align)
1531 return Error(Lex.getLoc(), "expected metadata or 'align'");
1533 if (ParseOptionalAlignment(Alignment)) return true;
1539 /// ParseScopeAndOrdering
1540 /// if isAtomic: ::= 'singlethread'? AtomicOrdering
1543 /// This sets Scope and Ordering to the parsed values.
1544 bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
1545 AtomicOrdering &Ordering) {
1549 Scope = CrossThread;
1550 if (EatIfPresent(lltok::kw_singlethread))
1551 Scope = SingleThread;
1553 return ParseOrdering(Ordering);
1557 /// ::= AtomicOrdering
1559 /// This sets Ordering to the parsed value.
1560 bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
1561 switch (Lex.getKind()) {
1562 default: return TokError("Expected ordering on atomic instruction");
1563 case lltok::kw_unordered: Ordering = Unordered; break;
1564 case lltok::kw_monotonic: Ordering = Monotonic; break;
1565 case lltok::kw_acquire: Ordering = Acquire; break;
1566 case lltok::kw_release: Ordering = Release; break;
1567 case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
1568 case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
1574 /// ParseOptionalStackAlignment
1576 /// ::= 'alignstack' '(' 4 ')'
1577 bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
1579 if (!EatIfPresent(lltok::kw_alignstack))
1581 LocTy ParenLoc = Lex.getLoc();
1582 if (!EatIfPresent(lltok::lparen))
1583 return Error(ParenLoc, "expected '('");
1584 LocTy AlignLoc = Lex.getLoc();
1585 if (ParseUInt32(Alignment)) return true;
1586 ParenLoc = Lex.getLoc();
1587 if (!EatIfPresent(lltok::rparen))
1588 return Error(ParenLoc, "expected ')'");
1589 if (!isPowerOf2_32(Alignment))
1590 return Error(AlignLoc, "stack alignment is not a power of two");
1594 /// ParseIndexList - This parses the index list for an insert/extractvalue
1595 /// instruction. This sets AteExtraComma in the case where we eat an extra
1596 /// comma at the end of the line and find that it is followed by metadata.
1597 /// Clients that don't allow metadata can call the version of this function that
1598 /// only takes one argument.
1601 /// ::= (',' uint32)+
1603 bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
1604 bool &AteExtraComma) {
1605 AteExtraComma = false;
1607 if (Lex.getKind() != lltok::comma)
1608 return TokError("expected ',' as start of index list");
1610 while (EatIfPresent(lltok::comma)) {
1611 if (Lex.getKind() == lltok::MetadataVar) {
1612 AteExtraComma = true;
1616 if (ParseUInt32(Idx)) return true;
1617 Indices.push_back(Idx);
1623 //===----------------------------------------------------------------------===//
1625 //===----------------------------------------------------------------------===//
1627 /// ParseType - Parse a type.
1628 bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
1629 SMLoc TypeLoc = Lex.getLoc();
1630 switch (Lex.getKind()) {
1632 return TokError("expected type");
1634 // Type ::= 'float' | 'void' (etc)
1635 Result = Lex.getTyVal();
1639 // Type ::= StructType
1640 if (ParseAnonStructType(Result, false))
1643 case lltok::lsquare:
1644 // Type ::= '[' ... ']'
1645 Lex.Lex(); // eat the lsquare.
1646 if (ParseArrayVectorType(Result, false))
1649 case lltok::less: // Either vector or packed struct.
1650 // Type ::= '<' ... '>'
1652 if (Lex.getKind() == lltok::lbrace) {
1653 if (ParseAnonStructType(Result, true) ||
1654 ParseToken(lltok::greater, "expected '>' at end of packed struct"))
1656 } else if (ParseArrayVectorType(Result, true))
1659 case lltok::LocalVar: {
1661 std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
1663 // If the type hasn't been defined yet, create a forward definition and
1664 // remember where that forward def'n was seen (in case it never is defined).
1666 Entry.first = StructType::create(Context, Lex.getStrVal());
1667 Entry.second = Lex.getLoc();
1669 Result = Entry.first;
1674 case lltok::LocalVarID: {
1676 if (Lex.getUIntVal() >= NumberedTypes.size())
1677 NumberedTypes.resize(Lex.getUIntVal()+1);
1678 std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
1680 // If the type hasn't been defined yet, create a forward definition and
1681 // remember where that forward def'n was seen (in case it never is defined).
1683 Entry.first = StructType::create(Context);
1684 Entry.second = Lex.getLoc();
1686 Result = Entry.first;
1692 // Parse the type suffixes.
1694 switch (Lex.getKind()) {
1697 if (!AllowVoid && Result->isVoidTy())
1698 return Error(TypeLoc, "void type only allowed for function results");
1701 // Type ::= Type '*'
1703 if (Result->isLabelTy())
1704 return TokError("basic block pointers are invalid");
1705 if (Result->isVoidTy())
1706 return TokError("pointers to void are invalid - use i8* instead");
1707 if (!PointerType::isValidElementType(Result))
1708 return TokError("pointer to this type is invalid");
1709 Result = PointerType::getUnqual(Result);
1713 // Type ::= Type 'addrspace' '(' uint32 ')' '*'
1714 case lltok::kw_addrspace: {
1715 if (Result->isLabelTy())
1716 return TokError("basic block pointers are invalid");
1717 if (Result->isVoidTy())
1718 return TokError("pointers to void are invalid; use i8* instead");
1719 if (!PointerType::isValidElementType(Result))
1720 return TokError("pointer to this type is invalid");
1722 if (ParseOptionalAddrSpace(AddrSpace) ||
1723 ParseToken(lltok::star, "expected '*' in address space"))
1726 Result = PointerType::get(Result, AddrSpace);
1730 /// Types '(' ArgTypeListI ')' OptFuncAttrs
1732 if (ParseFunctionType(Result))
1739 /// ParseParameterList
1741 /// ::= '(' Arg (',' Arg)* ')'
1743 /// ::= Type OptionalAttributes Value OptionalAttributes
1744 bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
1745 PerFunctionState &PFS) {
1746 if (ParseToken(lltok::lparen, "expected '(' in call"))
1749 unsigned AttrIndex = 1;
1750 while (Lex.getKind() != lltok::rparen) {
1751 // If this isn't the first argument, we need a comma.
1752 if (!ArgList.empty() &&
1753 ParseToken(lltok::comma, "expected ',' in argument list"))
1756 // Parse the argument.
1758 Type *ArgTy = nullptr;
1759 AttrBuilder ArgAttrs;
1761 if (ParseType(ArgTy, ArgLoc))
1764 // Otherwise, handle normal operands.
1765 if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
1767 ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
1772 Lex.Lex(); // Lex the ')'.
1778 /// ParseArgumentList - Parse the argument list for a function type or function
1780 /// ::= '(' ArgTypeListI ')'
1784 /// ::= ArgTypeList ',' '...'
1785 /// ::= ArgType (',' ArgType)*
1787 bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
1790 assert(Lex.getKind() == lltok::lparen);
1791 Lex.Lex(); // eat the (.
1793 if (Lex.getKind() == lltok::rparen) {
1795 } else if (Lex.getKind() == lltok::dotdotdot) {
1799 LocTy TypeLoc = Lex.getLoc();
1800 Type *ArgTy = nullptr;
1804 if (ParseType(ArgTy) ||
1805 ParseOptionalParamAttrs(Attrs)) return true;
1807 if (ArgTy->isVoidTy())
1808 return Error(TypeLoc, "argument can not have void type");
1810 if (Lex.getKind() == lltok::LocalVar) {
1811 Name = Lex.getStrVal();
1815 if (!FunctionType::isValidArgumentType(ArgTy))
1816 return Error(TypeLoc, "invalid type for function argument");
1818 unsigned AttrIndex = 1;
1819 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1820 AttributeSet::get(ArgTy->getContext(),
1821 AttrIndex++, Attrs), Name));
1823 while (EatIfPresent(lltok::comma)) {
1824 // Handle ... at end of arg list.
1825 if (EatIfPresent(lltok::dotdotdot)) {
1830 // Otherwise must be an argument type.
1831 TypeLoc = Lex.getLoc();
1832 if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
1834 if (ArgTy->isVoidTy())
1835 return Error(TypeLoc, "argument can not have void type");
1837 if (Lex.getKind() == lltok::LocalVar) {
1838 Name = Lex.getStrVal();
1844 if (!ArgTy->isFirstClassType())
1845 return Error(TypeLoc, "invalid type for function argument");
1847 ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
1848 AttributeSet::get(ArgTy->getContext(),
1849 AttrIndex++, Attrs),
1854 return ParseToken(lltok::rparen, "expected ')' at end of argument list");
1857 /// ParseFunctionType
1858 /// ::= Type ArgumentList OptionalAttrs
1859 bool LLParser::ParseFunctionType(Type *&Result) {
1860 assert(Lex.getKind() == lltok::lparen);
1862 if (!FunctionType::isValidReturnType(Result))
1863 return TokError("invalid function return type");
1865 SmallVector<ArgInfo, 8> ArgList;
1867 if (ParseArgumentList(ArgList, isVarArg))
1870 // Reject names on the arguments lists.
1871 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
1872 if (!ArgList[i].Name.empty())
1873 return Error(ArgList[i].Loc, "argument name invalid in function type");
1874 if (ArgList[i].Attrs.hasAttributes(i + 1))
1875 return Error(ArgList[i].Loc,
1876 "argument attributes invalid in function type");
1879 SmallVector<Type*, 16> ArgListTy;
1880 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
1881 ArgListTy.push_back(ArgList[i].Ty);
1883 Result = FunctionType::get(Result, ArgListTy, isVarArg);
1887 /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
1889 bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
1890 SmallVector<Type*, 8> Elts;
1891 if (ParseStructBody(Elts)) return true;
1893 Result = StructType::get(Context, Elts, Packed);
1897 /// ParseStructDefinition - Parse a struct in a 'type' definition.
1898 bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
1899 std::pair<Type*, LocTy> &Entry,
1901 // If the type was already defined, diagnose the redefinition.
1902 if (Entry.first && !Entry.second.isValid())
1903 return Error(TypeLoc, "redefinition of type");
1905 // If we have opaque, just return without filling in the definition for the
1906 // struct. This counts as a definition as far as the .ll file goes.
1907 if (EatIfPresent(lltok::kw_opaque)) {
1908 // This type is being defined, so clear the location to indicate this.
1909 Entry.second = SMLoc();
1911 // If this type number has never been uttered, create it.
1913 Entry.first = StructType::create(Context, Name);
1914 ResultTy = Entry.first;
1918 // If the type starts with '<', then it is either a packed struct or a vector.
1919 bool isPacked = EatIfPresent(lltok::less);
1921 // If we don't have a struct, then we have a random type alias, which we
1922 // accept for compatibility with old files. These types are not allowed to be
1923 // forward referenced and not allowed to be recursive.
1924 if (Lex.getKind() != lltok::lbrace) {
1926 return Error(TypeLoc, "forward references to non-struct type");
1930 return ParseArrayVectorType(ResultTy, true);
1931 return ParseType(ResultTy);
1934 // This type is being defined, so clear the location to indicate this.
1935 Entry.second = SMLoc();
1937 // If this type number has never been uttered, create it.
1939 Entry.first = StructType::create(Context, Name);
1941 StructType *STy = cast<StructType>(Entry.first);
1943 SmallVector<Type*, 8> Body;
1944 if (ParseStructBody(Body) ||
1945 (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
1948 STy->setBody(Body, isPacked);
1954 /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
1957 /// ::= '{' Type (',' Type)* '}'
1958 /// ::= '<' '{' '}' '>'
1959 /// ::= '<' '{' Type (',' Type)* '}' '>'
1960 bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
1961 assert(Lex.getKind() == lltok::lbrace);
1962 Lex.Lex(); // Consume the '{'
1964 // Handle the empty struct.
1965 if (EatIfPresent(lltok::rbrace))
1968 LocTy EltTyLoc = Lex.getLoc();
1970 if (ParseType(Ty)) return true;
1973 if (!StructType::isValidElementType(Ty))
1974 return Error(EltTyLoc, "invalid element type for struct");
1976 while (EatIfPresent(lltok::comma)) {
1977 EltTyLoc = Lex.getLoc();
1978 if (ParseType(Ty)) return true;
1980 if (!StructType::isValidElementType(Ty))
1981 return Error(EltTyLoc, "invalid element type for struct");
1986 return ParseToken(lltok::rbrace, "expected '}' at end of struct");
1989 /// ParseArrayVectorType - Parse an array or vector type, assuming the first
1990 /// token has already been consumed.
1992 /// ::= '[' APSINTVAL 'x' Types ']'
1993 /// ::= '<' APSINTVAL 'x' Types '>'
1994 bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
1995 if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
1996 Lex.getAPSIntVal().getBitWidth() > 64)
1997 return TokError("expected number in address space");
1999 LocTy SizeLoc = Lex.getLoc();
2000 uint64_t Size = Lex.getAPSIntVal().getZExtValue();
2003 if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
2006 LocTy TypeLoc = Lex.getLoc();
2007 Type *EltTy = nullptr;
2008 if (ParseType(EltTy)) return true;
2010 if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
2011 "expected end of sequential type"))
2016 return Error(SizeLoc, "zero element vector is illegal");
2017 if ((unsigned)Size != Size)
2018 return Error(SizeLoc, "size too large for vector");
2019 if (!VectorType::isValidElementType(EltTy))
2020 return Error(TypeLoc, "invalid vector element type");
2021 Result = VectorType::get(EltTy, unsigned(Size));
2023 if (!ArrayType::isValidElementType(EltTy))
2024 return Error(TypeLoc, "invalid array element type");
2025 Result = ArrayType::get(EltTy, Size);
2030 //===----------------------------------------------------------------------===//
2031 // Function Semantic Analysis.
2032 //===----------------------------------------------------------------------===//
2034 LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
2036 : P(p), F(f), FunctionNumber(functionNumber) {
2038 // Insert unnamed arguments into the NumberedVals list.
2039 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2042 NumberedVals.push_back(AI);
2045 LLParser::PerFunctionState::~PerFunctionState() {
2046 // If there were any forward referenced non-basicblock values, delete them.
2047 for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
2048 I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
2049 if (!isa<BasicBlock>(I->second.first)) {
2050 I->second.first->replaceAllUsesWith(
2051 UndefValue::get(I->second.first->getType()));
2052 delete I->second.first;
2053 I->second.first = nullptr;
2056 for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2057 I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
2058 if (!isa<BasicBlock>(I->second.first)) {
2059 I->second.first->replaceAllUsesWith(
2060 UndefValue::get(I->second.first->getType()));
2061 delete I->second.first;
2062 I->second.first = nullptr;
2066 bool LLParser::PerFunctionState::FinishFunction() {
2067 // Check to see if someone took the address of labels in this block.
2068 if (!P.ForwardRefBlockAddresses.empty()) {
2070 if (!F.getName().empty()) {
2071 FunctionID.Kind = ValID::t_GlobalName;
2072 FunctionID.StrVal = F.getName();
2074 FunctionID.Kind = ValID::t_GlobalID;
2075 FunctionID.UIntVal = FunctionNumber;
2078 std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
2079 FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
2080 if (FRBAI != P.ForwardRefBlockAddresses.end()) {
2081 // Resolve all these references.
2082 if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
2085 P.ForwardRefBlockAddresses.erase(FRBAI);
2089 if (!ForwardRefVals.empty())
2090 return P.Error(ForwardRefVals.begin()->second.second,
2091 "use of undefined value '%" + ForwardRefVals.begin()->first +
2093 if (!ForwardRefValIDs.empty())
2094 return P.Error(ForwardRefValIDs.begin()->second.second,
2095 "use of undefined value '%" +
2096 Twine(ForwardRefValIDs.begin()->first) + "'");
2101 /// GetVal - Get a value with the specified name or ID, creating a
2102 /// forward reference record if needed. This can return null if the value
2103 /// exists but does not have the right type.
2104 Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
2105 Type *Ty, LocTy Loc) {
2106 // Look this name up in the normal function symbol table.
2107 Value *Val = F.getValueSymbolTable().lookup(Name);
2109 // If this is a forward reference for the value, see if we already created a
2110 // forward ref record.
2112 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2113 I = ForwardRefVals.find(Name);
2114 if (I != ForwardRefVals.end())
2115 Val = I->second.first;
2118 // If we have the value in the symbol table or fwd-ref table, return it.
2120 if (Val->getType() == Ty) return Val;
2121 if (Ty->isLabelTy())
2122 P.Error(Loc, "'%" + Name + "' is not a basic block");
2124 P.Error(Loc, "'%" + Name + "' defined with type '" +
2125 getTypeString(Val->getType()) + "'");
2129 // Don't make placeholders with invalid type.
2130 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2131 P.Error(Loc, "invalid use of a non-first-class type");
2135 // Otherwise, create a new forward reference for this value and remember it.
2137 if (Ty->isLabelTy())
2138 FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
2140 FwdVal = new Argument(Ty, Name);
2142 ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
2146 Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
2148 // Look this name up in the normal function symbol table.
2149 Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
2151 // If this is a forward reference for the value, see if we already created a
2152 // forward ref record.
2154 std::map<unsigned, std::pair<Value*, LocTy> >::iterator
2155 I = ForwardRefValIDs.find(ID);
2156 if (I != ForwardRefValIDs.end())
2157 Val = I->second.first;
2160 // If we have the value in the symbol table or fwd-ref table, return it.
2162 if (Val->getType() == Ty) return Val;
2163 if (Ty->isLabelTy())
2164 P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
2166 P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
2167 getTypeString(Val->getType()) + "'");
2171 if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
2172 P.Error(Loc, "invalid use of a non-first-class type");
2176 // Otherwise, create a new forward reference for this value and remember it.
2178 if (Ty->isLabelTy())
2179 FwdVal = BasicBlock::Create(F.getContext(), "", &F);
2181 FwdVal = new Argument(Ty);
2183 ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
2187 /// SetInstName - After an instruction is parsed and inserted into its
2188 /// basic block, this installs its name.
2189 bool LLParser::PerFunctionState::SetInstName(int NameID,
2190 const std::string &NameStr,
2191 LocTy NameLoc, Instruction *Inst) {
2192 // If this instruction has void type, it cannot have a name or ID specified.
2193 if (Inst->getType()->isVoidTy()) {
2194 if (NameID != -1 || !NameStr.empty())
2195 return P.Error(NameLoc, "instructions returning void cannot have a name");
2199 // If this was a numbered instruction, verify that the instruction is the
2200 // expected value and resolve any forward references.
2201 if (NameStr.empty()) {
2202 // If neither a name nor an ID was specified, just use the next ID.
2204 NameID = NumberedVals.size();
2206 if (unsigned(NameID) != NumberedVals.size())
2207 return P.Error(NameLoc, "instruction expected to be numbered '%" +
2208 Twine(NumberedVals.size()) + "'");
2210 std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
2211 ForwardRefValIDs.find(NameID);
2212 if (FI != ForwardRefValIDs.end()) {
2213 if (FI->second.first->getType() != Inst->getType())
2214 return P.Error(NameLoc, "instruction forward referenced with type '" +
2215 getTypeString(FI->second.first->getType()) + "'");
2216 FI->second.first->replaceAllUsesWith(Inst);
2217 delete FI->second.first;
2218 ForwardRefValIDs.erase(FI);
2221 NumberedVals.push_back(Inst);
2225 // Otherwise, the instruction had a name. Resolve forward refs and set it.
2226 std::map<std::string, std::pair<Value*, LocTy> >::iterator
2227 FI = ForwardRefVals.find(NameStr);
2228 if (FI != ForwardRefVals.end()) {
2229 if (FI->second.first->getType() != Inst->getType())
2230 return P.Error(NameLoc, "instruction forward referenced with type '" +
2231 getTypeString(FI->second.first->getType()) + "'");
2232 FI->second.first->replaceAllUsesWith(Inst);
2233 delete FI->second.first;
2234 ForwardRefVals.erase(FI);
2237 // Set the name on the instruction.
2238 Inst->setName(NameStr);
2240 if (Inst->getName() != NameStr)
2241 return P.Error(NameLoc, "multiple definition of local value named '" +
2246 /// GetBB - Get a basic block with the specified name or ID, creating a
2247 /// forward reference record if needed.
2248 BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
2250 return cast_or_null<BasicBlock>(GetVal(Name,
2251 Type::getLabelTy(F.getContext()), Loc));
2254 BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
2255 return cast_or_null<BasicBlock>(GetVal(ID,
2256 Type::getLabelTy(F.getContext()), Loc));
2259 /// DefineBB - Define the specified basic block, which is either named or
2260 /// unnamed. If there is an error, this returns null otherwise it returns
2261 /// the block being defined.
2262 BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
2266 BB = GetBB(NumberedVals.size(), Loc);
2268 BB = GetBB(Name, Loc);
2269 if (!BB) return nullptr; // Already diagnosed error.
2271 // Move the block to the end of the function. Forward ref'd blocks are
2272 // inserted wherever they happen to be referenced.
2273 F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
2275 // Remove the block from forward ref sets.
2277 ForwardRefValIDs.erase(NumberedVals.size());
2278 NumberedVals.push_back(BB);
2280 // BB forward references are already in the function symbol table.
2281 ForwardRefVals.erase(Name);
2287 //===----------------------------------------------------------------------===//
2289 //===----------------------------------------------------------------------===//
2291 /// ParseValID - Parse an abstract value that doesn't necessarily have a
2292 /// type implied. For example, if we parse "4" we don't know what integer type
2293 /// it has. The value will later be combined with its type and checked for
2294 /// sanity. PFS is used to convert function-local operands of metadata (since
2295 /// metadata operands are not just parsed here but also converted to values).
2296 /// PFS can be null when we are not parsing metadata values inside a function.
2297 bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
2298 ID.Loc = Lex.getLoc();
2299 switch (Lex.getKind()) {
2300 default: return TokError("expected value token");
2301 case lltok::GlobalID: // @42
2302 ID.UIntVal = Lex.getUIntVal();
2303 ID.Kind = ValID::t_GlobalID;
2305 case lltok::GlobalVar: // @foo
2306 ID.StrVal = Lex.getStrVal();
2307 ID.Kind = ValID::t_GlobalName;
2309 case lltok::LocalVarID: // %42
2310 ID.UIntVal = Lex.getUIntVal();
2311 ID.Kind = ValID::t_LocalID;
2313 case lltok::LocalVar: // %foo
2314 ID.StrVal = Lex.getStrVal();
2315 ID.Kind = ValID::t_LocalName;
2317 case lltok::exclaim: // !42, !{...}, or !"foo"
2318 return ParseMetadataValue(ID, PFS);
2320 ID.APSIntVal = Lex.getAPSIntVal();
2321 ID.Kind = ValID::t_APSInt;
2323 case lltok::APFloat:
2324 ID.APFloatVal = Lex.getAPFloatVal();
2325 ID.Kind = ValID::t_APFloat;
2327 case lltok::kw_true:
2328 ID.ConstantVal = ConstantInt::getTrue(Context);
2329 ID.Kind = ValID::t_Constant;
2331 case lltok::kw_false:
2332 ID.ConstantVal = ConstantInt::getFalse(Context);
2333 ID.Kind = ValID::t_Constant;
2335 case lltok::kw_null: ID.Kind = ValID::t_Null; break;
2336 case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
2337 case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
2339 case lltok::lbrace: {
2340 // ValID ::= '{' ConstVector '}'
2342 SmallVector<Constant*, 16> Elts;
2343 if (ParseGlobalValueVector(Elts) ||
2344 ParseToken(lltok::rbrace, "expected end of struct constant"))
2347 ID.ConstantStructElts = new Constant*[Elts.size()];
2348 ID.UIntVal = Elts.size();
2349 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2350 ID.Kind = ValID::t_ConstantStruct;
2354 // ValID ::= '<' ConstVector '>' --> Vector.
2355 // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
2357 bool isPackedStruct = EatIfPresent(lltok::lbrace);
2359 SmallVector<Constant*, 16> Elts;
2360 LocTy FirstEltLoc = Lex.getLoc();
2361 if (ParseGlobalValueVector(Elts) ||
2363 ParseToken(lltok::rbrace, "expected end of packed struct")) ||
2364 ParseToken(lltok::greater, "expected end of constant"))
2367 if (isPackedStruct) {
2368 ID.ConstantStructElts = new Constant*[Elts.size()];
2369 memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
2370 ID.UIntVal = Elts.size();
2371 ID.Kind = ValID::t_PackedConstantStruct;
2376 return Error(ID.Loc, "constant vector must not be empty");
2378 if (!Elts[0]->getType()->isIntegerTy() &&
2379 !Elts[0]->getType()->isFloatingPointTy() &&
2380 !Elts[0]->getType()->isPointerTy())
2381 return Error(FirstEltLoc,
2382 "vector elements must have integer, pointer or floating point type");
2384 // Verify that all the vector elements have the same type.
2385 for (unsigned i = 1, e = Elts.size(); i != e; ++i)
2386 if (Elts[i]->getType() != Elts[0]->getType())
2387 return Error(FirstEltLoc,
2388 "vector element #" + Twine(i) +
2389 " is not of type '" + getTypeString(Elts[0]->getType()));
2391 ID.ConstantVal = ConstantVector::get(Elts);
2392 ID.Kind = ValID::t_Constant;
2395 case lltok::lsquare: { // Array Constant
2397 SmallVector<Constant*, 16> Elts;
2398 LocTy FirstEltLoc = Lex.getLoc();
2399 if (ParseGlobalValueVector(Elts) ||
2400 ParseToken(lltok::rsquare, "expected end of array constant"))
2403 // Handle empty element.
2405 // Use undef instead of an array because it's inconvenient to determine
2406 // the element type at this point, there being no elements to examine.
2407 ID.Kind = ValID::t_EmptyArray;
2411 if (!Elts[0]->getType()->isFirstClassType())
2412 return Error(FirstEltLoc, "invalid array element type: " +
2413 getTypeString(Elts[0]->getType()));
2415 ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
2417 // Verify all elements are correct type!
2418 for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
2419 if (Elts[i]->getType() != Elts[0]->getType())
2420 return Error(FirstEltLoc,
2421 "array element #" + Twine(i) +
2422 " is not of type '" + getTypeString(Elts[0]->getType()));
2425 ID.ConstantVal = ConstantArray::get(ATy, Elts);
2426 ID.Kind = ValID::t_Constant;
2429 case lltok::kw_c: // c "foo"
2431 ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
2433 if (ParseToken(lltok::StringConstant, "expected string")) return true;
2434 ID.Kind = ValID::t_Constant;
2437 case lltok::kw_asm: {
2438 // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
2440 bool HasSideEffect, AlignStack, AsmDialect;
2442 if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
2443 ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
2444 ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
2445 ParseStringConstant(ID.StrVal) ||
2446 ParseToken(lltok::comma, "expected comma in inline asm expression") ||
2447 ParseToken(lltok::StringConstant, "expected constraint string"))
2449 ID.StrVal2 = Lex.getStrVal();
2450 ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
2451 (unsigned(AsmDialect)<<2);
2452 ID.Kind = ValID::t_InlineAsm;
2456 case lltok::kw_blockaddress: {
2457 // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
2462 if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
2464 ParseToken(lltok::comma, "expected comma in block address expression")||
2465 ParseValID(Label) ||
2466 ParseToken(lltok::rparen, "expected ')' in block address expression"))
2469 if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
2470 return Error(Fn.Loc, "expected function name in blockaddress");
2471 if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
2472 return Error(Label.Loc, "expected basic block name in blockaddress");
2474 // Make a global variable as a placeholder for this reference.
2475 GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
2476 false, GlobalValue::InternalLinkage,
2478 ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
2479 ID.ConstantVal = FwdRef;
2480 ID.Kind = ValID::t_Constant;
2484 case lltok::kw_trunc:
2485 case lltok::kw_zext:
2486 case lltok::kw_sext:
2487 case lltok::kw_fptrunc:
2488 case lltok::kw_fpext:
2489 case lltok::kw_bitcast:
2490 case lltok::kw_addrspacecast:
2491 case lltok::kw_uitofp:
2492 case lltok::kw_sitofp:
2493 case lltok::kw_fptoui:
2494 case lltok::kw_fptosi:
2495 case lltok::kw_inttoptr:
2496 case lltok::kw_ptrtoint: {
2497 unsigned Opc = Lex.getUIntVal();
2498 Type *DestTy = nullptr;
2501 if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
2502 ParseGlobalTypeAndValue(SrcVal) ||
2503 ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
2504 ParseType(DestTy) ||
2505 ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
2507 if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
2508 return Error(ID.Loc, "invalid cast opcode for cast from '" +
2509 getTypeString(SrcVal->getType()) + "' to '" +
2510 getTypeString(DestTy) + "'");
2511 ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
2513 ID.Kind = ValID::t_Constant;
2516 case lltok::kw_extractvalue: {
2519 SmallVector<unsigned, 4> Indices;
2520 if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
2521 ParseGlobalTypeAndValue(Val) ||
2522 ParseIndexList(Indices) ||
2523 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
2526 if (!Val->getType()->isAggregateType())
2527 return Error(ID.Loc, "extractvalue operand must be aggregate type");
2528 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
2529 return Error(ID.Loc, "invalid indices for extractvalue");
2530 ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
2531 ID.Kind = ValID::t_Constant;
2534 case lltok::kw_insertvalue: {
2536 Constant *Val0, *Val1;
2537 SmallVector<unsigned, 4> Indices;
2538 if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
2539 ParseGlobalTypeAndValue(Val0) ||
2540 ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
2541 ParseGlobalTypeAndValue(Val1) ||
2542 ParseIndexList(Indices) ||
2543 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
2545 if (!Val0->getType()->isAggregateType())
2546 return Error(ID.Loc, "insertvalue operand must be aggregate type");
2547 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
2548 return Error(ID.Loc, "invalid indices for insertvalue");
2549 ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
2550 ID.Kind = ValID::t_Constant;
2553 case lltok::kw_icmp:
2554 case lltok::kw_fcmp: {
2555 unsigned PredVal, Opc = Lex.getUIntVal();
2556 Constant *Val0, *Val1;
2558 if (ParseCmpPredicate(PredVal, Opc) ||
2559 ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
2560 ParseGlobalTypeAndValue(Val0) ||
2561 ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
2562 ParseGlobalTypeAndValue(Val1) ||
2563 ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
2566 if (Val0->getType() != Val1->getType())
2567 return Error(ID.Loc, "compare operands must have the same type");
2569 CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
2571 if (Opc == Instruction::FCmp) {
2572 if (!Val0->getType()->isFPOrFPVectorTy())
2573 return Error(ID.Loc, "fcmp requires floating point operands");
2574 ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
2576 assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
2577 if (!Val0->getType()->isIntOrIntVectorTy() &&
2578 !Val0->getType()->getScalarType()->isPointerTy())
2579 return Error(ID.Loc, "icmp requires pointer or integer operands");
2580 ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
2582 ID.Kind = ValID::t_Constant;
2586 // Binary Operators.
2588 case lltok::kw_fadd:
2590 case lltok::kw_fsub:
2592 case lltok::kw_fmul:
2593 case lltok::kw_udiv:
2594 case lltok::kw_sdiv:
2595 case lltok::kw_fdiv:
2596 case lltok::kw_urem:
2597 case lltok::kw_srem:
2598 case lltok::kw_frem:
2600 case lltok::kw_lshr:
2601 case lltok::kw_ashr: {
2605 unsigned Opc = Lex.getUIntVal();
2606 Constant *Val0, *Val1;
2608 LocTy ModifierLoc = Lex.getLoc();
2609 if (Opc == Instruction::Add || Opc == Instruction::Sub ||
2610 Opc == Instruction::Mul || Opc == Instruction::Shl) {
2611 if (EatIfPresent(lltok::kw_nuw))
2613 if (EatIfPresent(lltok::kw_nsw)) {
2615 if (EatIfPresent(lltok::kw_nuw))
2618 } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
2619 Opc == Instruction::LShr || Opc == Instruction::AShr) {
2620 if (EatIfPresent(lltok::kw_exact))
2623 if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
2624 ParseGlobalTypeAndValue(Val0) ||
2625 ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
2626 ParseGlobalTypeAndValue(Val1) ||
2627 ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
2629 if (Val0->getType() != Val1->getType())
2630 return Error(ID.Loc, "operands of constexpr must have same type");
2631 if (!Val0->getType()->isIntOrIntVectorTy()) {
2633 return Error(ModifierLoc, "nuw only applies to integer operations");
2635 return Error(ModifierLoc, "nsw only applies to integer operations");
2637 // Check that the type is valid for the operator.
2639 case Instruction::Add:
2640 case Instruction::Sub:
2641 case Instruction::Mul:
2642 case Instruction::UDiv:
2643 case Instruction::SDiv:
2644 case Instruction::URem:
2645 case Instruction::SRem:
2646 case Instruction::Shl:
2647 case Instruction::AShr:
2648 case Instruction::LShr:
2649 if (!Val0->getType()->isIntOrIntVectorTy())
2650 return Error(ID.Loc, "constexpr requires integer operands");
2652 case Instruction::FAdd:
2653 case Instruction::FSub:
2654 case Instruction::FMul:
2655 case Instruction::FDiv:
2656 case Instruction::FRem:
2657 if (!Val0->getType()->isFPOrFPVectorTy())
2658 return Error(ID.Loc, "constexpr requires fp operands");
2660 default: llvm_unreachable("Unknown binary operator!");
2663 if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2664 if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
2665 if (Exact) Flags |= PossiblyExactOperator::IsExact;
2666 Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
2668 ID.Kind = ValID::t_Constant;
2672 // Logical Operations
2675 case lltok::kw_xor: {
2676 unsigned Opc = Lex.getUIntVal();
2677 Constant *Val0, *Val1;
2679 if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
2680 ParseGlobalTypeAndValue(Val0) ||
2681 ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
2682 ParseGlobalTypeAndValue(Val1) ||
2683 ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
2685 if (Val0->getType() != Val1->getType())
2686 return Error(ID.Loc, "operands of constexpr must have same type");
2687 if (!Val0->getType()->isIntOrIntVectorTy())
2688 return Error(ID.Loc,
2689 "constexpr requires integer or integer vector operands");
2690 ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
2691 ID.Kind = ValID::t_Constant;
2695 case lltok::kw_getelementptr:
2696 case lltok::kw_shufflevector:
2697 case lltok::kw_insertelement:
2698 case lltok::kw_extractelement:
2699 case lltok::kw_select: {
2700 unsigned Opc = Lex.getUIntVal();
2701 SmallVector<Constant*, 16> Elts;
2702 bool InBounds = false;
2704 if (Opc == Instruction::GetElementPtr)
2705 InBounds = EatIfPresent(lltok::kw_inbounds);
2706 if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
2707 ParseGlobalValueVector(Elts) ||
2708 ParseToken(lltok::rparen, "expected ')' in constantexpr"))
2711 if (Opc == Instruction::GetElementPtr) {
2712 if (Elts.size() == 0 ||
2713 !Elts[0]->getType()->getScalarType()->isPointerTy())
2714 return Error(ID.Loc, "getelementptr requires pointer operand");
2716 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2717 if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
2718 return Error(ID.Loc, "invalid indices for getelementptr");
2719 ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
2721 } else if (Opc == Instruction::Select) {
2722 if (Elts.size() != 3)
2723 return Error(ID.Loc, "expected three operands to select");
2724 if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
2726 return Error(ID.Loc, Reason);
2727 ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
2728 } else if (Opc == Instruction::ShuffleVector) {
2729 if (Elts.size() != 3)
2730 return Error(ID.Loc, "expected three operands to shufflevector");
2731 if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2732 return Error(ID.Loc, "invalid operands to shufflevector");
2734 ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
2735 } else if (Opc == Instruction::ExtractElement) {
2736 if (Elts.size() != 2)
2737 return Error(ID.Loc, "expected two operands to extractelement");
2738 if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
2739 return Error(ID.Loc, "invalid extractelement operands");
2740 ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
2742 assert(Opc == Instruction::InsertElement && "Unknown opcode");
2743 if (Elts.size() != 3)
2744 return Error(ID.Loc, "expected three operands to insertelement");
2745 if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
2746 return Error(ID.Loc, "invalid insertelement operands");
2748 ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
2751 ID.Kind = ValID::t_Constant;
2760 /// ParseGlobalValue - Parse a global value with the specified type.
2761 bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
2765 bool Parsed = ParseValID(ID) ||
2766 ConvertValIDToValue(Ty, ID, V, nullptr);
2767 if (V && !(C = dyn_cast<Constant>(V)))
2768 return Error(ID.Loc, "global values must be constants");
2772 bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
2774 return ParseType(Ty) ||
2775 ParseGlobalValue(Ty, V);
2778 /// ParseGlobalValueVector
2780 /// ::= TypeAndValue (',' TypeAndValue)*
2781 bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
2783 if (Lex.getKind() == lltok::rbrace ||
2784 Lex.getKind() == lltok::rsquare ||
2785 Lex.getKind() == lltok::greater ||
2786 Lex.getKind() == lltok::rparen)
2790 if (ParseGlobalTypeAndValue(C)) return true;
2793 while (EatIfPresent(lltok::comma)) {
2794 if (ParseGlobalTypeAndValue(C)) return true;
2801 bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
2802 assert(Lex.getKind() == lltok::lbrace);
2805 SmallVector<Value*, 16> Elts;
2806 if (ParseMDNodeVector(Elts, PFS) ||
2807 ParseToken(lltok::rbrace, "expected end of metadata node"))
2810 ID.MDNodeVal = MDNode::get(Context, Elts);
2811 ID.Kind = ValID::t_MDNode;
2815 /// ParseMetadataValue
2819 bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
2820 assert(Lex.getKind() == lltok::exclaim);
2825 if (Lex.getKind() == lltok::lbrace)
2826 return ParseMetadataListValue(ID, PFS);
2828 // Standalone metadata reference
2830 if (Lex.getKind() == lltok::APSInt) {
2831 if (ParseMDNodeID(ID.MDNodeVal)) return true;
2832 ID.Kind = ValID::t_MDNode;
2837 // ::= '!' STRINGCONSTANT
2838 if (ParseMDString(ID.MDStringVal)) return true;
2839 ID.Kind = ValID::t_MDString;
2844 //===----------------------------------------------------------------------===//
2845 // Function Parsing.
2846 //===----------------------------------------------------------------------===//
2848 bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
2849 PerFunctionState *PFS) {
2850 if (Ty->isFunctionTy())
2851 return Error(ID.Loc, "functions are not values, refer to them as pointers");
2854 case ValID::t_LocalID:
2855 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2856 V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
2857 return V == nullptr;
2858 case ValID::t_LocalName:
2859 if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
2860 V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
2861 return V == nullptr;
2862 case ValID::t_InlineAsm: {
2863 PointerType *PTy = dyn_cast<PointerType>(Ty);
2865 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : nullptr;
2866 if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
2867 return Error(ID.Loc, "invalid type for inline asm constraint string");
2868 V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
2869 (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
2872 case ValID::t_MDNode:
2873 if (!Ty->isMetadataTy())
2874 return Error(ID.Loc, "metadata value must have metadata type");
2877 case ValID::t_MDString:
2878 if (!Ty->isMetadataTy())
2879 return Error(ID.Loc, "metadata value must have metadata type");
2882 case ValID::t_GlobalName:
2883 V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
2884 return V == nullptr;
2885 case ValID::t_GlobalID:
2886 V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
2887 return V == nullptr;
2888 case ValID::t_APSInt:
2889 if (!Ty->isIntegerTy())
2890 return Error(ID.Loc, "integer constant must have integer type");
2891 ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
2892 V = ConstantInt::get(Context, ID.APSIntVal);
2894 case ValID::t_APFloat:
2895 if (!Ty->isFloatingPointTy() ||
2896 !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
2897 return Error(ID.Loc, "floating point constant invalid for type");
2899 // The lexer has no type info, so builds all half, float, and double FP
2900 // constants as double. Fix this here. Long double does not need this.
2901 if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
2904 ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
2906 else if (Ty->isFloatTy())
2907 ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
2910 V = ConstantFP::get(Context, ID.APFloatVal);
2912 if (V->getType() != Ty)
2913 return Error(ID.Loc, "floating point constant does not have type '" +
2914 getTypeString(Ty) + "'");
2918 if (!Ty->isPointerTy())
2919 return Error(ID.Loc, "null must be a pointer type");
2920 V = ConstantPointerNull::get(cast<PointerType>(Ty));
2922 case ValID::t_Undef:
2923 // FIXME: LabelTy should not be a first-class type.
2924 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2925 return Error(ID.Loc, "invalid type for undef constant");
2926 V = UndefValue::get(Ty);
2928 case ValID::t_EmptyArray:
2929 if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
2930 return Error(ID.Loc, "invalid empty array initializer");
2931 V = UndefValue::get(Ty);
2934 // FIXME: LabelTy should not be a first-class type.
2935 if (!Ty->isFirstClassType() || Ty->isLabelTy())
2936 return Error(ID.Loc, "invalid type for null constant");
2937 V = Constant::getNullValue(Ty);
2939 case ValID::t_Constant:
2940 if (ID.ConstantVal->getType() != Ty)
2941 return Error(ID.Loc, "constant expression type mismatch");
2945 case ValID::t_ConstantStruct:
2946 case ValID::t_PackedConstantStruct:
2947 if (StructType *ST = dyn_cast<StructType>(Ty)) {
2948 if (ST->getNumElements() != ID.UIntVal)
2949 return Error(ID.Loc,
2950 "initializer with struct type has wrong # elements");
2951 if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
2952 return Error(ID.Loc, "packed'ness of initializer and type don't match");
2954 // Verify that the elements are compatible with the structtype.
2955 for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
2956 if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
2957 return Error(ID.Loc, "element " + Twine(i) +
2958 " of struct initializer doesn't match struct element type");
2960 V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
2963 return Error(ID.Loc, "constant expression type mismatch");
2966 llvm_unreachable("Invalid ValID");
2969 bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
2972 return ParseValID(ID, PFS) ||
2973 ConvertValIDToValue(Ty, ID, V, PFS);
2976 bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
2978 return ParseType(Ty) ||
2979 ParseValue(Ty, V, PFS);
2982 bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
2983 PerFunctionState &PFS) {
2986 if (ParseTypeAndValue(V, PFS)) return true;
2987 if (!isa<BasicBlock>(V))
2988 return Error(Loc, "expected a basic block");
2989 BB = cast<BasicBlock>(V);
2995 /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
2996 /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
2997 /// OptionalAlign OptGC OptionalPrefix
2998 bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
2999 // Parse the linkage.
3000 LocTy LinkageLoc = Lex.getLoc();
3003 unsigned Visibility;
3004 unsigned DLLStorageClass;
3005 AttrBuilder RetAttrs;
3007 Type *RetType = nullptr;
3008 LocTy RetTypeLoc = Lex.getLoc();
3009 if (ParseOptionalLinkage(Linkage) ||
3010 ParseOptionalVisibility(Visibility) ||
3011 ParseOptionalDLLStorageClass(DLLStorageClass) ||
3012 ParseOptionalCallingConv(CC) ||
3013 ParseOptionalReturnAttrs(RetAttrs) ||
3014 ParseType(RetType, RetTypeLoc, true /*void allowed*/))
3017 // Verify that the linkage is ok.
3018 switch ((GlobalValue::LinkageTypes)Linkage) {
3019 case GlobalValue::ExternalLinkage:
3020 break; // always ok.
3021 case GlobalValue::ExternalWeakLinkage:
3023 return Error(LinkageLoc, "invalid linkage for function definition");
3025 case GlobalValue::PrivateLinkage:
3026 case GlobalValue::InternalLinkage:
3027 case GlobalValue::AvailableExternallyLinkage:
3028 case GlobalValue::LinkOnceAnyLinkage:
3029 case GlobalValue::LinkOnceODRLinkage:
3030 case GlobalValue::WeakAnyLinkage:
3031 case GlobalValue::WeakODRLinkage:
3033 return Error(LinkageLoc, "invalid linkage for function declaration");
3035 case GlobalValue::AppendingLinkage:
3036 case GlobalValue::CommonLinkage:
3037 return Error(LinkageLoc, "invalid function linkage type");
3040 if (!isValidVisibilityForLinkage(Visibility, Linkage))
3041 return Error(LinkageLoc,
3042 "symbol with local linkage must have default visibility");
3044 if (!FunctionType::isValidReturnType(RetType))
3045 return Error(RetTypeLoc, "invalid function return type");
3047 LocTy NameLoc = Lex.getLoc();
3049 std::string FunctionName;
3050 if (Lex.getKind() == lltok::GlobalVar) {
3051 FunctionName = Lex.getStrVal();
3052 } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
3053 unsigned NameID = Lex.getUIntVal();
3055 if (NameID != NumberedVals.size())
3056 return TokError("function expected to be numbered '%" +
3057 Twine(NumberedVals.size()) + "'");
3059 return TokError("expected function name");
3064 if (Lex.getKind() != lltok::lparen)
3065 return TokError("expected '(' in function argument list");
3067 SmallVector<ArgInfo, 8> ArgList;
3069 AttrBuilder FuncAttrs;
3070 std::vector<unsigned> FwdRefAttrGrps;
3072 std::string Section;
3076 LocTy UnnamedAddrLoc;
3077 Constant *Prefix = nullptr;
3079 if (ParseArgumentList(ArgList, isVarArg) ||
3080 ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
3082 ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
3084 (EatIfPresent(lltok::kw_section) &&
3085 ParseStringConstant(Section)) ||
3086 ParseOptionalAlignment(Alignment) ||
3087 (EatIfPresent(lltok::kw_gc) &&
3088 ParseStringConstant(GC)) ||
3089 (EatIfPresent(lltok::kw_prefix) &&
3090 ParseGlobalTypeAndValue(Prefix)))
3093 if (FuncAttrs.contains(Attribute::Builtin))
3094 return Error(BuiltinLoc, "'builtin' attribute not valid on function");
3096 // If the alignment was parsed as an attribute, move to the alignment field.
3097 if (FuncAttrs.hasAlignmentAttr()) {
3098 Alignment = FuncAttrs.getAlignment();
3099 FuncAttrs.removeAttribute(Attribute::Alignment);
3102 // Okay, if we got here, the function is syntactically valid. Convert types
3103 // and do semantic checks.
3104 std::vector<Type*> ParamTypeList;
3105 SmallVector<AttributeSet, 8> Attrs;
3107 if (RetAttrs.hasAttributes())
3108 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3109 AttributeSet::ReturnIndex,
3112 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3113 ParamTypeList.push_back(ArgList[i].Ty);
3114 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3115 AttrBuilder B(ArgList[i].Attrs, i + 1);
3116 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3120 if (FuncAttrs.hasAttributes())
3121 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3122 AttributeSet::FunctionIndex,
3125 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3127 if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
3128 return Error(RetTypeLoc, "functions with 'sret' argument must return void");
3131 FunctionType::get(RetType, ParamTypeList, isVarArg);
3132 PointerType *PFT = PointerType::getUnqual(FT);
3135 if (!FunctionName.empty()) {
3136 // If this was a definition of a forward reference, remove the definition
3137 // from the forward reference table and fill in the forward ref.
3138 std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
3139 ForwardRefVals.find(FunctionName);
3140 if (FRVI != ForwardRefVals.end()) {
3141 Fn = M->getFunction(FunctionName);
3143 return Error(FRVI->second.second, "invalid forward reference to "
3144 "function as global value!");
3145 if (Fn->getType() != PFT)
3146 return Error(FRVI->second.second, "invalid forward reference to "
3147 "function '" + FunctionName + "' with wrong type!");
3149 ForwardRefVals.erase(FRVI);
3150 } else if ((Fn = M->getFunction(FunctionName))) {
3151 // Reject redefinitions.
3152 return Error(NameLoc, "invalid redefinition of function '" +
3153 FunctionName + "'");
3154 } else if (M->getNamedValue(FunctionName)) {
3155 return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
3159 // If this is a definition of a forward referenced function, make sure the
3161 std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
3162 = ForwardRefValIDs.find(NumberedVals.size());
3163 if (I != ForwardRefValIDs.end()) {
3164 Fn = cast<Function>(I->second.first);
3165 if (Fn->getType() != PFT)
3166 return Error(NameLoc, "type of definition and forward reference of '@" +
3167 Twine(NumberedVals.size()) + "' disagree");
3168 ForwardRefValIDs.erase(I);
3173 Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
3174 else // Move the forward-reference to the correct spot in the module.
3175 M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
3177 if (FunctionName.empty())
3178 NumberedVals.push_back(Fn);
3180 Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
3181 Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
3182 Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
3183 Fn->setCallingConv(CC);
3184 Fn->setAttributes(PAL);
3185 Fn->setUnnamedAddr(UnnamedAddr);
3186 Fn->setAlignment(Alignment);
3187 Fn->setSection(Section);
3188 if (!GC.empty()) Fn->setGC(GC.c_str());
3189 Fn->setPrefixData(Prefix);
3190 ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
3192 // Add all of the arguments we parsed to the function.
3193 Function::arg_iterator ArgIt = Fn->arg_begin();
3194 for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
3195 // If the argument has a name, insert it into the argument symbol table.
3196 if (ArgList[i].Name.empty()) continue;
3198 // Set the name, if it conflicted, it will be auto-renamed.
3199 ArgIt->setName(ArgList[i].Name);
3201 if (ArgIt->getName() != ArgList[i].Name)
3202 return Error(ArgList[i].Loc, "redefinition of argument '%" +
3203 ArgList[i].Name + "'");
3210 /// ParseFunctionBody
3211 /// ::= '{' BasicBlock+ '}'
3213 bool LLParser::ParseFunctionBody(Function &Fn) {
3214 if (Lex.getKind() != lltok::lbrace)
3215 return TokError("expected '{' in function body");
3216 Lex.Lex(); // eat the {.
3218 int FunctionNumber = -1;
3219 if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
3221 PerFunctionState PFS(*this, Fn, FunctionNumber);
3223 // We need at least one basic block.
3224 if (Lex.getKind() == lltok::rbrace)
3225 return TokError("function body requires at least one basic block");
3227 while (Lex.getKind() != lltok::rbrace)
3228 if (ParseBasicBlock(PFS)) return true;
3233 // Verify function is ok.
3234 return PFS.FinishFunction();
3238 /// ::= LabelStr? Instruction*
3239 bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
3240 // If this basic block starts out with a name, remember it.
3242 LocTy NameLoc = Lex.getLoc();
3243 if (Lex.getKind() == lltok::LabelStr) {
3244 Name = Lex.getStrVal();
3248 BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
3249 if (!BB) return true;
3251 std::string NameStr;
3253 // Parse the instructions in this block until we get a terminator.
3256 // This instruction may have three possibilities for a name: a) none
3257 // specified, b) name specified "%foo =", c) number specified: "%4 =".
3258 LocTy NameLoc = Lex.getLoc();
3262 if (Lex.getKind() == lltok::LocalVarID) {
3263 NameID = Lex.getUIntVal();
3265 if (ParseToken(lltok::equal, "expected '=' after instruction id"))
3267 } else if (Lex.getKind() == lltok::LocalVar) {
3268 NameStr = Lex.getStrVal();
3270 if (ParseToken(lltok::equal, "expected '=' after instruction name"))
3274 switch (ParseInstruction(Inst, BB, PFS)) {
3275 default: llvm_unreachable("Unknown ParseInstruction result!");
3276 case InstError: return true;
3278 BB->getInstList().push_back(Inst);
3280 // With a normal result, we check to see if the instruction is followed by
3281 // a comma and metadata.
3282 if (EatIfPresent(lltok::comma))
3283 if (ParseInstructionMetadata(Inst, &PFS))
3286 case InstExtraComma:
3287 BB->getInstList().push_back(Inst);
3289 // If the instruction parser ate an extra comma at the end of it, it
3290 // *must* be followed by metadata.
3291 if (ParseInstructionMetadata(Inst, &PFS))
3296 // Set the name on the instruction.
3297 if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
3298 } while (!isa<TerminatorInst>(Inst));
3303 //===----------------------------------------------------------------------===//
3304 // Instruction Parsing.
3305 //===----------------------------------------------------------------------===//
3307 /// ParseInstruction - Parse one of the many different instructions.
3309 int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
3310 PerFunctionState &PFS) {
3311 lltok::Kind Token = Lex.getKind();
3312 if (Token == lltok::Eof)
3313 return TokError("found end of file when expecting more instructions");
3314 LocTy Loc = Lex.getLoc();
3315 unsigned KeywordVal = Lex.getUIntVal();
3316 Lex.Lex(); // Eat the keyword.
3319 default: return Error(Loc, "expected instruction opcode");
3320 // Terminator Instructions.
3321 case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
3322 case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
3323 case lltok::kw_br: return ParseBr(Inst, PFS);
3324 case lltok::kw_switch: return ParseSwitch(Inst, PFS);
3325 case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
3326 case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
3327 case lltok::kw_resume: return ParseResume(Inst, PFS);
3328 // Binary Operators.
3332 case lltok::kw_shl: {
3333 bool NUW = EatIfPresent(lltok::kw_nuw);
3334 bool NSW = EatIfPresent(lltok::kw_nsw);
3335 if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
3337 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3339 if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
3340 if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
3343 case lltok::kw_fadd:
3344 case lltok::kw_fsub:
3345 case lltok::kw_fmul:
3346 case lltok::kw_fdiv:
3347 case lltok::kw_frem: {
3348 FastMathFlags FMF = EatFastMathFlagsIfPresent();
3349 int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
3353 Inst->setFastMathFlags(FMF);
3357 case lltok::kw_sdiv:
3358 case lltok::kw_udiv:
3359 case lltok::kw_lshr:
3360 case lltok::kw_ashr: {
3361 bool Exact = EatIfPresent(lltok::kw_exact);
3363 if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
3364 if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
3368 case lltok::kw_urem:
3369 case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
3372 case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
3373 case lltok::kw_icmp:
3374 case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
3376 case lltok::kw_trunc:
3377 case lltok::kw_zext:
3378 case lltok::kw_sext:
3379 case lltok::kw_fptrunc:
3380 case lltok::kw_fpext:
3381 case lltok::kw_bitcast:
3382 case lltok::kw_addrspacecast:
3383 case lltok::kw_uitofp:
3384 case lltok::kw_sitofp:
3385 case lltok::kw_fptoui:
3386 case lltok::kw_fptosi:
3387 case lltok::kw_inttoptr:
3388 case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
3390 case lltok::kw_select: return ParseSelect(Inst, PFS);
3391 case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
3392 case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
3393 case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
3394 case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
3395 case lltok::kw_phi: return ParsePHI(Inst, PFS);
3396 case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
3398 case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
3399 case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
3400 case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
3402 case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
3403 case lltok::kw_load: return ParseLoad(Inst, PFS);
3404 case lltok::kw_store: return ParseStore(Inst, PFS);
3405 case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
3406 case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
3407 case lltok::kw_fence: return ParseFence(Inst, PFS);
3408 case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
3409 case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
3410 case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
3414 /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
3415 bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
3416 if (Opc == Instruction::FCmp) {
3417 switch (Lex.getKind()) {
3418 default: return TokError("expected fcmp predicate (e.g. 'oeq')");
3419 case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
3420 case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
3421 case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
3422 case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
3423 case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
3424 case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
3425 case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
3426 case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
3427 case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
3428 case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
3429 case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
3430 case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
3431 case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
3432 case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
3433 case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
3434 case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
3437 switch (Lex.getKind()) {
3438 default: return TokError("expected icmp predicate (e.g. 'eq')");
3439 case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
3440 case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
3441 case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
3442 case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
3443 case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
3444 case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
3445 case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
3446 case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
3447 case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
3448 case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
3455 //===----------------------------------------------------------------------===//
3456 // Terminator Instructions.
3457 //===----------------------------------------------------------------------===//
3459 /// ParseRet - Parse a return instruction.
3460 /// ::= 'ret' void (',' !dbg, !1)*
3461 /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
3462 bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
3463 PerFunctionState &PFS) {
3464 SMLoc TypeLoc = Lex.getLoc();
3466 if (ParseType(Ty, true /*void allowed*/)) return true;
3468 Type *ResType = PFS.getFunction().getReturnType();
3470 if (Ty->isVoidTy()) {
3471 if (!ResType->isVoidTy())
3472 return Error(TypeLoc, "value doesn't match function result type '" +
3473 getTypeString(ResType) + "'");
3475 Inst = ReturnInst::Create(Context);
3480 if (ParseValue(Ty, RV, PFS)) return true;
3482 if (ResType != RV->getType())
3483 return Error(TypeLoc, "value doesn't match function result type '" +
3484 getTypeString(ResType) + "'");
3486 Inst = ReturnInst::Create(Context, RV);
3492 /// ::= 'br' TypeAndValue
3493 /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3494 bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
3497 BasicBlock *Op1, *Op2;
3498 if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
3500 if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
3501 Inst = BranchInst::Create(BB);
3505 if (Op0->getType() != Type::getInt1Ty(Context))
3506 return Error(Loc, "branch condition must have 'i1' type");
3508 if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
3509 ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
3510 ParseToken(lltok::comma, "expected ',' after true destination") ||
3511 ParseTypeAndBasicBlock(Op2, Loc2, PFS))
3514 Inst = BranchInst::Create(Op1, Op2, Op0);
3520 /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
3522 /// ::= (TypeAndValue ',' TypeAndValue)*
3523 bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
3524 LocTy CondLoc, BBLoc;
3526 BasicBlock *DefaultBB;
3527 if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
3528 ParseToken(lltok::comma, "expected ',' after switch condition") ||
3529 ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
3530 ParseToken(lltok::lsquare, "expected '[' with switch table"))
3533 if (!Cond->getType()->isIntegerTy())
3534 return Error(CondLoc, "switch condition must have integer type");
3536 // Parse the jump table pairs.
3537 SmallPtrSet<Value*, 32> SeenCases;
3538 SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
3539 while (Lex.getKind() != lltok::rsquare) {
3543 if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
3544 ParseToken(lltok::comma, "expected ',' after case value") ||
3545 ParseTypeAndBasicBlock(DestBB, PFS))
3548 if (!SeenCases.insert(Constant))
3549 return Error(CondLoc, "duplicate case value in switch");
3550 if (!isa<ConstantInt>(Constant))
3551 return Error(CondLoc, "case value is not a constant integer");
3553 Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
3556 Lex.Lex(); // Eat the ']'.
3558 SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
3559 for (unsigned i = 0, e = Table.size(); i != e; ++i)
3560 SI->addCase(Table[i].first, Table[i].second);
3567 /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
3568 bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
3571 if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
3572 ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
3573 ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
3576 if (!Address->getType()->isPointerTy())
3577 return Error(AddrLoc, "indirectbr address must have pointer type");
3579 // Parse the destination list.
3580 SmallVector<BasicBlock*, 16> DestList;
3582 if (Lex.getKind() != lltok::rsquare) {
3584 if (ParseTypeAndBasicBlock(DestBB, PFS))
3586 DestList.push_back(DestBB);
3588 while (EatIfPresent(lltok::comma)) {
3589 if (ParseTypeAndBasicBlock(DestBB, PFS))
3591 DestList.push_back(DestBB);
3595 if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
3598 IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
3599 for (unsigned i = 0, e = DestList.size(); i != e; ++i)
3600 IBI->addDestination(DestList[i]);
3607 /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
3608 /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
3609 bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
3610 LocTy CallLoc = Lex.getLoc();
3611 AttrBuilder RetAttrs, FnAttrs;
3612 std::vector<unsigned> FwdRefAttrGrps;
3615 Type *RetType = nullptr;
3618 SmallVector<ParamInfo, 16> ArgList;
3620 BasicBlock *NormalBB, *UnwindBB;
3621 if (ParseOptionalCallingConv(CC) ||
3622 ParseOptionalReturnAttrs(RetAttrs) ||
3623 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
3624 ParseValID(CalleeID) ||
3625 ParseParameterList(ArgList, PFS) ||
3626 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
3628 ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
3629 ParseTypeAndBasicBlock(NormalBB, PFS) ||
3630 ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
3631 ParseTypeAndBasicBlock(UnwindBB, PFS))
3634 // If RetType is a non-function pointer type, then this is the short syntax
3635 // for the call, which means that RetType is just the return type. Infer the
3636 // rest of the function argument types from the arguments that are present.
3637 PointerType *PFTy = nullptr;
3638 FunctionType *Ty = nullptr;
3639 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
3640 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3641 // Pull out the types of all of the arguments...
3642 std::vector<Type*> ParamTypes;
3643 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
3644 ParamTypes.push_back(ArgList[i].V->getType());
3646 if (!FunctionType::isValidReturnType(RetType))
3647 return Error(RetTypeLoc, "Invalid result type for LLVM function");
3649 Ty = FunctionType::get(RetType, ParamTypes, false);
3650 PFTy = PointerType::getUnqual(Ty);
3653 // Look up the callee.
3655 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
3657 // Set up the Attribute for the function.
3658 SmallVector<AttributeSet, 8> Attrs;
3659 if (RetAttrs.hasAttributes())
3660 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3661 AttributeSet::ReturnIndex,
3664 SmallVector<Value*, 8> Args;
3666 // Loop through FunctionType's arguments and ensure they are specified
3667 // correctly. Also, gather any parameter attributes.
3668 FunctionType::param_iterator I = Ty->param_begin();
3669 FunctionType::param_iterator E = Ty->param_end();
3670 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
3671 Type *ExpectedTy = nullptr;
3674 } else if (!Ty->isVarArg()) {
3675 return Error(ArgList[i].Loc, "too many arguments specified");
3678 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
3679 return Error(ArgList[i].Loc, "argument is not of expected type '" +
3680 getTypeString(ExpectedTy) + "'");
3681 Args.push_back(ArgList[i].V);
3682 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
3683 AttrBuilder B(ArgList[i].Attrs, i + 1);
3684 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
3689 return Error(CallLoc, "not enough parameters specified for call");
3691 if (FnAttrs.hasAttributes())
3692 Attrs.push_back(AttributeSet::get(RetType->getContext(),
3693 AttributeSet::FunctionIndex,
3696 // Finish off the Attribute and check them
3697 AttributeSet PAL = AttributeSet::get(Context, Attrs);
3699 InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
3700 II->setCallingConv(CC);
3701 II->setAttributes(PAL);
3702 ForwardRefAttrGroups[II] = FwdRefAttrGrps;
3708 /// ::= 'resume' TypeAndValue
3709 bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
3710 Value *Exn; LocTy ExnLoc;
3711 if (ParseTypeAndValue(Exn, ExnLoc, PFS))
3714 ResumeInst *RI = ResumeInst::Create(Exn);
3719 //===----------------------------------------------------------------------===//
3720 // Binary Operators.
3721 //===----------------------------------------------------------------------===//
3724 /// ::= ArithmeticOps TypeAndValue ',' Value
3726 /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
3727 /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
3728 bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
3729 unsigned Opc, unsigned OperandType) {
3730 LocTy Loc; Value *LHS, *RHS;
3731 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3732 ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
3733 ParseValue(LHS->getType(), RHS, PFS))
3737 switch (OperandType) {
3738 default: llvm_unreachable("Unknown operand type!");
3739 case 0: // int or FP.
3740 Valid = LHS->getType()->isIntOrIntVectorTy() ||
3741 LHS->getType()->isFPOrFPVectorTy();
3743 case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
3744 case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
3748 return Error(Loc, "invalid operand type for instruction");
3750 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3755 /// ::= ArithmeticOps TypeAndValue ',' Value {
3756 bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
3758 LocTy Loc; Value *LHS, *RHS;
3759 if (ParseTypeAndValue(LHS, Loc, PFS) ||
3760 ParseToken(lltok::comma, "expected ',' in logical operation") ||
3761 ParseValue(LHS->getType(), RHS, PFS))
3764 if (!LHS->getType()->isIntOrIntVectorTy())
3765 return Error(Loc,"instruction requires integer or integer vector operands");
3767 Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3773 /// ::= 'icmp' IPredicates TypeAndValue ',' Value
3774 /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
3775 bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
3777 // Parse the integer/fp comparison predicate.
3781 if (ParseCmpPredicate(Pred, Opc) ||
3782 ParseTypeAndValue(LHS, Loc, PFS) ||
3783 ParseToken(lltok::comma, "expected ',' after compare value") ||
3784 ParseValue(LHS->getType(), RHS, PFS))
3787 if (Opc == Instruction::FCmp) {
3788 if (!LHS->getType()->isFPOrFPVectorTy())
3789 return Error(Loc, "fcmp requires floating point operands");
3790 Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3792 assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
3793 if (!LHS->getType()->isIntOrIntVectorTy() &&
3794 !LHS->getType()->getScalarType()->isPointerTy())
3795 return Error(Loc, "icmp requires integer operands");
3796 Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
3801 //===----------------------------------------------------------------------===//
3802 // Other Instructions.
3803 //===----------------------------------------------------------------------===//
3807 /// ::= CastOpc TypeAndValue 'to' Type
3808 bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
3812 Type *DestTy = nullptr;
3813 if (ParseTypeAndValue(Op, Loc, PFS) ||
3814 ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
3818 if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
3819 CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
3820 return Error(Loc, "invalid cast opcode for cast from '" +
3821 getTypeString(Op->getType()) + "' to '" +
3822 getTypeString(DestTy) + "'");
3824 Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
3829 /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3830 bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
3832 Value *Op0, *Op1, *Op2;
3833 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3834 ParseToken(lltok::comma, "expected ',' after select condition") ||
3835 ParseTypeAndValue(Op1, PFS) ||
3836 ParseToken(lltok::comma, "expected ',' after select value") ||
3837 ParseTypeAndValue(Op2, PFS))
3840 if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
3841 return Error(Loc, Reason);
3843 Inst = SelectInst::Create(Op0, Op1, Op2);
3848 /// ::= 'va_arg' TypeAndValue ',' Type
3849 bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
3851 Type *EltTy = nullptr;
3853 if (ParseTypeAndValue(Op, PFS) ||
3854 ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
3855 ParseType(EltTy, TypeLoc))
3858 if (!EltTy->isFirstClassType())
3859 return Error(TypeLoc, "va_arg requires operand with first class type");
3861 Inst = new VAArgInst(Op, EltTy);
3865 /// ParseExtractElement
3866 /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
3867 bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
3870 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3871 ParseToken(lltok::comma, "expected ',' after extract value") ||
3872 ParseTypeAndValue(Op1, PFS))
3875 if (!ExtractElementInst::isValidOperands(Op0, Op1))
3876 return Error(Loc, "invalid extractelement operands");
3878 Inst = ExtractElementInst::Create(Op0, Op1);
3882 /// ParseInsertElement
3883 /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3884 bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
3886 Value *Op0, *Op1, *Op2;
3887 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3888 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3889 ParseTypeAndValue(Op1, PFS) ||
3890 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3891 ParseTypeAndValue(Op2, PFS))
3894 if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
3895 return Error(Loc, "invalid insertelement operands");
3897 Inst = InsertElementInst::Create(Op0, Op1, Op2);
3901 /// ParseShuffleVector
3902 /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
3903 bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
3905 Value *Op0, *Op1, *Op2;
3906 if (ParseTypeAndValue(Op0, Loc, PFS) ||
3907 ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
3908 ParseTypeAndValue(Op1, PFS) ||
3909 ParseToken(lltok::comma, "expected ',' after shuffle value") ||
3910 ParseTypeAndValue(Op2, PFS))
3913 if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
3914 return Error(Loc, "invalid shufflevector operands");
3916 Inst = new ShuffleVectorInst(Op0, Op1, Op2);
3921 /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
3922 int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
3923 Type *Ty = nullptr; LocTy TypeLoc;
3926 if (ParseType(Ty, TypeLoc) ||
3927 ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3928 ParseValue(Ty, Op0, PFS) ||
3929 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3930 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3931 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3934 bool AteExtraComma = false;
3935 SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
3937 PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
3939 if (!EatIfPresent(lltok::comma))
3942 if (Lex.getKind() == lltok::MetadataVar) {
3943 AteExtraComma = true;
3947 if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
3948 ParseValue(Ty, Op0, PFS) ||
3949 ParseToken(lltok::comma, "expected ',' after insertelement value") ||
3950 ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
3951 ParseToken(lltok::rsquare, "expected ']' in phi value list"))
3955 if (!Ty->isFirstClassType())
3956 return Error(TypeLoc, "phi node must have first class type");
3958 PHINode *PN = PHINode::Create(Ty, PHIVals.size());
3959 for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
3960 PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
3962 return AteExtraComma ? InstExtraComma : InstNormal;
3966 /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
3968 /// ::= 'catch' TypeAndValue
3970 /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
3971 bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
3972 Type *Ty = nullptr; LocTy TyLoc;
3973 Value *PersFn; LocTy PersFnLoc;
3975 if (ParseType(Ty, TyLoc) ||
3976 ParseToken(lltok::kw_personality, "expected 'personality'") ||
3977 ParseTypeAndValue(PersFn, PersFnLoc, PFS))
3980 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
3981 LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
3983 while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
3984 LandingPadInst::ClauseType CT;
3985 if (EatIfPresent(lltok::kw_catch))
3986 CT = LandingPadInst::Catch;
3987 else if (EatIfPresent(lltok::kw_filter))
3988 CT = LandingPadInst::Filter;
3990 return TokError("expected 'catch' or 'filter' clause type");
3992 Value *V; LocTy VLoc;
3993 if (ParseTypeAndValue(V, VLoc, PFS)) {
3998 // A 'catch' type expects a non-array constant. A filter clause expects an
4000 if (CT == LandingPadInst::Catch) {
4001 if (isa<ArrayType>(V->getType()))
4002 Error(VLoc, "'catch' clause has an invalid type");
4004 if (!isa<ArrayType>(V->getType()))
4005 Error(VLoc, "'filter' clause has an invalid type");
4016 /// ::= 'call' OptionalCallingConv OptionalAttrs Type Value
4017 /// ParameterList OptionalAttrs
4018 /// ::= 'tail' 'call' OptionalCallingConv OptionalAttrs Type Value
4019 /// ParameterList OptionalAttrs
4020 /// ::= 'musttail' 'call' OptionalCallingConv OptionalAttrs Type Value
4021 /// ParameterList OptionalAttrs
4022 bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
4023 CallInst::TailCallKind TCK) {
4024 AttrBuilder RetAttrs, FnAttrs;
4025 std::vector<unsigned> FwdRefAttrGrps;
4028 Type *RetType = nullptr;
4031 SmallVector<ParamInfo, 16> ArgList;
4032 LocTy CallLoc = Lex.getLoc();
4034 if ((TCK != CallInst::TCK_None &&
4035 ParseToken(lltok::kw_call, "expected 'tail call'")) ||
4036 ParseOptionalCallingConv(CC) ||
4037 ParseOptionalReturnAttrs(RetAttrs) ||
4038 ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
4039 ParseValID(CalleeID) ||
4040 ParseParameterList(ArgList, PFS) ||
4041 ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
4045 // If RetType is a non-function pointer type, then this is the short syntax
4046 // for the call, which means that RetType is just the return type. Infer the
4047 // rest of the function argument types from the arguments that are present.
4048 PointerType *PFTy = nullptr;
4049 FunctionType *Ty = nullptr;
4050 if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
4051 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
4052 // Pull out the types of all of the arguments...
4053 std::vector<Type*> ParamTypes;
4054 for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
4055 ParamTypes.push_back(ArgList[i].V->getType());
4057 if (!FunctionType::isValidReturnType(RetType))
4058 return Error(RetTypeLoc, "Invalid result type for LLVM function");
4060 Ty = FunctionType::get(RetType, ParamTypes, false);
4061 PFTy = PointerType::getUnqual(Ty);
4064 // Look up the callee.
4066 if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
4068 // Set up the Attribute for the function.
4069 SmallVector<AttributeSet, 8> Attrs;
4070 if (RetAttrs.hasAttributes())
4071 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4072 AttributeSet::ReturnIndex,
4075 SmallVector<Value*, 8> Args;
4077 // Loop through FunctionType's arguments and ensure they are specified
4078 // correctly. Also, gather any parameter attributes.
4079 FunctionType::param_iterator I = Ty->param_begin();
4080 FunctionType::param_iterator E = Ty->param_end();
4081 for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
4082 Type *ExpectedTy = nullptr;
4085 } else if (!Ty->isVarArg()) {
4086 return Error(ArgList[i].Loc, "too many arguments specified");
4089 if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
4090 return Error(ArgList[i].Loc, "argument is not of expected type '" +
4091 getTypeString(ExpectedTy) + "'");
4092 Args.push_back(ArgList[i].V);
4093 if (ArgList[i].Attrs.hasAttributes(i + 1)) {
4094 AttrBuilder B(ArgList[i].Attrs, i + 1);
4095 Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
4100 return Error(CallLoc, "not enough parameters specified for call");
4102 if (FnAttrs.hasAttributes())
4103 Attrs.push_back(AttributeSet::get(RetType->getContext(),
4104 AttributeSet::FunctionIndex,
4107 // Finish off the Attribute and check them
4108 AttributeSet PAL = AttributeSet::get(Context, Attrs);
4110 CallInst *CI = CallInst::Create(Callee, Args);
4111 CI->setTailCallKind(TCK);
4112 CI->setCallingConv(CC);
4113 CI->setAttributes(PAL);
4114 ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
4119 //===----------------------------------------------------------------------===//
4120 // Memory Instructions.
4121 //===----------------------------------------------------------------------===//
4124 /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
4125 int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
4126 Value *Size = nullptr;
4128 unsigned Alignment = 0;
4131 bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
4133 if (ParseType(Ty)) return true;
4135 bool AteExtraComma = false;
4136 if (EatIfPresent(lltok::comma)) {
4137 if (Lex.getKind() == lltok::kw_align) {
4138 if (ParseOptionalAlignment(Alignment)) return true;
4139 } else if (Lex.getKind() == lltok::MetadataVar) {
4140 AteExtraComma = true;
4142 if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
4143 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4148 if (Size && !Size->getType()->isIntegerTy())
4149 return Error(SizeLoc, "element count must have integer type");
4151 AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
4152 AI->setUsedWithInAlloca(IsInAlloca);
4154 return AteExtraComma ? InstExtraComma : InstNormal;
4158 /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
4159 /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
4160 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4161 int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
4162 Value *Val; LocTy Loc;
4163 unsigned Alignment = 0;
4164 bool AteExtraComma = false;
4165 bool isAtomic = false;
4166 AtomicOrdering Ordering = NotAtomic;
4167 SynchronizationScope Scope = CrossThread;
4169 if (Lex.getKind() == lltok::kw_atomic) {
4174 bool isVolatile = false;
4175 if (Lex.getKind() == lltok::kw_volatile) {
4180 if (ParseTypeAndValue(Val, Loc, PFS) ||
4181 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4182 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4185 if (!Val->getType()->isPointerTy() ||
4186 !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
4187 return Error(Loc, "load operand must be a pointer to a first class type");
4188 if (isAtomic && !Alignment)
4189 return Error(Loc, "atomic load must have explicit non-zero alignment");
4190 if (Ordering == Release || Ordering == AcquireRelease)
4191 return Error(Loc, "atomic load cannot use Release ordering");
4193 Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
4194 return AteExtraComma ? InstExtraComma : InstNormal;
4199 /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
4200 /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
4201 /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
4202 int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
4203 Value *Val, *Ptr; LocTy Loc, PtrLoc;
4204 unsigned Alignment = 0;
4205 bool AteExtraComma = false;
4206 bool isAtomic = false;
4207 AtomicOrdering Ordering = NotAtomic;
4208 SynchronizationScope Scope = CrossThread;
4210 if (Lex.getKind() == lltok::kw_atomic) {
4215 bool isVolatile = false;
4216 if (Lex.getKind() == lltok::kw_volatile) {
4221 if (ParseTypeAndValue(Val, Loc, PFS) ||
4222 ParseToken(lltok::comma, "expected ',' after store operand") ||
4223 ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4224 ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
4225 ParseOptionalCommaAlign(Alignment, AteExtraComma))
4228 if (!Ptr->getType()->isPointerTy())
4229 return Error(PtrLoc, "store operand must be a pointer");
4230 if (!Val->getType()->isFirstClassType())
4231 return Error(Loc, "store operand must be a first class value");
4232 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4233 return Error(Loc, "stored value and pointer type do not match");
4234 if (isAtomic && !Alignment)
4235 return Error(Loc, "atomic store must have explicit non-zero alignment");
4236 if (Ordering == Acquire || Ordering == AcquireRelease)
4237 return Error(Loc, "atomic store cannot use Acquire ordering");
4239 Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
4240 return AteExtraComma ? InstExtraComma : InstNormal;
4244 /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
4245 /// 'singlethread'? AtomicOrdering AtomicOrdering
4246 int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
4247 Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
4248 bool AteExtraComma = false;
4249 AtomicOrdering SuccessOrdering = NotAtomic;
4250 AtomicOrdering FailureOrdering = NotAtomic;
4251 SynchronizationScope Scope = CrossThread;
4252 bool isVolatile = false;
4254 if (EatIfPresent(lltok::kw_volatile))
4257 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4258 ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
4259 ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
4260 ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
4261 ParseTypeAndValue(New, NewLoc, PFS) ||
4262 ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
4263 ParseOrdering(FailureOrdering))
4266 if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
4267 return TokError("cmpxchg cannot be unordered");
4268 if (SuccessOrdering < FailureOrdering)
4269 return TokError("cmpxchg must be at least as ordered on success as failure");
4270 if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
4271 return TokError("cmpxchg failure ordering cannot include release semantics");
4272 if (!Ptr->getType()->isPointerTy())
4273 return Error(PtrLoc, "cmpxchg operand must be a pointer");
4274 if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
4275 return Error(CmpLoc, "compare value and pointer type do not match");
4276 if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
4277 return Error(NewLoc, "new value and pointer type do not match");
4278 if (!New->getType()->isIntegerTy())
4279 return Error(NewLoc, "cmpxchg operand must be an integer");
4280 unsigned Size = New->getType()->getPrimitiveSizeInBits();
4281 if (Size < 8 || (Size & (Size - 1)))
4282 return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
4285 AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
4286 FailureOrdering, Scope);
4287 CXI->setVolatile(isVolatile);
4289 return AteExtraComma ? InstExtraComma : InstNormal;
4293 /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
4294 /// 'singlethread'? AtomicOrdering
4295 int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
4296 Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
4297 bool AteExtraComma = false;
4298 AtomicOrdering Ordering = NotAtomic;
4299 SynchronizationScope Scope = CrossThread;
4300 bool isVolatile = false;
4301 AtomicRMWInst::BinOp Operation;
4303 if (EatIfPresent(lltok::kw_volatile))
4306 switch (Lex.getKind()) {
4307 default: return TokError("expected binary operation in atomicrmw");
4308 case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
4309 case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
4310 case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
4311 case lltok::kw_and: Operation = AtomicRMWInst::And; break;
4312 case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
4313 case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
4314 case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
4315 case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
4316 case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
4317 case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
4318 case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
4320 Lex.Lex(); // Eat the operation.
4322 if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
4323 ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
4324 ParseTypeAndValue(Val, ValLoc, PFS) ||
4325 ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4328 if (Ordering == Unordered)
4329 return TokError("atomicrmw cannot be unordered");
4330 if (!Ptr->getType()->isPointerTy())
4331 return Error(PtrLoc, "atomicrmw operand must be a pointer");
4332 if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
4333 return Error(ValLoc, "atomicrmw value and pointer type do not match");
4334 if (!Val->getType()->isIntegerTy())
4335 return Error(ValLoc, "atomicrmw operand must be an integer");
4336 unsigned Size = Val->getType()->getPrimitiveSizeInBits();
4337 if (Size < 8 || (Size & (Size - 1)))
4338 return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
4341 AtomicRMWInst *RMWI =
4342 new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
4343 RMWI->setVolatile(isVolatile);
4345 return AteExtraComma ? InstExtraComma : InstNormal;
4349 /// ::= 'fence' 'singlethread'? AtomicOrdering
4350 int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
4351 AtomicOrdering Ordering = NotAtomic;
4352 SynchronizationScope Scope = CrossThread;
4353 if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
4356 if (Ordering == Unordered)
4357 return TokError("fence cannot be unordered");
4358 if (Ordering == Monotonic)
4359 return TokError("fence cannot be monotonic");
4361 Inst = new FenceInst(Context, Ordering, Scope);
4365 /// ParseGetElementPtr
4366 /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
4367 int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
4368 Value *Ptr = nullptr;
4369 Value *Val = nullptr;
4372 bool InBounds = EatIfPresent(lltok::kw_inbounds);
4374 if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
4376 Type *BaseType = Ptr->getType();
4377 PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
4378 if (!BasePointerType)
4379 return Error(Loc, "base of getelementptr must be a pointer");
4381 SmallVector<Value*, 16> Indices;
4382 bool AteExtraComma = false;
4383 while (EatIfPresent(lltok::comma)) {
4384 if (Lex.getKind() == lltok::MetadataVar) {
4385 AteExtraComma = true;
4388 if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
4389 if (!Val->getType()->getScalarType()->isIntegerTy())
4390 return Error(EltLoc, "getelementptr index must be an integer");
4391 if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
4392 return Error(EltLoc, "getelementptr index type missmatch");
4393 if (Val->getType()->isVectorTy()) {
4394 unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
4395 unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
4396 if (ValNumEl != PtrNumEl)
4397 return Error(EltLoc,
4398 "getelementptr vector index has a wrong number of elements");
4400 Indices.push_back(Val);
4403 if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
4404 return Error(Loc, "base element of getelementptr must be sized");
4406 if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
4407 return Error(Loc, "invalid getelementptr indices");
4408 Inst = GetElementPtrInst::Create(Ptr, Indices);
4410 cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
4411 return AteExtraComma ? InstExtraComma : InstNormal;
4414 /// ParseExtractValue
4415 /// ::= 'extractvalue' TypeAndValue (',' uint32)+
4416 int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
4417 Value *Val; LocTy Loc;
4418 SmallVector<unsigned, 4> Indices;
4420 if (ParseTypeAndValue(Val, Loc, PFS) ||
4421 ParseIndexList(Indices, AteExtraComma))
4424 if (!Val->getType()->isAggregateType())
4425 return Error(Loc, "extractvalue operand must be aggregate type");
4427 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
4428 return Error(Loc, "invalid indices for extractvalue");
4429 Inst = ExtractValueInst::Create(Val, Indices);
4430 return AteExtraComma ? InstExtraComma : InstNormal;
4433 /// ParseInsertValue
4434 /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
4435 int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
4436 Value *Val0, *Val1; LocTy Loc0, Loc1;
4437 SmallVector<unsigned, 4> Indices;
4439 if (ParseTypeAndValue(Val0, Loc0, PFS) ||
4440 ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
4441 ParseTypeAndValue(Val1, Loc1, PFS) ||
4442 ParseIndexList(Indices, AteExtraComma))
4445 if (!Val0->getType()->isAggregateType())
4446 return Error(Loc0, "insertvalue operand must be aggregate type");
4448 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
4449 return Error(Loc0, "invalid indices for insertvalue");
4450 Inst = InsertValueInst::Create(Val0, Val1, Indices);
4451 return AteExtraComma ? InstExtraComma : InstNormal;
4454 //===----------------------------------------------------------------------===//
4455 // Embedded metadata.
4456 //===----------------------------------------------------------------------===//
4458 /// ParseMDNodeVector
4459 /// ::= Element (',' Element)*
4461 /// ::= 'null' | TypeAndValue
4462 bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
4463 PerFunctionState *PFS) {
4464 // Check for an empty list.
4465 if (Lex.getKind() == lltok::rbrace)
4469 // Null is a special case since it is typeless.
4470 if (EatIfPresent(lltok::kw_null)) {
4471 Elts.push_back(nullptr);
4476 if (ParseTypeAndValue(V, PFS)) return true;
4478 } while (EatIfPresent(lltok::comma));